Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): declare and enforce who may write above the cache line

thinhlpgc2a70bd3b879
diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rs
index f32c42e88..8770eb0d1 100644
--- a/src-tauri/src/core/agent/context.rs
+++ b/src-tauri/src/core/agent/context.rs
@@ -1,12 +1,16 @@
-//! Assembles system-prompt additions from a project's context. Today this is
-//! skill loading: markdown files under `.jan/agent/skills/` concatenated
-//! Claude-style into a single block appended to the agent's system prompt.
+//! Assembles the system prompt from named composers, and decides -- through the
+//! `[prompt]` placement policy -- which of them are allowed to sit above the
+//! cache line.
+//!
+//! Every block of the prompt is a [`Composer`]: one named contributor with a
+//! declared placement and an id the policy can name. [`compose_system_prompt`]
+//! walks the registry, renders each block, and routes it by the resolved
+//! placement, so "who writes above the cache line" is answered by config and by
+//! one exhaustive match rather than by whoever edited the builder last.
use std::path::Path;
-use chrono::Local;
-
-use crate::core::agent::git;
+use crate::core::agent::prompt::{Composer, Placement, PromptPolicy};
use tauri_plugin_agent_tools::{memory, workspace};
/// Default persona used only when no assistant instructions are supplied, so a
@@ -176,11 +180,13 @@ fn display_path(path: &Path) -> String {
}
/// Build a compact runtime environment block injected into the system prompt at
-/// session start so the agent is grounded from turn one. Mirrors the
-/// `<workstation>` / cwd / date context blocks that harnesses like this one
-/// already inject. Fields: working directory, OS/platform/arch, date, shell, and
-/// git state (branch name when the project is inside a git repo). Kept short —
-/// a few lines, not a wall of text.
+/// session start so the agent is grounded from turn one. Fields: working
+/// directory, OS/platform/arch, shell, and scratch space.
+///
+/// Deliberately carries nothing that varies within a session -- today's date and
+/// the current git branch have their own tail composers ([`Composer::Date`] and
+/// [`Composer::GitState`]) -- so this block stays constant for the session and
+/// can sit above the cache line. Kept short: a few lines, not a wall of text.
fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> String {
let cwd = display_path(project_root);
@@ -190,19 +196,10 @@ fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> Str
std::env::consts::ARCH
);
- let now = Local::now();
- let date = now.format("%Y-%m-%d").to_string();
-
let shell = std::env::var("SHELL")
.or_else(|_| std::env::var("COMSPEC"))
.unwrap_or_else(|_| "unknown".to_string());
- let git_branch = git::current_branch(project_root);
- let git_line = match &git_branch {
- Some(branch) => format!("Git branch: `{branch}`"),
- None => "Git: not a git repository (or no commits yet)".to_string(),
- };
-
// Where to do temporary work. Named by the one spelling that resolves from
// both `bash` and the filesystem tools on this platform: `/tmp` where the
// sandbox binds the scratch over it, the real path where nothing is mounted
@@ -220,9 +217,7 @@ fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> Str
"# Runtime Environment\n\n\
Work directory: `{cwd}`\n\
OS: `{os}`\n\
-Date: `{date}`\n\
-Shell: `{shell}`\n\
-{git_line}{scratch_line}"
+Shell: `{shell}`{scratch_line}"
)
}
@@ -251,41 +246,114 @@ pub(crate) fn load_memory_catalog(project_root: &Path) -> Option<String> {
))
}
-/// Assemble the project system prompt: the optional base prompt, the always-on
-/// built-in skills/memory guide, then any project-authored skills. The guide is
-/// always present for project runs, so this never returns None.
-pub(crate) fn build_system_prompt(
+/// Everything the prompt-block composers read.
+struct CompositionInputs<'a> {
+ base: Option<&'a str>,
+ project_root: &'a Path,
+ scratch: Option<&'a Path>,
+ subagents_enabled: bool,
+}
+
+/// The system prompt, split by where the placement policy sent each block.
+#[derive(Debug, Clone)]
+pub(crate) struct ComposedPrompt {
+ /// Above the cache line, in [`Composer::ALL`] order.
+ pub prefix: String,
+ /// The blocks the policy kept below the cache line, each with the composer
+ /// that rendered it so a run can merge its own per-turn blocks and re-sort
+ /// into one deterministic order.
+ pub tail: Vec<(Composer, String)>,
+}
+
+impl ComposedPrompt {
+ /// The whole prompt as one string, prefix first. For callers that only need
+ /// the bytes: the CLI's `/context` sizing, and the tests that assert on
+ /// content rather than placement.
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn as_prompt(&self) -> String {
+ let mut blocks: Vec<&str> = vec![self.prefix.as_str()];
+ blocks.extend(self.tail.iter().map(|(_, block)| block.as_str()));
+ blocks.join("\n\n")
+ }
+}
+
+/// Render one composer's block, or `None` when it has nothing to contribute to
+/// this project (no JAN.md, no skills, no memory notes).
+///
+/// Exhaustive over the registry on purpose: a new composer does not compile
+/// until somebody decides what it writes, which is the same review that decides
+/// where it goes.
+fn render(composer: Composer, inputs: &CompositionInputs) -> Option<String> {
+ match composer {
+ Composer::AssistantInstructions => {
+ Some(inputs.base.unwrap_or(DEFAULT_IDENTITY).to_string())
+ }
+ Composer::Guidelines => Some(GUIDELINES.to_string()),
+ Composer::WorkingDirectory => Some(format!(
+ "# Working Directory\n\nCurrent project directory: `{}`\n\nAll relative paths in tool calls resolve against this directory unless stated otherwise.",
+ inputs.project_root.display()
+ )),
+ Composer::RuntimeEnvironment => {
+ Some(runtime_environment_block(inputs.project_root, inputs.scratch))
+ }
+ Composer::SubagentGuide => inputs.subagents_enabled.then(|| SUBAGENT_GUIDE.to_string()),
+ Composer::SkillGuide => Some(DEFAULT_SKILL_GUIDE.trim().to_string()),
+ Composer::WebToolsGuide => Some(WEB_TOOLS_GUIDE.to_string()),
+ Composer::ProjectContext => load_context_files(inputs.project_root),
+ Composer::Skills => load_skills(inputs.project_root),
+ Composer::MemoryCatalog => load_memory_catalog(inputs.project_root),
+ // Built where the request is assembled, because they need state the
+ // composition has no access to: the tool array is a request field, the
+ // date and git state are the run's own clock and checkout, and the last
+ // three read per-turn state (a query, the todo registry).
+ Composer::ToolSchemas
+ | Composer::Date
+ | Composer::GitState
+ | Composer::MemoryRecall
+ | Composer::PlanAddendum
+ | Composer::TodoAddendum => None,
+ }
+}
+
+/// Assemble the project system prompt through the placement policy: the base
+/// prompt (or the default identity), the always-on guides, the environment, then
+/// any project-authored context, skills, and memory.
+///
+/// Every composer's placement is resolved here, so a policy that cannot be
+/// honored -- a contributor that varies asked to sit above the cache line --
+/// fails the run instead of quietly costing a cache miss per turn. Blocks the
+/// policy sends to the tail are returned rather than dropped: they reach the
+/// model, just below the conversation instead of in front of it.
+pub(crate) fn compose_system_prompt(
base: Option<&str>,
project_root: &Path,
scratch: Option<&Path>,
subagents_enabled: bool,
-) -> Option<String> {
- let mut blocks: Vec<String> = Vec::new();
- match base {
- Some(b) => blocks.push(b.to_string()),
- None => blocks.push(DEFAULT_IDENTITY.to_string()),
- }
- blocks.push(GUIDELINES.to_string());
- blocks.push(format!(
- "# Working Directory\n\nCurrent project directory: `{}`\n\nAll relative paths in tool calls resolve against this directory unless stated otherwise.",
- project_root.display()
- ));
- blocks.push(runtime_environment_block(project_root, scratch));
- if subagents_enabled {
- blocks.push(SUBAGENT_GUIDE.to_string());
- }
- blocks.push(DEFAULT_SKILL_GUIDE.trim().to_string());
- blocks.push(WEB_TOOLS_GUIDE.to_string());
- if let Some(context) = load_context_files(project_root) {
- blocks.push(context);
- }
- if let Some(skills) = load_skills(project_root) {
- blocks.push(skills);
- }
- if let Some(memory) = load_memory_catalog(project_root) {
- blocks.push(memory);
- }
- Some(blocks.join("\n\n"))
+ policy: &PromptPolicy,
+) -> Result<ComposedPrompt, String> {
+ let inputs = CompositionInputs {
+ base,
+ project_root,
+ scratch,
+ subagents_enabled,
+ };
+ policy.validate()?;
+ let mut prefix: Vec<String> = Vec::new();
+ let mut tail: Vec<(Composer, String)> = Vec::new();
+ for composer in Composer::ALL.iter().copied() {
+ let placement = policy.placement_of(composer)?;
+ let Some(block) = render(composer, &inputs) else {
+ continue;
+ };
+ match placement {
+ Placement::Prefix => prefix.push(block),
+ Placement::Tail => tail.push((composer, block)),
+ }
+ }
+ Ok(ComposedPrompt {
+ prefix: prefix.join("\n\n"),
+ tail,
+ })
}
#[cfg(test)]
@@ -294,6 +362,26 @@ mod tests {
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};
+ /// The prompt a project gets with no `[prompt]` policy: every composer where
+ /// the registry declares it should sit, as one string. What the content
+ /// assertions below read; placement itself is asserted on `ComposedPrompt`.
+ fn default_prompt(
+ base: Option<&str>,
+ root: &Path,
+ scratch: Option<&Path>,
+ subagents_enabled: bool,
+ ) -> Option<String> {
+ compose_system_prompt(
+ base,
+ root,
+ scratch,
+ subagents_enabled,
+ &PromptPolicy::default(),
+ )
+ .ok()
+ .map(|composed| composed.as_prompt())
+ }
+
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn scratch_project(tag: &str) -> PathBuf {
@@ -412,7 +500,7 @@ mod tests {
fn build_system_prompt_orders_base_guide_then_skills() {
let root = scratch_project("merge");
write_skill(&root, "s.md", "Do the thing.");
- let out = build_system_prompt(Some("You are Jan."), &root, None, false).expect("prompt");
+ let out = default_prompt(Some("You are Jan."), &root, None, false).expect("prompt");
assert!(out.starts_with("You are Jan."));
assert!(out.contains("Do the thing."));
// Guide sits between the base prompt and the project skills.
@@ -425,7 +513,7 @@ mod tests {
#[test]
fn build_system_prompt_advertises_native_web_tools() {
let root = scratch_project("web");
- let out = build_system_prompt(None, &root, None, false).expect("prompt");
+ let out = default_prompt(None, &root, None, false).expect("prompt");
assert!(out.contains("# Web Access"));
assert!(out.contains("web_search"));
assert!(out.contains("web_fetch"));
@@ -443,13 +531,13 @@ mod tests {
fn build_system_prompt_always_includes_guide() {
let root = scratch_project("guide");
// No base and no project skills: the built-in guide is still injected.
- let out = build_system_prompt(None, &root, None, false).expect("guide always present");
+ let out = default_prompt(None, &root, None, false).expect("guide always present");
assert!(out.contains("Skills and Project Memory"));
assert!(out.contains("skill_write"));
assert!(out.contains("memory_write"));
// Base is preserved and precedes the guide.
- let with_base = build_system_prompt(Some("base"), &root, None, false).expect("prompt");
+ let with_base = default_prompt(Some("base"), &root, None, false).expect("prompt");
assert!(with_base.starts_with("base"));
assert!(with_base.contains("Skills and Project Memory"));
let _ = std::fs::remove_dir_all(&root);
@@ -458,7 +546,7 @@ mod tests {
#[test]
fn default_identity_and_guidelines_present_without_base() {
let root = scratch_project("identity");
- let out = build_system_prompt(None, &root, None, false).expect("prompt");
+ let out = default_prompt(None, &root, None, false).expect("prompt");
assert!(out.starts_with("You're currently running on Jan agent harness"));
assert!(out.contains("# Guidelines"));
assert!(out.contains("Be concise"));
@@ -486,7 +574,7 @@ mod tests {
// Nearest (nested) file wins by appearing last.
assert!(block.find("ROOT_RULES").unwrap() < block.find("NESTED_RULES").unwrap());
- let prompt = build_system_prompt(None, &nested, None, false).expect("prompt");
+ let prompt = default_prompt(None, &nested, None, false).expect("prompt");
// Context files precede the skills catalog position and follow the guide.
assert!(prompt.contains("NESTED_RULES"));
let _ = std::fs::remove_dir_all(&root);
@@ -503,9 +591,9 @@ mod tests {
#[test]
fn build_system_prompt_advertises_subagents_only_when_enabled() {
let root = scratch_project("subagents");
- let without = build_system_prompt(None, &root, None, false).expect("prompt");
+ let without = default_prompt(None, &root, None, false).expect("prompt");
assert!(!without.contains("dispatch_subagent"));
- let with = build_system_prompt(None, &root, None, true).expect("prompt");
+ let with = default_prompt(None, &root, None, true).expect("prompt");
assert!(with.contains("dispatch_subagent"));
let _ = std::fs::remove_dir_all(&root);
}
@@ -516,7 +604,7 @@ mod tests {
#[test]
fn subagent_guide_hands_off_ownership_of_a_delegated_task() {
let root = scratch_project("subagent-handoff");
- let with = build_system_prompt(None, &root, None, true).expect("prompt");
+ let with = default_prompt(None, &root, None, true).expect("prompt");
assert!(with.contains("belongs to that subagent"));
assert!(with.contains("do not do the same work yourself"));
assert!(!with.contains("keep working rather than waiting"));
@@ -533,13 +621,15 @@ mod tests {
// Must be a handful of lines, not a wall of text.
let lines: Vec<_> = block.lines().filter(|l| !l.is_empty()).collect();
assert!(lines.len() <= 15, "env block is too large: {} lines", lines.len());
- // Must contain the key sections.
+ // Must contain the key sections. Today's date and the git branch are
+ // deliberately NOT here: they vary within a session, so they are their
+ // own per-turn composers rather than part of this cache-line block.
assert!(block.contains("# Runtime Environment"));
assert!(block.contains("Work directory:"));
assert!(block.contains("OS:"));
- assert!(block.contains("Date:"));
assert!(block.contains("Shell:"));
- assert!(block.contains("Git:"));
+ assert!(!block.contains("Date:"));
+ assert!(!block.contains("Git:"));
// Must reference actual compile-time constants.
assert!(block.contains(std::env::consts::OS));
assert!(block.contains(std::env::consts::ARCH));
@@ -550,7 +640,7 @@ mod tests {
fn runtime_environment_block_injected_into_system_prompt() {
let root = scratch_project("inject");
std::fs::create_dir_all(&root).unwrap();
- let out = build_system_prompt(None, &root, None, false).expect("prompt");
+ let out = default_prompt(None, &root, None, false).expect("prompt");
assert!(out.contains("# Runtime Environment"));
assert!(out.contains("Work directory:"));
// The block sits right after the Working Directory section.
@@ -561,12 +651,10 @@ mod tests {
}
#[test]
- fn runtime_environment_block_answers_os_date_cwd() {
+ fn runtime_environment_block_answers_os_and_cwd() {
let root = scratch_project("answer");
std::fs::create_dir_all(&root).unwrap();
let block = runtime_environment_block(&root, None);
- // The date field must be a real-looking ISO date.
- assert!(block.contains("Date: `20"), "date should be a 20xx year");
// The OS field must identify the host platform.
assert!(block.contains(format!("OS: `{}", std::env::consts::OS).as_str()));
// Work directory should be present and non-empty.
@@ -574,6 +662,130 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// The date is per-turn content: it belongs in the volatile block, not in
+ /// the stable prefix, or a run that crosses midnight moves every byte behind
+ /// the cache line.
+ #[test]
+ fn the_date_is_a_tail_composer() {
+ let root = scratch_project("date-tail");
+ std::fs::create_dir_all(&root).unwrap();
+ let composed = compose_system_prompt(None, &root, None, false, &PromptPolicy::default())
+ .expect("default policy");
+ assert!(
+ !composed.prefix.contains("Today's date"),
+ "the date must not sit above the cache line: {}",
+ composed.prefix
+ );
+ assert!(
+ composed
+ .tail
+ .iter()
+ .all(|(composer, _)| *composer != Composer::Date),
+ "the date is rendered by the run, not by this composition"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A policy can narrow the prefix: a block it does not allow is emitted below
+ /// the cache line instead of in front of it, so the config decides what a
+ /// provider can cache. The blanket `default` is deliberately hostile here --
+ /// `prefix` -- because a list has to hold whatever it says.
+ #[test]
+ fn a_policy_moves_a_disallowed_block_below_the_cache_line() {
+ let root = scratch_project("narrow");
+ write_skill(&root, "s.md", "Do the thing.");
+ let policy = PromptPolicy::new(
+ Placement::Prefix,
+ Some(vec![
+ "assistant_instructions".to_string(),
+ "guidelines".to_string(),
+ ]),
+ );
+ let composed = compose_system_prompt(None, &root, None, false, &policy).expect("policy");
+
+ assert!(composed.prefix.contains("# Guidelines"));
+ assert!(
+ !composed.prefix.contains("Do the thing."),
+ "a disallowed block must not reach the prefix: {}",
+ composed.prefix
+ );
+ assert!(
+ !composed.prefix.contains("# Web Access"),
+ "a disallowed block must not reach the prefix: {}",
+ composed.prefix
+ );
+ // ...and it still reaches the model, from the tail.
+ let tail: Vec<&str> = composed
+ .tail
+ .iter()
+ .map(|(_, block)| block.as_str())
+ .collect();
+ assert!(tail.iter().any(|block| block.contains("Do the thing.")));
+ assert!(tail.iter().any(|block| block.contains("# Web Access")));
+ assert!(composed.tail.iter().any(|(c, _)| *c == Composer::Skills));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The hard failure, at the composition the run actually goes through: a
+ /// policy that would put a varying composer above the cache line stops the
+ /// run instead of costing a cache miss every turn.
+ #[test]
+ fn a_policy_that_allows_a_varying_composer_fails_composition() {
+ let root = scratch_project("varying");
+ std::fs::create_dir_all(&root).unwrap();
+ let policy = PromptPolicy::new(Placement::Tail, Some(vec!["date".to_string()]));
+ let error = compose_system_prompt(None, &root, None, false, &policy)
+ .expect_err("a per-turn composer cannot be allowed into the prefix");
+ assert!(error.contains("date"), "{error}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// An allowlist that names something that is not a composer is a typo, not a
+ /// silently empty prefix policy.
+ #[test]
+ fn an_unknown_allowlist_entry_fails_composition() {
+ let root = scratch_project("typo");
+ std::fs::create_dir_all(&root).unwrap();
+ let policy = PromptPolicy::new(Placement::Tail, Some(vec!["skils".to_string()]));
+ let error = compose_system_prompt(None, &root, None, false, &policy)
+ .expect_err("an unknown id must not read as a policy");
+ assert!(error.contains("skils"), "{error}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The default policy is today's layout: the same blocks, in the same order,
+ /// in the prefix -- the policy formalizes what the builder already did rather
+ /// than changing it.
+ #[test]
+ fn the_default_policy_keeps_the_prefix_in_registry_order() {
+ let root = scratch_project("order");
+ write_skill(&root, "s.md", "Do the thing.");
+ std::fs::write(root.join("JAN.md"), "PROJECT_RULES").unwrap();
+ let composed = compose_system_prompt(None, &root, None, false, &PromptPolicy::default())
+ .expect("default policy");
+
+ // Every block the registry declares for the prefix is present, in the
+ // order it declares them.
+ let mut cursor = 0;
+ for marker in [
+ "You're currently running on Jan agent harness",
+ "# Guidelines",
+ "# Working Directory",
+ "# Runtime Environment",
+ "# Web Access",
+ "<project_context>",
+ "## Skill: s",
+ ] {
+ let at = composed
+ .prefix
+ .find(marker)
+ .unwrap_or_else(|| panic!("{marker} missing from the prefix"));
+ assert!(at >= cursor, "{marker} is out of order");
+ cursor = at;
+ }
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
/// The scratch must be advertised under the name that resolves from both
/// `bash` and the filesystem tools: `/tmp` where the sandbox binds it there,
/// the real path where nothing is mounted over `/tmp`. Naming the host path
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 9b23b746f..2c5aa8793 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -15,7 +15,9 @@ use reqwest13::Client;
use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, Mutex};
+use crate::core::agent::context::ComposedPrompt;
use crate::core::agent::events::{StreamEvent, Usage};
+use crate::core::agent::prompt::{Composer, Placement, PromptPolicy};
use crate::core::agent::session::SessionBudget;
use crate::core::agent::upstream::{
arguments_are_executable, collect_mcp_openai_tools, copy_optional_chat_params,
@@ -499,6 +501,9 @@ struct ResolvedSettings {
sandbox: bool,
env_passthrough: Vec<String>,
env_set: Vec<(String, String)>,
+ /// `[prompt]`: where each system-prompt composer may sit. Resolved with the
+ /// rest so composition and `agent status` answer from one parse.
+ prompt: PromptPolicy,
}
/// Kept out of the invoker's struct literal so it is reachable from a test.
@@ -516,6 +521,7 @@ fn resolve_run_settings(
sandbox: resolve_sandbox(sandbox_flag, settings.sandbox),
env_passthrough: resolve_env_passthrough(settings.env_passthrough),
env_set: resolve_env_set(settings.env_set),
+ prompt: settings.prompt,
}
}
@@ -2056,10 +2062,16 @@ fn latest_user_text(messages: &[serde_json::Value]) -> Option<String> {
/// Assembles the run's system prompt: `override_prompt` (a subagent's
/// definition prompt) replaces the assistant identity when set, but the
-/// project-context and tool-use guidance from `build_system_prompt` is still
+/// project-context and tool-use guidance from `compose_system_prompt` is still
/// built around it when a project is selected — a subagent gets the same
/// grounding (guidelines, web access, tool docs) as a normal run, not a bare
/// verbatim prompt with no instruction on how to actually use its tools.
+///
+/// The blocks are split by where `[prompt]` allows them to sit, so the caller
+/// places the prefix above the history and the tail below it. A policy that
+/// cannot be honored — a contributor that varies asked to sit above the cache
+/// line — is an error, not a warning: that is the whole point of resolving
+/// placement at composition.
fn build_run_system_prompt(
assistant_instructions: Option<&str>,
override_prompt: Option<&str>,
@@ -2067,7 +2079,8 @@ fn build_run_system_prompt(
session_id: Option<&str>,
subagents_enabled: bool,
sandbox: bool,
-) -> Option<String> {
+ policy: &PromptPolicy,
+) -> Result<Option<ComposedPrompt>, String> {
let base = override_prompt.or(assistant_instructions);
match project_root {
Some(root) => {
@@ -2075,24 +2088,32 @@ fn build_run_system_prompt(
// real `/tmp`, and advertising a scratch nothing binds would send
// the model to a directory only the filesystem tools can see.
let scratch = sandbox.then(|| scratch_root_for(session_id, root));
- crate::core::agent::context::build_system_prompt(
+ crate::core::agent::context::compose_system_prompt(
base,
root,
scratch.as_deref(),
subagents_enabled,
+ policy,
)
+ .map(Some)
}
- None => base.map(str::to_string),
+ None => Ok(base.map(|prompt| ComposedPrompt {
+ prefix: prompt.to_string(),
+ tail: Vec::new(),
+ })),
}
}
/// The system prompt the *next* ordinary turn in `project_root` would carry,
/// built through the exact path a real run takes (`build_run_system_prompt`
-/// with this project's resolved sandbox/scratch). Used by the CLI `/context`
-/// view to size the system segments: routing it through the same builder is
-/// what keeps the reported breakdown from drifting away from what is actually
-/// sent. Excludes the two per-turn additions a run makes on top -- the date
-/// line and query-dependent memory recall -- which are not knowable while idle.
+/// with this project's resolved sandbox/scratch and `[prompt]` policy). Used by
+/// the CLI `/context` view to size the system segments: routing it through the
+/// same builder is what keeps the reported breakdown from drifting away from
+/// what is actually sent. Excludes the per-turn additions a run makes on top --
+/// the date, git state, query-dependent memory recall, and plan/todo state --
+/// which are not knowable while idle. `None` when no prompt would be built, or
+/// when the project's `[prompt]` policy cannot be honored (the run itself
+/// reports that failure with the same message).
#[cfg(feature = "cli")]
pub(crate) fn context_system_prompt_preview(
override_prompt: Option<&str>,
@@ -2102,6 +2123,7 @@ pub(crate) fn context_system_prompt_preview(
sandbox_flag: Option<bool>,
) -> Option<String> {
let settings = resolve_run_settings(project_root, sandbox_flag);
+ let policy = crate::core::agent::project::prompt_policy(project_root);
build_run_system_prompt(
None,
override_prompt,
@@ -2109,7 +2131,11 @@ pub(crate) fn context_system_prompt_preview(
session_id,
subagents_enabled,
settings.sandbox,
+ &policy,
)
+ .ok()
+ .flatten()
+ .map(|composed| composed.as_prompt())
}
/// The tool array the *next* ordinary turn would advertise: the MCP tools
@@ -2155,6 +2181,20 @@ pub(crate) async fn context_advertised_tools(
tools
}
+/// The git state block: which branch the project is on, so the model knows what
+/// its edits apply to.
+///
+/// A per-turn block rather than part of the environment in the stable prefix:
+/// the answer changes the moment anything checks out another branch, including
+/// the agent itself, and a branch switch inside a turn would otherwise move
+/// every byte behind the cache line.
+fn git_state_block(project_root: &std::path::Path) -> String {
+ match crate::core::agent::git::current_branch(project_root) {
+ Some(branch) => format!("# Git\n\nGit branch: `{branch}`"),
+ None => "# Git\n\nGit: not a git repository (or no commits yet)".to_string(),
+ }
+}
+
/// Where this run's scratch lives. Session-keyed so it persists across turns in
/// the interactive TUI (and across calls in a one-shot run), then is wiped at the
/// session boundary. Pure path math -- [`ensure_scratch_dir`] is what creates it
@@ -2308,9 +2348,17 @@ async fn orchestrate_inner(
// the memory catalog. Byte-identical across the turns of a session (within a
// day), so it is kept as system message 0 and never mixed with per-turn
// content -- that is what lets a provider cache this long prefix. Volatile
- // per-turn context (date, query memory recall, plan/todo state) is collected
- // separately below and emitted as a second system message so it cannot
- // invalidate the cached prefix above.
+ // per-turn context (date, git state, query memory recall, plan/todo state)
+ // is collected separately below and emitted as a second system message so it
+ // cannot invalidate the cached prefix above.
+ //
+ // Which blocks land in which half is `[prompt]`'s decision, resolved here:
+ // the composition returns them split rather than joined, and a composer the
+ // policy sends to the tail is emitted below instead of dropped.
+ let prompt_policy = settings
+ .as_ref()
+ .map(|s| s.prompt.clone())
+ .unwrap_or_default();
let stable_system = build_run_system_prompt(
assistant_instructions.as_deref(),
system_prompt_override.as_deref(),
@@ -2318,21 +2366,31 @@ async fn orchestrate_inner(
session_id.as_deref(),
*subagents_enabled,
settings.as_ref().is_some_and(|s| s.sandbox),
- );
+ &prompt_policy,
+ )?;
- let mut volatile_parts: Vec<String> = Vec::new();
+ let mut volatile_parts: Vec<(Composer, String)> = Vec::new();
// Always tell the model today's date, including isolated child runs.
- volatile_parts.push(format!(
- "Today's date is {}.",
- chrono::Local::now().format("%Y-%m-%d")
+ volatile_parts.push((
+ Composer::Date,
+ format!(
+ "Today's date is {}.",
+ chrono::Local::now().format("%Y-%m-%d")
+ ),
));
+ // Which checkout the work applies to. Per-turn rather than part of the
+ // environment block above, because anything that switches branch -- the
+ // agent included -- would otherwise move every byte behind it.
+ if let Some(root) = project_root.as_deref() {
+ volatile_parts.push((Composer::GitState, git_state_block(root)));
+ }
// Normal parent runs recall project memory for the current query before it
// is indexed. Child runs keep their isolated history and skip memory.
if system_prompt_override.is_none() {
if let Some(root) = project_root {
if let Some(query) = latest_user_text(&conversation_messages) {
if let Some(mem) = crate::core::agent::memory::retrieve_block(root, &query) {
- volatile_parts.push(mem);
+ volatile_parts.push((Composer::MemoryRecall, mem));
}
}
}
@@ -2352,18 +2410,53 @@ async fn orchestrate_inner(
&& system_prompt_override.is_none()
&& should_force_goal_todo_plan(goal_mode, todo_registry).await;
if run_mode == crate::core::agent::plan::RunMode::Plan {
- volatile_parts.push(crate::core::agent::plan::plan_mode_prompt_addendum().to_string());
+ volatile_parts.push((
+ Composer::PlanAddendum,
+ crate::core::agent::plan::plan_mode_prompt_addendum().to_string(),
+ ));
} else if let Some(addendum) = todo_prompt_addendum(eager_todo_plan, todo_registry).await {
- volatile_parts.push(addendum.to_string());
- }
-
- if let Some(sys) = stable_system {
- set_system_prompt(&mut conversation_messages, &sys);
- insert_volatile_system(&mut conversation_messages, &volatile_parts.join("\n\n"));
- } else {
+ volatile_parts.push((Composer::TodoAddendum, addendum.to_string()));
+ }
+
+ // One volatile message, built from every block the policy kept below the
+ // cache line: the composition's tail (a block `[prompt]` moved down) plus
+ // the per-turn blocks above, in registry order so the message's bytes do
+ // not depend on which caller built which block.
+ let mut tail: Vec<(Composer, String)> = stable_system
+ .as_ref()
+ .map(|composed| composed.tail.clone())
+ .unwrap_or_default();
+ for (composer, block) in volatile_parts {
+ if prompt_policy.placement_of(composer)? != Placement::Tail {
+ // Unreachable while these composers vary -- `placement_of` fails
+ // first -- and kept as an explicit error rather than a silent
+ // unwrap, because "per-turn content above the cache line" is
+ // exactly the bug this whole policy exists to prevent.
+ return Err(format!(
+ "`{}` is per-turn content and cannot sit above the cache line",
+ composer.id()
+ ));
+ }
+ tail.push((composer, block));
+ }
+ tail.sort_by_key(|(composer, _)| composer.order());
+ let volatile_block = tail
+ .into_iter()
+ .map(|(_, block)| block)
+ .collect::<Vec<_>>()
+ .join("\n\n");
+
+ match &stable_system {
+ // An allowlist can move every block below the cache line, which leaves
+ // no stable prompt at all: the volatile block then stands in as
+ // message 0 rather than an empty system node preceding it.
+ Some(composed) if !composed.prefix.is_empty() => {
+ set_system_prompt(&mut conversation_messages, &composed.prefix);
+ insert_volatile_system(&mut conversation_messages, &volatile_block);
+ }
// No stable prompt (an isolated child run with no override): the
// volatile block is all there is, so it stands in as message 0.
- set_system_prompt(&mut conversation_messages, &volatile_parts.join("\n\n"));
+ _ => set_system_prompt(&mut conversation_messages, &volatile_block),
}
// Paired with the addendum above: force the model's very first tool call
// to actually be `todo` rather than leaving compliance up to a prompt it
@@ -3778,8 +3871,11 @@ mod tests {
Some("test-session"),
false,
true,
+ &PromptPolicy::default(),
)
- .expect("prompt");
+ .expect("prompt")
+ .expect("project prompt")
+ .as_prompt();
assert!(prompt.starts_with("You are a robotics researcher."));
assert!(!prompt.contains("main assistant"));
@@ -3790,6 +3886,88 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ /// `[prompt]` in agent.toml is what decides which blocks reach the cache
+ /// line: the run resolves the policy from the project's config and composes
+ /// through it, so an allowlist naming two contributors really does move the
+ /// rest below the line.
+ #[test]
+ #[cfg(feature = "cli")]
+ fn agent_toml_narrows_what_reaches_the_cache_line() {
+ let root = unique_project_root();
+ let agent_dir = root.join(".jan").join("agent");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ std::fs::write(
+ agent_dir.join("agent.toml"),
+ "[prompt]\nprefix_allow = [\"assistant_instructions\", \"tool_schemas\"]\n",
+ )
+ .expect("agent.toml");
+
+ let policy = crate::core::agent::project::prompt_policy(&root);
+ assert_eq!(policy.prefix_allow().map(<[String]>::len), Some(2));
+ // ...and the run's resolved settings carry the same policy, which is
+ // what `orchestrate_inner` composes with.
+ assert_eq!(
+ resolve_run_settings(&root, None)
+ .prompt
+ .prefix_allow()
+ .map(<[String]>::len),
+ Some(2)
+ );
+ let composed = build_run_system_prompt(
+ Some("main assistant"),
+ None,
+ Some(&root),
+ Some("s1"),
+ false,
+ false,
+ &policy,
+ )
+ .expect("prompt")
+ .expect("project prompt");
+
+ // Only the identity is allowed above the line...
+ assert_eq!(composed.prefix, "main assistant");
+ // ...and everything else still reaches the model, from the tail.
+ let tail: Vec<&str> = composed
+ .tail
+ .iter()
+ .map(|(_, block)| block.as_str())
+ .collect();
+ assert!(tail.iter().any(|block| block.contains("# Guidelines")));
+ assert!(tail.iter().any(|block| block.contains("# Web Access")));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// An allowlist that would put a varying composer above the cache line stops
+ /// the run, rather than costing a cache miss on every turn. The failure is
+ /// the same one `agent status` reports, from the same resolution.
+ #[test]
+ #[cfg(feature = "cli")]
+ fn agent_toml_that_allows_a_varying_composer_fails_the_run() {
+ let root = unique_project_root();
+ let agent_dir = root.join(".jan").join("agent");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ std::fs::write(
+ agent_dir.join("agent.toml"),
+ "[prompt]\nprefix_allow = [\"todo_addendum\"]\n",
+ )
+ .expect("agent.toml");
+
+ let policy = crate::core::agent::project::prompt_policy(&root);
+ let error = build_run_system_prompt(
+ Some("main assistant"),
+ None,
+ Some(&root),
+ Some("s1"),
+ false,
+ false,
+ &policy,
+ )
+ .expect_err("a per-turn composer cannot be allowed above the cache line");
+ assert!(error.contains("todo_addendum"), "{error}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
fn tool_call_completion() -> serde_json::Value {
json!({
"choices": [{
@@ -6566,8 +6744,11 @@ mod tests {
Some("s1"),
false,
true,
+ &PromptPolicy::default(),
)
- .expect("prompt");
+ .expect("prompt")
+ .expect("project prompt")
+ .as_prompt();
assert!(confined.contains("Scratch:"), "{confined}");
let bare = build_run_system_prompt(
None,
@@ -6576,8 +6757,11 @@ mod tests {
Some("s1"),
false,
false,
+ &PromptPolicy::default(),
)
- .expect("prompt");
+ .expect("prompt")
+ .expect("project prompt")
+ .as_prompt();
assert!(!bare.contains("Scratch:"), "{bare}");
}
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 6f44c1cad..1646acae2 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -31,6 +31,7 @@ pub mod plan;
pub mod plugin_commands;
pub mod plugins;
pub mod project;
+pub mod prompt;
pub mod reminder;
pub mod session;
pub mod skill_hub;
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 6df61cf4d..aab12a01d 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -5,6 +5,7 @@ use std::path::{Path, PathBuf};
use serde::Deserialize;
+use crate::core::agent::prompt::{Placement, PromptPolicy};
use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};
/// `[tools]`/`[skills]` are always modeled. `[agent]` and `[budget]` are only
@@ -23,6 +24,8 @@ pub(crate) struct AgentToml {
#[serde(default)]
pub tools: ToolsSection,
#[serde(default)]
+ pub prompt: PromptSection,
+ #[serde(default)]
pub skills: SkillsSection,
#[serde(default)]
pub plugins: PluginsSection,
@@ -33,6 +36,24 @@ pub(crate) struct AgentToml {
pub hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,
}
+/// `[prompt]` — where each contributor to the system prompt may sit. Deny-wins,
+/// like `[tools]`: nothing reaches the cache line without being allowed there,
+/// and the safe answer for a composer no policy mentions is the tail.
+#[derive(Debug, Clone, Default, Deserialize)]
+pub(crate) struct PromptSection {
+ /// Placement for a composer no policy mentions, `tail` by default. A
+ /// composer that varies within a session stays in the tail whatever this
+ /// says: the constancy rule outranks it.
+ #[serde(default)]
+ pub default: Placement,
+ /// Composer ids allowed above the cache line (`assistant_instructions`,
+ /// `skills`, ...). Unset keeps each composer's own placement; setting it
+ /// narrows the prefix to exactly the ids listed. An unknown id is an error,
+ /// not a silent no-op.
+ #[serde(default)]
+ pub prefix_allow: Option<Vec<String>>,
+}
+
/// `[plugins]` — plugin installs and marketplace. Installed plugins live in
/// `.jan/agent/plugins/`; this section only carries configuration.
#[derive(Debug, Clone, Default, Deserialize)]
@@ -269,6 +290,23 @@ allow_write = []
enabled = []
# always | relevance
inject = "always"
+
+# Where each contributor to the system prompt may sit, deny-wins like [tools].
+# Above the cache line ("prefix") a contributor must be constant for the whole
+# session: a provider only reuses a prefix whose bytes are identical to the
+# previous request, so per-turn content belongs in the tail. `jan cli agent
+# status` prints the resolved placement of every contributor.
+[prompt]
+# Unset keeps each composer's own placement. Setting it narrows the prefix to
+# exactly the ids listed -- everything else moves below the cache line whatever
+# it asks for. Ids: assistant_instructions, guidelines, working_directory,
+# runtime_environment, subagent_guide, skill_guide, web_tools_guide,
+# project_context, skills, memory_catalog, tool_schemas (the tool array is a
+# request field and is always above the cache line).
+# prefix_allow = ["assistant_instructions", "guidelines", "skills", "tool_schemas"]
+# Placement for a composer no policy mentions: tail (the default) or prefix.
+# A composer that varies within a session stays in the tail regardless.
+# default = "tail"
"#;
/// Path to `<project_root>/.jan/agent/agent.toml`.
@@ -307,6 +345,9 @@ pub(crate) struct RunSettings {
pub env_passthrough: Vec<String>,
/// `[tools].env_set`: explicit shell-env overrides, sorted by key.
pub env_set: Vec<(String, String)>,
+ /// `[prompt]`: where each system-prompt composer may sit. Resolved here so
+ /// composition and `agent status` answer the same question from one parse.
+ pub prompt: PromptPolicy,
/// `[agent].worktree`: give each session its own git checkout. Merged with
/// the global setting and the `--worktree` flag by the caller. CLI-only,
/// like the `[agent]` section it comes from.
@@ -327,6 +368,7 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {
sandbox: cfg.tools.sandbox,
env_passthrough: cfg.tools.env_passthrough,
env_set: cfg.tools.env_set.into_iter().collect(),
+ prompt: PromptPolicy::new(cfg.prompt.default, cfg.prompt.prefix_allow),
#[cfg(feature = "cli")]
worktree: cfg.agent.worktree,
}
@@ -336,6 +378,15 @@ pub(crate) fn enabled_skills(project_root: &Path) -> Vec<String> {
run_settings(project_root).enabled_skills
}
+/// The `[prompt]` placement policy for `project_root`, or the defaults when the
+/// project has no agent.toml. A thin read of [`run_settings`] for the callers
+/// that need only this: the status report and the `/context` sizing. Both are
+/// CLI surfaces, hence the desktop-build allowance.
+#[cfg_attr(not(feature = "cli"), allow(dead_code))]
+pub(crate) fn prompt_policy(project_root: &Path) -> PromptPolicy {
+ run_settings(project_root).prompt
+}
+
/// Build a `ToolPermissions` from the parsed `[tools]` section.
///
/// CLI-only: the desktop no longer runs the agent loop in Rust, so its tool
@@ -467,6 +518,7 @@ pub(crate) fn set_skills_enabled_in_agent_toml(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::core::agent::prompt::Composer;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -601,6 +653,60 @@ mod tests {
ensure_project(&root).expect("scaffold");
let cfg = load_agent_config(&root).expect("load");
assert_eq!(cfg.tools.default.as_deref(), Some("read-only"));
+ // The scaffolded `[prompt]` section is all comments: the defaults it
+ // documents are what a fresh project gets.
+ assert_eq!(cfg.prompt.default, Placement::Tail);
+ assert_eq!(cfg.prompt.prefix_allow, None);
+ assert!(AGENT_TOML_TEMPLATE.contains("[prompt]"));
+ assert!(AGENT_TOML_TEMPLATE.contains("prefix_allow"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn prompt_policy_defaults_to_the_declared_placements() {
+ let root = unique_root("prompt_default");
+ write_agent_toml(&root, "[skills]\nenabled = []\n");
+ let policy = prompt_policy(&root);
+ assert_eq!(policy.default_placement(), Placement::Tail);
+ assert_eq!(
+ policy.prefix_allow(),
+ None,
+ "an absent allowlist keeps each composer's own placement"
+ );
+ assert_eq!(
+ policy.placement_of(Composer::Skills).unwrap(),
+ Placement::Prefix
+ );
+ assert_eq!(
+ policy.placement_of(Composer::Date).unwrap(),
+ Placement::Tail
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn prompt_policy_reads_the_allowlist_and_the_default() {
+ let root = unique_root("prompt_allow");
+ write_agent_toml(
+ &root,
+ "[prompt]\ndefault = \"tail\"\nprefix_allow = [\"assistant_instructions\"]\n",
+ );
+ let policy = prompt_policy(&root);
+ assert_eq!(
+ policy.prefix_allow(),
+ Some(&["assistant_instructions".to_string()][..])
+ );
+ assert_eq!(
+ policy
+ .placement_of(Composer::AssistantInstructions)
+ .unwrap(),
+ Placement::Prefix
+ );
+ assert_eq!(
+ policy.placement_of(Composer::Skills).unwrap(),
+ Placement::Tail,
+ "the allowlist denies a declared-prefix composer it does not name"
+ );
let _ = std::fs::remove_dir_all(&root);
}
diff --git a/src-tauri/src/core/agent/prompt.rs b/src-tauri/src/core/agent/prompt.rs
new file mode 100644
index 000000000..d2958e6e1
--- /dev/null
+++ b/src-tauri/src/core/agent/prompt.rs
@@ -0,0 +1,537 @@
+//! Who may write above the cache line, and who decides.
+//!
+//! A request's reusable region is its *leading* bytes: a provider reuses the
+//! prefix it has already seen only while every byte of it is identical to the
+//! previous request. Everything that contributes to a request's front --
+//! identity, guidelines, the skill and memory catalogs, the advertised tool
+//! array -- therefore shares one cache line, and one contributor that changes
+//! per turn invalidates every byte behind it.
+//!
+//! That failure is compositional: each contributor is locally correct, and no
+//! single one of them is obviously the culprit. So placement here is declared
+//! rather than conventional:
+//!
+//! - every contribution is a named [`Composer`], enumerated once, in code;
+//! - a composer that declares nothing lands in the tail -- the safe answer, and
+//! the one a new composer gets for free;
+//! - a composer that is not constant for the session can never sit above the
+//! cache line, and a policy that would put it there fails loudly instead of
+//! costing money quietly;
+//! - `[prompt].prefix_allow` can only *narrow* what sits above the line. Moving
+//! something into the prefix is a code change, where "is this constant for a
+//! session" can actually be reviewed.
+
+use serde::Deserialize;
+
+/// Where a composer's contribution sits relative to the cache line.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub(crate) enum Placement {
+ /// Above the cache line: part of the leading bytes a provider can reuse.
+ /// Only for content that is constant for the whole session.
+ Prefix,
+ /// Below the accepted history: free to change every turn. The default,
+ /// because a composer has to argue its way into the prefix, not out of it.
+ #[default]
+ Tail,
+}
+
+impl Placement {
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Placement::Prefix => "prefix",
+ Placement::Tail => "tail",
+ }
+ }
+}
+
+/// How a composer's content reaches the request.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Source {
+ /// A block of the system prompt, placed by [`PromptPolicy`].
+ PromptBlock,
+ /// A request field outside the prompt: the advertised tool array. The wire
+ /// format has no tail for it, so it is always above the cache line and the
+ /// allowlist does not apply to it.
+ RequestField,
+}
+
+impl Source {
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Source::PromptBlock => "prompt",
+ Source::RequestField => "request_field",
+ }
+ }
+}
+
+/// Every contribution to the front of a request, as the code declares it.
+///
+/// This enum *is* the registry: [`Composer::ALL`] enumerates it, `agent status`
+/// reports it, and the composition in [`crate::core::agent::context`] matches on
+/// it exhaustively -- so adding a contributor without deciding its placement
+/// does not compile.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Composer {
+ // Above the cache line today.
+ AssistantInstructions,
+ Guidelines,
+ WorkingDirectory,
+ RuntimeEnvironment,
+ SubagentGuide,
+ SkillGuide,
+ WebToolsGuide,
+ ProjectContext,
+ Skills,
+ MemoryCatalog,
+ ToolSchemas,
+ // Below it today: per-turn content, so they can never be in the prefix.
+ Date,
+ GitState,
+ MemoryRecall,
+ PlanAddendum,
+ TodoAddendum,
+}
+
+impl Composer {
+ /// Every composer, in the order their blocks enter the prompt.
+ pub(crate) const ALL: &'static [Composer] = &[
+ Composer::AssistantInstructions,
+ Composer::Guidelines,
+ Composer::WorkingDirectory,
+ Composer::RuntimeEnvironment,
+ Composer::SubagentGuide,
+ Composer::SkillGuide,
+ Composer::WebToolsGuide,
+ Composer::ProjectContext,
+ Composer::Skills,
+ Composer::MemoryCatalog,
+ Composer::ToolSchemas,
+ Composer::Date,
+ Composer::GitState,
+ Composer::MemoryRecall,
+ Composer::PlanAddendum,
+ Composer::TodoAddendum,
+ ];
+
+ /// The stable id: what `[prompt].prefix_allow` names and `agent status`
+ /// prints.
+ pub(crate) fn id(self) -> &'static str {
+ match self {
+ Composer::AssistantInstructions => "assistant_instructions",
+ Composer::Guidelines => "guidelines",
+ Composer::WorkingDirectory => "working_directory",
+ Composer::RuntimeEnvironment => "runtime_environment",
+ Composer::SubagentGuide => "subagent_guide",
+ Composer::SkillGuide => "skill_guide",
+ Composer::WebToolsGuide => "web_tools_guide",
+ Composer::ProjectContext => "project_context",
+ Composer::Skills => "skills",
+ Composer::MemoryCatalog => "memory_catalog",
+ Composer::ToolSchemas => "tool_schemas",
+ Composer::Date => "date",
+ Composer::GitState => "git_state",
+ Composer::MemoryRecall => "memory_recall",
+ Composer::PlanAddendum => "plan_addendum",
+ Composer::TodoAddendum => "todo_addendum",
+ }
+ }
+
+ /// One line for `agent status` and the docs. Reported by the CLI's status
+ /// command only, hence the desktop-build allowance.
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn what(self) -> &'static str {
+ match self {
+ Composer::AssistantInstructions => {
+ "the assistant's instructions, or the default identity"
+ }
+ Composer::Guidelines => "the always-on behavioral guidelines",
+ Composer::WorkingDirectory => "the project directory relative paths resolve against",
+ Composer::RuntimeEnvironment => "OS, architecture, shell, and scratch space",
+ Composer::SubagentGuide => "how to delegate context-heavy exploration",
+ Composer::SkillGuide => "the skills and memory file conventions",
+ Composer::WebToolsGuide => "the native web tools and when to reach for them",
+ Composer::ProjectContext => "JAN.md, from the project and its ancestors",
+ Composer::Skills => "the installed skill catalog",
+ Composer::MemoryCatalog => "the curated memory note catalog",
+ Composer::ToolSchemas => "the advertised tool array (a request field)",
+ Composer::Date => "today's date",
+ Composer::GitState => "the current git branch",
+ Composer::MemoryRecall => "memory recalled for this request",
+ Composer::PlanAddendum => "the plan-mode instructions",
+ Composer::TodoAddendum => "the active todo list",
+ }
+ }
+
+ pub(crate) fn source(self) -> Source {
+ match self {
+ Composer::ToolSchemas => Source::RequestField,
+ _ => Source::PromptBlock,
+ }
+ }
+
+ /// The placement this composer asks for. `None` means "no request": the
+ /// policy default applies, which is the tail.
+ pub(crate) fn declared(self) -> Option<Placement> {
+ match self {
+ Composer::AssistantInstructions
+ | Composer::Guidelines
+ | Composer::WorkingDirectory
+ | Composer::RuntimeEnvironment
+ | Composer::SubagentGuide
+ | Composer::SkillGuide
+ | Composer::WebToolsGuide
+ | Composer::ProjectContext
+ | Composer::Skills
+ | Composer::MemoryCatalog
+ | Composer::ToolSchemas => Some(Placement::Prefix),
+ Composer::Date
+ | Composer::GitState
+ | Composer::MemoryRecall
+ | Composer::PlanAddendum
+ | Composer::TodoAddendum => None,
+ }
+ }
+
+ /// Whether this composer's content is constant for a session.
+ ///
+ /// A composer that reads the clock, the branch, the query, or the todo list
+ /// is not, and cannot sit above the cache line: it would break the prefix
+ /// on the turn its value changed. Composition happens once per run, so a
+ /// composer that reads the project directory is constant *within a run* --
+ /// which is what "for a session" means here.
+ pub(crate) fn constant(self) -> bool {
+ match self {
+ Composer::AssistantInstructions
+ | Composer::Guidelines
+ | Composer::WorkingDirectory
+ | Composer::RuntimeEnvironment
+ | Composer::SubagentGuide
+ | Composer::SkillGuide
+ | Composer::WebToolsGuide
+ | Composer::ProjectContext
+ | Composer::Skills
+ | Composer::MemoryCatalog
+ | Composer::ToolSchemas => true,
+ Composer::Date
+ | Composer::GitState
+ | Composer::MemoryRecall
+ | Composer::PlanAddendum
+ | Composer::TodoAddendum => false,
+ }
+ }
+
+ /// Look a composer up by its id, as `[prompt].prefix_allow` and the status
+ /// report spell it.
+ pub(crate) fn from_id(id: &str) -> Option<Composer> {
+ Composer::ALL.iter().copied().find(|c| c.id() == id)
+ }
+
+ /// This composer's position in [`Composer::ALL`]: the order its block
+ /// appears in the prompt. Used to merge blocks built by different callers
+ /// into one deterministic sequence.
+ pub(crate) fn order(self) -> usize {
+ Composer::ALL
+ .iter()
+ .position(|composer| *composer == self)
+ .unwrap_or(usize::MAX)
+ }
+}
+
+/// The resolved `[prompt]` policy: where each composer's content may go.
+#[derive(Debug, Clone, Default)]
+pub(crate) struct PromptPolicy {
+ default: Placement,
+ /// `None` when `prefix_allow` is absent, i.e. each composer's own
+ /// declaration stands. `Some(list)` narrows the prefix to exactly the
+ /// listed ids.
+ prefix_allow: Option<Vec<String>>,
+}
+
+impl PromptPolicy {
+ pub(crate) fn new(default: Placement, prefix_allow: Option<Vec<String>>) -> Self {
+ Self {
+ default,
+ prefix_allow,
+ }
+ }
+
+ /// The placement for a composer the policy does not mention. Reported by
+ /// the CLI's status command only.
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn default_placement(&self) -> Placement {
+ self.default
+ }
+
+ /// The configured allowlist, when it is set. Reported by the CLI's status
+ /// command only.
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn prefix_allow(&self) -> Option<&[String]> {
+ self.prefix_allow.as_deref()
+ }
+
+ /// Reject an allowlist that names something that is not a composer: a typo
+ /// would otherwise move a contributor to the tail (or read as an empty
+ /// prefix policy) instead of saying what is wrong.
+ pub(crate) fn validate(&self) -> Result<(), String> {
+ let Some(allow) = &self.prefix_allow else {
+ return Ok(());
+ };
+ let unknown: Vec<&str> = allow
+ .iter()
+ .filter(|id| Composer::from_id(id).is_none())
+ .map(String::as_str)
+ .collect();
+ if unknown.is_empty() {
+ return Ok(());
+ }
+ let registered: Vec<&str> = Composer::ALL.iter().map(|c| c.id()).collect();
+ Err(format!(
+ "`[prompt].prefix_allow` names no such composer: {}. Registered composers: {}.",
+ unknown.join(", "),
+ registered.join(", ")
+ ))
+ }
+
+ /// Whether the operator explicitly allowed this composer above the cache
+ /// line (as opposed to it being there by its own declaration).
+ pub(crate) fn explicitly_allowed(&self, composer: Composer) -> bool {
+ self.prefix_allow
+ .as_ref()
+ .is_some_and(|allow| allow.iter().any(|id| id == composer.id()))
+ }
+
+ /// Where `composer`'s content goes, or why the policy cannot be honored.
+ ///
+ /// A hard failure, not a warning: the whole point is that a contributor
+ /// which varies cannot quietly reach the cache line. The two ways to ask
+ /// for that are a composer that declares `prefix` while varying (a code
+ /// bug) and a `[prompt].prefix_allow` that names one (a config bug).
+ pub(crate) fn placement_of(&self, composer: Composer) -> Result<Placement, String> {
+ // A request field is not a prompt block: the wire format has no tail
+ // for it, so no policy can move it and the allowlist does not apply.
+ if composer.source() == Source::RequestField {
+ return Ok(Placement::Prefix);
+ }
+ if !composer.constant() {
+ if composer.declared() == Some(Placement::Prefix) {
+ return Err(format!(
+ "`{}` is declared above the cache line but its content is not constant for a session. \
+ A composer that varies would break the cached prefix on the turn its value changed: \
+ declare it in the tail (see Composer::declared), or make it constant.",
+ composer.id()
+ ));
+ }
+ if self.explicitly_allowed(composer) {
+ return Err(format!(
+ "`[prompt].prefix_allow` lists `{}`, which varies within a session. Only a composer \
+ that is constant for the session can sit above the cache line; remove it from the list.",
+ composer.id()
+ ));
+ }
+ return Ok(Placement::Tail);
+ }
+ Ok(if self.prefix_allow.is_some() {
+ // An allowlist is the whole answer, not a starting point: what it
+ // names sits above the line and everything else sits below it,
+ // whatever the composer declared and whatever `default` says. It
+ // narrows; it cannot widen.
+ if self.explicitly_allowed(composer) {
+ Placement::Prefix
+ } else {
+ Placement::Tail
+ }
+ } else {
+ // No list: the composer's own declaration decides, and `default`
+ // answers for one the code does not classify.
+ composer.declared().unwrap_or(self.default)
+ })
+ }
+
+ /// Every composer's resolved placement, for `jan cli agent status` and the
+ /// `[prompt]` docs. Fails on the same contradiction composition would.
+ #[cfg_attr(not(feature = "cli"), allow(dead_code))]
+ pub(crate) fn placements(&self) -> Result<Vec<(Composer, Placement)>, String> {
+ self.validate()?;
+ Composer::ALL
+ .iter()
+ .copied()
+ .map(|composer| self.placement_of(composer).map(|p| (composer, p)))
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn an_undeclared_composer_takes_the_policy_default() {
+ // A composer that asks for nothing is the case a new contributor
+ // starts from: the default policy puts it in the tail, so a new writer
+ // is safe before anybody reviews it.
+ let policy = PromptPolicy::default();
+ assert_eq!(Placement::default(), Placement::Tail);
+ assert_eq!(Composer::Date.declared(), None);
+ assert_eq!(
+ policy.placement_of(Composer::Date).unwrap(),
+ Placement::Tail
+ );
+ }
+
+ #[test]
+ fn an_undeclared_composer_stays_in_the_tail_even_under_a_blanket_prefix_default() {
+ // `default` is a blanket answer, but the constancy rule outranks it:
+ // a composer that varies is demoted rather than allowed to break the
+ // prefix on the turn it changes.
+ let policy = PromptPolicy::new(Placement::Prefix, None);
+ assert_eq!(
+ policy.placement_of(Composer::Date).unwrap(),
+ Placement::Tail
+ );
+ assert_eq!(
+ policy.placement_of(Composer::Guidelines).unwrap(),
+ Placement::Prefix
+ );
+ }
+
+ #[test]
+ fn a_declared_prefix_composer_sits_in_the_prefix_by_default() {
+ let policy = PromptPolicy::default();
+ for composer in Composer::ALL.iter().copied().filter(|c| c.constant()) {
+ assert_eq!(
+ policy.placement_of(composer).unwrap(),
+ Placement::Prefix,
+ "{} declares the prefix",
+ composer.id()
+ );
+ }
+ }
+
+ #[test]
+ fn the_allowlist_narrows_the_prefix_and_denies_win() {
+ // The case the issue is about: an operator lists the two contributors
+ // they trust above the cache line, and everything else moves below it
+ // whatever it asked for.
+ let policy = PromptPolicy::new(
+ Placement::Tail,
+ Some(vec!["assistant_instructions".to_string()]),
+ );
+ assert_eq!(
+ policy
+ .placement_of(Composer::AssistantInstructions)
+ .unwrap(),
+ Placement::Prefix
+ );
+ assert_eq!(
+ policy.placement_of(Composer::Skills).unwrap(),
+ Placement::Tail,
+ "a declared-prefix composer is denied by an allowlist that omits it"
+ );
+ }
+
+ #[test]
+ fn the_allowlist_is_exhaustive_even_when_the_default_asks_for_the_prefix() {
+ // `default` answers for a composer the code does not classify. It must
+ // not re-open a narrowed prefix: listing one contributor while leaving
+ // `default = "prefix"` would otherwise keep every other declared
+ // contributor above the cache line -- the silent widening the
+ // allowlist exists to prevent.
+ let policy = PromptPolicy::new(
+ Placement::Prefix,
+ Some(vec!["assistant_instructions".to_string()]),
+ );
+ assert_eq!(
+ policy
+ .placement_of(Composer::AssistantInstructions)
+ .unwrap(),
+ Placement::Prefix
+ );
+ assert_eq!(
+ policy.placement_of(Composer::Guidelines).unwrap(),
+ Placement::Tail,
+ "the list is exhaustive: a composer it omits is below the line"
+ );
+ assert_eq!(
+ policy.placement_of(Composer::ProjectContext).unwrap(),
+ Placement::Tail
+ );
+ assert_eq!(
+ policy.placement_of(Composer::ToolSchemas).unwrap(),
+ Placement::Prefix,
+ "a request field has no tail to move to"
+ );
+ }
+
+ #[test]
+ fn allowing_a_composer_that_varies_is_a_hard_failure() {
+ let policy = PromptPolicy::new(Placement::Tail, Some(vec!["date".to_string()]));
+ let error = policy
+ .placement_of(Composer::Date)
+ .expect_err("a per-turn composer cannot be allowed into the prefix");
+ assert!(error.contains("date"), "{error}");
+ assert!(error.contains("prefix_allow"), "{error}");
+ // ...and the failure is reported for the policy as a whole, so a run
+ // cannot start without resolving every composer.
+ assert!(policy.placements().is_err());
+ }
+
+ #[test]
+ fn the_tool_array_cannot_be_moved_out_of_the_prefix() {
+ // It is a request field, not a prompt block: `prefix_allow` governs
+ // prompt blocks, and the wire format has no tail for tools.
+ let policy = PromptPolicy::new(Placement::Tail, Some(vec!["guidelines".to_string()]));
+ assert_eq!(
+ policy.placement_of(Composer::ToolSchemas).unwrap(),
+ Placement::Prefix
+ );
+ }
+
+ #[test]
+ fn composer_ids_are_unique_and_resolvable() {
+ let mut ids: Vec<&str> = Composer::ALL.iter().map(|c| c.id()).collect();
+ let count = ids.len();
+ ids.sort_unstable();
+ ids.dedup();
+ assert_eq!(
+ ids.len(),
+ count,
+ "ids name composers in config: no duplicates"
+ );
+ for composer in Composer::ALL {
+ assert_eq!(Composer::from_id(composer.id()), Some(*composer));
+ }
+ assert_eq!(Composer::from_id("nope"), None);
+ }
+
+ #[test]
+ fn every_composer_is_classified() {
+ // The registry's whole job is that nothing is unclassified: a constant
+ // composer has to say where it goes, and a varying one has to be
+ // reported as varying.
+ for composer in Composer::ALL.iter().copied() {
+ if composer.constant() {
+ assert!(
+ composer.declared().is_some(),
+ "{} is constant, so it must declare a placement",
+ composer.id()
+ );
+ } else {
+ assert_eq!(
+ composer.declared(),
+ None,
+ "{} varies, so it cannot request the prefix",
+ composer.id()
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn placements_cover_every_composer() {
+ let resolved = PromptPolicy::default().placements().unwrap();
+ assert_eq!(resolved.len(), Composer::ALL.len());
+ }
+}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 93499f48d..191207c0b 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -771,6 +771,26 @@ pub fn cli_agent_status(
let cfg = load_agent_config(&project_root)?;
let provider_configs = load_provider_configs(Some(&project_root), overrides)?;
+ // Resolved once, and reported for every registered composer: "which of my
+ // contributors is writing into the cached prefix" is one command, not an
+ // investigation. An unusable `[prompt]` policy (an allowlist naming
+ // something that varies, or a typo) fails here with the same message
+ // composition would give.
+ let prompt_policy = crate::core::agent::project::prompt_policy(&project_root);
+ let prompt_components: Vec<serde_json::Value> = prompt_policy
+ .placements()?
+ .into_iter()
+ .map(|(composer, placement)| {
+ serde_json::json!({
+ "id": composer.id(),
+ "placement": placement.as_str(),
+ "constant": composer.constant(),
+ "source": composer.source().as_str(),
+ "what": composer.what(),
+ })
+ })
+ .collect();
+
// Only providers this build can reach: local-engine entries inherited from
// the desktop store have no upstream here (see `is_cli_reachable`).
let mut providers: Vec<serde_json::Value> = provider_configs
@@ -844,6 +864,14 @@ pub fn cli_agent_status(
// unless they can tell which of the three layers installed it.
"hooks": hooks,
"plugin_tools": plugin_tools,
+ // Who may write above the cache line, and where each registered
+ // contributor actually lands: the code-level placement, narrowed by
+ // `[prompt].prefix_allow`.
+ "prompt": {
+ "default": prompt_policy.default_placement().as_str(),
+ "prefix_allow": prompt_policy.prefix_allow(),
+ "components": prompt_components,
+ },
"providers": providers,
}))
}