| 1 | //! Shared project-context types: the load-error enum and the |
| 2 | //! `ProjectContext` value that carries loaded instructions, rules, and the |
| 3 | //! rendered repo-constitution block into the system prompt. |
| 4 | |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | use thiserror::Error; |
| 8 | |
| 9 | use super::budget::{InstructionNotice, InstructionSegment}; |
| 10 | |
| 11 | // === Errors === |
| 12 | |
| 13 | #[derive(Debug, Error)] |
| 14 | pub enum ProjectContextError { |
| 15 | #[error("Failed to read context metadata for {path}: {source}")] |
| 16 | Metadata { |
| 17 | path: PathBuf, |
| 18 | source: std::io::Error, |
| 19 | }, |
| 20 | #[error("Context file {path} is too large ({size} bytes, max {max})")] |
| 21 | TooLarge { |
| 22 | path: PathBuf, |
| 23 | size: u64, |
| 24 | max: usize, |
| 25 | }, |
| 26 | #[error("Failed to read context file {path}: {source}")] |
| 27 | Read { |
| 28 | path: PathBuf, |
| 29 | source: std::io::Error, |
| 30 | }, |
| 31 | #[error("Context file {path} is empty")] |
| 32 | Empty { path: PathBuf }, |
| 33 | } |
| 34 | |
| 35 | impl ProjectContextError { |
| 36 | /// Machine-readable reason, so a skip can name the limit that produced it. |
| 37 | pub fn kind(&self) -> super::budget::InstructionLimit { |
| 38 | match self { |
| 39 | Self::TooLarge { .. } => super::budget::InstructionLimit::FileCeiling, |
| 40 | Self::Empty { .. } => super::budget::InstructionLimit::EmptyFile, |
| 41 | Self::Metadata { .. } | Self::Read { .. } => super::budget::InstructionLimit::None, |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub fn detail(&self) -> Option<super::budget::InstructionDetail> { |
| 46 | match self { |
| 47 | Self::TooLarge { max, .. } => Some(super::budget::InstructionDetail::OverFileCeiling { |
| 48 | max_bytes: *max as u64, |
| 49 | }), |
| 50 | Self::Empty { .. } => None, |
| 51 | Self::Metadata { source, .. } | Self::Read { source, .. } => { |
| 52 | Some(super::budget::InstructionDetail::unreadable(source)) |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Result of loading project context |
| 59 | #[derive(Debug, Clone)] |
| 60 | pub struct ProjectContext { |
| 61 | /// The loaded instructions content. |
| 62 | /// |
| 63 | /// This is the rendered join of [`Self::instruction_segments`] — global |
| 64 | /// scope first, then the project chain — and is rebuilt after every |
| 65 | /// budget trim, so a consumer that only reads the joined string always |
| 66 | /// sees post-budget content. |
| 67 | pub instructions: Option<String>, |
| 68 | /// Raw instruction content kept per source, untrimmed. |
| 69 | /// |
| 70 | /// Segment-level trimming needs to know where one file ends and the next |
| 71 | /// begins; a flattened string cannot answer that. The cached project |
| 72 | /// context is therefore stored raw and trimmed per request, so a context |
| 73 | /// window change never invalidates the file-keyed cache and a content |
| 74 | /// change never reuses trimmed text. |
| 75 | pub instruction_segments: Vec<InstructionSegment>, |
| 76 | /// Every instruction source that was trimmed, skipped, or refused while |
| 77 | /// loading or budgeting, for the startup notice and `/context report`. |
| 78 | pub notices: Vec<InstructionNotice>, |
| 79 | /// Auto-discovered rules from `.codewhale/rules/` / `.claude/rules/`. |
| 80 | /// Kept separate from `instructions` so rules alone don't block |
| 81 | /// parent-directory AGENTS.md discovery via `has_instructions()`. |
| 82 | pub rules_block: Option<String>, |
| 83 | /// Path to the loaded file (for display) |
| 84 | pub source_path: Option<PathBuf>, |
| 85 | /// Any warnings during loading |
| 86 | pub warnings: Vec<String>, |
| 87 | /// Rendered `.codewhale/constitution.json` authority block, if present. |
| 88 | /// Codewhale-specific repo authority/prioritization policy — distinct from |
| 89 | /// the cross-agent prose in `instructions`. |
| 90 | pub constitution_block: Option<String>, |
| 91 | /// Path to the repo constitution file that produced `constitution_block`. |
| 92 | pub constitution_source_path: Option<PathBuf>, |
| 93 | pub loaded_rule_paths: Vec<PathBuf>, |
| 94 | /// Project root directory |
| 95 | pub project_root: PathBuf, |
| 96 | } |
| 97 | |
| 98 | impl ProjectContext { |
| 99 | /// Create an empty project context |
| 100 | pub fn empty(project_root: PathBuf) -> Self { |
| 101 | Self { |
| 102 | instructions: None, |
| 103 | instruction_segments: Vec::new(), |
| 104 | notices: Vec::new(), |
| 105 | rules_block: None, |
| 106 | source_path: None, |
| 107 | warnings: Vec::new(), |
| 108 | constitution_block: None, |
| 109 | constitution_source_path: None, |
| 110 | loaded_rule_paths: Vec::new(), |
| 111 | project_root, |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | /// Check if any instructions were loaded |
| 116 | pub fn has_instructions(&self) -> bool { |
| 117 | self.instructions.is_some() |
| 118 | } |
| 119 | |
| 120 | /// Rebuild [`Self::instructions`] from the current segments. |
| 121 | /// |
| 122 | /// Called after assembly and after every trim. Global scope renders |
| 123 | /// first so the workspace keeps the last word, exactly as the single |
| 124 | /// merged block did before segments existed. |
| 125 | pub fn rebuild_joined_instructions(&mut self) { |
| 126 | self.instructions = super::render_joined_instructions(&self.instruction_segments); |
| 127 | } |
| 128 | |
| 129 | /// Get the instructions as a formatted block for system prompt. |
| 130 | /// |
| 131 | /// The Codewhale repo constitution (`.codewhale/constitution.json`), when |
| 132 | /// present, is emitted first as a higher-authority block, followed by the |
| 133 | /// cross-agent `<project_instructions>` prose. Either may be absent. |
| 134 | pub fn as_system_block(&self) -> Option<String> { |
| 135 | let instructions_block = self.instructions.as_ref().map(|content| { |
| 136 | let source = project_instructions_source_label(self.source_path.as_deref()); |
| 137 | |
| 138 | let mut block = format!( |
| 139 | "<project_instructions source=\"{source}\">\n{content}\n</project_instructions>" |
| 140 | ); |
| 141 | // Append rules after instructions, inside the same logical block. |
| 142 | // Rules are kept separate from `instructions` so they don't block |
| 143 | // parent-directory AGENTS.md discovery via `has_instructions()`. |
| 144 | if let Some(rules) = &self.rules_block { |
| 145 | block.push('\n'); |
| 146 | block.push_str(rules); |
| 147 | } |
| 148 | block |
| 149 | }); |
| 150 | |
| 151 | match (self.constitution_block.as_ref(), instructions_block) { |
| 152 | (Some(constitution), Some(instructions)) => { |
| 153 | Some(format!("{constitution}\n\n{instructions}")) |
| 154 | } |
| 155 | (Some(constitution), None) => { |
| 156 | // Constitution present but no main instructions — still emit rules if any |
| 157 | if let Some(rules) = &self.rules_block { |
| 158 | Some(format!("{constitution}\n\n{rules}")) |
| 159 | } else { |
| 160 | Some(constitution.clone()) |
| 161 | } |
| 162 | } |
| 163 | (None, Some(instructions)) => Some(instructions), |
| 164 | (None, None) => { |
| 165 | // No main instructions, but rules may exist on their own |
| 166 | self.rules_block.clone() |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// The `source` label for `<project_instructions>` (and repo constitution) |
| 173 | /// blocks: the context file's name only, never its absolute path. The label |
| 174 | /// sits inside the pinned system prompt, so keeping it stable across |
| 175 | /// directory moves and recasings means an unchanged file does not emit a |
| 176 | /// spurious `<context_update>` history append after a move, and absolute |
| 177 | /// project paths stay out of provider-bound prompt labels. Directory |
| 178 | /// identity stays discoverable via the shell; the label names the origin, |
| 179 | /// it is not a locator. |
| 180 | pub fn project_instructions_source_label(source_path: Option<&Path>) -> String { |
| 181 | source_path |
| 182 | .and_then(|path| path.file_name()) |
| 183 | .map(|name| name.to_string_lossy().into_owned()) |
| 184 | .unwrap_or_else(|| "project".to_string()) |
| 185 | } |
| 186 | |
| 187 | /// The `source` label for prompt blocks that must keep sibling scopes |
| 188 | /// distinguishable (ancestor instruction-chain segments, `<project_rule>` |
| 189 | /// blocks): the file's path relative to `root` — the containing checkout — |
| 190 | /// rendered with forward slashes. When `root` is `None` or `path` is not |
| 191 | /// inside it, falls back to the absolute spelling rather than guessing. |
| 192 | /// |
| 193 | /// Like [`project_instructions_source_label`], the label sits inside the |
| 194 | /// pinned system prompt, so keeping it stable across directory moves and |
| 195 | /// recasings means an unchanged file does not emit a spurious |
| 196 | /// `<context_update>` history append after a move, and absolute project |
| 197 | /// paths stay out of provider-bound prompt labels. Root-relative spelling |
| 198 | /// (rather than the bare file name) is deliberate: chain segments and rule |
| 199 | /// files legitimately share basenames across scopes, and the label exists |
| 200 | /// precisely to disambiguate them. |
| 201 | pub fn repo_relative_source_label(path: &Path, root: Option<&Path>) -> String { |
| 202 | if let Some(root) = root |
| 203 | && let Ok(relative) = path.strip_prefix(root) |
| 204 | { |
| 205 | return relative.to_string_lossy().replace('\\', "/"); |
| 206 | } |
| 207 | path.display().to_string() |
| 208 | } |
| 209 | |
| 210 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 211 | pub struct PinnedProjectInstructions { |
| 212 | pub user_level: Option<String>, |
| 213 | pub user_sha256: Option<String>, |
| 214 | pub repository_level: Option<String>, |
| 215 | pub repository_sha256: Option<String>, |
| 216 | pub loaded_paths: Vec<PathBuf>, |
| 217 | } |
| 218 | |
| 219 | impl PinnedProjectInstructions { |
| 220 | pub fn from_project_context(ctx: &ProjectContext) -> Self { |
| 221 | let user_level = super::render_instruction_scope( |
| 222 | &ctx.instruction_segments, |
| 223 | super::InstructionScope::Global, |
| 224 | ) |
| 225 | .filter(|text| !text.trim().is_empty()); |
| 226 | |
| 227 | let repo_segments: Vec<super::InstructionSegment> = ctx |
| 228 | .instruction_segments |
| 229 | .iter() |
| 230 | .filter(|segment| { |
| 231 | segment.scope == super::InstructionScope::Project && segment.path.is_some() |
| 232 | }) |
| 233 | .cloned() |
| 234 | .collect(); |
| 235 | let mut repo_parts = Vec::new(); |
| 236 | if let Some(rendered) = |
| 237 | super::render_instruction_scope(&repo_segments, super::InstructionScope::Project) |
| 238 | && !rendered.trim().is_empty() |
| 239 | { |
| 240 | repo_parts.push(rendered); |
| 241 | } |
| 242 | if let Some(rules) = ctx.rules_block.as_deref() |
| 243 | && !rules.trim().is_empty() |
| 244 | { |
| 245 | repo_parts.push(rules.to_string()); |
| 246 | } |
| 247 | if let Some(constitution) = ctx.constitution_block.as_deref() |
| 248 | && !constitution.trim().is_empty() |
| 249 | { |
| 250 | repo_parts.push(constitution.to_string()); |
| 251 | } |
| 252 | let repository_level = if repo_parts.is_empty() { |
| 253 | None |
| 254 | } else { |
| 255 | Some(repo_parts.join("\n\n")) |
| 256 | }; |
| 257 | |
| 258 | let user_sha256 = user_level |
| 259 | .as_deref() |
| 260 | .map(|text| codewhale_runtime::hashing::sha256_hex(text.as_bytes())); |
| 261 | let repository_sha256 = repository_level |
| 262 | .as_deref() |
| 263 | .map(|text| codewhale_runtime::hashing::sha256_hex(text.as_bytes())); |
| 264 | |
| 265 | let mut loaded_paths = Vec::new(); |
| 266 | let mut push_unique = |path: &PathBuf| { |
| 267 | if !loaded_paths.contains(path) { |
| 268 | loaded_paths.push(path.clone()); |
| 269 | } |
| 270 | }; |
| 271 | for segment in &ctx.instruction_segments { |
| 272 | if let Some(path) = segment.path.as_ref() { |
| 273 | push_unique(path); |
| 274 | } |
| 275 | if let Some(canonical) = segment.canonical_path.as_ref() { |
| 276 | push_unique(canonical); |
| 277 | } |
| 278 | } |
| 279 | for path in &ctx.loaded_rule_paths { |
| 280 | push_unique(path); |
| 281 | } |
| 282 | if let Some(path) = ctx.constitution_source_path.as_ref() { |
| 283 | push_unique(path); |
| 284 | } |
| 285 | |
| 286 | Self { |
| 287 | user_level, |
| 288 | user_sha256, |
| 289 | repository_level, |
| 290 | repository_sha256, |
| 291 | loaded_paths, |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 |