返回 CodeWhale
prompts.rs
根目录 / crates / engine / src / prompts.rs
1 //! System prompt composition.
2 //!
3 //! Prompts are assembled from composable layers loaded at compile time from
4 //! the single [`text`] module:
5 //! constitution → `message[0]` (byte-stable).
6 //! approval policy → request-time runtime metadata.
7 //! Tool availability comes only from the per-turn model catalog.
8 //!
9 //! Keeping every layer's text in one module makes prompt tuning a
10 //! single-file operation.
11
12 use codewhale_config::AppMode;
13 use codewhale_models::{SystemBlock, SystemPrompt, Tool};
14 use std::path::{Path, PathBuf};
15 use std::sync::{LazyLock, Mutex};
16
17 pub mod base_preview;
18 pub mod text;
19
20 #[derive(Debug, Clone)]
21 pub struct PromptSessionContext<'a> {
22 pub user_memory_block: Option<&'a str>,
23 pub goal_objective: Option<&'a str>,
24 pub project_context_pack_enabled: bool,
25 /// Resolved BCP-47 locale tag for the `## Environment` block in
26 /// the system prompt (e.g. `"en"`, `"zh-Hans"`, `"ja"`). The
27 /// caller is responsible for resolving this from `Settings`; no
28 /// disk I/O happens inside the prompt builder, so the workspace-
29 /// static portion of the system prompt stays cache-friendly.
30 pub locale_tag: &'a str,
31 /// When true, a ## Language Output Requirement block is appended
32 /// to the system prompt instructing the model to respond in
33 /// the resolved session locale.
34 pub translation_enabled: bool,
35 /// Active model identifier. The bundled constitution is model-agnostic,
36 /// but embedders may still provide a prompt override containing
37 /// `{model_id}`. Defaults to `"codewhale"` when the caller doesn't supply one.
38 pub model_id: &'a str,
39 /// Route-effective context window, when known. Prompt composition no
40 /// longer prints context-window facts, but the field remains part of the
41 /// session context contract for embedders and future runtime metadata.
42 pub context_window_override: Option<u32>,
43 /// Optional output-verbosity mode. `concise` appends a short output
44 /// discipline block; unset keeps the normal conversational prompt.
45 pub verbosity: Option<&'a str>,
46 /// One-line notice that a prior session in this workspace left a
47 /// recovery checkpoint (#5715). KV effect: frozen-prefix contributor —
48 /// computed at engine construction and stable for the session; absent
49 /// entirely when no interrupted session exists, so clean sessions share
50 /// the same prefix bytes.
51 pub recovery_hint: Option<&'a str>,
52 /// Session-pinned skill discovery, bundle policy and ambient index limits.
53 pub skills_config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>,
54 /// Immutable plugin snapshot owned by this App/Engine workspace context.
55 /// Never sourced from process-global mutable state.
56 pub plugin_registry: Option<&'a codewhale_plugins::PluginRegistry>,
57 /// Active runtime mode. Retained in the session contract for embedders;
58 /// bundled prompt text deliberately ignores it because policy and the live
59 /// tool catalog already express the mode.
60 pub mode: AppMode,
61 }
62
63 impl Default for PromptSessionContext<'_> {
64 fn default() -> Self {
65 Self {
66 user_memory_block: None,
67 goal_objective: None,
68 project_context_pack_enabled: false,
69 locale_tag: "en",
70 translation_enabled: false,
71 model_id: "codewhale",
72 context_window_override: None,
73 verbosity: None,
74 recovery_hint: None,
75 skills_config: Default::default(),
76 plugin_registry: None,
77 mode: AppMode::Agent,
78 }
79 }
80 }
81
82 /// Conventional location for the structured session relay artifact (#32).
83 /// A previous session writes it on exit / `/compact`; the next session reads
84 /// it back on startup and prepends it to the system prompt so a fresh agent
85 /// doesn't have to re-discover open blockers from scratch.
86 pub const HANDOFF_RELATIVE_PATH: &str = ".codewhale/handoff.md";
87 /// Legacy handoff path for reading from existing installs.
88 const LEGACY_HANDOFF_RELATIVE_PATH: &str = ".deepseek/handoff.md";
89
90 /// The relay artifact a new session reads: the primary path when a file
91 /// exists there, otherwise the legacy fallback. Returns the file to read and
92 /// its workspace-relative name, so every caller names the path actually read.
93 pub fn resolve_handoff_path(workspace: &Path) -> (PathBuf, &'static str) {
94 let primary = workspace.join(HANDOFF_RELATIVE_PATH);
95 if primary.exists() {
96 (primary, HANDOFF_RELATIVE_PATH)
97 } else {
98 (
99 workspace.join(LEGACY_HANDOFF_RELATIVE_PATH),
100 LEGACY_HANDOFF_RELATIVE_PATH,
101 )
102 }
103 }
104
105 /// Per-file size cap for the workspace relay artifact (`/relay`, compaction).
106 ///
107 /// Deliberately separate from the instruction-file ceiling: the relay is a
108 /// workspace-writable checkpoint with its own trim marker, and
109 /// `[instruction_budget] policy = "refuse"` must not change how the relay is
110 /// read.
111 const RELAY_ARTIFACT_MAX_BYTES: usize = 3 * 1024;
112
113 fn read_prompt_file_bounded(path: &Path, cap: usize) -> std::io::Result<(String, usize)> {
114 read_prompt_text_bounded(std::fs::File::open(path)?, cap)
115 }
116
117 /// Read at most `cap` bytes of a prompt file plus slack for the leading
118 /// whitespace the renderers trim, so an oversized file is never read whole
119 /// into memory just to be truncated. Returns the text and the file's full
120 /// length (for the truncation note). A file that is not UTF-8 within the read
121 /// window is an error, as a whole-file `read_to_string` would report; only a
122 /// character cut by the window's end is dropped.
123 pub fn read_prompt_text_bounded(
124 file: std::fs::File,
125 cap: usize,
126 ) -> std::io::Result<(String, usize)> {
127 use std::io::Read as _;
128
129 const LEADING_WHITESPACE_SLACK: usize = 4 * 1024;
130 let full_len = usize::try_from(file.metadata()?.len()).unwrap_or(usize::MAX);
131 let mut bytes = Vec::new();
132 file.take((cap + LEADING_WHITESPACE_SLACK) as u64)
133 .read_to_end(&mut bytes)?;
134 let truncated = bytes.len() < full_len;
135 let text = match String::from_utf8(bytes) {
136 Ok(text) => text,
137 Err(error) => {
138 let valid = error.utf8_error().valid_up_to();
139 let mut bytes = error.into_bytes();
140 // Only a multi-byte character split by the read window is
141 // forgiven; invalid bytes anywhere else still fail the read.
142 if !truncated || bytes.len() - valid > 3 {
143 return Err(std::io::Error::new(
144 std::io::ErrorKind::InvalidData,
145 "stream did not contain valid UTF-8",
146 ));
147 }
148 bytes.truncate(valid);
149 String::from_utf8(bytes)
150 .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?
151 }
152 };
153 Ok((text, full_len))
154 }
155
156 /// System prompt block appended when `translation_enabled` is true.
157 /// Instructs the model to respond in the resolved session locale for all
158 /// natural-language output — explanations, summaries, conversation.
159 /// Code identifiers, untranslatable technical terms, and explicitly
160 /// requested English code blocks are exempt.
161 fn translation_output_instruction(locale_tag: &str) -> String {
162 let target_language = translation_target_language_for_tag(locale_tag);
163 format!(
164 "\
165 ## Language Output Requirement\n\
166 \n\
167 The user requires all responses in {target_language}. \
168 Always respond in {target_language} — use natural, professional language for all \
169 explanations, code comments, summaries, and conversational turns. \
170 Only output English for:\n\
171 - Code identifiers (variable names, function names, file paths)\n\
172 - Technical terms that lack a standard translation in {target_language}\n\
173 - Code blocks the user explicitly requests in English\n\n\
174 This is a hard display requirement: the user does not read English, \
175 so any English prose in your response will block their decision-making."
176 )
177 }
178
179 fn translation_target_language_for_tag(locale_tag: &str) -> &'static str {
180 let normalized = locale_tag.trim().to_ascii_lowercase();
181 if normalized.starts_with("ja") {
182 "Japanese (日本語)"
183 } else if normalized.starts_with("zh-hant")
184 || normalized.contains("-tw")
185 || normalized.contains("-hk")
186 || normalized.contains("-mo")
187 {
188 "Traditional Chinese (繁體中文)"
189 } else if normalized.starts_with("zh") {
190 "Simplified Chinese (简体中文)"
191 } else if normalized.starts_with("pt") {
192 "Brazilian Portuguese (Português do Brasil)"
193 } else if normalized.starts_with("es") {
194 "Latin American Spanish (Español latinoamericano)"
195 } else if normalized.starts_with("vi") {
196 "Vietnamese (Tiếng Việt)"
197 } else if normalized.starts_with("ko") {
198 "Korean (한국어)"
199 } else if normalized.starts_with("ca") {
200 "Catalan (Català)"
201 } else if normalized.starts_with("de") {
202 "German (Deutsch)"
203 } else if normalized.starts_with("fr") {
204 "French (Français)"
205 } else if normalized.starts_with("id") {
206 "Indonesian (Bahasa Indonesia)"
207 } else if normalized.starts_with("hi") {
208 "Hindi (हिन्दी)"
209 } else if normalized.starts_with("ru") {
210 "Russian (Русский)"
211 } else if normalized.starts_with("uk") {
212 "Ukrainian (Українська)"
213 } else {
214 "English"
215 }
216 }
217
218 /// Render a `## Environment` block listing the resolved locale tag and the
219 /// actionable host facts that affect command syntax.
220 ///
221 /// The block is appended to the workspace-static portion of the system
222 /// prompt (after the shared constitution + project context, before configured
223 /// instructions / skills). `locale_tag` is resolved by the caller from
224 /// `Settings` so this function stays I/O-free.
225 ///
226 /// `platform` and `shell` remain because they change how commands must be
227 /// written and are stable for the life of the process. The release version was
228 /// removed by the turn-meta diet: it is telemetry the model cannot act on and
229 /// churned the otherwise-static prefix on every release. The live workspace
230 /// path is delivered per-turn via `<turn_meta>` (see `turn_metadata_block_from_snapshot`).
231 pub fn render_environment_block(_workspace: &Path, locale_tag: &str) -> String {
232 let (platform, shell) = environment_host_facts();
233 format_environment_block(locale_tag, &platform, &shell, npm_launcher_fact())
234 }
235
236 /// Pair a memory packet with the hygiene rules that say how to read it.
237 ///
238 /// One rule for every host: the root session and an inherited child prompt
239 /// must never ship the packet without its guidance, or the same bytes would
240 /// arrive with different statements about their authority. The block is
241 /// inserted verbatim — trimming it would break the byte-stable prefix.
242 #[must_use]
243 pub fn memory_prompt_section(memory_block: Option<&str>) -> Option<String> {
244 let block = memory_block?;
245 if block.trim().is_empty() {
246 return None;
247 }
248 Some(format!("{block}\n\n{MEMORY_GUIDANCE}"))
249 }
250
251 /// Format the `## Environment` block from already-resolved facts. Pure, so
252 /// the plain and npm-launcher shapes can both be tested on any host.
253 fn format_environment_block(
254 locale_tag: &str,
255 platform: &str,
256 shell: &str,
257 launcher: Option<&str>,
258 ) -> String {
259 let mut block = format!(
260 "## Environment\n\
261 \n\
262 - lang: {locale_tag}\n\
263 - platform: {platform}\n\
264 - shell: {shell}"
265 );
266 if let Some(launcher) = launcher {
267 block.push_str("\n- launcher: ");
268 block.push_str(launcher);
269 }
270 block
271 }
272
273 /// On Windows an npm install keeps the launcher's `node.exe` as this
274 /// process's parent for the whole session, and Windows ends `codewhale.exe`
275 /// with it (#6827). Like `platform` and `shell`, this is stable for the life
276 /// of the process and changes how commands must be written, so it belongs in
277 /// the static block. It names no PID, so the prefix stays cacheable.
278 const NPM_LAUNCHER_FACT: &str = "npm (node.exe is this session's parent; killing node.exe by name ends this and other npm-launched Codewhale sessions, so stop servers by PID or port)";
279
280 fn launcher_fact(
281 is_windows: bool,
282 method: codewhale_release::InstallMethod,
283 ) -> Option<&'static str> {
284 (is_windows && method == codewhale_release::InstallMethod::Npm).then_some(NPM_LAUNCHER_FACT)
285 }
286
287 /// The launcher line for this process. Install detection reads the
288 /// executable's path, so it runs once and only on Windows; recorded
289 /// conformance environments never carry it.
290 fn npm_launcher_fact() -> Option<&'static str> {
291 #[cfg(any(test, feature = "test-support"))]
292 if RECORDED_ENVIRONMENT.with(|cell| cell.borrow().is_some()) {
293 return None;
294 }
295 if !cfg!(windows) {
296 return None;
297 }
298 static METHOD: std::sync::OnceLock<codewhale_release::InstallMethod> =
299 std::sync::OnceLock::new();
300 launcher_fact(
301 true,
302 *METHOD.get_or_init(codewhale_release::current_install_method),
303 )
304 }
305
306 #[cfg(test)]
307 mod npm_launcher_fact_tests {
308 use super::*;
309 use codewhale_release::InstallMethod;
310
311 #[test]
312 fn plain_environment_block_is_unchanged() {
313 assert_eq!(
314 format_environment_block("en", "windows", "powershell", None),
315 "## Environment\n\n- lang: en\n- platform: windows\n- shell: powershell"
316 );
317 }
318
319 #[test]
320 fn windows_npm_install_names_the_node_launcher() {
321 let block = format_environment_block(
322 "en",
323 "windows",
324 "powershell",
325 launcher_fact(true, InstallMethod::Npm),
326 );
327 assert!(
328 block.ends_with(&format!("\n- launcher: {NPM_LAUNCHER_FACT}")),
329 "{block}"
330 );
331 assert!(block.contains("stop servers by PID or port"), "{block}");
332 }
333
334 #[test]
335 fn launcher_fact_is_windows_npm_only() {
336 assert_eq!(launcher_fact(false, InstallMethod::Npm), None);
337 for method in [
338 InstallMethod::Binary,
339 InstallMethod::Cargo,
340 InstallMethod::Homebrew,
341 InstallMethod::Omarchy,
342 ] {
343 assert_eq!(launcher_fact(true, method), None);
344 }
345 }
346 }
347
348 /// The host facts the `## Environment` block names: this process's OS and
349 /// the shell commands run under. Conformance goldens recorded on one host
350 /// replay that host's facts on the recording thread
351 /// ([`pin_recorded_environment`]); production always reports this host.
352 fn environment_host_facts() -> (String, String) {
353 #[cfg(any(test, feature = "test-support"))]
354 if let Some(recorded) = RECORDED_ENVIRONMENT.with(|cell| cell.borrow().clone()) {
355 return recorded;
356 }
357 (
358 std::env::consts::OS.to_string(),
359 codewhale_sandbox::shell_dispatcher::global_dispatcher()
360 .kind()
361 .binary()
362 .to_string(),
363 )
364 }
365
366 #[cfg(any(test, feature = "test-support"))]
367 thread_local! {
368 static RECORDED_ENVIRONMENT: std::cell::RefCell<Option<(String, String)>> =
369 const { std::cell::RefCell::new(None) };
370 }
371
372 /// Replay a recorded host's OS and shell in this thread's environment block
373 /// until the guard drops. Scripted conformance and runtime measurements pin
374 /// their fixture facts on the thread that renders the prompt.
375 #[cfg(any(test, feature = "test-support"))]
376 pub fn pin_recorded_environment(os: &str, shell: &str) -> RecordedEnvironmentGuard {
377 RECORDED_ENVIRONMENT
378 .with(|cell| *cell.borrow_mut() = Some((os.to_string(), shell.to_string())));
379 RecordedEnvironmentGuard
380 }
381
382 /// The replayed shell on this thread, when a recorded environment is pinned.
383 /// Tool descriptions that name the shell use it too, so a replay never
384 /// depends on which shell first initialized their process-wide caches.
385 #[cfg(all(any(test, feature = "test-support"), unix))]
386 pub fn recorded_shell() -> Option<String> {
387 RECORDED_ENVIRONMENT.with(|cell| cell.borrow().as_ref().map(|(_, shell)| shell.clone()))
388 }
389
390 #[cfg(any(test, feature = "test-support"))]
391 pub struct RecordedEnvironmentGuard;
392
393 #[cfg(any(test, feature = "test-support"))]
394 impl Drop for RecordedEnvironmentGuard {
395 fn drop(&mut self) {
396 RECORDED_ENVIRONMENT.with(|cell| *cell.borrow_mut() = None);
397 }
398 }
399
400 /// Source for an `EngineConfig.instructions` entry. Either a disk file (loaded
401 /// at render time, original semantics) or an inline string (content baked into
402 /// `EngineConfig`, no disk I/O at render time).
403 ///
404 /// The inline variant is useful for embedders that compute instructions at
405 /// runtime (e.g. rendering a template with workspace-specific substitutions)
406 /// and don't want to stage the content to a disk file just to satisfy a path
407 /// API. Staging adds two problems the inline path avoids:
408 ///
409 /// 1. The disk file looks like editable config but gets overwritten on
410 /// every launch — confusing for users browsing the install dir.
411 /// 2. Multi-engine setups need per-engine paths to avoid `rehydrate`
412 /// reading another session's instructions; with inline sources the
413 /// content lives in the per-engine `EngineConfig` and the race
414 /// surface goes away.
415 ///
416 /// `From<PathBuf>` is provided so existing callers passing `Vec<PathBuf>` can
417 /// keep working with a `.into()` upgrade at the call site.
418 #[derive(Debug, Clone)]
419 pub enum InstructionSource {
420 /// Read this file from disk when the instruction assembly runs.
421 /// Missing, empty, and over-`file_max_bytes` files are skipped with a
422 /// notice; a file that fits is charged to the global scope budget.
423 File(PathBuf),
424 /// Use the provided string directly. `name` becomes the
425 /// `<instructions source="…">` attribute (typically a synthetic
426 /// identifier like `embedded:my-template` or a logical path).
427 Inline { name: String, content: String },
428 }
429
430 impl From<PathBuf> for InstructionSource {
431 fn from(path: PathBuf) -> Self {
432 InstructionSource::File(path)
433 }
434 }
435
436 impl From<&PathBuf> for InstructionSource {
437 fn from(path: &PathBuf) -> Self {
438 InstructionSource::File(path.clone())
439 }
440 }
441
442 /// Read the workspace-local relay artifact, if present, and format it as a
443 /// system-prompt block. Returns `None` when the file is absent or empty so
444 /// callers can keep the default-uncluttered prompt for fresh workspaces.
445 fn load_handoff_block(workspace: &Path) -> Option<String> {
446 let (path, shown) = resolve_handoff_path(workspace);
447 let (raw, full_len) = read_prompt_file_bounded(&path, RELAY_ARTIFACT_MAX_BYTES).ok()?;
448 let trimmed = raw.trim();
449 if trimmed.is_empty() {
450 return None;
451 }
452 let truncated = raw.len() < full_len || trimmed.len() > RELAY_ARTIFACT_MAX_BYTES;
453 let relay = if truncated {
454 let window = &trimmed[..(0..=RELAY_ARTIFACT_MAX_BYTES.min(trimmed.len()))
455 .rev()
456 .find(|&i| trimmed.is_char_boundary(i))
457 .unwrap_or(0)];
458 let kept = window.rfind('\n').map_or(window, |end| &window[..end]);
459 format!(
460 "{}\n\n[Relay shortened here; read `{shown}` for the rest.]",
461 kept.trim_end()
462 )
463 } else {
464 trimmed.to_string()
465 };
466 Some(format!(
467 "## Previous Session Relay\n\nThe previous session in this workspace left a relay artifact at `{shown}`. Consider it the first artifact to read on this turn — open blockers, in-flight changes, and recent decisions live there. Update or rewrite it before exiting if state changes materially.\n\n{relay}"
468 ))
469 }
470
471 /// Load the structured user-global constitution, if present, and render it as
472 /// its own model-facing block.
473 pub fn load_user_constitution_block() -> Option<String> {
474 load_active_user_constitution()?.render_block(None)
475 }
476
477 pub fn load_active_user_constitution() -> Option<Box<codewhale_config::UserConstitution>> {
478 if user_constitution_disabled_by_setup_state() {
479 return None;
480 }
481
482 let path = match codewhale_config::UserConstitution::path() {
483 Ok(path) => path,
484 Err(err) => {
485 tracing::warn!(
486 target: "prompts",
487 "could not resolve user-global constitution path: {err:#}"
488 );
489 return None;
490 }
491 };
492
493 match codewhale_config::UserConstitution::load_from(&path) {
494 codewhale_config::UserConstitutionLoad::Loaded(constitution) => Some(constitution),
495 codewhale_config::UserConstitutionLoad::Missing
496 | codewhale_config::UserConstitutionLoad::Empty => None,
497 codewhale_config::UserConstitutionLoad::Invalid(err) => {
498 tracing::warn!(
499 target: "prompts",
500 "skipping invalid user-global constitution {}: {err}",
501 path.display()
502 );
503 None
504 }
505 codewhale_config::UserConstitutionLoad::Unreadable(err) => {
506 tracing::warn!(
507 target: "prompts",
508 "skipping unreadable user-global constitution {}: {err}",
509 path.display()
510 );
511 None
512 }
513 }
514 }
515
516 fn user_constitution_disabled_by_setup_state() -> bool {
517 match codewhale_config::SetupState::load() {
518 Ok(Some(state)) => !state.constitution_choice.applies_user_global(),
519 Ok(None) => false,
520 Err(err) => {
521 tracing::warn!(
522 target: "prompts",
523 "could not resolve setup-state path while loading user constitution: {err:#}"
524 );
525 false
526 }
527 }
528 }
529
530 // ── Prompt layers loaded at compile time ──────────────────────────────
531 //
532 // Every bundled prompt layer lives in `prompts/text.rs` as a compile-time
533 // constant (consolidated from the retired per-layer `prompts/*.md` files;
534 // each constant is byte-identical to the file it replaced, trailing newline
535 // included). The constants are re-exported here so the existing
536 // `crate::prompts::NAME` paths used across the crate are unchanged. Edit
537 // prompt text in `text.rs` directly; the test suite below guards content
538 // and ordering invariants (constitution structure and binding gates #4032,
539 // byte-stable prefix ordering, prefix privacy #4632).
540 pub use text::{
541 BASE_PROMPT, COMPACT_TEMPLATE, CORE_EXECUTION_PROFILE_PROMPT, GOAL_CONTINUATION_PROMPT,
542 LANGUAGE_PROMPT, MEMORY_GUIDANCE, OUTPUT_PROMPT,
543 };
544
545 // ── Embedder prompt overrides ──
546 // Let an embedder replace these compile-time prompt constants at startup,
547 // so brand / slimming customizations live in the embedder crate instead of
548 // editing these files in-tree. Unset → the bundled constant (fully
549 // backward compatible). Intended to be set once at process start, before
550 // any engine spawns; later sets return the rejected override string.
551 static BASE_PROMPT_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
552 static LOCALE_PREAMBLE_ZH_HANS_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
553 static LOCALE_PREAMBLE_JA_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
554 static LOCALE_PREAMBLE_PT_BR_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
555 static LOCALE_PREAMBLE_VI_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
556 static LOCALE_CLOSER_ZH_HANS_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
557 static LOCALE_CLOSER_JA_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
558 static LOCALE_CLOSER_PT_BR_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
559 static LOCALE_CLOSER_VI_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
560 static AUTHORITY_RECAP_OVERRIDE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
561 static STATIC_PROMPT_COMPOSER: std::sync::OnceLock<Box<StaticPromptComposer>> =
562 std::sync::OnceLock::new();
563 static PROMPT_OVERRIDE_NOTICES: LazyLock<Mutex<Vec<String>>> =
564 LazyLock::new(|| Mutex::new(Vec::new()));
565
566 /// Context passed to an embedder-provided static prompt composer.
567 ///
568 /// This hook only replaces the byte-stable base prompt segment.
569 /// Approval policy, Core Execution, and action-specific relay formatting stay
570 /// owned by Codewhale.
571 #[non_exhaustive]
572 #[derive(Debug)]
573 pub struct StaticPromptCtx<'a> {
574 /// Active model identifier after caller-side routing.
575 pub model_id: &'a str,
576 /// Default base prompt layers that would be used without an
577 /// override.
578 pub default_layers: &'a str,
579 }
580
581 /// Embedder hook for replacing Codewhale's byte-stable base prompt
582 /// segment.
583 pub type StaticPromptComposer = dyn Fn(&StaticPromptCtx<'_>) -> String + Send + Sync + 'static;
584
585 /// Replace `BASE_PROMPT` for all subsequent prompt composition. First call
586 /// wins; later calls return the rejected string. Set before spawning any
587 /// engine.
588 pub fn set_base_prompt_override(s: String) -> Result<(), String> {
589 set_prompt_override(&BASE_PROMPT_OVERRIDE, s)
590 }
591
592 // ── Config-directory prompt overrides (issue #3638) ──
593 // Bridge the embedder override hooks above to a user-facing source: an
594 // optional file in the Codewhale config directory. This lets users repurpose
595 // the TUI for non-software use cases (e.g. long-form writing) by swapping the
596 // constitutional base prompt, without editing in-tree files or shipping a
597 // custom embedder build.
598 //
599 // Scope is deliberately narrow: only the byte-stable base prompt segment is
600 // user-overridable. Approval policy, Core Execution, and
601 // action-specific relay formatting stay owned by the runtime assembly (see
602 // `StaticPromptCtx`), so an override cannot strip safety-relevant guidance.
603 // A missing or empty file is a no-op — the bundled constant is used — so this
604 // is fully backward compatible.
605 //
606 // Because replacing the base prompt is a trust-boundary action (per maintainer
607 // review on #3638), the override file alone is NOT sufficient: the user must
608 // also set an explicit opt-in flag (`CODEWHALE_ALLOW_BASE_PROMPT_OVERRIDE`).
609 // This keeps replacing the global Constitution a deliberate, auditable act
610 // rather than something a stray file can do.
611
612 /// Target lane for the once-per-version constitution checkpoint. Bumped per
613 /// release when the bundled constitution materially changes, so existing users
614 /// re-acknowledge it once. 0.9.4 re-ships the Fleet/operate constitution.
615 pub const CONSTITUTION_CHECKPOINT_VERSION: &str = "0.9.4";
616
617 /// Relative path, under the config directory, of the optional base-prompt
618 /// (constitution) override file.
619 pub const CONSTITUTION_OVERRIDE_FILE: &str = "prompts/constitution.md";
620
621 /// Env flag that must be set (`1`/`true`/`on`/`yes`) to enable config-dir base
622 /// prompt overrides. Required in addition to the override file so the global
623 /// base prompt can never be replaced by file presence alone.
624 pub const BASE_PROMPT_OVERRIDE_OPT_IN_ENV: &str = "CODEWHALE_ALLOW_BASE_PROMPT_OVERRIDE";
625
626 /// Whether the user has explicitly opted in to base-prompt overrides.
627 pub fn base_prompt_override_opt_in() -> bool {
628 match std::env::var(BASE_PROMPT_OVERRIDE_OPT_IN_ENV) {
629 Ok(v) => matches!(
630 v.trim().to_ascii_lowercase().as_str(),
631 "1" | "true" | "on" | "yes"
632 ),
633 Err(_) => false,
634 }
635 }
636
637 /// Read an optional prompt-override file rooted at `config_dir`.
638 ///
639 /// Returns the file contents when it exists and is non-empty after trimming;
640 /// otherwise `None` so the caller falls back to the embedded default. Pure
641 /// over `config_dir`, so it is unit-testable without touching the global
642 /// override cells.
643 fn read_prompt_override_file(config_dir: &Path, relative: &str) -> Option<String> {
644 let path = config_dir.join(relative);
645 let raw = std::fs::read_to_string(&path).ok()?;
646 if raw.trim().is_empty() {
647 tracing::warn!(
648 target: "prompts",
649 "ignoring empty prompt override file {}",
650 path.display(),
651 );
652 return None;
653 }
654 tracing::info!(
655 target: "prompts",
656 "loaded prompt override from {}",
657 path.display(),
658 );
659 Some(raw)
660 }
661
662 fn push_prompt_override_notice(message: String) {
663 if let Ok(mut notices) = PROMPT_OVERRIDE_NOTICES.lock() {
664 notices.push(message);
665 }
666 }
667
668 pub fn take_prompt_override_notices() -> Vec<String> {
669 PROMPT_OVERRIDE_NOTICES
670 .lock()
671 .map(|mut notices| std::mem::take(&mut *notices))
672 .unwrap_or_default()
673 }
674
675 /// Load user prompt overrides from `config_dir` and install them through the
676 /// existing override hooks. Returns the names of the overrides that were
677 /// applied (for logging/diagnostics).
678 ///
679 /// Call once at startup, before any engine spawns, because the underlying
680 /// override cells are first-call-wins. Missing files are a no-op, preserving
681 /// the bundled defaults.
682 pub fn load_config_dir_prompt_overrides(config_dir: &Path) -> Vec<&'static str> {
683 let mut applied = Vec::new();
684 if let Some(text) = read_prompt_override_file(config_dir, CONSTITUTION_OVERRIDE_FILE) {
685 if !base_prompt_override_opt_in() {
686 // A file exists but the user hasn't opted in. Don't silently
687 // replace the base prompt — surface the gate instead.
688 let warning = format!(
689 "Custom Constitution override found at {}/{} but {} is not set; using the bundled Constitution. Set {}=1 to opt in.",
690 config_dir.display(),
691 CONSTITUTION_OVERRIDE_FILE,
692 BASE_PROMPT_OVERRIDE_OPT_IN_ENV,
693 BASE_PROMPT_OVERRIDE_OPT_IN_ENV,
694 );
695 tracing::warn!(
696 target: "prompts",
697 "{warning}",
698 );
699 push_prompt_override_notice(warning);
700 } else if set_base_prompt_override(text).is_ok() {
701 applied.push("constitution");
702 }
703 }
704 applied
705 }
706
707 /// Resolve the Codewhale config directory and load any prompt overrides found
708 /// there. Convenience wrapper around [`load_config_dir_prompt_overrides`] for
709 /// startup wiring; silently does nothing when the config home cannot be
710 /// resolved.
711 pub fn load_prompt_overrides_from_config_home() {
712 let Ok(home) = codewhale_config::codewhale_home() else {
713 return;
714 };
715 let applied = load_config_dir_prompt_overrides(&home);
716 if !applied.is_empty() {
717 tracing::info!(
718 target: "prompts",
719 "applied {} config-directory prompt override(s): {}",
720 applied.len(),
721 applied.join(", "),
722 );
723 }
724 }
725
726 fn set_prompt_override(cell: &std::sync::OnceLock<String>, s: String) -> Result<(), String> {
727 cell.set(s)
728 }
729
730 fn effective_prompt_override<'a>(
731 cell: &'a std::sync::OnceLock<String>,
732 fallback: &'static str,
733 ) -> &'a str {
734 cell.get().map(String::as_str).unwrap_or(fallback)
735 }
736
737 fn effective_base_prompt() -> &'static str {
738 effective_prompt_override(&BASE_PROMPT_OVERRIDE, BASE_PROMPT)
739 }
740
741 /// Where the base-prompt bytes used by this process actually came from.
742 ///
743 /// #3928: diagnostics used to cite `crates/engine/src/prompts/text.rs`, which is
744 /// a source-tree path that does not exist on an installed binary and says
745 /// nothing about whether an override replaced the constant at startup. This
746 /// reports the runtime truth instead.
747 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
748 pub enum BasePromptOrigin {
749 /// The `BASE_PROMPT` constant compiled into this binary.
750 Bundled,
751 /// An opted-in `prompts/constitution.md` override installed at startup.
752 ConfigOverride,
753 }
754
755 impl BasePromptOrigin {
756 /// Short, user-facing provenance label. Contains no filesystem paths.
757 pub fn label(self) -> &'static str {
758 match self {
759 Self::Bundled => "bundled in this codewhale-engine build (BASE_PROMPT, compiled in)",
760 Self::ConfigOverride => concat!(
761 "config-directory override installed at startup ",
762 "(prompts/constitution.md, opt-in enabled)"
763 ),
764 }
765 }
766 }
767
768 /// Runtime provenance of the base prompt for this process.
769 pub fn base_prompt_origin() -> BasePromptOrigin {
770 if BASE_PROMPT_OVERRIDE.get().is_some() {
771 BasePromptOrigin::ConfigOverride
772 } else {
773 BasePromptOrigin::Bundled
774 }
775 }
776
777 /// The exact base-prompt bytes this process will compose into the system
778 /// prompt — the override when one is installed, the bundled constant
779 /// otherwise.
780 pub fn effective_base_prompt_text() -> &'static str {
781 effective_base_prompt()
782 }
783
784 /// Where the effective base prompt actually comes from right now (#3928).
785 ///
786 /// Reads the same cells composition reads, so a preview cannot claim "bundled"
787 /// while an override is live. `config_dir` only supplies the path shown in the
788 /// override label; it does not decide whether an override is in effect.
789 #[must_use]
790 pub fn effective_base_prompt_source(config_dir: Option<&Path>) -> base_preview::BasePromptSource {
791 if STATIC_PROMPT_COMPOSER.get().is_some() {
792 // An embedder composer wraps or replaces the whole static layer set, so
793 // it outranks the base-prompt cell as the honest answer.
794 return base_preview::BasePromptSource::EmbedderComposer;
795 }
796 if BASE_PROMPT_OVERRIDE.get().is_some() {
797 return base_preview::BasePromptSource::ConfigOverride {
798 path: config_dir.map_or_else(
799 || CONSTITUTION_OVERRIDE_FILE.to_string(),
800 |dir| dir.join(CONSTITUTION_OVERRIDE_FILE).display().to_string(),
801 ),
802 };
803 }
804 base_preview::BasePromptSource::Bundled
805 }
806
807 fn effective_static_prompt_composer() -> Option<&'static StaticPromptComposer> {
808 STATIC_PROMPT_COMPOSER.get().map(Box::as_ref)
809 }
810
811 fn effective_locale_preamble_zh_hans() -> &'static str {
812 effective_prompt_override(&LOCALE_PREAMBLE_ZH_HANS_OVERRIDE, LOCALE_PREAMBLE_ZH_HANS)
813 }
814
815 fn effective_locale_preamble_ja() -> &'static str {
816 effective_prompt_override(&LOCALE_PREAMBLE_JA_OVERRIDE, LOCALE_PREAMBLE_JA)
817 }
818
819 fn effective_locale_preamble_pt_br() -> &'static str {
820 effective_prompt_override(&LOCALE_PREAMBLE_PT_BR_OVERRIDE, LOCALE_PREAMBLE_PT_BR)
821 }
822
823 fn effective_locale_preamble_vi() -> &'static str {
824 effective_prompt_override(&LOCALE_PREAMBLE_VI_OVERRIDE, LOCALE_PREAMBLE_VI)
825 }
826
827 fn effective_locale_closer_zh_hans() -> &'static str {
828 effective_prompt_override(&LOCALE_CLOSER_ZH_HANS_OVERRIDE, LOCALE_CLOSER_ZH_HANS)
829 }
830
831 fn effective_locale_closer_ja() -> &'static str {
832 effective_prompt_override(&LOCALE_CLOSER_JA_OVERRIDE, LOCALE_CLOSER_JA)
833 }
834
835 fn effective_locale_closer_pt_br() -> &'static str {
836 effective_prompt_override(&LOCALE_CLOSER_PT_BR_OVERRIDE, LOCALE_CLOSER_PT_BR)
837 }
838
839 fn effective_locale_closer_vi() -> &'static str {
840 effective_prompt_override(&LOCALE_CLOSER_VI_OVERRIDE, LOCALE_CLOSER_VI)
841 }
842
843 pub fn effective_authority_recap() -> &'static str {
844 effective_prompt_override(&AUTHORITY_RECAP_OVERRIDE, AUTHORITY_RECAP)
845 }
846
847 /// Optional locale-native reinforcement preamble prepended to the system
848 /// prompt when the user's UI locale is non-English.
849 ///
850 /// `constitution.md` itself stays English (single source of truth, model is
851 /// natively multilingual, prefix-cache stable across users in the same
852 /// locale). For non-English locales we prepend a short locale-native
853 /// passage so the model's first exposure to the prompt overrides the
854 /// "match user message language" English directive with an explicit
855 /// "use {locale}" instruction in the user's own writing system. Reduces
856 /// the model's reliance on inferring intent from `## Environment.lang`
857 /// — which previously got overpowered by overwhelmingly English task
858 /// context, the symptom reported in #1118 and visible in the WeChat
859 /// screenshot that prompted this change.
860 ///
861 /// The list is intentionally short (`zh-Hans`, `ja`, `pt-BR`, `vi`) even
862 /// though the TUI ships UI packs for many more locales. Other locales fall
863 /// through to `None` and get the English-only directive, which is the same
864 /// behavior as before this change; the test
865 /// `v092_locales_add_no_prompt_bookends_so_prompt_bytes_stay_stable` locks
866 /// that set so adding a UI pack never silently changes prompt bytes.
867 ///
868 /// ## Design philosophy: why a bookend, not a full translation
869 ///
870 /// Community feedback on the WeChat thread that prompted this work
871 /// pointed out — correctly — that DeepSeek V4 is a Chinese-first
872 /// multilingual model, not an English-only model with multilingual
873 /// veneer. Its tokenizer is co-trained on Chinese; `你好` typically
874 /// encodes to ~1 token, not 2 — the "Chinese is expensive in tokens"
875 /// folk wisdom from Western-LLM commentary doesn't apply here.
876 ///
877 /// The naïve translation of that argument would be: ship a fully
878 /// translated `constitution.md` per locale. We deliberately stop short of
879 /// that for v0.8.29. The reasons, ranked:
880 ///
881 /// 1. **Drift risk.** A 200+ line technical prompt has subtle
882 /// phrasing that drives subtle behavior. Every rule change has
883 /// to land in N translated copies, kept in lockstep. The class
884 /// of bug that arises (Chinese users see slightly different
885 /// agent behavior than English users) is hard to reproduce and
886 /// hard to triage from bug reports.
887 /// 2. **Cache stability.** With one English `constitution.md` and a
888 /// per-locale preamble+closer, the largest cacheable chunk
889 /// (shared constitution + project context + environment) stays
890 /// byte-stable within a session and across users in the same
891 /// locale. A fully translated per-locale `constitution.md` keeps cache
892 /// per-locale but doesn't share with English users.
893 /// 3. **Translation QA is expensive.** Each prompt-language pair
894 /// needs a native speaker reviewing tone, register, and rule
895 /// preservation. Getting it 95% right is bad, because the
896 /// missing 5% becomes silent behavior divergence.
897 ///
898 /// What we DO instead — the bookend pattern @MuMu described from
899 /// their other project — is reinforce the locale directive in
900 /// native script at BOTH ends of the prompt. The opening anchors
901 /// behavior at session start; the closing reinforcement
902 /// (`locale_reinforcement_closer`) sits at the maximum-recency
903 /// position right before the user's next message. Empirically this
904 /// is sufficient to keep `reasoning_content` in the target locale
905 /// even as English code accumulates in context turn-over-turn.
906 ///
907 /// If at some future point the bookend proves insufficient — or if
908 /// the maintenance cost of per-locale `constitution.md` files becomes
909 /// preferable to whatever's blocking it — full translation is the
910 /// natural next step. The locale tags here, the test invariants,
911 /// and the closer position would all carry over unchanged.
912 pub fn locale_reinforcement_preamble(locale_tag: &str) -> Option<&'static str> {
913 match locale_tag {
914 "zh-Hans" | "zh-CN" | "zh" => Some(effective_locale_preamble_zh_hans()),
915 "ja" | "ja-JP" => Some(effective_locale_preamble_ja()),
916 "pt-BR" | "pt" => Some(effective_locale_preamble_pt_br()),
917 "vi" | "vi-VN" => Some(effective_locale_preamble_vi()),
918 _ => None,
919 }
920 }
921
922 /// Locale-native closing reinforcement appended to the very end of the
923 /// system prompt — the bookend MuMu described in the WeChat thread that
924 /// prompted #1118 follow-up work.
925 ///
926 /// The opening preamble alone is not enough: as the model accumulates
927 /// English context turn-over-turn (code, error logs, search results,
928 /// file listings), the recency bias of the transformer's attention
929 /// drifts thinking back toward English even when the user keeps writing
930 /// in their own language. A closing native-script reinforcement sits at
931 /// the position closest to the user's next message — where attention
932 /// weight is highest — and re-asserts the language rule right before
933 /// the model generates `reasoning_content` for the turn.
934 ///
935 /// Like the opening preamble, English (and unknown) locales return
936 /// `None` and the system prompt is byte-identical to the pre-bookend
937 /// behavior.
938 pub fn locale_reinforcement_closer(locale_tag: &str) -> Option<&'static str> {
939 match locale_tag {
940 "zh-Hans" | "zh-CN" | "zh" => Some(effective_locale_closer_zh_hans()),
941 "ja" | "ja-JP" => Some(effective_locale_closer_ja()),
942 "pt-BR" | "pt" => Some(effective_locale_closer_pt_br()),
943 "vi" | "vi-VN" => Some(effective_locale_closer_vi()),
944 _ => None,
945 }
946 }
947
948 const LOCALE_PREAMBLE_ZH_HANS: &str = "## 语言要求\n\n\
949 你正在 codewhale 中运行。无论任务上下文(代码、错误日志、文件名)\
950 是英文,无论系统提示的其余部分是英文,你都必须用简体中文进行 \
951 `reasoning_content`(内部思考)和最终回复。代码、文件路径、工具名称\
952 (例如 `read`、`bash`)、环境变量、命令行参数和 URL \
953 保持原样 —— 只有自然语言散文要切换到简体中文。\n\n\
954 如果用户在会话中切换到另一种语言,从下一轮开始跟随切换。\
955 如果用户明确要求(例如 \"think in English\"),则覆盖此规则。";
956
957 const LOCALE_PREAMBLE_JA: &str = "## 言語要件\n\n\
958 codewhale を実行しています。タスクコンテキスト(コード、エラーログ、\
959 ファイル名)が英語であっても、システムプロンプトの他の部分が英語で\
960 あっても、`reasoning_content`(内部思考)と最終的な返信は日本語で\
961 行ってください。コード、ファイルパス、ツール名(例:`read`、\
962 `bash`)、環境変数、コマンドライン引数、URL は元のまま —— \
963 自然言語の文章のみ日本語に切り替えます。\n\n\
964 ユーザーがセッション中に別の言語に切り替えた場合は、次のターンから\
965 それに従ってください。ユーザーが明示的に要求した場合(例:\
966 \"think in English\")はこのルールを上書きします。";
967
968 const LOCALE_PREAMBLE_PT_BR: &str = "## Requisito de Idioma\n\n\
969 Você está rodando dentro do codewhale. Escreva tanto \
970 `reasoning_content` (seu pensamento interno) quanto a resposta final \
971 em português do Brasil, mesmo quando o contexto da tarefa (código, \
972 logs de erro, nomes de arquivos) estiver em inglês e mesmo quando o \
973 resto do system prompt for em inglês. Mantenha código, caminhos de \
974 arquivos, nomes de ferramentas (por exemplo `read`, \
975 `bash`), variáveis de ambiente, flags de linha de comando e \
976 URLs no formato original — apenas a prosa em linguagem natural muda \
977 para português do Brasil.\n\n\
978 Se o usuário mudar de idioma no meio da sessão, mude no próximo turno. \
979 Se o usuário pedir explicitamente (por exemplo, \"think in English\"), \
980 isso sobrescreve esta regra.";
981
982 // ── Closing bookends (appended to the very end of the system prompt) ──
983
984 const LOCALE_CLOSER_ZH_HANS: &str = "## 语言再次提醒\n\n\
985 **重要:你的 `reasoning_content`(内部思考)和最终回复必须保持简体中文。** \
986 无论你在这次会话中读到了多少英文代码、错误日志或文档,无论项目上下文 \
987 是英文,思考过程不能漂移到英文。这是会话级硬性要求 —— 用户的语言决定 \
988 你的语言,与上下文中累积的英文内容无关。除非用户明确要求切换(例如 \
989 \"think in English\"),否则继续用简体中文思考和回答。";
990
991 const LOCALE_CLOSER_JA: &str = "## 言語再確認\n\n\
992 **重要:`reasoning_content`(内部思考)と最終的な返信は日本語で行ってください。** \
993 このセッションで読み込んだ英語のコード、エラーログ、ドキュメントの量に \
994 関係なく、プロジェクトコンテキストが英語であっても、思考プロセスを \
995 英語に逸らさないでください。これはセッションレベルの厳格な要件であり、 \
996 ユーザーの言語があなたの言語を決定します。ユーザーが明示的に切り替えを \
997 要求しない限り(例:\"think in English\")、日本語で思考し、回答し続けて \
998 ください。";
999
1000 const LOCALE_CLOSER_PT_BR: &str = "## Reforço de Idioma\n\n\
1001 **Importante: seu `reasoning_content` (pensamento interno) e a resposta \
1002 final devem permanecer em português do Brasil.** Independentemente de \
1003 quanto código em inglês, logs de erro ou documentação você ler nesta \
1004 sessão, e independentemente de o contexto do projeto ser em inglês, o \
1005 processo de pensamento não pode derivar para o inglês. Este é um \
1006 requisito rígido em nível de sessão — o idioma do usuário define seu \
1007 idioma. A menos que o usuário peça explicitamente a troca (por exemplo, \
1008 \"think in English\"), continue pensando e respondendo em português do \
1009 Brasil.";
1010
1011 const LOCALE_PREAMBLE_VI: &str = "## Yêu cầu ngôn ngữ\n\n\
1012 Bạn đang chạy trong codewhale. Cho dù ngữ cảnh tác vụ (mã nguồn, nhật ký lỗi, tên tệp) \
1013 là tiếng Anh, cho dù phần còn lại của system prompt là tiếng Anh, bạn đều phải sử dụng \
1014 tiếng Việt cho phần `reasoning_content` (suy nghĩ nội bộ) và câu trả lời cuối cùng. Các từ \
1015 mã nguồn, đường dẫn tệp, tên công cụ (ví dụ `read`, `bash`), biến môi trường, \
1016 tham số dòng lệnh và URL giữ nguyên dạng gốc —— chỉ các văn bản giải thích bằng ngôn ngữ \
1017 tự nhiên mới được chuyển sang tiếng Việt.\n\n\
1018 Nếu người dùng chuyển sang ngôn ngữ khác trong phiên làm việc, hãy chuyển theo từ lượt tiếp theo. \
1019 Nếu người dùng yêu cầu rõ ràng (ví dụ \"think in English\"), hãy ghi đè quy tắc này.";
1020
1021 const LOCALE_CLOSER_VI: &str = "## Nhắc nhở ngôn ngữ một lần nữa\n\n\
1022 **Quan trọng: phần `reasoning_content` (suy nghĩ nội bộ) và phản hồi cuối cùng của bạn phải được viết bằng tiếng Việt.** \
1023 Dù bạn có đọc bao nhiêu mã nguồn tiếng Anh, nhật ký lỗi hay tài liệu trong phiên làm việc này, và dù ngữ cảnh \
1024 dự án có là tiếng Anh, quá trình suy nghĩ của bạn cũng không được chuyển sang tiếng Anh. Đây là yêu cầu cứng \
1025 ở cấp phiên làm việc —— ngôn ngữ của người dùng quyết định ngôn ngữ của bạn, không phụ thuộc vào nội dung tiếng Anh \
1026 tích lũy trong ngữ cảnh. Trừ khi người dùng yêu cầu rõ ràng việc chuyển đổi (ví dụ \"think in English\"), \
1027 hãy tiếp tục suy nghĩ và trả lời bằng tiếng Việt.";
1028
1029 // ── Composition ───────────────────────────────────────────────────────
1030
1031 /// Substitute the model id for embedder-supplied prompt overrides that still
1032 /// template it. The bundled constitution is deliberately model-agnostic and
1033 /// carries no model-fact placeholders.
1034 fn apply_model_template(
1035 prompt: &str,
1036 model_id: &str,
1037 _context_window_override: Option<u32>,
1038 ) -> String {
1039 prompt.replace("{model_id}", model_id)
1040 }
1041
1042 /// Authority recap block — appended at the end of the system prompt,
1043 /// just before the user's first message. Uses recency bias constructively
1044 /// without restating ranks: precedence is stated only in `BASE_PROMPT`
1045 /// § Whose word wins (#4777).
1046 const AUTHORITY_RECAP: &str = "\
1047 ## Authority Recap
1048
1049 Codewhale's constitution governs your behavior. Ground truth underlies the
1050 whole list: the user may override a fact, but no one may invent one. When
1051 guidance conflicts, consult ### Whose word wins — that is the only place
1052 precedence is stated.";
1053
1054 pub fn compose_prompt_with_approval_model_and_shell(model_id: &str) -> String {
1055 let default_layers = compose_default_static_layers(model_id);
1056 apply_static_prompt_composer(
1057 effective_static_prompt_composer(),
1058 model_id,
1059 &default_layers,
1060 )
1061 }
1062
1063 pub fn compose_default_static_layers(model_id: &str) -> String {
1064 compose_default_static_layers_with_context(model_id, None)
1065 }
1066
1067 fn compose_default_static_layers_with_context(
1068 model_id: &str,
1069 context_window_override: Option<u32>,
1070 ) -> String {
1071 // Voice and tone live in the constitutional preamble. Language and output
1072 // rules are split into their own static segments so the constitution
1073 // stays compact.
1074 let layers = format!(
1075 "{}\n\n{}\n\n{}",
1076 effective_base_prompt().trim(),
1077 LANGUAGE_PROMPT.trim(),
1078 OUTPUT_PROMPT.trim()
1079 );
1080 apply_model_template(&layers, model_id, context_window_override)
1081 }
1082
1083 /// Host surface selecting the bundled constitution size.
1084 ///
1085 /// Modes never select prompt doctrine. Their permissions and capabilities are
1086 /// expressed by runtime policy and the live tool catalog.
1087 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1088 pub enum PromptHost {
1089 Interactive,
1090 Headless,
1091 }
1092
1093 fn apply_static_prompt_composer(
1094 composer: Option<&StaticPromptComposer>,
1095 model_id: &str,
1096 default_layers: &str,
1097 ) -> String {
1098 match composer {
1099 Some(composer) => composer(&StaticPromptCtx {
1100 model_id,
1101 default_layers,
1102 }),
1103 None => default_layers.to_string(),
1104 }
1105 }
1106
1107 // Every host shares BASE_PROMPT — one constitution, one stance. Host selects
1108 // only which ceremony layers follow it; tool availability is enforced by the
1109 // catalog and execution layer, never by mode-specific prompt text.
1110
1111 // ── Public API ────────────────────────────────────────────────────────
1112
1113 /// Get the system prompt for a specific mode with project context.
1114 pub fn system_prompt_for_mode_with_context(
1115 workspace: &Path,
1116 working_set_summary: Option<&str>,
1117 ) -> SystemPrompt {
1118 system_prompt_for_mode_with_context_and_skills(workspace, working_set_summary, None, None, None)
1119 }
1120
1121 /// Get the system prompt for a specific mode with project and skills context.
1122 ///
1123 /// **Volatile-content-last invariant.** Blocks are appended in order from
1124 /// most-static to most-volatile so DeepSeek's KV prefix cache hits the
1125 /// longest possible byte prefix turn-over-turn:
1126 ///
1127 /// 1. shared constitution (compile-time constant)
1128 /// 2. `## Core Execution` (compile-time constant)
1129 /// 3. compaction relay template (compile-time constant)
1130 /// 4. relay block — file-backed; rewritten by `/compact` and on exit
1131 ///
1132 /// Anything appended after a volatile block forfeits the cache for the rest
1133 /// of the request. New blocks belong above the relay boundary unless they
1134 /// themselves are turn-volatile. Working-set metadata is now injected into the
1135 /// latest user message as per-turn metadata instead of this system prompt.
1136 pub fn system_prompt_for_mode_with_context_and_skills(
1137 workspace: &Path,
1138 working_set_summary: Option<&str>,
1139 skills_dir: Option<&Path>,
1140 instructions: Option<&[InstructionSource]>,
1141 user_memory_block: Option<&str>,
1142 ) -> SystemPrompt {
1143 system_prompt_for_mode_with_context_skills_and_session(
1144 workspace,
1145 working_set_summary,
1146 skills_dir,
1147 instructions,
1148 PromptSessionContext {
1149 user_memory_block,
1150 goal_objective: None,
1151 project_context_pack_enabled: false,
1152 locale_tag: "en",
1153 translation_enabled: false,
1154 model_id: "codewhale",
1155 context_window_override: None,
1156 verbosity: None,
1157 recovery_hint: None,
1158 skills_config: Default::default(),
1159 plugin_registry: None,
1160 mode: AppMode::Agent,
1161 },
1162 )
1163 }
1164
1165 pub fn system_prompt_for_mode_with_context_skills_and_session(
1166 workspace: &Path,
1167 _working_set_summary: Option<&str>,
1168 skills_dir: Option<&Path>,
1169 instructions: Option<&[InstructionSource]>,
1170 session_context: PromptSessionContext<'_>,
1171 ) -> SystemPrompt {
1172 system_prompt_for_mode_with_context_skills_session_and_approval(
1173 workspace,
1174 _working_set_summary,
1175 skills_dir,
1176 instructions,
1177 session_context,
1178 )
1179 }
1180
1181 pub fn system_prompt_for_mode_with_context_skills_session_and_approval(
1182 workspace: &Path,
1183 _working_set_summary: Option<&str>,
1184 skills_dir: Option<&Path>,
1185 instructions: Option<&[InstructionSource]>,
1186 session_context: PromptSessionContext<'_>,
1187 ) -> SystemPrompt {
1188 system_prompt_for_mode_with_context_skills_session_and_approval_for_host(
1189 workspace,
1190 _working_set_summary,
1191 skills_dir,
1192 instructions,
1193 session_context,
1194 PromptHost::Interactive,
1195 )
1196 }
1197
1198 pub fn system_prompt_for_mode_with_context_skills_session_and_approval_for_host(
1199 workspace: &Path,
1200 _working_set_summary: Option<&str>,
1201 skills_dir: Option<&Path>,
1202 instructions: Option<&[InstructionSource]>,
1203 session_context: PromptSessionContext<'_>,
1204 prompt_host: PromptHost,
1205 ) -> SystemPrompt {
1206 system_prompt_with_instruction_assembly_for_host(
1207 workspace,
1208 _working_set_summary,
1209 skills_dir,
1210 instructions,
1211 session_context,
1212 prompt_host,
1213 None,
1214 )
1215 .0
1216 }
1217
1218 /// Compose the system prompt **and** the instruction assembly that produced
1219 /// its instruction block.
1220 ///
1221 /// The assembly carries the per-scope budgets and every trim/skip notice, so
1222 /// the engine can enforce the static-prefix guard and surface the losses to
1223 /// the user, the model, and `/context` from one measurement.
1224 pub fn system_prompt_with_instruction_assembly_for_host(
1225 workspace: &Path,
1226 _working_set_summary: Option<&str>,
1227 _skills_dir: Option<&Path>,
1228 instructions: Option<&[InstructionSource]>,
1229 session_context: PromptSessionContext<'_>,
1230 prompt_host: PromptHost,
1231 instruction_input: Option<(
1232 &crate::project_context::ProjectContext,
1233 &crate::project_context::InstructionSettings,
1234 crate::project_context::InstructionBudgets,
1235 )>,
1236 ) -> (SystemPrompt, crate::project_context::InstructionAssembly) {
1237 // One base prompt for every host (AGENTS.md: `BASE_PROMPT` is the sole
1238 // base prompt). Headless still skips interactive ceremony layers below —
1239 // the execution profile and authority recap — which are host chrome, not
1240 // doctrine.
1241 let headless = prompt_host == PromptHost::Headless;
1242 let default_layers = compose_default_static_layers_with_context(
1243 session_context.model_id,
1244 session_context.context_window_override,
1245 );
1246 let composed = apply_static_prompt_composer(
1247 effective_static_prompt_composer(),
1248 session_context.model_id,
1249 &default_layers,
1250 );
1251
1252 let default_settings = crate::project_context::InstructionSettings::default();
1253 let settings = instruction_input
1254 .as_ref()
1255 .map_or(&default_settings, |input| input.1);
1256 let raw_context = instruction_input.as_ref().map_or_else(
1257 || {
1258 crate::project_context::capture_instruction_context(
1259 workspace,
1260 instructions.unwrap_or_default(),
1261 settings,
1262 )
1263 },
1264 |input| input.0.clone(),
1265 );
1266 let mut project_context = raw_context;
1267 let budgets = instruction_input.map_or_else(
1268 || {
1269 crate::project_context::InstructionBudgets::defaults_for(
1270 session_context
1271 .context_window_override
1272 .map(|window| window as usize),
1273 )
1274 },
1275 |input| input.2,
1276 );
1277 let assembly =
1278 crate::project_context::assemble_instruction_block(&mut project_context, &[], &budgets);
1279
1280 // 0. Locale-native reinforcement preamble (#1118 follow-up). When the
1281 // user's UI locale is non-English we prepend a short native-script
1282 // passage so the model's first exposure to the prompt is an explicit
1283 // "think and reply in {locale}" directive in the user's own writing
1284 // system — defeats the "task context is English, so the model thinks
1285 // in English even though `lang: zh-Hans` is set" failure mode that
1286 // PR #1398 partially addressed. English (and unknown) locales get
1287 // `None` and keep the previous behavior unchanged.
1288 let preamble = locale_reinforcement_preamble(session_context.locale_tag);
1289
1290 // 1–2. Shared constitution + project context. Mode is deliberately absent:
1291 // permissions and capabilities come from runtime policy and the tool catalog.
1292 // `load_project_context_with_parents` generates an in-memory bounded
1293 // overview when no context file exists, so the fallback should usually be
1294 // available without writing project-local files.
1295 if assembly.block.is_none() {
1296 tracing::warn!("No project context available and auto-generation failed");
1297 }
1298 let mut full_prompt = composed.trim().to_string();
1299
1300 if let Some(preamble) = preamble {
1301 full_prompt = format!("{preamble}\n\n{full_prompt}");
1302 }
1303
1304 // Personal preferences are captured once at turn admission and recorded in
1305 // history, so live profile edits never mutate an in-flight prompt prefix.
1306
1307 if session_context.project_context_pack_enabled
1308 && let Some(pack) = crate::project_context::generate_project_context_pack(workspace)
1309 {
1310 full_prompt = format!("{full_prompt}\n\n{pack}");
1311 }
1312
1313 // 2.3a. Translation output instruction — when enabled, instruct
1314 // the model to respond in the resolved session locale. Stays
1315 // above the volatile-content boundary because it's a per-session
1316 // flag, not a per-turn one: enabling `/translate` is a session
1317 // toggle, so the prompt-prefix bytes don't drift turn-over-turn.
1318 if session_context.translation_enabled {
1319 full_prompt = format!(
1320 "{full_prompt}\n\n{}",
1321 translation_output_instruction(session_context.locale_tag)
1322 );
1323 }
1324
1325 // 4. Lean, runtime-only coding discipline. Context pressure, prompt-cache
1326 // accounting, footer presentation, and automatic compaction are host
1327 // responsibilities; teaching their UI to the model dilutes the task.
1328 if !headless {
1329 full_prompt.push_str("\n\n");
1330 full_prompt.push_str(CORE_EXECUTION_PROFILE_PROMPT.trim());
1331 }
1332
1333 // The compaction/relay format is action-specific context. Automatic
1334 // compaction owns its structured successor brief, while `/relay` appends
1335 // `COMPACT_TEMPLATE` to that command's user message. Keeping the template
1336 // out of every fresh session saves a stable-prefix block without removing
1337 // the capability.
1338
1339 // ── Volatile-content boundary → WorldState fragments ──────────────────
1340 // Constitution (`full_prompt`) stays the cache-stable Blocks[0] prefix.
1341 // Everything below drifts mid-session and is assembled as marked
1342 // WorldState fragments so an env/memory/goal/handoff change can
1343 // `render_diff` without rebuilding unrelated material.
1344
1345 // Workspace fragment: environment + mid-session memory/goal facts.
1346 let mut workspace_parts = vec![render_environment_block(
1347 workspace,
1348 session_context.locale_tag,
1349 )];
1350 if let Some(section) = memory_prompt_section(session_context.user_memory_block) {
1351 workspace_parts.push(section);
1352 }
1353 if let Some(goal_objective) = session_context.goal_objective
1354 && !goal_objective.trim().is_empty()
1355 {
1356 workspace_parts.push(format!(
1357 "## Current Goal\n\n<session_goal>\n{}\n</session_goal>",
1358 goal_objective.trim()
1359 ));
1360 }
1361 // #5715: name an interrupted prior workspace session so the model can
1362 // offer recovery. Session-pinned: absent entirely on clean sessions so
1363 // they share identical prefix bytes.
1364 if let Some(hint) = session_context.recovery_hint
1365 && !hint.trim().is_empty()
1366 {
1367 workspace_parts.push(format!(
1368 "## Prior Session\n\n<session_recovery>\n{}\n</session_recovery>",
1369 hint.trim()
1370 ));
1371 }
1372 let workspace_body = workspace_parts.join("\n\n");
1373
1374 // Configured `instructions = [...]` files (#454) are global-scope
1375 // instruction authority now: the assembly reads and charges them, and they
1376 // render inside the project-instructions block instead of as a separate
1377 // world-state fragment. Exactly one owner, one charge.
1378 let runtime_sections: Vec<_> = instructions
1379 .unwrap_or_default()
1380 .iter()
1381 .filter_map(|source| match source {
1382 InstructionSource::Inline { name, content } if name.starts_with("runtime:") => Some(
1383 format!("<instructions source=\"{name}\">\n{content}\n</instructions>"),
1384 ),
1385 _ => None,
1386 })
1387 .collect();
1388 let permissions_body = (!runtime_sections.is_empty()).then(|| runtime_sections.join("\n\n"));
1389
1390 // Route fragment: verbosity / translation posture (the model id was
1391 // removed by the turn-meta diet — it is telemetry the model cannot act on).
1392 let route_body = render_route_fragment(&session_context);
1393
1394 let session_relay_body = load_handoff_block(workspace);
1395
1396 let mut world_state = world_state_from_session_facts(
1397 Some(workspace_body.as_str()),
1398 permissions_body.as_deref(),
1399 Some(route_body.as_str()),
1400 None, // AgentTopology is updated by runtime callers when available.
1401 None, // Skills stay in the constitution prefix (skills-dir-static).
1402 session_relay_body.as_deref(),
1403 );
1404 // Project-instruction import (#3978, #4079) as a typed fragment with
1405 // hard caps — unified with `codewhale_core::fragments`. This covers
1406 // `.cursorrules`, `.clinerules`, `.windsurf/rules/*`, `.gemini/*`,
1407 // `.github/copilot-instructions.md` etc., beyond the canonical
1408 // `AGENTS.md` already in the constitution prefix.
1409 if let Some(fragment) =
1410 codewhale_core::fragments::load_selected_project_instruction_fragment_with_reader(
1411 workspace,
1412 &crate::project_context::fragment_candidates_for(&settings.imports),
1413 |path| codewhale_util::fs_confined::open_read(workspace, path),
1414 )
1415 {
1416 // `BoundedFragment` already enforces `MAX_FRAGMENT_BYTES` (10K-token
1417 // ceiling) and per-fragment caps; WorldState's `with_*` also clamps.
1418 world_state = world_state.with_project_instructions(fragment.content);
1419 debug_assert!(world_state.validate_caps().is_ok());
1420 }
1421
1422 let mut blocks = codewhale_runtime::model_context::WorldStateSnapshot {
1423 constitution: full_prompt,
1424 world_state,
1425 }
1426 .to_system_blocks();
1427
1428 // Trailers keep recency bias after WorldState: authority, then locale.
1429 if !headless {
1430 blocks.push(SystemBlock {
1431 block_type: "text".to_string(),
1432 text: effective_authority_recap().trim().to_string(),
1433 cache_control: None,
1434 });
1435 }
1436 if let Some(closer) = locale_reinforcement_closer(session_context.locale_tag) {
1437 blocks.push(SystemBlock {
1438 block_type: "text".to_string(),
1439 text: closer.trim().to_string(),
1440 cache_control: None,
1441 });
1442 }
1443
1444 (SystemPrompt::Blocks(blocks), assembly)
1445 }
1446
1447 /// Estimated tokens of the request prefix before any conversation: every
1448 /// system block — so inline authority appended after the constitution counts
1449 /// — plus the tool schemas the request carries.
1450 #[must_use]
1451 pub fn measure_static_prefix(system: Option<&SystemPrompt>, tools: &[Tool]) -> usize {
1452 let text_tokens = match system {
1453 Some(SystemPrompt::Text(text)) => {
1454 crate::compaction::estimate_text_tokens_conservative(text)
1455 }
1456 Some(SystemPrompt::Blocks(blocks)) => blocks
1457 .iter()
1458 .map(|block| crate::compaction::estimate_text_tokens_conservative(&block.text))
1459 .sum(),
1460 None => 0,
1461 };
1462 let tool_tokens: usize = tools
1463 .iter()
1464 .map(|tool| {
1465 serde_json::to_string(tool).map_or(0, |json| {
1466 crate::compaction::estimate_text_tokens_conservative(&json)
1467 })
1468 })
1469 .sum();
1470 text_tokens.saturating_add(tool_tokens)
1471 }
1472
1473 const GUARD_PASSES_PER_SCOPE: usize = 2;
1474
1475 type GuardInstructionResult = Result<
1476 (
1477 Option<SystemPrompt>,
1478 Option<crate::project_context::InstructionAssembly>,
1479 Vec<crate::project_context::InstructionNotice>,
1480 ),
1481 crate::project_context::InstructionRefusal,
1482 >;
1483
1484 fn replace_installed_instruction_block(
1485 prompt: &mut Option<SystemPrompt>,
1486 raw: &crate::project_context::ProjectContext,
1487 installed: &crate::project_context::InstructionAssembly,
1488 budgets: &crate::project_context::InstructionBudgets,
1489 ) -> Result<
1490 Option<crate::project_context::InstructionAssembly>,
1491 crate::project_context::InstructionRefusal,
1492 > {
1493 let Some(range) = installed.prompt_range.clone() else {
1494 return Ok(None);
1495 };
1496 let text = match prompt.as_mut() {
1497 Some(SystemPrompt::Text(text)) => text,
1498 Some(SystemPrompt::Blocks(blocks)) => match blocks.first_mut() {
1499 Some(block) => &mut block.text,
1500 None => return Ok(None),
1501 },
1502 None => return Ok(None),
1503 };
1504 let owned = |block: Option<&str>| {
1505 block
1506 .filter(|block| !block.is_empty())
1507 .map_or_else(String::new, |block| format!("\n\n{block}"))
1508 };
1509 if text.get(range.clone()) != Some(owned(installed.block.as_deref()).as_str()) {
1510 return Err(crate::project_context::InstructionRefusal::ReceiptMismatch);
1511 }
1512 let mut candidate = raw.clone();
1513 let mut next = crate::project_context::assemble_instruction_block(&mut candidate, &[], budgets);
1514 let replacement = owned(next.block.as_deref());
1515 text.replace_range(range.clone(), &replacement);
1516 next.prompt_range = Some(range.start..range.start + replacement.len());
1517 Ok(Some(next))
1518 }
1519
1520 pub fn guard_instruction_prefix(
1521 mut prompt: Option<SystemPrompt>,
1522 raw: Option<&crate::project_context::ProjectContext>,
1523 mut assembly: Option<crate::project_context::InstructionAssembly>,
1524 budgets: crate::project_context::InstructionBudgets,
1525 tools: &[Tool],
1526 ) -> GuardInstructionResult {
1527 use crate::project_context::{
1528 InstructionAction, InstructionBudgetPolicy, InstructionLimit, InstructionNotice,
1529 InstructionRefusal, InstructionScope,
1530 };
1531 if let Some(assembly) = assembly.as_mut() {
1532 assembly
1533 .notices
1534 .retain(|notice| notice.limit != InstructionLimit::StaticGuard);
1535 }
1536 let refuse = budgets.policy == InstructionBudgetPolicy::Refuse;
1537 if let Some((raw, installed)) = raw.zip(assembly.as_ref())
1538 && installed.budgets != budgets
1539 && let Some(next) =
1540 replace_installed_instruction_block(&mut prompt, raw, installed, &budgets)?
1541 {
1542 assembly = Some(next);
1543 }
1544 if let Some(loss) = assembly
1545 .as_ref()
1546 .and_then(|assembly| budgets.first_refused_loss(&assembly.notices))
1547 {
1548 let mut refused = loss.clone();
1549 refused.action = InstructionAction::Refused;
1550 return Err(InstructionRefusal::Loss(refused));
1551 }
1552 let Some(guard) = budgets.static_guard_tokens else {
1553 return Ok((prompt, assembly, Vec::new()));
1554 };
1555 let mut measured = measure_static_prefix(prompt.as_ref(), tools);
1556 if measured <= guard {
1557 return Ok((prompt, assembly, Vec::new()));
1558 }
1559 if refuse {
1560 return Err(InstructionRefusal::OverGuard { measured, guard });
1561 }
1562 let mut guard_notices: Vec<InstructionNotice> = Vec::new();
1563 if let (Some(raw), Some(first)) = (raw, assembly.as_ref()) {
1564 let mut effective = first.budgets;
1565 let mut order = [
1566 (InstructionScope::Global, first.global_tokens),
1567 (InstructionScope::Project, first.project_tokens),
1568 ];
1569 order.sort_by_key(|&(_, retained)| std::cmp::Reverse(retained));
1570 'scopes: for (scope, initial) in order {
1571 let mut retained = initial;
1572 for _ in 0..GUARD_PASSES_PER_SCOPE {
1573 if measured <= guard || retained == 0 {
1574 break;
1575 }
1576 effective =
1577 effective.with_scope_ceiling(scope, retained.saturating_sub(measured - guard));
1578 let Some(installed) = assembly.as_ref() else {
1579 break 'scopes;
1580 };
1581 let Some(next) =
1582 replace_installed_instruction_block(&mut prompt, raw, installed, &effective)?
1583 else {
1584 break 'scopes;
1585 };
1586 retained = match scope {
1587 InstructionScope::Global => next.global_tokens,
1588 InstructionScope::Project => next.project_tokens,
1589 };
1590 assembly = Some(next);
1591 measured = measure_static_prefix(prompt.as_ref(), tools);
1592 }
1593 if retained < initial {
1594 guard_notices.push(InstructionNotice::static_guard(
1595 scope,
1596 initial - retained,
1597 false,
1598 ));
1599 }
1600 }
1601 }
1602 if measured > guard {
1603 guard_notices.push(InstructionNotice::static_guard(
1604 InstructionScope::Global,
1605 measured - guard,
1606 true,
1607 ));
1608 }
1609 if let Some(assembly) = assembly.as_mut() {
1610 assembly.notices.append(&mut guard_notices);
1611 }
1612 Ok((prompt, assembly, guard_notices))
1613 }
1614
1615 /// Flatten a system prompt to joined text (tests + debug inspectors).
1616 #[must_use]
1617 pub fn system_prompt_flat_text(prompt: &SystemPrompt) -> String {
1618 match prompt {
1619 SystemPrompt::Text(text) => text.clone(),
1620 SystemPrompt::Blocks(blocks) => blocks
1621 .iter()
1622 .map(|block| block.text.as_str())
1623 .collect::<Vec<_>>()
1624 .join("\n\n"),
1625 }
1626 }
1627
1628 fn render_route_fragment(session_context: &PromptSessionContext<'_>) -> String {
1629 let verbosity = session_context
1630 .verbosity
1631 .map(str::trim)
1632 .filter(|value| !value.is_empty())
1633 .unwrap_or("default");
1634 format!(
1635 "verbosity: {verbosity}\ntranslation: {}",
1636 if session_context.translation_enabled {
1637 "on"
1638 } else {
1639 "off"
1640 },
1641 )
1642 }
1643
1644 /// Build a WorldState from the common volatile session facts.
1645 ///
1646 /// Does not load constitution — callers keep that as the stable base.
1647 pub fn world_state_from_session_facts(
1648 workspace_body: Option<&str>,
1649 permissions_body: Option<&str>,
1650 route_body: Option<&str>,
1651 agent_topology_body: Option<&str>,
1652 skills_tools_body: Option<&str>,
1653 session_relay_body: Option<&str>,
1654 ) -> codewhale_runtime::model_context::WorldState {
1655 let mut state = codewhale_runtime::model_context::WorldState::new();
1656 if let Some(body) = workspace_body.filter(|s| !s.trim().is_empty()) {
1657 state = state.with_workspace(body);
1658 }
1659 if let Some(body) = permissions_body.filter(|s| !s.trim().is_empty()) {
1660 state = state.with_permissions(body);
1661 }
1662 if let Some(body) = route_body.filter(|s| !s.trim().is_empty()) {
1663 state = state.with_route(body);
1664 }
1665 if let Some(body) = agent_topology_body.filter(|s| !s.trim().is_empty()) {
1666 state = state.with_agent_topology(body);
1667 }
1668 if let Some(body) = skills_tools_body.filter(|s| !s.trim().is_empty()) {
1669 state = state.with_skills_tools(body);
1670 }
1671 if let Some(body) = session_relay_body.filter(|s| !s.trim().is_empty()) {
1672 state = state.with_session_relay(body);
1673 }
1674 state
1675 }
1676
1677 #[cfg(test)]
1678 mod tests {
1679 // Don't assert on prose. If you wouldn't fail a code review for
1680 // changing the wording, don't fail a test for it.
1681 use super::*;
1682 use crate::tools::apply_patch::ApplyPatchTool;
1683 use crate::tools::file::{EditFileTool, WriteFileTool};
1684 use crate::tools::handle::HandleReadTool;
1685 use crate::tools::rlm::RlmTool;
1686 use crate::tools::shell::BashTool;
1687 use crate::tools::spec::ToolSpec;
1688 use tempfile::tempdir;
1689
1690 /// Discriminator unique to the injected relay block (not present in the
1691 /// agent prompt's own discussion of the convention). It stops before the
1692 /// path because the block names whichever file was read; the tests that
1693 /// care about the path assert it themselves.
1694 const HANDOFF_BLOCK_MARKER: &str = "left a relay artifact at `";
1695
1696 // Config-directory prompt override resolution (#3638). These exercise the
1697 // pure file resolver only; the global install path is intentionally not
1698 // unit-tested here because `set_base_prompt_override` writes a process-wide
1699 // `OnceLock` that would leak into sibling tests (same reason
1700 // `prompt_override_storage_reports_duplicate_sets` uses a local cell).
1701
1702 #[test]
1703 fn config_override_reads_present_nonempty_file() {
1704 let tmp = tempdir().expect("tempdir");
1705 let prompts_dir = tmp.path().join("prompts");
1706 std::fs::create_dir_all(&prompts_dir).expect("mkdir");
1707 std::fs::write(
1708 prompts_dir.join("constitution.md"),
1709 "You are a long-form writing companion.\n",
1710 )
1711 .expect("write override");
1712
1713 let got = read_prompt_override_file(tmp.path(), CONSTITUTION_OVERRIDE_FILE);
1714 assert_eq!(
1715 got.as_deref(),
1716 Some("You are a long-form writing companion.\n")
1717 );
1718 }
1719
1720 #[test]
1721 fn config_override_absent_file_falls_back() {
1722 let tmp = tempdir().expect("tempdir");
1723 // No prompts/ directory at all → None so the embedded constant is used.
1724 assert!(read_prompt_override_file(tmp.path(), CONSTITUTION_OVERRIDE_FILE).is_none());
1725 }
1726
1727 #[test]
1728 fn config_override_requires_explicit_opt_in() {
1729 // A present, non-empty override file must NOT replace the base prompt
1730 // unless the explicit opt-in flag is set. This test drains the shared
1731 // process-global PROMPT_OVERRIDE_NOTICES queue, so it must serialize
1732 // against the sibling test that also touches it
1733 // (`tui::ui::tests::prompt_override_notice_surfaces_in_transcript_and_toast`);
1734 // both take `lock_test_env()` for mutual exclusion under the multi-
1735 // threaded test binary.
1736 let _env_guard = crate::test_support::lock_test_env();
1737 let tmp = tempdir().expect("tempdir");
1738 let prompts_dir = tmp.path().join("prompts");
1739 std::fs::create_dir_all(&prompts_dir).expect("mkdir");
1740 std::fs::write(
1741 prompts_dir.join("constitution.md"),
1742 "You are a long-form writing companion.\n",
1743 )
1744 .expect("write override");
1745
1746 // The resolver still finds the file...
1747 assert!(read_prompt_override_file(tmp.path(), CONSTITUTION_OVERRIDE_FILE).is_some());
1748 // ...but without the opt-in flag, nothing is applied.
1749 if std::env::var(BASE_PROMPT_OVERRIDE_OPT_IN_ENV).is_err() {
1750 let _ = take_prompt_override_notices();
1751 assert!(
1752 load_config_dir_prompt_overrides(tmp.path()).is_empty(),
1753 "override must require the explicit opt-in flag, not just a file"
1754 );
1755 let notices = take_prompt_override_notices();
1756 assert!(
1757 notices
1758 .iter()
1759 .any(|notice| notice.contains(BASE_PROMPT_OVERRIDE_OPT_IN_ENV)
1760 && notice.contains("using the bundled Constitution")),
1761 "gated override should record a visible notice, got {notices:?}"
1762 );
1763 }
1764 }
1765
1766 #[test]
1767 fn config_override_empty_file_is_ignored() {
1768 let tmp = tempdir().expect("tempdir");
1769 let prompts_dir = tmp.path().join("prompts");
1770 std::fs::create_dir_all(&prompts_dir).expect("mkdir");
1771 std::fs::write(prompts_dir.join("constitution.md"), " \n\t\n").expect("write blank");
1772
1773 // Whitespace-only overrides are treated as absent so a stray empty file
1774 // can't silently blank the system prompt.
1775 assert!(read_prompt_override_file(tmp.path(), CONSTITUTION_OVERRIDE_FILE).is_none());
1776 }
1777
1778 #[test]
1779 fn prompt_override_storage_reports_duplicate_sets() {
1780 let cell = std::sync::OnceLock::new();
1781
1782 assert_eq!(effective_prompt_override(&cell, "fallback"), "fallback");
1783 assert!(set_prompt_override(&cell, "first".to_string()).is_ok());
1784 assert_eq!(effective_prompt_override(&cell, "fallback"), "first");
1785 assert_eq!(
1786 set_prompt_override(&cell, "second".to_string()),
1787 Err("second".to_string())
1788 );
1789 assert_eq!(effective_prompt_override(&cell, "fallback"), "first");
1790 }
1791
1792 #[test]
1793 fn static_prompt_composer_unset_keeps_default_layers_byte_identical() {
1794 let default_layers = compose_default_static_layers("deepseek-v4-flash");
1795 let composed = apply_static_prompt_composer(None, "deepseek-v4-flash", &default_layers);
1796
1797 assert_byte_identical("unset static prompt composer", &default_layers, &composed);
1798 }
1799
1800 #[test]
1801 fn static_prompt_composer_receives_context_and_replaces_layers() {
1802 let default_layers = compose_default_static_layers("deepseek-v4-pro");
1803 let composer: Box<StaticPromptComposer> = Box::new(|ctx| {
1804 assert_eq!(ctx.model_id, "deepseek-v4-pro");
1805 // The core is model-agnostic ("You are Codewhale") and carries
1806 // tone in the preamble — no per-model id line.
1807 assert!(ctx.default_layers.contains("You are Codewhale"));
1808 assert!(
1809 ctx.default_layers
1810 .contains("Take the work seriously. Don't take")
1811 );
1812 assert!(!ctx.default_layers.contains("## Core Tool Taxonomy"));
1813 assert!(!ctx.default_layers.contains("Approval Policy"));
1814 "embedder static prompt".to_string()
1815 });
1816
1817 let composed = apply_static_prompt_composer(
1818 Some(composer.as_ref()),
1819 "deepseek-v4-pro",
1820 &default_layers,
1821 );
1822
1823 assert_eq!(composed, "embedder static prompt");
1824 }
1825
1826 fn contains_cjk(text: &str) -> bool {
1827 text.chars().any(|ch| {
1828 matches!(
1829 ch,
1830 '\u{3040}'..='\u{30ff}'
1831 | '\u{3400}'..='\u{4dbf}'
1832 | '\u{4e00}'..='\u{9fff}'
1833 | '\u{f900}'..='\u{faff}'
1834 )
1835 })
1836 }
1837
1838 #[test]
1839 fn every_mode_shares_one_prompt_per_host() {
1840 let _env_lock = crate::test_support::lock_test_env();
1841 let tmp = tempdir().expect("tempdir");
1842 std::fs::write(
1843 tmp.path().join("AGENTS.md"),
1844 "# Project instruction\nPreserve the blue-ocean marker.\n",
1845 )
1846 .expect("write project instruction");
1847 for host in [PromptHost::Interactive, PromptHost::Headless] {
1848 let prompts = [AppMode::Plan, AppMode::Agent].map(|mode| {
1849 system_prompt_flat_text(
1850 &system_prompt_for_mode_with_context_skills_session_and_approval_for_host(
1851 tmp.path(),
1852 None,
1853 None,
1854 None,
1855 PromptSessionContext {
1856 mode,
1857 ..PromptSessionContext::default()
1858 },
1859 host,
1860 ),
1861 )
1862 });
1863 assert_eq!(prompts[0], prompts[1]);
1864 assert!(!prompts[0].contains("Preserve the blue-ocean marker"));
1865 assert!(!prompts[0].contains("##### Mode:"));
1866 if host == PromptHost::Headless {
1867 // One base prompt for every host; headless still omits the
1868 // interactive ceremony layers.
1869 assert!(prompts[0].contains("The A is already yours"));
1870 assert!(!prompts[0].contains("## Core Execution"));
1871 assert!(!prompts[0].contains("## Authority Recap"));
1872 }
1873 }
1874 }
1875
1876 #[test]
1877 fn base_prompt_carries_constitutional_core() {
1878 for phrase in [
1879 "## Codewhale",
1880 "You are Codewhale",
1881 "The A is already yours",
1882 "Let the work speak",
1883 "### Ground truth",
1884 "### User intent and scope",
1885 "### Truthful completion",
1886 "### Put guarantees in mechanism",
1887 "### Whose word wins",
1888 ] {
1889 assert!(
1890 BASE_PROMPT.contains(phrase),
1891 "BASE_PROMPT missing Constitutional phrase {phrase:?}"
1892 );
1893 }
1894 }
1895
1896 #[test]
1897 fn constitutional_kernel_keeps_first_turn_authority_safety_and_completion() {
1898 let fresh_prefix = compose_default_static_layers("deepseek-v4-pro");
1899 for phrase in [
1900 "Do what the user's current request asks, no more.",
1901 "require express user authorization in",
1902 "otherwise name the decision and ask with options.",
1903 "external publication, spending",
1904 "credentials, and material scope expansion",
1905 "prohibitions stay binding; convenience creates no exception",
1906 "never route around it or claim prose granted",
1907 "Nothing is done until checked.",
1908 "Read test output, not only exit status",
1909 "External actions are not complete until",
1910 "Work still running is not complete",
1911 "Never present a partial result as the whole.",
1912 "no one may tell you to invent one",
1913 "1. The user's request, this turn.",
1914 "2. This constitution.",
1915 ] {
1916 assert!(
1917 fresh_prefix.contains(phrase),
1918 "fresh constitution prefix missing kernel invariant {phrase:?}"
1919 );
1920 }
1921 }
1922
1923 #[test]
1924 fn procedural_playbooks_are_not_eager_constitution() {
1925 let fresh_prefix = compose_default_static_layers("deepseek-v4-pro");
1926 for heading in [
1927 "### Keep momentum",
1928 "### Think in causes",
1929 "### Honor constraints before preferences",
1930 "### Skill and role constraints are binding",
1931 "### Restraint",
1932 "### Leave continuity",
1933 ] {
1934 assert!(
1935 !fresh_prefix.contains(heading),
1936 "procedural playbook should stay outside the full fresh prefix: {heading:?}"
1937 );
1938 }
1939 assert!(
1940 !BASE_PROMPT.contains("## STATUTES (Tier 2)")
1941 && !BASE_PROMPT.contains("## REGULATIONS (Tier 3)"),
1942 "the balanced Constitution must not restore the old procedural policy tail"
1943 );
1944 }
1945
1946 #[test]
1947 fn base_prompt_carries_verify_then_stop_completion_contract() {
1948 // The completion contract behind "Truthful completion": verify with real
1949 // evidence, keep running work visible, and hand back exactly what
1950 // changed. These phrases encode the contract's semantics, not its
1951 // prose — a rewording that keeps the contract should keep these, and
1952 // one that drops them is a real behavior change worth failing review
1953 // for. (Constitution kernel rewrite in #5077 renamed the section and
1954 // condensed the prose; the contract stands.)
1955 for phrase in [
1956 "Nothing is done until checked.",
1957 "Read test output, not only exit status",
1958 "Work still running is not complete",
1959 "Never present a partial result as the whole.",
1960 ] {
1961 assert!(
1962 BASE_PROMPT.contains(phrase),
1963 "BASE_PROMPT missing completion-contract phrase {phrase:?}"
1964 );
1965 }
1966 }
1967
1968 #[test]
1969 fn full_access_posture_uses_the_shared_completion_contract() {
1970 // `codewhale exec --auto` runs Act with the Full Access posture; the
1971 // verify-then-stop contract must survive composition into the prompt
1972 // that posture ships.
1973 let tmp = tempdir().expect("tempdir");
1974 let text = system_prompt_flat_text(
1975 &system_prompt_for_mode_with_context_skills_session_and_approval(
1976 tmp.path(),
1977 None,
1978 None,
1979 None,
1980 PromptSessionContext {
1981 user_memory_block: None,
1982 goal_objective: None,
1983 project_context_pack_enabled: false,
1984 locale_tag: "en",
1985 translation_enabled: false,
1986 model_id: "codewhale",
1987 context_window_override: None,
1988 verbosity: None,
1989 skills_config: Default::default(),
1990 plugin_registry: None,
1991 recovery_hint: None,
1992 mode: AppMode::Agent,
1993 },
1994 ),
1995 );
1996 for phrase in [
1997 "### Truthful completion",
1998 "Nothing is done until checked.",
1999 "Never present a partial result as the whole.",
2000 ] {
2001 assert!(
2002 text.contains(phrase),
2003 "YOLO-mode composed prompt missing completion-contract phrase {phrase:?}"
2004 );
2005 }
2006 assert!(!text.contains("##### Mode:"));
2007 }
2008
2009 #[test]
2010 fn constitutional_hierarchy_keeps_user_turn_above_local_law() {
2011 let heading_at = BASE_PROMPT
2012 .find("### Whose word wins")
2013 .expect("Whose word wins heading present");
2014 let user_at = BASE_PROMPT
2015 .find("1. The user's request, this turn.")
2016 .expect("user request tier present");
2017 let constitution_at = BASE_PROMPT
2018 .find("2. This constitution.")
2019 .expect("constitution tier present");
2020 let project_at = BASE_PROMPT
2021 .find("3. Project law and instructions")
2022 .expect("project tier present");
2023 let preference_at = BASE_PROMPT
2024 .find("4. Your standing user-global preferences.")
2025 .expect("user-global preference tier present");
2026 let memory_at = BASE_PROMPT
2027 .find("5. Memory and previous-session handoffs.")
2028 .expect("memory/handoff tier present");
2029
2030 assert!(
2031 heading_at < user_at
2032 && user_at < constitution_at
2033 && constitution_at < project_at
2034 && project_at < preference_at
2035 && preference_at < memory_at,
2036 "Whose word wins must rank the current user request above constitution, \
2037 project law, standing user-global preferences, then memory/handoffs"
2038 );
2039 assert!(
2040 BASE_PROMPT.contains("the user may override a fact, but no one may invent\none"),
2041 "Whose word wins must keep ground truth overridable but never inventable"
2042 );
2043 assert!(
2044 BASE_PROMPT.contains("A tie you cannot break is not yours to break"),
2045 "Whose word wins must keep tie-break escalation"
2046 );
2047 }
2048
2049 #[test]
2050 fn base_prompt_is_model_fact_free() {
2051 for placeholder in [
2052 "{model_id}",
2053 "{context_window_note}",
2054 "{subagent_economics}",
2055 "{model_thinking_note}",
2056 "{model_characteristics}",
2057 ] {
2058 assert!(
2059 !BASE_PROMPT.contains(placeholder),
2060 "0.9.0 BASE_PROMPT must not contain model-fact placeholder {placeholder}"
2061 );
2062 }
2063 for forbidden in [
2064 "Your V4 Characteristics",
2065 "Model Characteristics",
2066 "one-million-token context window",
2067 "provider-dependent and not known",
2068 ] {
2069 assert!(
2070 !BASE_PROMPT.contains(forbidden),
2071 "0.9.0 BASE_PROMPT must not contain model-specific fact {forbidden:?}"
2072 );
2073 }
2074 }
2075
2076 fn assert_no_unresolved_model_placeholders(prompt: &str) {
2077 for placeholder in [
2078 "{model_id}",
2079 "{context_window_note}",
2080 "{subagent_economics}",
2081 "{model_thinking_note}",
2082 "{model_characteristics}",
2083 ] {
2084 assert!(
2085 !prompt.contains(placeholder),
2086 "composed prompt must not contain unresolved {placeholder}"
2087 );
2088 }
2089 }
2090
2091 #[test]
2092 fn compose_prompt_for_v4_model_stays_model_fact_free() {
2093 let prompt = compose_prompt_with_approval_model_and_shell("deepseek-v4-pro");
2094 assert!(prompt.contains("You are Codewhale"));
2095 assert!(!prompt.contains("Your V4 Characteristics"));
2096 assert!(!prompt.contains("one-million-token context window"));
2097 assert_no_unresolved_model_placeholders(&prompt);
2098 }
2099
2100 #[test]
2101 fn compose_prompt_for_kimi_stays_model_fact_free() {
2102 let prompt = compose_prompt_with_approval_model_and_shell("moonshotai/kimi-k2.6");
2103 assert!(prompt.contains("You are Codewhale"));
2104 assert!(!prompt.contains("Your V4 Characteristics"));
2105 assert!(!prompt.contains("one-million"));
2106 assert!(!prompt.contains("$0.14"));
2107 assert!(!prompt.contains("262144-token context window"));
2108 assert!(!prompt.contains("Models may emit *thinking tokens*"));
2109 assert_no_unresolved_model_placeholders(&prompt);
2110 }
2111
2112 #[test]
2113 fn compose_prompt_for_openai_api_gpt_55_stays_model_fact_free() {
2114 let prompt = compose_prompt_with_approval_model_and_shell("gpt-5.5");
2115 assert!(prompt.contains("You are Codewhale"));
2116 assert!(!prompt.contains("Your V4 Characteristics"));
2117 assert!(!prompt.contains("1050000-token context window"));
2118 assert!(!prompt.contains("Models may emit *thinking tokens*"));
2119 assert!(!prompt.contains("provider-dependent and not known"));
2120 assert_no_unresolved_model_placeholders(&prompt);
2121 }
2122
2123 #[test]
2124 fn compose_prompt_for_unknown_model_stays_model_fact_free() {
2125 let prompt = compose_prompt_with_approval_model_and_shell("llama3.3:70b");
2126 assert!(prompt.contains("You are Codewhale"));
2127 assert!(!prompt.contains("Your V4 Characteristics"));
2128 assert!(!prompt.contains("one-million"));
2129 assert!(!prompt.contains("$0.14"));
2130 assert!(!prompt.contains("provider-dependent and not known"));
2131 assert!(!prompt.contains("Models may emit *thinking tokens*"));
2132 assert_no_unresolved_model_placeholders(&prompt);
2133 }
2134
2135 #[test]
2136 fn apply_model_template_replaces_placeholder() {
2137 let result = apply_model_template("You are {model_id}", "deepseek-v4-pro", None);
2138 assert_eq!(result, "You are deepseek-v4-pro");
2139 assert!(!result.contains("{model_id}"));
2140 }
2141
2142 #[test]
2143 fn apply_model_template_does_not_resolve_removed_model_fact_templates() {
2144 let result = apply_model_template("{context_window_note}", "gpt-5.5", Some(400_000));
2145 assert_eq!(result, "{context_window_note}");
2146 assert!(!result.contains("400000-token context window"));
2147 assert!(!result.contains("1050000-token context window"));
2148 }
2149
2150 #[test]
2151 fn compose_prompt_is_model_agnostic_in_preamble() {
2152 // 0.9.0 keeps the preamble byte-for-byte the same regardless of
2153 // model id, and no {model_id} placeholder leaks.
2154 let flash = compose_prompt_with_approval_model_and_shell("deepseek-v4-flash");
2155 let kimi = compose_prompt_with_approval_model_and_shell("moonshotai/kimi-k2.6");
2156 assert!(
2157 flash.contains("You are Codewhale"),
2158 "0.9.0 preamble must open with the model-agnostic Codewhale stance"
2159 );
2160 assert!(
2161 !flash.contains("You are deepseek-v4-flash")
2162 && !kimi.contains("You are moonshotai/kimi-k2.6"),
2163 "0.9.0 preamble must not inject a per-model identity line"
2164 );
2165 assert!(
2166 !flash.contains("{model_id}") && !kimi.contains("{model_id}"),
2167 "composed prompt must not contain the raw {{model_id}} placeholder"
2168 );
2169 }
2170
2171 #[test]
2172 fn locale_preambles_name_only_model_visible_tools() {
2173 for tag in ["zh-Hans", "ja", "pt-BR", "vi"] {
2174 let preamble = locale_reinforcement_preamble(tag).expect("preamble exists");
2175 assert!(
2176 preamble.contains("`read`") && preamble.contains("`bash`"),
2177 "{tag} preamble must use model-visible tool names: {preamble:?}"
2178 );
2179 assert!(
2180 !preamble.contains("`File`") && !preamble.contains("`Bash`"),
2181 "{tag} preamble must not teach hidden compatibility names: {preamble:?}"
2182 );
2183 }
2184 }
2185
2186 #[test]
2187 fn visible_tool_descriptions_do_not_point_at_hidden_file_or_bash() {
2188 use crate::tools::pandoc::PandocConvertTool;
2189 use crate::tools::tasks::TaskShellWaitTool;
2190 let surfaces = [
2191 (
2192 "handle_read",
2193 format!(
2194 "{} {}",
2195 HandleReadTool.description(),
2196 HandleReadTool.input_schema()
2197 ),
2198 ),
2199 (
2200 "pandoc_convert",
2201 format!(
2202 "{} {}",
2203 PandocConvertTool.description(),
2204 PandocConvertTool.input_schema()
2205 ),
2206 ),
2207 (
2208 "task_shell_wait",
2209 format!(
2210 "{} {}",
2211 TaskShellWaitTool.description(),
2212 TaskShellWaitTool.input_schema()
2213 ),
2214 ),
2215 ];
2216 for (name, text) in surfaces {
2217 assert!(
2218 !text.contains("File action=") && !text.contains("`Bash`"),
2219 "{name} must not point models at the hidden File/Bash tools: {text}"
2220 );
2221 }
2222 assert!(HandleReadTool.description().contains("`read` (path=...)"));
2223 }
2224
2225 #[test]
2226 fn tool_descriptions_carry_edit_and_shell_guidance() {
2227 let write = WriteFileTool.description();
2228 assert!(
2229 write.contains("Unlike heredocs")
2230 && write.contains("`bash`")
2231 && !write.contains("exec_shell"),
2232 "write guidance must name the live bash tool and never the retired exec_shell name"
2233 );
2234
2235 let edit = EditFileTool.description();
2236 assert!(edit.contains("with `read` in this session"));
2237 assert!(edit.contains("`apply_patch` handles structural"));
2238 assert!(!edit.contains("instead"), "{edit}");
2239 assert!(
2240 !edit.contains("read_file") && !edit.contains("write_file"),
2241 "edit guidance must not teach a retired tool name: {edit:?}"
2242 );
2243
2244 let patch = ApplyPatchTool.description();
2245 assert!(patch.contains("unified-diff") && patch.contains("transactional"));
2246
2247 let shell_tool = BashTool::new("Bash");
2248 let shell = shell_tool.description();
2249 assert!(shell.contains("background=true"));
2250 assert!(shell.contains(">5 seconds"));
2251 }
2252
2253 #[test]
2254 fn composed_prompt_does_not_claim_tool_availability() {
2255 let prompt = compose_prompt_with_approval_model_and_shell("deepseek-v4-pro");
2256 assert!(!prompt.contains("## Core Tool Taxonomy"));
2257 assert!(!prompt.contains("## Toolbox"));
2258 assert!(prompt.contains("You are Codewhale"));
2259 }
2260
2261 #[test]
2262 fn authority_recap_appears_in_full_prompt() {
2263 let tmp = tempdir().expect("tempdir");
2264 let text = system_prompt_flat_text(
2265 &system_prompt_for_mode_with_context_skills_session_and_approval(
2266 tmp.path(),
2267 None,
2268 None,
2269 None,
2270 PromptSessionContext::default(),
2271 ),
2272 );
2273 assert!(
2274 text.contains("## Authority Recap"),
2275 "full system prompt must contain the authority recap"
2276 );
2277 assert!(
2278 text.contains("Codewhale's constitution governs your behavior"),
2279 "authority recap must reference the Constitution"
2280 );
2281 assert!(
2282 text.contains("consult ### Whose word wins"),
2283 "authority recap must point at 0.9.0's precedence section"
2284 );
2285 }
2286
2287 #[test]
2288 fn system_prompt_carries_no_skills_index() {
2289 let _env_guard = crate::test_support::lock_test_env();
2290 let tmp = tempdir().expect("tempdir");
2291 let _home = ScopedHome::set(tmp.path().join("home"));
2292 let workspace = tmp.path().join("workspace");
2293 crate::test_support::trust_workspace(&workspace);
2294 let configured_dir = tmp.path().join("configured-skills");
2295 write_test_skill(
2296 &workspace.join(".claude").join("skills"),
2297 "workspace-skill",
2298 "workspace skill",
2299 );
2300 write_test_skill(&configured_dir, "configured-skill", "configured skill");
2301
2302 let text = system_prompt_flat_text(&system_prompt_for_mode_with_context_and_skills(
2303 &workspace,
2304 None,
2305 Some(&configured_dir),
2306 None,
2307 None,
2308 ));
2309
2310 assert!(!text.contains("workspace-skill"));
2311 assert!(!text.contains("configured-skill"));
2312 assert!(text.contains("load_skill"));
2313 }
2314
2315 struct ScopedHome {
2316 previous: Option<std::ffi::OsString>,
2317 }
2318
2319 impl ScopedHome {
2320 fn set(path: std::path::PathBuf) -> Self {
2321 let previous = std::env::var_os("HOME");
2322 // Safety: this test serializes environment access with
2323 // lock_test_env and restores HOME in Drop.
2324 unsafe {
2325 std::env::set_var("HOME", path);
2326 }
2327 Self { previous }
2328 }
2329 }
2330
2331 impl Drop for ScopedHome {
2332 fn drop(&mut self) {
2333 // Safety: this test serializes environment access with
2334 // lock_test_env and restores HOME in Drop.
2335 unsafe {
2336 if let Some(previous) = self.previous.take() {
2337 std::env::set_var("HOME", previous);
2338 } else {
2339 std::env::remove_var("HOME");
2340 }
2341 }
2342 }
2343 }
2344
2345 fn write_test_skill(root: &std::path::Path, name: &str, description: &str) {
2346 let dir = root.join(name);
2347 std::fs::create_dir_all(&dir).expect("skill dir");
2348 std::fs::write(
2349 dir.join("SKILL.md"),
2350 format!("---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n"),
2351 )
2352 .expect("skill file");
2353 }
2354
2355 #[test]
2356 fn constitution_carries_tone_and_rejection_behavior() {
2357 // Voice and tone live in the compact constitution's preamble.
2358 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
2359 assert!(
2360 prompt.contains("Take the work seriously. Don't take"),
2361 "Preamble should carry tone guidance (take the work, not yourself, seriously)"
2362 );
2363 // Verify the preamble still carries the Codewhale identity.
2364 assert!(prompt.contains("You are Codewhale"));
2365 assert!(prompt.contains("Let the work speak"));
2366 }
2367
2368 #[test]
2369 fn render_environment_block_keeps_actionable_host_facts_without_version() {
2370 let tmp = tempdir().expect("tempdir");
2371 let block = render_environment_block(tmp.path(), "zh-Hans");
2372 assert!(block.starts_with("## Environment"));
2373 assert!(block.contains("- lang: zh-Hans"));
2374 // The workspace remains per-turn and the release version is telemetry;
2375 // platform and shell still steer valid command syntax.
2376 assert!(!block.contains("- pwd:"));
2377 assert!(!block.contains("- codewhale_version:"));
2378 assert!(block.contains("- platform:"));
2379 assert!(block.contains("- shell:"));
2380 }
2381
2382 #[test]
2383 fn locale_reinforcement_preamble_returns_native_script_for_supported_locales() {
2384 // English (and unknown locales) get None — the existing English
2385 // directive in `constitution.md` is sufficient.
2386 assert!(locale_reinforcement_preamble("en").is_none());
2387 assert!(locale_reinforcement_preamble("en-US").is_none());
2388 assert!(locale_reinforcement_preamble("fr-FR").is_none());
2389 assert!(locale_reinforcement_preamble("").is_none());
2390
2391 // zh-Hans (and the de-facto equivalents the TUI accepts) get a
2392 // native-script preamble. The text must explicitly mention
2393 // `reasoning_content` (the V4 knob this is meant to steer) and
2394 // preserve tool-name immutability — those are the load-bearing
2395 // claims behind the #1118 fix that someone could quietly
2396 // delete in a future translation pass.
2397 for tag in ["zh-Hans", "zh-CN", "zh"] {
2398 let preamble =
2399 locale_reinforcement_preamble(tag).expect("zh-Hans preamble should exist");
2400 assert!(
2401 preamble.contains("简体中文"),
2402 "zh preamble must be in Simplified Chinese: {preamble:?}"
2403 );
2404 assert!(
2405 preamble.contains("reasoning_content"),
2406 "zh preamble must steer reasoning_content: {preamble:?}"
2407 );
2408 assert!(
2409 preamble.contains("`read`") && preamble.contains("`bash`"),
2410 "zh preamble must call out tool-name immutability with a model-visible \
2411 tool name: {preamble:?}"
2412 );
2413 assert!(
2414 !preamble.contains("`File`") && !preamble.contains("`Bash`"),
2415 "zh preamble must not teach the hidden compatibility `File`/`Bash` \
2416 names: {preamble:?}"
2417 );
2418 assert!(
2419 !preamble.contains("read_file") && !preamble.contains("exec_shell"),
2420 "zh preamble must never teach a retired tool name: {preamble:?}"
2421 );
2422 }
2423
2424 let ja = locale_reinforcement_preamble("ja").expect("ja preamble");
2425 assert!(ja.contains("日本語"), "ja preamble must be in Japanese");
2426 assert!(ja.contains("reasoning_content"));
2427
2428 let pt = locale_reinforcement_preamble("pt-BR").expect("pt-BR preamble");
2429 assert!(
2430 pt.contains("português do Brasil"),
2431 "pt preamble must call out pt-BR explicitly"
2432 );
2433 assert!(pt.contains("reasoning_content"));
2434 }
2435
2436 #[test]
2437 fn system_prompt_prepends_locale_preamble_for_zh_hans() {
2438 // Build the full system prompt with locale=zh-Hans and assert
2439 // the native-script preamble shows up *before* the English
2440 // base-prompt body. Cache stability and attention precedence
2441 // both depend on this ordering.
2442 let tmp = tempdir().expect("tempdir");
2443 let text = system_prompt_flat_text(
2444 &system_prompt_for_mode_with_context_skills_session_and_approval(
2445 tmp.path(),
2446 None,
2447 None,
2448 None,
2449 PromptSessionContext {
2450 user_memory_block: None,
2451 goal_objective: None,
2452 project_context_pack_enabled: false,
2453 locale_tag: "zh-Hans",
2454 translation_enabled: false,
2455 model_id: "codewhale",
2456 context_window_override: None,
2457 verbosity: None,
2458 skills_config: Default::default(),
2459 plugin_registry: None,
2460 recovery_hint: None,
2461 mode: AppMode::Agent,
2462 },
2463 ),
2464 );
2465 let preamble_marker = "## 语言要求";
2466 let base_marker = "You are Codewhale";
2467 let preamble_pos = text
2468 .find(preamble_marker)
2469 .expect("zh-Hans preamble should be present");
2470 let base_pos = text
2471 .find(base_marker)
2472 .expect("base prompt should be present");
2473 assert!(
2474 preamble_pos < base_pos,
2475 "locale preamble must precede the English base prompt (preamble={preamble_pos}, base={base_pos})",
2476 );
2477 }
2478
2479 #[test]
2480 fn locale_reinforcement_closer_returns_native_script_for_supported_locales() {
2481 // English (and unknown locales) get None.
2482 assert!(locale_reinforcement_closer("en").is_none());
2483 assert!(locale_reinforcement_closer("fr-FR").is_none());
2484 assert!(locale_reinforcement_closer("").is_none());
2485
2486 // Each supported locale gets a closer in its own script that
2487 // explicitly tells the model "don't drift to English even as
2488 // English context accumulates" — that's the load-bearing claim
2489 // behind the bookend pattern.
2490 let zh = locale_reinforcement_closer("zh-Hans").expect("zh closer");
2491 assert!(
2492 zh.contains("简体中文"),
2493 "zh closer must be in Simplified Chinese"
2494 );
2495 assert!(
2496 zh.contains("reasoning_content"),
2497 "zh closer must steer reasoning_content"
2498 );
2499 let ja = locale_reinforcement_closer("ja").expect("ja closer");
2500 assert!(ja.contains("日本語"), "ja closer must be in Japanese");
2501 assert!(ja.contains("reasoning_content"));
2502 let pt = locale_reinforcement_closer("pt-BR").expect("pt-BR closer");
2503 assert!(pt.contains("português do Brasil"));
2504 assert!(pt.contains("reasoning_content"));
2505 }
2506
2507 #[test]
2508 fn v092_locales_add_no_prompt_bookends_so_prompt_bytes_stay_stable() {
2509 // Cache-stability contract: adding the v0.9.2 UI locales
2510 // (ca, de, fr, id, hi, ru, uk) — and the already-shipped UI packs
2511 // that never had bookends (ko, es-419, zh-Hant) — must not change
2512 // the model-visible system prompt for an identical route/session
2513 // when translation is not explicitly enabled. The bookend list
2514 // stays intentionally short (zh-Hans, ja, pt-BR, vi); every other
2515 // shipped locale resolves to None and therefore renders the exact
2516 // same prompt bytes as English.
2517 for tag in [
2518 "zh-Hant", "ko", "es-419", "ca", "de", "fr", "id", "hi", "ru", "uk",
2519 ] {
2520 assert!(
2521 locale_reinforcement_preamble(tag).is_none(),
2522 "{tag} must not gain a locale preamble"
2523 );
2524 assert!(
2525 locale_reinforcement_closer(tag).is_none(),
2526 "{tag} must not gain a locale closer"
2527 );
2528 }
2529 // The bookend set is exactly the original four locales — growing it
2530 // is a deliberate, reviewable prompt change, not a side effect of
2531 // adding a UI pack.
2532 for tag in ["zh-Hans", "ja", "pt-BR", "vi"] {
2533 assert!(
2534 locale_reinforcement_preamble(tag).is_some(),
2535 "{tag} lost its locale preamble"
2536 );
2537 assert!(
2538 locale_reinforcement_closer(tag).is_some(),
2539 "{tag} lost its locale closer"
2540 );
2541 }
2542 }
2543
2544 #[test]
2545 fn translation_seam_names_every_shipped_locale_canonically() {
2546 // The translation output instruction is the declared model-facing
2547 // seam: it only enters the prompt when `translation_enabled` is
2548 // true. When it does, every shipped locale must be named
2549 // canonically (English name + endonym) — never silently "English".
2550 for locale in codewhale_localization::Locale::shipped() {
2551 assert_eq!(
2552 translation_target_language_for_tag(locale.tag()),
2553 locale.translation_target_name(),
2554 "{} translation seam drifted from the canonical locale name",
2555 locale.tag()
2556 );
2557 }
2558 }
2559
2560 #[test]
2561 fn system_prompt_bookends_zh_hans_with_preamble_and_closer() {
2562 // The full system prompt for zh-Hans must contain BOTH the
2563 // opening preamble (`## 语言要求`) and the closing reinforcement
2564 // (`## 语言再次提醒`), with the closer appearing AFTER the
2565 // preamble — i.e. the prompt is "bookended" in native script,
2566 // matching the empirical finding from the WeChat thread that
2567 // motivated the closer.
2568 let tmp = tempdir().expect("tempdir");
2569 let text = system_prompt_flat_text(
2570 &system_prompt_for_mode_with_context_skills_session_and_approval(
2571 tmp.path(),
2572 None,
2573 None,
2574 None,
2575 PromptSessionContext {
2576 user_memory_block: None,
2577 goal_objective: None,
2578 project_context_pack_enabled: false,
2579 locale_tag: "zh-Hans",
2580 translation_enabled: false,
2581 model_id: "codewhale",
2582 context_window_override: None,
2583 verbosity: None,
2584 skills_config: Default::default(),
2585 plugin_registry: None,
2586 recovery_hint: None,
2587 mode: AppMode::Agent,
2588 },
2589 ),
2590 );
2591 let preamble_pos = text
2592 .find("## 语言要求")
2593 .expect("zh-Hans preamble must be in prompt");
2594 let closer_pos = text
2595 .find("## 语言再次提醒")
2596 .expect("zh-Hans closer must be in prompt");
2597 assert!(
2598 preamble_pos < closer_pos,
2599 "closer must come after preamble (preamble={preamble_pos}, closer={closer_pos})",
2600 );
2601 // The closer must be the very last block — anything else after
2602 // it defeats the recency-bias purpose. Skip the closer's own
2603 // `## ` header before scanning.
2604 let closer_header_end = closer_pos + "## 语言再次提醒".len();
2605 let after_closer_body = &text[closer_header_end..];
2606 assert!(
2607 !after_closer_body.contains("\n## "),
2608 "no other top-level section should follow the closer; got: {after_closer_body:?}",
2609 );
2610 }
2611
2612 #[test]
2613 fn system_prompt_skips_locale_preamble_for_english() {
2614 // English locale → no preamble injected. Asserts the
2615 // "preamble is opt-in for non-English" invariant.
2616 let tmp = tempdir().expect("tempdir");
2617 let text = system_prompt_flat_text(
2618 &system_prompt_for_mode_with_context_skills_session_and_approval(
2619 tmp.path(),
2620 None,
2621 None,
2622 None,
2623 PromptSessionContext {
2624 user_memory_block: None,
2625 goal_objective: None,
2626 project_context_pack_enabled: false,
2627 locale_tag: "en",
2628 translation_enabled: false,
2629 model_id: "codewhale",
2630 context_window_override: None,
2631 verbosity: None,
2632 skills_config: Default::default(),
2633 plugin_registry: None,
2634 recovery_hint: None,
2635 mode: AppMode::Agent,
2636 },
2637 ),
2638 );
2639 assert!(
2640 !text.contains("语言要求"),
2641 "English locale must not get a zh preamble: {text:?}"
2642 );
2643 assert!(
2644 !text.contains("言語要件"),
2645 "English locale must not get a ja preamble: {text:?}"
2646 );
2647 assert!(
2648 !text.contains("Requisito de Idioma"),
2649 "English locale must not get a pt-BR preamble: {text:?}"
2650 );
2651 // Closer too — same bookend rule.
2652 assert!(
2653 !text.contains("语言再次提醒"),
2654 "English locale must not get a zh closer: {text:?}"
2655 );
2656 assert!(
2657 !text.contains("言語再確認"),
2658 "English locale must not get a ja closer: {text:?}"
2659 );
2660 assert!(
2661 !text.contains("Reforço de Idioma"),
2662 "English locale must not get a pt-BR closer: {text:?}"
2663 );
2664 assert!(
2665 !contains_cjk(BASE_PROMPT),
2666 "base prompt must not contain static CJK priming tokens"
2667 );
2668 // Do not assert on arbitrary CJK in the full system prompt: project
2669 // context may legitimately contain localized file names, README text,
2670 // or user-authored instructions. The locale bookend markers above are
2671 // the priming tokens this test is meant to guard.
2672 }
2673
2674 #[test]
2675 fn locale_bookends_carry_reasoning_content_directives_for_1118() {
2676 // #1118 ("Language has been configured to Chinese, but thinking
2677 // outputs are still in English"): after the 0.9.0 constitution
2678 // reduction, locale-native bookends carry the runtime language
2679 // reinforcement instead of the base constitution.
2680 let lang = LOCALE_PREAMBLE_ZH_HANS;
2681 assert!(
2682 lang.contains("reasoning_content"),
2683 "locale preamble must explicitly call out reasoning_content"
2684 );
2685 assert!(
2686 lang.contains("最终回复"),
2687 "locale preamble must explicitly cover the final reply"
2688 );
2689 assert!(
2690 lang.contains("代码") && lang.contains("工具名称"),
2691 "code and tool names must be named as non-language signals"
2692 );
2693 assert!(
2694 LOCALE_CLOSER_ZH_HANS.contains("reasoning_content")
2695 && LOCALE_CLOSER_ZH_HANS.contains("继续用简体中文思考和回答"),
2696 "closing bookend must preserve recency-positioned language reinforcement"
2697 );
2698 // Explicit-user-override clause keeps the prompt useful for the
2699 // opposite preference (#1118 commenters who want English
2700 // thinking for token-cost reasons).
2701 let phrase = "think in English";
2702 assert!(
2703 lang.contains(phrase) && LOCALE_CLOSER_ZH_HANS.contains(phrase),
2704 "expected the user-override example `{phrase}`"
2705 );
2706 }
2707
2708 #[test]
2709 fn environment_block_is_inserted_into_system_prompt() {
2710 let tmp = tempdir().expect("tempdir");
2711 let prompt =
2712 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
2713 tmp.path(),
2714 None,
2715 None,
2716 None,
2717 PromptSessionContext {
2718 user_memory_block: None,
2719 goal_objective: None,
2720 project_context_pack_enabled: false,
2721 locale_tag: "ja",
2722 translation_enabled: false,
2723 model_id: "codewhale",
2724 context_window_override: None,
2725 verbosity: None,
2726 skills_config: Default::default(),
2727 plugin_registry: None,
2728 recovery_hint: None,
2729 mode: AppMode::Agent,
2730 },
2731 ));
2732 assert!(prompt.contains("## Environment"));
2733 assert!(prompt.contains("- lang: ja"));
2734 assert!(!prompt.contains("- codewhale_version:"));
2735 assert!(prompt.contains("- platform:"));
2736 assert!(prompt.contains("- shell:"));
2737 }
2738
2739 #[test]
2740 fn user_global_constitution_is_captured_outside_the_stable_prefix() {
2741 let _env_guard = crate::test_support::lock_test_env();
2742 let tmp = tempdir().expect("tempdir");
2743 let workspace = tmp.path().join("workspace");
2744 std::fs::create_dir_all(&workspace).expect("workspace dir");
2745 let codewhale_home = tmp.path().join("codewhale-home");
2746 std::fs::create_dir_all(&codewhale_home).expect("codewhale home");
2747 let _codewhale_home =
2748 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str());
2749
2750 let constitution = codewhale_config::UserConstitution {
2751 about: Some("Maintains Codewhale release lanes.".to_string()),
2752 working_style: vec!["Prefer live verification before claims.".to_string()],
2753 priorities: vec!["Keep release gates green.".to_string()],
2754 autonomy_preference: codewhale_config::AutonomyPreference::Balanced,
2755 ..codewhale_config::UserConstitution::default()
2756 };
2757 constitution
2758 .save_to(
2759 &codewhale_home
2760 .join(codewhale_config::user_constitution::USER_CONSTITUTION_FILE_NAME),
2761 )
2762 .expect("save user constitution");
2763
2764 let prompt =
2765 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
2766 &workspace,
2767 None,
2768 None,
2769 None,
2770 PromptSessionContext {
2771 project_context_pack_enabled: false,
2772 ..PromptSessionContext::default()
2773 },
2774 ));
2775
2776 assert!(!prompt.contains("<codewhale_user_constitution"));
2777 let block = load_user_constitution_block().expect("admission snapshot");
2778 assert!(block.contains("Maintains Codewhale release lanes."));
2779 assert!(block.contains("Prefer live verification before claims."));
2780 assert!(!block.contains(&codewhale_home.display().to_string()));
2781 }
2782
2783 #[test]
2784 fn bundled_choice_disables_user_global_constitution_block() {
2785 let _env_guard = crate::test_support::lock_test_env();
2786 let tmp = tempdir().expect("tempdir");
2787 let workspace = tmp.path().join("workspace");
2788 std::fs::create_dir_all(&workspace).expect("workspace dir");
2789 let codewhale_home = tmp.path().join("codewhale-home");
2790 std::fs::create_dir_all(&codewhale_home).expect("codewhale home");
2791 let _codewhale_home =
2792 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str());
2793
2794 let constitution = codewhale_config::UserConstitution {
2795 about: Some("This file should stay inactive.".to_string()),
2796 ..codewhale_config::UserConstitution::default()
2797 };
2798 constitution
2799 .save_to(
2800 &codewhale_home
2801 .join(codewhale_config::user_constitution::USER_CONSTITUTION_FILE_NAME),
2802 )
2803 .expect("save user constitution");
2804
2805 let mut state = codewhale_config::SetupState::default();
2806 state.complete_constitution_checkpoint(
2807 crate::prompts::CONSTITUTION_CHECKPOINT_VERSION,
2808 codewhale_config::ConstitutionChoice::Bundled,
2809 );
2810 state
2811 .save_to(&codewhale_home.join(codewhale_config::setup_state::SETUP_STATE_FILE_NAME))
2812 .expect("save setup state");
2813
2814 let prompt =
2815 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
2816 &workspace,
2817 None,
2818 None,
2819 None,
2820 PromptSessionContext {
2821 project_context_pack_enabled: false,
2822 ..PromptSessionContext::default()
2823 },
2824 ));
2825
2826 assert!(!prompt.contains("<codewhale_user_constitution"));
2827 assert!(!prompt.contains("This file should stay inactive."));
2828 }
2829
2830 #[test]
2831 fn invalid_user_global_constitution_is_skipped() {
2832 let _env_guard = crate::test_support::lock_test_env();
2833 let tmp = tempdir().expect("tempdir");
2834 let workspace = tmp.path().join("workspace");
2835 std::fs::create_dir_all(&workspace).expect("workspace dir");
2836 let codewhale_home = tmp.path().join("codewhale-home");
2837 std::fs::create_dir_all(&codewhale_home).expect("codewhale home");
2838 std::fs::write(
2839 codewhale_home.join(codewhale_config::user_constitution::USER_CONSTITUTION_FILE_NAME),
2840 "{ not valid json",
2841 )
2842 .expect("write invalid user constitution");
2843 let _codewhale_home =
2844 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str());
2845
2846 let prompt =
2847 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
2848 &workspace,
2849 None,
2850 None,
2851 None,
2852 PromptSessionContext {
2853 project_context_pack_enabled: false,
2854 ..PromptSessionContext::default()
2855 },
2856 ));
2857
2858 assert!(!prompt.contains("<codewhale_user_constitution"));
2859 }
2860
2861 #[test]
2862 fn memory_guidance_carries_paired_examples() {
2863 // The fragment is the contract — verify the verbatim ✓ / ✗
2864 // pair is present so V4 has both shapes to imitate.
2865 assert!(MEMORY_GUIDANCE.contains("declarative facts"));
2866 assert!(MEMORY_GUIDANCE.contains(" ✓"));
2867 assert!(MEMORY_GUIDANCE.contains(" ✗"));
2868 assert!(MEMORY_GUIDANCE.contains("Imperative"));
2869 }
2870
2871 #[test]
2872 fn memory_guidance_does_not_reference_scrapped_moraine() {
2873 // Moraine was scrapped for v0.9.4 (no in-repo server ever existed);
2874 // the native Markdown + SQLite FTS5 memory is the surviving system.
2875 assert!(!MEMORY_GUIDANCE.contains("Moraine"));
2876 assert!(!MEMORY_GUIDANCE.contains("moraine"));
2877 }
2878
2879 #[test]
2880 fn memory_guidance_absent_when_no_memory_block() {
2881 let tmp = tempdir().expect("tempdir");
2882 let prompt =
2883 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
2884 tmp.path(),
2885 None,
2886 None,
2887 None,
2888 PromptSessionContext {
2889 user_memory_block: None,
2890 goal_objective: None,
2891 project_context_pack_enabled: false,
2892 locale_tag: "en",
2893 translation_enabled: false,
2894 model_id: "codewhale",
2895 context_window_override: None,
2896 verbosity: None,
2897 skills_config: Default::default(),
2898 plugin_registry: None,
2899 recovery_hint: None,
2900 mode: AppMode::Agent,
2901 },
2902 ));
2903 assert!(
2904 !prompt.contains("Memory Hygiene"),
2905 "memory guidance must not leak into sessions without a memory block"
2906 );
2907 }
2908
2909 #[test]
2910 fn memory_guidance_appended_after_memory_block() {
2911 let tmp = tempdir().expect("tempdir");
2912 let block = "## User Memory\n\n- prefers Rust\n";
2913 let prompt =
2914 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
2915 tmp.path(),
2916 None,
2917 None,
2918 None,
2919 PromptSessionContext {
2920 user_memory_block: Some(block),
2921 goal_objective: None,
2922 project_context_pack_enabled: false,
2923 locale_tag: "en",
2924 translation_enabled: false,
2925 model_id: "codewhale",
2926 context_window_override: None,
2927 verbosity: None,
2928 skills_config: Default::default(),
2929 plugin_registry: None,
2930 recovery_hint: None,
2931 mode: AppMode::Agent,
2932 },
2933 ));
2934 let mem_at = prompt.find("User Memory").expect("user memory present");
2935 let guide_at = prompt.find("Memory Hygiene").expect("guidance present");
2936 assert!(
2937 mem_at < guide_at,
2938 "guidance must come after the user memory block"
2939 );
2940 }
2941
2942 #[test]
2943 fn memory_guidance_does_not_state_precedence() {
2944 // #4777: only BASE_PROMPT § Whose word wins states ranks. Memory
2945 // hygiene keeps the imperative→preference rule and drops the
2946 // inverted Tier list that used to put Constitution above the user.
2947 let guidance = MEMORY_GUIDANCE.to_ascii_lowercase();
2948 for forbidden in [
2949 "tier 1",
2950 "tier 2",
2951 "tier 7",
2952 "statute",
2953 "regulation",
2954 "local law",
2955 "constitutional hierarchy",
2956 ] {
2957 assert!(
2958 !guidance.contains(forbidden),
2959 "MEMORY_GUIDANCE must not restate ranks (found {forbidden:?})"
2960 );
2961 }
2962 assert!(
2963 MEMORY_GUIDANCE.contains("treated as a preference")
2964 && MEMORY_GUIDANCE.contains("not a command"),
2965 "keep the imperative-as-preference rule"
2966 );
2967 }
2968
2969 #[test]
2970 fn only_the_constitution_states_precedence() {
2971 // Composed overlays must describe behavior, never their own rank.
2972 let overlays = [
2973 ("COMPACT_TEMPLATE", COMPACT_TEMPLATE),
2974 ("MEMORY_GUIDANCE", MEMORY_GUIDANCE),
2975 ("LANGUAGE_PROMPT", LANGUAGE_PROMPT),
2976 ("OUTPUT_PROMPT", OUTPUT_PROMPT),
2977 ("AUTHORITY_RECAP", AUTHORITY_RECAP),
2978 ];
2979 let rank_markers = [
2980 "Tier 1",
2981 "Tier 2",
2982 "Tier 3",
2983 "Tier 4",
2984 "Tier 5",
2985 "Tier 6",
2986 "Tier 7",
2987 "Tier 8",
2988 "Tier 9",
2989 "Statute",
2990 "Article IV",
2991 "Article V",
2992 "Article VII",
2993 "Local Law",
2994 "Regulation (Tier",
2995 ];
2996 for (name, text) in overlays {
2997 for marker in rank_markers {
2998 assert!(
2999 !text.contains(marker),
3000 "{name} must not carry rank vocabulary {marker:?}"
3001 );
3002 }
3003 }
3004 assert!(
3005 BASE_PROMPT.contains("### Whose word wins"),
3006 "canonical precedence section must remain in BASE_PROMPT"
3007 );
3008 assert!(
3009 BASE_PROMPT.contains("This ordering is stated here and nowhere else"),
3010 "BASE_PROMPT must assert single-source precedence"
3011 );
3012 }
3013
3014 #[test]
3015 fn project_context_pack_can_be_disabled() {
3016 let tmp = tempdir().expect("tempdir");
3017 std::fs::write(tmp.path().join("README.md"), "# Pack test").expect("write readme");
3018 let prompt =
3019 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
3020 tmp.path(),
3021 None,
3022 None,
3023 None,
3024 PromptSessionContext {
3025 user_memory_block: None,
3026 goal_objective: None,
3027 project_context_pack_enabled: false,
3028 locale_tag: "en",
3029 translation_enabled: false,
3030 model_id: "codewhale",
3031 context_window_override: None,
3032 verbosity: None,
3033 skills_config: Default::default(),
3034 plugin_registry: None,
3035 recovery_hint: None,
3036 mode: AppMode::Agent,
3037 },
3038 ));
3039 assert!(!prompt.contains("<project_context_pack>"));
3040 }
3041
3042 #[test]
3043 fn project_context_pack_is_before_dynamic_tail() {
3044 let tmp = tempdir().expect("tempdir");
3045 std::fs::write(tmp.path().join("README.md"), "# Pack test").expect("write readme");
3046 std::fs::create_dir_all(tmp.path().join(".deepseek")).expect("mkdir");
3047 std::fs::write(tmp.path().join(".deepseek").join("handoff.md"), "handoff")
3048 .expect("handoff");
3049 let prompt =
3050 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
3051 tmp.path(),
3052 None,
3053 None,
3054 None,
3055 PromptSessionContext {
3056 user_memory_block: None,
3057 goal_objective: None,
3058 // Explicit opt-in — pack is off by default (#4781).
3059 project_context_pack_enabled: true,
3060 locale_tag: "en",
3061 translation_enabled: false,
3062 model_id: "codewhale",
3063 context_window_override: None,
3064 verbosity: None,
3065 skills_config: Default::default(),
3066 plugin_registry: None,
3067 recovery_hint: None,
3068 mode: AppMode::Agent,
3069 },
3070 ));
3071 assert!(prompt.contains("<project_context_pack>"));
3072 assert!(
3073 prompt.find("<project_context_pack>").expect("pack")
3074 < prompt.find("## Previous Session Relay").expect("relay")
3075 );
3076 }
3077
3078 #[test]
3079 fn handoff_artifact_is_prepended_to_system_prompt_when_present() {
3080 let tmp = tempdir().expect("tempdir");
3081 let workspace = tmp.path();
3082 let handoff_dir = workspace.join(".deepseek");
3083 std::fs::create_dir_all(&handoff_dir).unwrap();
3084 std::fs::write(
3085 handoff_dir.join("handoff.md"),
3086 "# Session relay — prior\n\n## Active task\nFinish #32.\n\n## Open blockers\n- [ ] write the basic version\n",
3087 )
3088 .unwrap();
3089
3090 let prompt = system_prompt_flat_text(&system_prompt_for_mode_with_context(workspace, None));
3091
3092 assert!(prompt.contains(HANDOFF_BLOCK_MARKER));
3093 assert!(prompt.contains("Finish #32."));
3094 assert!(prompt.contains("write the basic version"));
3095 // Only the legacy file exists, so the block must name it rather
3096 // than send the model to a primary file that is not there.
3097 assert!(prompt.contains("left a relay artifact at `.deepseek/handoff.md`"));
3098 assert!(!prompt.contains("left a relay artifact at `.codewhale/handoff.md`"));
3099 }
3100
3101 #[test]
3102 fn primary_handoff_wins_over_legacy_and_is_named() {
3103 let tmp = tempdir().expect("tempdir");
3104 let workspace = tmp.path();
3105 for (dir, body) in [
3106 (".codewhale", "# Session relay\n\nprimary relay body\n"),
3107 (".deepseek", "# Session relay\n\nlegacy relay body\n"),
3108 ] {
3109 std::fs::create_dir_all(workspace.join(dir)).unwrap();
3110 std::fs::write(workspace.join(dir).join("handoff.md"), body).unwrap();
3111 }
3112
3113 let prompt = system_prompt_flat_text(&system_prompt_for_mode_with_context(workspace, None));
3114
3115 assert!(prompt.contains("left a relay artifact at `.codewhale/handoff.md`"));
3116 assert!(prompt.contains("primary relay body"));
3117 assert!(!prompt.contains("legacy relay body"));
3118 assert!(!prompt.contains("left a relay artifact at `.deepseek/handoff.md`"));
3119 }
3120
3121 #[test]
3122 fn missing_handoff_does_not_inject_block() {
3123 let tmp = tempdir().expect("tempdir");
3124 let prompt =
3125 system_prompt_flat_text(&system_prompt_for_mode_with_context(tmp.path(), None));
3126 assert!(!prompt.contains(HANDOFF_BLOCK_MARKER));
3127 }
3128
3129 #[test]
3130 fn empty_handoff_file_does_not_inject_block() {
3131 let tmp = tempdir().expect("tempdir");
3132 let dir = tmp.path().join(".deepseek");
3133 std::fs::create_dir_all(&dir).unwrap();
3134 std::fs::write(dir.join("handoff.md"), " \n\n ").unwrap();
3135 let prompt =
3136 system_prompt_flat_text(&system_prompt_for_mode_with_context(tmp.path(), None));
3137 assert!(!prompt.contains(HANDOFF_BLOCK_MARKER));
3138 }
3139
3140 #[test]
3141 fn compose_prompt_includes_all_layers() {
3142 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3143 // Base layer — balanced Constitution; procedural recipes stay out.
3144 assert!(prompt.contains("## Codewhale"));
3145 assert!(prompt.contains("### Whose word wins"));
3146 assert!(!prompt.contains("## STATUTES (Tier 2)"));
3147 assert!(!prompt.contains("## EVIDENCE (Tier 6)"));
3148 // Mode and approval are not inlined — they travel as
3149 // request-time runtime metadata.
3150 assert!(!prompt.contains("Mode: Agent"));
3151 assert!(!prompt.contains("Approval Policy:"));
3152 }
3153
3154 /// `constitution.md` is the single hand-maintained source of the balanced
3155 /// constitutional core. This replaces the old 600-line policy tail: a
3156 /// hand-edit that drops a core section or reorders the skeleton fails the
3157 /// build instead of silently shipping a malformed prompt.
3158 #[test]
3159 fn constitution_md_carries_required_structure() {
3160 let md = BASE_PROMPT;
3161 assert!(md.contains("## Codewhale"), "missing title");
3162 let mut cursor = 0usize;
3163 for needle in [
3164 "## Codewhale",
3165 "### Ground truth",
3166 "### User intent and scope",
3167 "### Truthful completion",
3168 "### Put guarantees in mechanism",
3169 "### Whose word wins",
3170 ] {
3171 let pos = md
3172 .find(needle)
3173 .unwrap_or_else(|| panic!("ordering check: {needle:?} not found"));
3174 assert!(
3175 pos >= cursor,
3176 "cache-stable ordering broken: {needle:?} at {pos} precedes a previous section at {cursor}"
3177 );
3178 cursor = pos + needle.len();
3179 }
3180 }
3181
3182 /// Gate against shipping a release with a missing CHANGELOG entry — which
3183 /// is exactly what happened with v0.8.21 / v0.8.22 (entries had to be
3184 /// backfilled in v0.8.23). Asserts the top-of-file CHANGELOG contains a
3185 /// `## [X.Y.Z]` heading matching the current `CARGO_PKG_VERSION`. No
3186 /// hardcoded version string — the test self-updates with the workspace
3187 /// version bump and only fires when the CHANGELOG is the missing piece.
3188 ///
3189 /// Walks up from `CARGO_MANIFEST_DIR` to find `CHANGELOG.md` instead of
3190 /// assuming a fixed `../../CHANGELOG.md` layout. The workspace root is
3191 /// the common case, but the walk also tolerates deeper crate layouts and
3192 /// the packaged-crate case (where the workspace root has been stripped
3193 /// out): if no `CHANGELOG.md` is reachable, the gate quietly skips
3194 /// rather than panicking, so consumers running the suite outside the
3195 /// workspace checkout don't see a spurious failure.
3196 #[test]
3197 fn changelog_entry_exists_for_current_package_version() {
3198 let version = env!("CARGO_PKG_VERSION");
3199 let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
3200 let Some(changelog_path) = manifest_dir
3201 .ancestors()
3202 .map(|dir| dir.join("CHANGELOG.md"))
3203 .find(|candidate| candidate.is_file())
3204 else {
3205 eprintln!(
3206 "changelog_entry_exists_for_current_package_version: no \
3207 CHANGELOG.md found above {} — skipping (this gate only \
3208 fires inside a workspace checkout).",
3209 manifest_dir.display()
3210 );
3211 return;
3212 };
3213
3214 let contents = std::fs::read_to_string(&changelog_path).unwrap_or_else(|err| {
3215 panic!(
3216 "failed to read CHANGELOG.md at {}: {err}",
3217 changelog_path.display()
3218 )
3219 });
3220 let header = format!("## [{version}]");
3221 assert!(
3222 contents.contains(&header),
3223 "CHANGELOG.md is missing a `{header}` entry for the current package \
3224 version. Add a release section at the top before tagging — see \
3225 docs/RELEASE_CHECKLIST.md."
3226 );
3227 }
3228
3229 #[test]
3230 fn compose_prompt_deterministic_order() {
3231 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3232 let base_pos = prompt.find("## Codewhale").unwrap();
3233 let article_pos = prompt.find("### Ground truth").unwrap();
3234
3235 assert!(base_pos < article_pos);
3236 }
3237
3238 #[test]
3239 fn base_prompt_is_mode_agnostic() {
3240 // Mode and approval text are no longer inlined into compose_prompt —
3241 // they travel as request-time runtime metadata.
3242 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3243 assert!(!prompt.contains("Mode: Agent"));
3244 assert!(!prompt.contains("Mode: YOLO"));
3245 assert!(!prompt.contains("Mode: Plan"));
3246 assert!(!prompt.contains("Approval Policy:"));
3247 // Base prompt carries the 0.9.0 compact Constitution.
3248 assert!(prompt.contains("You are Codewhale"));
3249 assert!(prompt.contains("Take the work seriously. Don't take"));
3250 }
3251
3252 #[test]
3253 fn approval_policy_no_longer_inlined_in_base_prompt() {
3254 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3255 assert!(!prompt.contains("Mode: Agent"));
3256 assert!(!prompt.contains("Approval Policy:"));
3257 // The compact Constitutional preamble is still present.
3258 assert!(prompt.contains("You are Codewhale"));
3259 }
3260
3261 #[test]
3262 fn execution_contract_states_proposal_is_not_execution() {
3263 // #5146: the live execution layer must make the propose-vs-execute
3264 // contract explicit after the legacy approval overlay was removed.
3265 assert!(
3266 CORE_EXECUTION_PROFILE_PROMPT.contains("is the proposal, not the execution"),
3267 "Execution profile must state the propose-vs-execute contract"
3268 );
3269 assert!(
3270 CORE_EXECUTION_PROFILE_PROMPT.contains("present the change in your plan"),
3271 "Execution profile must name the correct behavior on rejection"
3272 );
3273 }
3274
3275 #[test]
3276 fn compact_template_is_lazy_in_fresh_prompt() {
3277 let tmp = tempdir().expect("tempdir");
3278 let prompt =
3279 system_prompt_flat_text(&system_prompt_for_mode_with_context(tmp.path(), None));
3280 assert!(!prompt.contains("# Session relay"));
3281 assert!(!prompt.contains("## Verification"));
3282 }
3283
3284 #[test]
3285 fn session_goal_stays_volatile_while_compact_template_is_lazy() {
3286 let tmp = tempdir().expect("tempdir");
3287 let prompt =
3288 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
3289 tmp.path(),
3290 Some("## Repo Working Set\nsrc/lib.rs"),
3291 None,
3292 None,
3293 PromptSessionContext {
3294 user_memory_block: None,
3295 goal_objective: Some("Fix transcript corruption"),
3296 project_context_pack_enabled: false,
3297 locale_tag: "en",
3298 translation_enabled: false,
3299 model_id: "codewhale",
3300 context_window_override: None,
3301 verbosity: None,
3302 skills_config: Default::default(),
3303 plugin_registry: None,
3304 recovery_hint: None,
3305 mode: AppMode::Agent,
3306 },
3307 ));
3308
3309 let goal_pos = prompt.find("<session_goal>").expect("goal block");
3310 assert!(prompt.contains("Fix transcript corruption"));
3311 // Session goal remains volatile content below the stable static
3312 // layers. The relay template is injected only when relay/compaction
3313 // actually needs it.
3314 assert!(goal_pos > 0);
3315 assert!(!prompt.contains("# Session relay"));
3316 assert!(!prompt.contains("src/lib.rs"));
3317 }
3318
3319 #[test]
3320 fn empty_session_goal_is_not_injected() {
3321 let tmp = tempdir().expect("tempdir");
3322 let prompt =
3323 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
3324 tmp.path(),
3325 None,
3326 None,
3327 None,
3328 PromptSessionContext {
3329 user_memory_block: None,
3330 goal_objective: Some(" "),
3331 project_context_pack_enabled: false,
3332 locale_tag: "en",
3333 translation_enabled: false,
3334 model_id: "codewhale",
3335 context_window_override: None,
3336 verbosity: None,
3337 skills_config: Default::default(),
3338 plugin_registry: None,
3339 recovery_hint: None,
3340 mode: AppMode::Agent,
3341 },
3342 ));
3343
3344 assert!(!prompt.contains("<session_goal>"));
3345 assert!(!prompt.contains("## Current Goal"));
3346 }
3347
3348 #[test]
3349 fn recovery_hint_renders_only_when_present() {
3350 // Prompt assembly reads env-dependent paths (skills, memory, session
3351 // state); the byte-equality check must serialize against env-guard
3352 // tests in the same binary.
3353 let _env_guard = crate::test_support::lock_test_env();
3354 let tmp = tempdir().expect("tempdir");
3355 let build = |recovery_hint: Option<&str>| {
3356 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
3357 tmp.path(),
3358 None,
3359 None,
3360 None,
3361 PromptSessionContext {
3362 user_memory_block: None,
3363 goal_objective: None,
3364 project_context_pack_enabled: false,
3365 locale_tag: "en",
3366 translation_enabled: false,
3367 model_id: "codewhale",
3368 context_window_override: None,
3369 verbosity: None,
3370 recovery_hint,
3371 skills_config: Default::default(),
3372 plugin_registry: None,
3373 mode: AppMode::Agent,
3374 },
3375 ))
3376 };
3377
3378 let hinted = build(Some(
3379 "A previous session (\"fix\", id abc12345) has a recovery checkpoint",
3380 ));
3381 assert!(hinted.contains("## Prior Session"));
3382 assert!(hinted.contains("<session_recovery>"));
3383 assert!(hinted.contains("recovery checkpoint"));
3384
3385 // Clean sessions share identical prefix bytes: no block, no heading.
3386 let clean = build(None);
3387 assert!(!clean.contains("## Prior Session"));
3388 assert!(!clean.contains("session_recovery"));
3389 let blank = build(Some(" "));
3390 for (i, (a, b)) in clean.lines().zip(blank.lines()).enumerate() {
3391 assert_eq!(a, b, "line {i} differs");
3392 }
3393 assert_eq!(
3394 clean.lines().count(),
3395 blank.lines().count(),
3396 "line counts differ"
3397 );
3398 }
3399
3400 #[test]
3401 fn universal_prompt_leaves_tool_selection_to_the_catalog() {
3402 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3403 assert!(!prompt.contains("Tool Selection Guide"));
3404 for forbidden in [
3405 "`File`",
3406 "`Git`",
3407 "`Run`",
3408 "`Bash`",
3409 "read_file",
3410 "git_status",
3411 "run_tests",
3412 "exec_shell",
3413 "When NOT to use certain tools",
3414 "Don't reach for",
3415 ] {
3416 assert!(!BASE_PROMPT.contains(forbidden));
3417 }
3418 }
3419
3420 /// #588: after the 0.9.0 constitution reduction, language-mirroring
3421 /// reinforcement lives in its own static segment plus locale bookends.
3422 #[test]
3423 fn language_segment_present_outside_reduced_constitution() {
3424 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3425 assert!(
3426 !BASE_PROMPT.contains("## Language"),
3427 "0.9.0 constitution.md should stay reduced; language belongs in its own segment"
3428 );
3429 assert!(
3430 LANGUAGE_PROMPT.contains("## Language") && prompt.contains("## Language"),
3431 "default static prompt must still include the language segment"
3432 );
3433 assert!(
3434 LANGUAGE_PROMPT.contains("latest user message")
3435 && LANGUAGE_PROMPT.contains("fallback, not an override")
3436 && LANGUAGE_PROMPT.contains("localized READMEs")
3437 && LANGUAGE_PROMPT.contains("Use the `lang` field only when")
3438 && LANGUAGE_PROMPT.contains("constitution and other system law stay English"),
3439 "language segment must keep the mirror contract while staying short (#4784)"
3440 );
3441 assert!(
3442 LANGUAGE_PROMPT.contains("reasoning_content")
3443 && prompt.contains("reasoning_content")
3444 && LOCALE_PREAMBLE_ZH_HANS.contains("reasoning_content")
3445 && LOCALE_CLOSER_ZH_HANS.contains("reasoning_content"),
3446 "language segment and locale bookends must keep the reasoning_content anchor"
3447 );
3448 }
3449
3450 #[test]
3451 fn output_formatting_segment_present_outside_reduced_constitution() {
3452 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3453 assert!(
3454 !BASE_PROMPT.contains("## Output Formatting"),
3455 "0.9.0 constitution.md should stay reduced; output formatting belongs in its own segment"
3456 );
3457 assert!(OUTPUT_PROMPT.contains("## Output Formatting"));
3458 assert!(prompt.contains("## Output Formatting"));
3459 assert!(prompt.contains("terminal, not a browser"));
3460 assert!(prompt.contains("Markdown tables almost never render correctly"));
3461 }
3462
3463 #[test]
3464 fn runtime_prompt_assembly_preserves_split_static_layers() {
3465 let tmp = tempdir().expect("tempdir");
3466 let prompt =
3467 system_prompt_flat_text(&system_prompt_for_mode_with_context_skills_and_session(
3468 tmp.path(),
3469 None,
3470 None,
3471 None,
3472 PromptSessionContext {
3473 user_memory_block: None,
3474 goal_objective: None,
3475 project_context_pack_enabled: false,
3476 locale_tag: "en",
3477 translation_enabled: false,
3478 model_id: "glm-5.2",
3479 context_window_override: Some(1_000_000),
3480 verbosity: None,
3481 skills_config: Default::default(),
3482 plugin_registry: None,
3483 recovery_hint: None,
3484 mode: AppMode::Agent,
3485 },
3486 ));
3487
3488 assert!(prompt.contains("## Codewhale"));
3489 assert!(prompt.contains("## Language"));
3490 assert!(prompt.contains("## Output Formatting"));
3491 assert!(prompt.contains("Use the `lang` field only when"));
3492 }
3493
3494 #[test]
3495 fn locale_bookends_resist_english_context_drift() {
3496 assert!(
3497 LOCALE_PREAMBLE_ZH_HANS.contains("reasoning_content")
3498 && LOCALE_CLOSER_ZH_HANS.contains("reasoning_content"),
3499 "locale bookends must keep the reasoning_content anchor"
3500 );
3501 assert!(
3502 LOCALE_CLOSER_ZH_HANS.contains("英文代码")
3503 && LOCALE_CLOSER_ZH_HANS.contains("用户的语言决定"),
3504 "closing locale bookend must explicitly resist English-context drift"
3505 );
3506 assert!(
3507 LOCALE_PREAMBLE_ZH_HANS.contains("代码、文件路径、工具名称"),
3508 "opening locale bookend must keep code/tool tokens untranslated"
3509 );
3510 }
3511
3512 #[test]
3513 fn english_base_prompt_avoids_native_script_language_priming() {
3514 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3515 assert!(
3516 !contains_cjk(&prompt),
3517 "English base prompt should keep native-script reinforcement in locale bookends only"
3518 );
3519 assert!(
3520 !prompt.contains("multilingual coding agent"),
3521 "identity should not prime language switching; language belongs in runtime bookends"
3522 );
3523 }
3524
3525 #[test]
3526 fn rlm_tool_description_carries_the_rlm_surface_outside_the_base_prompt() {
3527 let tool = RlmTool::new("rlm");
3528 let description = tool.description();
3529 for action in ["session_objects", "open", "eval", "configure", "close"] {
3530 assert!(description.contains(action), "{action}: {description}");
3531 }
3532 assert!(description.contains("handle_read"), "{description}");
3533 assert!(!BASE_PROMPT.contains("`rlm`"));
3534 }
3535
3536 /// Project instructions rank above memory, with the nearest scope winning
3537 /// over the broader. The embedder-injected-instructions case is covered
3538 /// by project law/instructions sitting above memory/handoffs.
3539 #[test]
3540 fn project_instructions_outrank_memory_in_whose_word_wins() {
3541 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3542 let project_at = prompt
3543 .find("3. Project law and instructions")
3544 .expect("Whose word wins must rank project instructions");
3545 let memory_at = prompt
3546 .find("5. Memory and previous-session handoffs.")
3547 .expect("Whose word wins must rank memory below project instructions");
3548 assert!(
3549 project_at < memory_at,
3550 "project instructions must outrank memory so embedder-injected \
3551 instructions are not treated as mere memory preferences"
3552 );
3553 }
3554
3555 #[test]
3556 fn workspace_orientation_guidance_present() {
3557 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3558 assert!(prompt.contains("Project law and instructions"));
3559 assert!(
3560 prompt.contains("the nearest in\nscope winning over the broader")
3561 || prompt.contains("the nearest in scope winning over the broader"),
3562 "Whose word wins must keep the nearest-scope-wins rule for project instructions"
3563 );
3564 }
3565
3566 #[test]
3567 fn prompt_documents_fork_context_prefix_cache_contract() {
3568 let source = include_str!("tools/subagent/mod.rs");
3569 assert!(source.contains("fork_context"));
3570 assert!(!BASE_PROMPT.contains("fork_context"));
3571 }
3572
3573 #[test]
3574 fn prompt_documents_explicit_subagent_model_strength() {
3575 let source = include_str!("tools/subagent/mod.rs");
3576 assert!(source.contains("model_strength"));
3577 assert!(!BASE_PROMPT.contains("model_strength"));
3578 }
3579
3580 #[test]
3581 fn prompt_documents_structured_subagent_briefs() {
3582 assert!(!BASE_PROMPT.contains("Subagent Brief"));
3583 for heading in [
3584 "### SUMMARY",
3585 "### EVIDENCE",
3586 "### CHANGES",
3587 "### RISKS",
3588 "### BLOCKERS",
3589 ] {
3590 assert!(text::SUBAGENT_OUTPUT_FORMAT.contains(heading));
3591 }
3592 }
3593
3594 #[test]
3595 fn universal_prompt_does_not_invent_orchestration_limits() {
3596 assert!(!BASE_PROMPT.contains("3-5 tool calls"));
3597 assert!(!BASE_PROMPT.contains("No fan-out without a fan-in owner"));
3598 }
3599
3600 #[test]
3601 fn universal_prompt_does_not_teach_optional_workflow_recipes() {
3602 for recipe in [
3603 "Workflow",
3604 "responseSchema",
3605 "request_user_input",
3606 ".workflow.js",
3607 ] {
3608 assert!(!BASE_PROMPT.contains(recipe));
3609 }
3610 }
3611
3612 #[test]
3613 fn universal_prompt_does_not_expose_control_plane_ceremony() {
3614 for internal in [
3615 "completion sentinels",
3616 "<codewhale:subagent.done>",
3617 "<codewhale:runtime_event",
3618 "busy-waiting",
3619 ] {
3620 assert!(!BASE_PROMPT.contains(internal));
3621 }
3622 }
3623
3624 #[test]
3625 fn preamble_carries_tone_and_ownership_guidance() {
3626 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
3627 assert!(prompt.contains("The A is already yours"));
3628 assert!(prompt.contains("Your competence is a settled fact"));
3629 assert!(prompt.contains("Take the work seriously. Don't take"));
3630 assert!(prompt.contains("Let the work speak"));
3631 }
3632
3633 // ── Cache-prefix stability harness (#263 step 2) ───────────────────────
3634 //
3635 // These tests pin the byte-stability invariant required for DeepSeek's
3636 // KV prefix cache to hit: any prompt-construction surface that ends up
3637 // in the cached prefix must produce identical bytes given identical
3638 // inputs across calls.
3639
3640 use crate::test_support::{EnvVarGuard, assert_byte_identical};
3641
3642 #[test]
3643 fn compose_prompt_is_byte_stable_across_calls() {
3644 // Suspect #4 from #263: stable prompt churn within a single session.
3645 // Two calls with identical inputs must produce
3646 // identical bytes — anything else is a cache buster.
3647 let a = compose_prompt_with_approval_model_and_shell("codewhale");
3648 let b = compose_prompt_with_approval_model_and_shell("codewhale");
3649 assert_byte_identical("compose_prompt", &a, &b);
3650 }
3651
3652 #[test]
3653 fn system_prompt_for_mode_with_context_is_byte_stable_for_unchanged_workspace() {
3654 // Same workspace, no working_set / skills churn between calls →
3655 // identical bytes. This pins the most representative production
3656 // surface (engine.rs builds the system prompt via this fn or
3657 // its sibling _and_skills variant on every turn).
3658 let _env_guard = crate::test_support::lock_test_env();
3659 let workspace_tmp = tempdir().expect("workspace tempdir");
3660 let home_tmp = tempdir().expect("home tempdir");
3661 let _home = EnvVarGuard::set("HOME", home_tmp.path().as_os_str());
3662 let _userprofile = EnvVarGuard::set("USERPROFILE", home_tmp.path().as_os_str());
3663 let _skills_dir = EnvVarGuard::remove("DEEPSEEK_SKILLS_DIR");
3664 let workspace = workspace_tmp.path();
3665
3666 let a = system_prompt_flat_text(&system_prompt_for_mode_with_context(workspace, None));
3667 let b = system_prompt_flat_text(&system_prompt_for_mode_with_context(workspace, None));
3668 assert_byte_identical(
3669 "system_prompt_for_mode_with_context() on empty workspace",
3670 &a,
3671 &b,
3672 );
3673 }
3674
3675 #[test]
3676 fn system_prompt_ignores_working_set_summary_argument() {
3677 // Working-set metadata is now injected into the latest user message
3678 // per turn. The legacy argument remains for call-site compatibility
3679 // but must not reintroduce volatile bytes into the system prompt.
3680 let _env_guard = crate::test_support::lock_test_env();
3681 let tmp = tempdir().expect("tempdir");
3682 let home_tmp = tempdir().expect("home tempdir");
3683 let _home = EnvVarGuard::set("HOME", home_tmp.path().as_os_str());
3684 let _userprofile = EnvVarGuard::set("USERPROFILE", home_tmp.path().as_os_str());
3685 let _skills_dir = EnvVarGuard::remove("DEEPSEEK_SKILLS_DIR");
3686 let workspace = tmp.path();
3687 let summary = "## Repo Working Set\nWorkspace: /tmp/x\n";
3688
3689 let a = system_prompt_flat_text(&system_prompt_for_mode_with_context(
3690 workspace,
3691 Some(summary),
3692 ));
3693 let b = system_prompt_flat_text(&system_prompt_for_mode_with_context(
3694 workspace,
3695 Some(summary),
3696 ));
3697 assert_byte_identical(
3698 "system_prompt_for_mode_with_context with constant working_set summary",
3699 &a,
3700 &b,
3701 );
3702 assert!(
3703 !a.contains(summary),
3704 "summary must not be embedded in system prompt"
3705 );
3706 }
3707
3708 #[test]
3709 fn oversized_relay_artifact_fits_its_fragment_and_points_at_the_file() {
3710 let tmp = tempdir().expect("tempdir");
3711 let dir = tmp.path().join(".codewhale");
3712 std::fs::create_dir_all(&dir).unwrap();
3713 let relay = "- runtime_handoff entry with detail\n".repeat(10 * 1024);
3714 std::fs::write(dir.join("handoff.md"), &relay).unwrap();
3715
3716 let block = super::load_handoff_block(tmp.path()).expect("relay block");
3717 assert!(
3718 block.len() <= codewhale_core::fragments::DEFAULT_FRAGMENT_MAX_BYTES,
3719 "relay must fit its fragment, got {} bytes",
3720 block.len()
3721 );
3722 assert!(
3723 block.contains("read `.codewhale/handoff.md` for the rest"),
3724 "{block}"
3725 );
3726 let before_note = block.split("\n\n[Relay shortened").next().unwrap();
3727 assert!(before_note.ends_with("with detail"), "{before_note}");
3728 }
3729
3730 #[test]
3731 fn system_prompt_with_handoff_file_is_byte_stable_when_file_is_unchanged() {
3732 // If `.deepseek/handoff.md` hasn't moved between two builds, the
3733 // rendered prompt must produce identical bytes. The relay block
3734 // lands below the static boundary in
3735 // `system_prompt_for_mode_with_context_and_skills`.
3736 let _env_guard = crate::test_support::lock_test_env();
3737 let tmp = tempdir().expect("tempdir");
3738 let home_tmp = tempdir().expect("home tempdir");
3739 let _home = EnvVarGuard::set("HOME", home_tmp.path().as_os_str());
3740 let _userprofile = EnvVarGuard::set("USERPROFILE", home_tmp.path().as_os_str());
3741 let _skills_dir = EnvVarGuard::remove("DEEPSEEK_SKILLS_DIR");
3742 let workspace = tmp.path();
3743 let handoff_dir = workspace.join(".deepseek");
3744 std::fs::create_dir_all(&handoff_dir).unwrap();
3745 std::fs::write(
3746 handoff_dir.join("handoff.md"),
3747 "# Session relay\n\n## Active task\nFinish #280.\n\n## Open blockers\n- [ ] none\n",
3748 )
3749 .unwrap();
3750
3751 let a = system_prompt_flat_text(&system_prompt_for_mode_with_context(workspace, None));
3752 let b = system_prompt_flat_text(&system_prompt_for_mode_with_context(workspace, None));
3753 assert_byte_identical(
3754 "system_prompt_for_mode_with_context with constant handoff file",
3755 &a,
3756 &b,
3757 );
3758 assert!(a.contains(HANDOFF_BLOCK_MARKER), "relay must be embedded");
3759 assert!(a.contains("Finish #280."), "relay body must be present");
3760 }
3761
3762 #[test]
3763 fn handoff_appears_after_static_blocks_without_working_set() {
3764 // Cache-prefix invariant: the relay artifact must come after static
3765 // `## Core Execution`. The relay template itself is now action-local,
3766 // not part of every system prompt. Working-set metadata is per-turn
3767 // user metadata, not a system-prompt tail block.
3768 let tmp = tempdir().expect("tempdir");
3769 let workspace = tmp.path();
3770 let handoff_dir = workspace.join(".deepseek");
3771 std::fs::create_dir_all(&handoff_dir).unwrap();
3772 std::fs::write(handoff_dir.join("handoff.md"), "# handoff body\n").unwrap();
3773
3774 let summary = "## Repo Working Set\nWorkspace: /tmp/x\n";
3775 let prompt = system_prompt_flat_text(&system_prompt_for_mode_with_context(
3776 workspace,
3777 Some(summary),
3778 ));
3779
3780 let execution_pos = prompt
3781 .find("## Core Execution")
3782 .expect("Core Execution section present in Agent mode");
3783 let handoff_pos = prompt
3784 .find(HANDOFF_BLOCK_MARKER)
3785 .expect("relay block present when fixture file exists");
3786 assert!(
3787 !prompt.contains("## Repo Working Set"),
3788 "working-set summary must stay out of the system prompt"
3789 );
3790
3791 assert!(
3792 execution_pos < handoff_pos,
3793 "## Core Execution must precede the relay block"
3794 );
3795 assert!(!prompt.contains("# Session relay"));
3796 }
3797
3798 /// #4632 — The system prompt prefix (the byte-stable part cached by
3799 /// inference servers) must never contain private content: absolute
3800 /// filesystem paths, API keys, or home-directory references.
3801 ///
3802 /// Pin `HOME`/`USERPROFILE` to a scratch dir (and hold the env barrier)
3803 /// so global `~/.codewhale/instructions.md` and home-resolved skills
3804 /// cannot leak their real absolute paths into the prompt under test.
3805 /// Without this a machine that has `~/.codewhale/instructions.md` fails
3806 /// the absolute-path assertion, and the test only passes in parallel
3807 /// runs when a sibling test happens to hold a temporary `HOME` guard at
3808 /// the same moment — process-global env, so the result must never
3809 /// depend on scheduling or the developer's machine.
3810 #[test]
3811 fn system_prompt_prefix_never_leaks_private_content() {
3812 let _env_guard = crate::test_support::lock_test_env();
3813 let tmp = tempdir().expect("tempdir");
3814 let home_tmp = tempdir().expect("home tempdir");
3815 let _home = EnvVarGuard::set("HOME", home_tmp.path().as_os_str());
3816 let _userprofile = EnvVarGuard::set("USERPROFILE", home_tmp.path().as_os_str());
3817 let _skills_dir = EnvVarGuard::remove("DEEPSEEK_SKILLS_DIR");
3818 let workspace = tmp.path();
3819 let prompt = match system_prompt_for_mode_with_context(workspace, None) {
3820 SystemPrompt::Text(text) => text,
3821 SystemPrompt::Blocks(blocks) => blocks
3822 .iter()
3823 .map(|block| block.text.as_str())
3824 .collect::<Vec<_>>()
3825 .join("\n"),
3826 };
3827
3828 // No absolute paths (Unix or Windows).
3829 let offending: Vec<&str> = prompt
3830 .lines()
3831 .filter(|line| {
3832 line.contains("/Users/") || line.contains("/home/") || line.contains("C:\\")
3833 })
3834 .collect();
3835 assert!(
3836 offending.is_empty(),
3837 "system prompt must not contain absolute user paths, found: {offending:?}"
3838 );
3839 // No API key patterns.
3840 assert!(
3841 !prompt.contains("sk-") && !prompt.contains("api_key") && !prompt.contains("API_KEY"),
3842 "system prompt must not contain API key material"
3843 );
3844 // The workspace path itself must not appear.
3845 assert!(
3846 !prompt.contains(workspace.to_str().unwrap_or("/nonexistent")),
3847 "system prompt must not embed the workspace path"
3848 );
3849 }
3850
3851 fn test_tool(name: &str, description: &str) -> Tool {
3852 Tool {
3853 tool_type: Some("function".to_string()),
3854 name: name.to_string(),
3855 description: description.to_string(),
3856 input_schema: serde_json::json!({
3857 "type": "object",
3858 "properties": {"path": {"type": "string"}}
3859 }),
3860 allowed_callers: None,
3861 defer_loading: None,
3862 input_examples: None,
3863 strict: None,
3864 cache_control: None,
3865 }
3866 }
3867
3868 #[test]
3869 fn static_prefix_guard_measures_tool_schemas() {
3870 let prompt = SystemPrompt::Blocks(vec![SystemBlock {
3871 block_type: "text".to_string(),
3872 text: "constitution".to_string(),
3873 cache_control: None,
3874 }]);
3875 let without_tools = super::measure_static_prefix(Some(&prompt), &[]);
3876 let with_tools = super::measure_static_prefix(
3877 Some(&prompt),
3878 &[test_tool("read_file", "Read a file from the workspace")],
3879 );
3880 assert!(
3881 with_tools > without_tools,
3882 "tool schemas are part of the stable prefix ({with_tools} vs {without_tools})"
3883 );
3884 }
3885
3886 #[test]
3887 fn prefix_guard_includes_memory_growth() {
3888 let stable = SystemBlock {
3889 block_type: "text".to_string(),
3890 text: "stable prefix".to_string(),
3891 cache_control: None,
3892 };
3893 let one_block = SystemPrompt::Blocks(vec![stable.clone()]);
3894 let with_volatile = SystemPrompt::Blocks(vec![
3895 stable,
3896 SystemBlock {
3897 block_type: "text".to_string(),
3898 text: "MEMORY_BLOCK ".repeat(2_000),
3899 cache_control: None,
3900 },
3901 ]);
3902 assert!(
3903 super::measure_static_prefix(Some(&with_volatile), &[])
3904 > super::measure_static_prefix(Some(&one_block), &[])
3905 );
3906 }
3907
3908 #[test]
3909 fn configured_instructions_render_inside_the_instruction_block() {
3910 let tmp = tempdir().expect("tempdir");
3911 let workspace = tmp.path();
3912 let present = workspace.join("present.md");
3913 std::fs::write(&present, "CONFIGURED_PRESENT").unwrap();
3914 let empty = workspace.join("empty.md");
3915 std::fs::write(&empty, " \n\n").unwrap();
3916 let missing = workspace.join("missing.md");
3917 let configured = vec![
3918 super::InstructionSource::File(missing),
3919 super::InstructionSource::File(empty),
3920 super::InstructionSource::File(present.clone()),
3921 super::InstructionSource::Inline {
3922 name: "embedded:test".to_string(),
3923 content: "INLINE_PRESENT".to_string(),
3924 },
3925 ];
3926 let mut ctx = crate::project_context::load_project_context_with_parents(workspace);
3927 let budgets = crate::project_context::InstructionBudgets::defaults_for(Some(128_000));
3928 let assembly =
3929 crate::project_context::assemble_instruction_block(&mut ctx, &configured, &budgets);
3930 let block = assembly.block.expect("a block");
3931 assert!(block.contains("CONFIGURED_PRESENT"), "{block}");
3932 assert!(block.contains("INLINE_PRESENT"), "{block}");
3933 assert!(block.contains("source=\"embedded:test\""), "{block}");
3934 let present_at = block.find("CONFIGURED_PRESENT").unwrap();
3935 let inline_at = block.find("INLINE_PRESENT").unwrap();
3936 assert!(present_at < inline_at, "declared order is preserved");
3937 assert!(
3938 assembly
3939 .notices
3940 .iter()
3941 .any(|notice| notice.action == crate::project_context::InstructionAction::Skipped),
3942 "missing and empty entries are reported: {:?}",
3943 assembly.notices
3944 );
3945 }
3946
3947 #[test]
3948 fn instructions_block_stays_out_of_system_prompt_when_configured() {
3949 let tmp = tempdir().expect("tempdir");
3950 let workspace = tmp.path();
3951 let extra = workspace.join("extra-instructions.md");
3952 std::fs::write(&extra, "EXTRA_INSTRUCTIONS_MARKER_BODY").unwrap();
3953
3954 let extra_source: super::InstructionSource = extra.clone().into();
3955 let prompt =
3956 system_prompt_flat_text(&super::system_prompt_for_mode_with_context_and_skills(
3957 workspace,
3958 None,
3959 None,
3960 Some(std::slice::from_ref(&extra_source)),
3961 None,
3962 ));
3963
3964 assert!(
3965 !prompt.contains("EXTRA_INSTRUCTIONS_MARKER_BODY"),
3966 "configured instructions are delivered as history, not in the system prompt"
3967 );
3968 assert!(!prompt.contains(&extra.display().to_string()));
3969 }
3970
3971 #[test]
3972 fn verbosity_concise_adds_no_separate_discipline_block() {
3973 let tmp = tempdir().expect("tempdir");
3974 let workspace = tmp.path();
3975 let prompt = system_prompt_flat_text(
3976 &super::system_prompt_for_mode_with_context_skills_session_and_approval(
3977 workspace,
3978 None,
3979 None,
3980 None,
3981 PromptSessionContext {
3982 user_memory_block: None,
3983 goal_objective: None,
3984 project_context_pack_enabled: false,
3985 locale_tag: "en",
3986 translation_enabled: false,
3987 model_id: "codewhale",
3988 context_window_override: None,
3989 verbosity: Some(" Concise "),
3990 skills_config: Default::default(),
3991 plugin_registry: None,
3992 recovery_hint: None,
3993 mode: AppMode::Agent,
3994 },
3995 ),
3996 );
3997
3998 assert!(
3999 !prompt.contains("## Concise Output Discipline"),
4000 "conciseness is one line of Output Formatting, not a separate block"
4001 );
4002 assert!(prompt.contains("Be concise."));
4003 }
4004
4005 #[test]
4006 fn live_prompt_path_returns_world_state_blocks_with_markers() {
4007 let tmp = tempdir().expect("tempdir");
4008 let prompt = system_prompt_for_mode_with_context_skills_session_and_approval(
4009 tmp.path(),
4010 None,
4011 None,
4012 None,
4013 PromptSessionContext {
4014 user_memory_block: Some("## Memory\n- remember the cutover"),
4015 goal_objective: Some("ship WorldState Blocks"),
4016 project_context_pack_enabled: false,
4017 locale_tag: "en",
4018 translation_enabled: false,
4019 model_id: "deepseek-v4-pro",
4020 context_window_override: None,
4021 verbosity: Some("concise"),
4022 skills_config: Default::default(),
4023 plugin_registry: None,
4024 recovery_hint: None,
4025 mode: AppMode::Agent,
4026 },
4027 );
4028
4029 let SystemPrompt::Blocks(blocks) = prompt else {
4030 panic!("live prompt assembly must return SystemPrompt::Blocks");
4031 };
4032 assert!(
4033 blocks.len() >= 3,
4034 "constitution + at least one WorldState fragment + authority trailer"
4035 );
4036 assert!(
4037 !blocks[0].text.contains("<!-- cw:ctx:"),
4038 "constitution block must stay marker-free for prefix cache stability"
4039 );
4040 assert!(
4041 blocks[0].text.contains("## Core Execution"),
4042 "constitution retains static core execution guidance"
4043 );
4044
4045 let flat = system_prompt_flat_text(&SystemPrompt::Blocks(blocks.clone()));
4046 assert!(flat.contains(codewhale_runtime::model_context::FragmentId::Workspace.marker()));
4047 assert!(flat.contains(codewhale_runtime::model_context::FragmentId::Route.marker()));
4048 assert!(flat.contains("## Environment"));
4049 assert!(
4050 flat.contains("verbosity: concise") && flat.contains("translation: off"),
4051 "route fragment keeps verbosity/translation but drops the model id"
4052 );
4053 assert!(!flat.contains("model: deepseek-v4-pro"));
4054 assert!(flat.contains("<session_goal>"));
4055 assert!(flat.contains("ship WorldState Blocks"));
4056 assert!(flat.contains("remember the cutover"));
4057 assert!(flat.contains("## Authority Recap"));
4058 assert!(
4059 !flat.contains(codewhale_runtime::model_context::FragmentId::SkillsTools.marker()),
4060 "skills remain in constitution, not a volatile SkillsTools fragment"
4061 );
4062 }
4063
4064 #[test]
4065 fn live_prompt_world_state_diff_retains_unchanged_fragments() {
4066 let tmp = tempdir().expect("tempdir");
4067 let session = PromptSessionContext {
4068 user_memory_block: None,
4069 goal_objective: None,
4070 project_context_pack_enabled: false,
4071 locale_tag: "en",
4072 translation_enabled: false,
4073 model_id: "codewhale",
4074 context_window_override: None,
4075 verbosity: None,
4076 skills_config: Default::default(),
4077 plugin_registry: None,
4078 recovery_hint: None,
4079 mode: AppMode::Agent,
4080 };
4081 let first = system_prompt_for_mode_with_context_skills_session_and_approval(
4082 tmp.path(),
4083 None,
4084 None,
4085 None,
4086 session.clone(),
4087 );
4088 let second = system_prompt_for_mode_with_context_skills_session_and_approval(
4089 tmp.path(),
4090 None,
4091 None,
4092 None,
4093 PromptSessionContext {
4094 goal_objective: Some("only goal changed"),
4095 ..session
4096 },
4097 );
4098
4099 let extract_world =
4100 |prompt: &SystemPrompt| -> codewhale_runtime::model_context::WorldState {
4101 let SystemPrompt::Blocks(blocks) = prompt else {
4102 panic!("expected Blocks");
4103 };
4104 let mut state = codewhale_runtime::model_context::WorldState::new();
4105 for block in blocks.iter().skip(1) {
4106 for id in codewhale_runtime::model_context::FragmentId::all() {
4107 let marker = id.marker();
4108 if let Some(rest) = block.text.strip_prefix(marker) {
4109 let body = rest.trim_start_matches('\n');
4110 state.upsert(
4111 codewhale_runtime::model_context::ModelContextFragment::new(
4112 *id,
4113 id.role(),
4114 body,
4115 ),
4116 );
4117 }
4118 }
4119 }
4120 state
4121 };
4122
4123 let previous = extract_world(&first);
4124 let next = extract_world(&second);
4125 let diff = next.render_diff(Some(&previous));
4126 assert!(
4127 diff.retained.iter().any(
4128 |marker| marker == codewhale_runtime::model_context::FragmentId::Route.marker()
4129 ),
4130 "unchanged route fragment must be retained: {diff:?}"
4131 );
4132 assert!(
4133 diff.updated
4134 .iter()
4135 .any(|fragment| fragment.id
4136 == codewhale_runtime::model_context::FragmentId::Workspace),
4137 "goal change must update workspace fragment: {diff:?}"
4138 );
4139 }
4140
4141 #[test]
4142 fn default_prompt_stays_under_2953_static_baseline() {
4143 const ISSUE_2953_BASELINE_CHARS: usize = 30_461;
4144 let prompt = compose_prompt_with_approval_model_and_shell("codewhale");
4145
4146 assert!(
4147 prompt.chars().count() < ISSUE_2953_BASELINE_CHARS,
4148 "default static prompt should stay below the #2953 baseline"
4149 );
4150 }
4151 }
4152 #[test]
4153 fn core_execution_profile_is_runtime_only() {
4154 for required in [
4155 "repository instructions",
4156 "inspect the narrow owner",
4157 "verify it",
4158 "Report changed files",
4159 ] {
4160 assert!(CORE_EXECUTION_PROFILE_PROMPT.contains(required));
4161 }
4162 for forbidden in [
4163 "footer",
4164 "color",
4165 "hotbar",
4166 "panel",
4167 "Fleet",
4168 "Workflow",
4169 "OpenHands",
4170 ] {
4171 assert!(!CORE_EXECUTION_PROFILE_PROMPT.contains(forbidden));
4172 }
4173 }
4174
4174 lines RUST