Skip to main content

trusty_code/project_context/
mod.rs

1//! Project-context ingestion — load `CLAUDE.md` for prompt injection (#1033).
2//!
3//! Why: A Claude-Code-compatible harness must give the PM and every sub-agent
4//! the same project-specific rules a human Claude Code session would see — the
5//! `CLAUDE.md` at the project root. The parity prompt assembler (#1032) already
6//! accepts a verbatim project-context section; this module is the missing piece
7//! that *reads* that section off disk, bounds its size so a runaway file cannot
8//! blow the model's context budget, and degrades gracefully when no file exists.
9//! What: [`load_project_context`] walks the project root for `CLAUDE.md` (and,
10//! when present, the nested `.claude/CLAUDE.md` Claude-Code convention), reads
11//! the first one found, caps it at [`MAX_CONTEXT_BYTES`], and — on truncation —
12//! appends a provenance note so the model knows the context was clipped. A
13//! missing file yields `None`, never an error.
14//! Test: `project_context::tests` cover present/oversized/missing/positioning.
15//!
16//! [`load_project_context`]: crate::project_context::load_project_context
17//! [`MAX_CONTEXT_BYTES`]: crate::project_context::MAX_CONTEXT_BYTES
18
19use std::path::{Path, PathBuf};
20
21/// Maximum number of bytes of `CLAUDE.md` content injected into a prompt.
22///
23/// Why: `CLAUDE.md` can grow without bound (this very repo's is tens of KB).
24/// Injecting it whole would dominate the model's context window and inflate
25/// per-call cost. 16 KiB is a generous budget for project rules while keeping
26/// the injected surface bounded and comparable across runs.
27/// What: 16 * 1024 bytes. Content longer than this is truncated on a UTF-8
28/// boundary and annotated (see [`truncate_with_note`]).
29/// Test: `oversized_context_is_truncated_with_note`.
30pub const MAX_CONTEXT_BYTES: usize = 16 * 1024;
31
32/// Canonical filename for Claude-Code project context.
33///
34/// Why: Centralises the magic string so the root and nested lookups agree.
35/// What: The literal `"CLAUDE.md"`.
36/// Test: Exercised by every loader test.
37const CLAUDE_MD: &str = "CLAUDE.md";
38
39/// Load the project's `CLAUDE.md` context, size-capped and provenance-annotated.
40///
41/// Why: The PM and sub-agents must see the project's own rules; this is the
42/// single entry point the `run-task` handler and the in-process runner use to
43/// obtain the verbatim context section for `assemble_system_prompt`.
44/// What: Resolves the first existing of `<root>/CLAUDE.md` then
45/// `<root>/.claude/CLAUDE.md`; reads it; returns `Some(content)` capped at
46/// [`MAX_CONTEXT_BYTES`] (with a truncation note appended when clipped). Returns
47/// `None` when no file exists or the file cannot be read (absence is not an
48/// error — a project simply may not define project context).
49/// Test: `loads_root_claude_md`, `loads_nested_claude_md`,
50/// `missing_file_returns_none`, `oversized_context_is_truncated_with_note`.
51pub fn load_project_context(project_root: &Path) -> Option<String> {
52    let path = locate_claude_md(project_root)?;
53    // A read failure (permissions, races) is treated as "no context" rather than
54    // a hard error: the harness must still run with just the BASE + agent prompt.
55    let raw = std::fs::read_to_string(&path).ok()?;
56    Some(truncate_with_note(&raw, MAX_CONTEXT_BYTES))
57}
58
59/// Locate the project `CLAUDE.md`, preferring the root then a nested copy.
60///
61/// Why: Claude Code reads a root `CLAUDE.md`; some projects nest it under
62/// `.claude/`. Checking the root first matches what a human session sees
63/// without forcing a particular layout. #5426 adds the nested
64/// `.trusty-code/CLAUDE.md` ahead of `.claude/CLAUDE.md` so a project can hold
65/// its context entirely inside Trusty Code's own directory.
66/// What: `<root>/CLAUDE.md` if it exists; otherwise
67/// [`crate::paths::resolve_project_entry`] for `CLAUDE.md` as a file, which
68/// walks `.trusty-code/` → `.claude/` → `.open-mpm/`. `None` when none exists.
69/// Test: `loads_root_claude_md`, `loads_nested_claude_md`,
70/// `loads_trusty_code_claude_md`, `missing_file_returns_none`.
71fn locate_claude_md(project_root: &Path) -> Option<PathBuf> {
72    let root = project_root.join(CLAUDE_MD);
73    if root.is_file() {
74        return Some(root);
75    }
76    // #5426: one resolver for every nested project-config lookup.
77    let nested =
78        crate::paths::resolve_project_entry(project_root, CLAUDE_MD, crate::paths::EntryKind::File);
79    (nested.source != crate::paths::ConfigSource::Default).then_some(nested.path)
80}
81
82/// Truncate `content` to at most `max_bytes`, appending a provenance note when
83/// clipping occurs.
84///
85/// Why: A bounded context must remain valid UTF-8 (the model receives a string,
86/// and slicing mid-codepoint would panic) and must tell the model it is reading
87/// a partial file so it does not assume the rules are complete.
88/// What: If `content` is within budget, returns it unchanged. Otherwise truncates
89/// at the largest UTF-8 char boundary `<= max_bytes`, then appends
90/// `"\n\n[CLAUDE.md truncated to N bytes of M total]"` where `N` is the kept byte
91/// count and `M` the original length.
92/// Test: `oversized_context_is_truncated_with_note`,
93/// `within_budget_is_returned_verbatim`, `truncation_respects_utf8_boundary`.
94fn truncate_with_note(content: &str, max_bytes: usize) -> String {
95    if content.len() <= max_bytes {
96        return content.to_string();
97    }
98
99    // Find the largest char boundary at or below max_bytes so the slice is valid
100    // UTF-8 even when a multi-byte codepoint straddles the cap.
101    let mut end = max_bytes;
102    while end > 0 && !content.is_char_boundary(end) {
103        end -= 1;
104    }
105
106    let kept = &content[..end];
107    format!(
108        "{kept}\n\n[CLAUDE.md truncated to {end} bytes of {total} total]",
109        total = content.len()
110    )
111}
112
113// ── Tests ─────────────────────────────────────────────────────────────────────
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    /// A root `CLAUDE.md` is loaded and its content returned verbatim.
120    ///
121    /// Why: The common case — the PM must see the project's rules from the root
122    /// file exactly as written.
123    /// What: Write `<root>/CLAUDE.md`; assert `load_project_context` returns its
124    /// exact content.
125    /// Test: this test.
126    #[test]
127    fn loads_root_claude_md() {
128        let tmp = tempfile::tempdir().expect("tempdir");
129        std::fs::write(tmp.path().join("CLAUDE.md"), "PROJECT RULES: be concise.")
130            .expect("write CLAUDE.md");
131
132        let ctx = load_project_context(tmp.path()).expect("context loaded");
133        assert_eq!(ctx, "PROJECT RULES: be concise.");
134    }
135
136    /// A nested `.claude/CLAUDE.md` is loaded when no root file exists.
137    ///
138    /// Why: Some projects nest their context; the loader must find it too.
139    /// What: Write only `<root>/.claude/CLAUDE.md`; assert it is returned.
140    /// Test: this test.
141    #[test]
142    fn loads_nested_claude_md() {
143        let tmp = tempfile::tempdir().expect("tempdir");
144        let nested = tmp.path().join(".claude");
145        std::fs::create_dir_all(&nested).expect("mkdir .claude");
146        std::fs::write(nested.join("CLAUDE.md"), "NESTED RULES").expect("write nested");
147
148        let ctx = load_project_context(tmp.path()).expect("nested context loaded");
149        assert_eq!(ctx, "NESTED RULES");
150    }
151
152    /// A nested `.trusty-code/CLAUDE.md` is loaded, and outranks `.claude/`.
153    ///
154    /// Why: #5426 — a project must be able to hold its context entirely inside
155    /// Trusty Code's own directory. On `origin/main` this fails: the loader
156    /// checked only `<root>/CLAUDE.md` and `<root>/.claude/CLAUDE.md`.
157    /// What: writes the `.trusty-code/` copy alone, then adds a `.claude/` one
158    /// and asserts the native copy still wins.
159    /// Test: this function IS the test.
160    #[test]
161    fn loads_trusty_code_claude_md() {
162        let tmp = tempfile::tempdir().expect("tempdir");
163        let native = tmp.path().join(".trusty-code");
164        std::fs::create_dir_all(&native).expect("mkdir .trusty-code");
165        std::fs::write(native.join("CLAUDE.md"), "NATIVE RULES").expect("write native");
166
167        assert_eq!(
168            load_project_context(tmp.path()).expect("native context loaded"),
169            "NATIVE RULES"
170        );
171
172        let compat = tmp.path().join(".claude");
173        std::fs::create_dir_all(&compat).expect("mkdir .claude");
174        std::fs::write(compat.join("CLAUDE.md"), "COMPAT RULES").expect("write compat");
175
176        assert_eq!(
177            load_project_context(tmp.path()).expect("native context still wins"),
178            "NATIVE RULES"
179        );
180    }
181
182    /// The root file wins over a nested one when both exist.
183    ///
184    /// Why: Precedence must be deterministic; a human session reads the root.
185    /// What: Write both; assert the root content is returned.
186    /// Test: this test.
187    #[test]
188    fn root_takes_precedence_over_nested() {
189        let tmp = tempfile::tempdir().expect("tempdir");
190        std::fs::write(tmp.path().join("CLAUDE.md"), "ROOT").expect("write root");
191        let nested = tmp.path().join(".claude");
192        std::fs::create_dir_all(&nested).expect("mkdir .claude");
193        std::fs::write(nested.join("CLAUDE.md"), "NESTED").expect("write nested");
194
195        let ctx = load_project_context(tmp.path()).expect("loaded");
196        assert_eq!(ctx, "ROOT", "root CLAUDE.md must take precedence");
197    }
198
199    /// A project with no `CLAUDE.md` yields `None` (no error).
200    ///
201    /// Why: Absence must be handled gracefully — the harness still runs with just
202    /// the BASE + agent prompt.
203    /// What: Empty tempdir; assert `None`.
204    /// Test: this test.
205    #[test]
206    fn missing_file_returns_none() {
207        let tmp = tempfile::tempdir().expect("tempdir");
208        assert!(
209            load_project_context(tmp.path()).is_none(),
210            "missing CLAUDE.md must return None, not error"
211        );
212    }
213
214    /// Content within budget is returned verbatim (no note).
215    ///
216    /// Why: The truncation note must only appear when clipping actually happens.
217    /// What: A short file is returned byte-for-byte with no annotation.
218    /// Test: this test.
219    #[test]
220    fn within_budget_is_returned_verbatim() {
221        let small = "a".repeat(100);
222        let out = truncate_with_note(&small, MAX_CONTEXT_BYTES);
223        assert_eq!(out, small);
224        assert!(!out.contains("truncated"), "no note for in-budget content");
225    }
226
227    /// Oversized content is truncated and annotated with a provenance note.
228    ///
229    /// Why: A runaway `CLAUDE.md` must not blow the context budget, and the model
230    /// must know it received a partial file.
231    /// What: Build content larger than a tiny cap; assert the result is within the
232    /// cap-plus-note, that it carries the provenance note, and that the kept
233    /// prefix matches the original.
234    /// Test: this test.
235    #[test]
236    fn oversized_context_is_truncated_with_note() {
237        let content = "x".repeat(50);
238        let out = truncate_with_note(&content, 10);
239        assert!(
240            out.starts_with(&"x".repeat(10)),
241            "kept prefix must be the first 10 bytes"
242        );
243        assert!(
244            out.contains("[CLAUDE.md truncated to 10 bytes of 50 total]"),
245            "must carry the provenance note, got: {out}"
246        );
247    }
248
249    /// Truncation never splits a multi-byte UTF-8 codepoint.
250    ///
251    /// Why: Slicing a `&str` mid-codepoint panics; the cap must back off to a
252    /// char boundary so any content (incl. emoji / accented text) is safe.
253    /// What: Content of multi-byte chars truncated at a cap that lands mid-char;
254    /// assert the result is valid UTF-8 (it is, by construction) and the kept
255    /// length is `<= cap`.
256    /// Test: this test.
257    #[test]
258    fn truncation_respects_utf8_boundary() {
259        // "é" is 2 bytes in UTF-8; a cap of 5 lands mid-char on the 3rd "é".
260        let content = "é".repeat(10); // 20 bytes
261        let out = truncate_with_note(&content, 5);
262        // The kept portion before the note must be 4 bytes (two full "é"), not 5.
263        let note_start = out.find("\n\n[CLAUDE.md").expect("note present");
264        assert_eq!(&out[..note_start], "éé", "must back off to a char boundary");
265    }
266
267    /// Loaded context lands in the assembled prompt AFTER the agent prompt.
268    ///
269    /// Why: Parity-spec §2 fixes section order as BASE → agent prompt → project
270    /// context. This test ties `load_project_context` to `assemble_system_prompt`
271    /// to prove the injected context is positioned correctly (criterion d),
272    /// not merely present.
273    /// What: Build an `AgentConfig` with a distinctive agent-prompt marker; load a
274    /// project `CLAUDE.md` with its own marker; assemble; assert both markers are
275    /// present and the project marker appears strictly after the agent marker.
276    /// Test: this test.
277    #[test]
278    fn loaded_context_is_positioned_after_agent_prompt() {
279        use crate::agents::AgentConfig;
280        use crate::agents::config::{AgentInfo, SystemPrompt};
281        use crate::prompt::assemble_system_prompt;
282
283        let tmp = tempfile::tempdir().expect("tempdir");
284        std::fs::write(tmp.path().join("CLAUDE.md"), "PROJECT-CONTEXT-MARKER").expect("write");
285        let ctx = load_project_context(tmp.path()).expect("loaded");
286
287        let config = AgentConfig {
288            agent: AgentInfo {
289                name: "pm".into(),
290                ..Default::default()
291            },
292            system_prompt: SystemPrompt {
293                content: "AGENT-PROMPT-MARKER".into(),
294                ..Default::default()
295            },
296            ..Default::default()
297        };
298
299        let prompt = assemble_system_prompt(&config, Some(&ctx), None);
300        let agent_at = prompt
301            .find("AGENT-PROMPT-MARKER")
302            .expect("agent marker present");
303        let ctx_at = prompt
304            .find("PROJECT-CONTEXT-MARKER")
305            .expect("project context marker present");
306        assert!(
307            ctx_at > agent_at,
308            "project context must be positioned after the agent prompt"
309        );
310    }
311
312    /// `load_project_context` applies the byte cap end-to-end through the loader.
313    ///
314    /// Why: Guards the integration of file read + truncation, not just the helper.
315    /// What: Write a file larger than `MAX_CONTEXT_BYTES`; assert the loaded
316    /// context carries the truncation note and the kept body is within budget.
317    /// Test: this test.
318    #[test]
319    fn loader_enforces_byte_cap() {
320        let tmp = tempfile::tempdir().expect("tempdir");
321        let big = "z".repeat(MAX_CONTEXT_BYTES + 4096);
322        std::fs::write(tmp.path().join("CLAUDE.md"), &big).expect("write big");
323
324        let ctx = load_project_context(tmp.path()).expect("loaded");
325        assert!(
326            ctx.contains("[CLAUDE.md truncated to"),
327            "oversized file must be truncated with a note"
328        );
329        let note_start = ctx.find("\n\n[CLAUDE.md").expect("note present");
330        assert!(
331            note_start <= MAX_CONTEXT_BYTES,
332            "kept body must be within the byte cap"
333        );
334    }
335}