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