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