Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): read AGENTS.md when a directory has no JAN.md (#9079)
thinhlpge110c259038a
diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdxindex ca773a82b..76714c7f0 100644--- a/docs/src/pages/docs/agent/context.mdx+++ b/docs/src/pages/docs/agent/context.mdx@@ -43,7 +43,10 @@ Inside is a rail that shows the fill as a percentage of the window, a visual bar`^` marker at the current usage point and `╳` marking the auto-compact reserve zone, atoken scale, and a headroom line (`N tokens available before auto-compact`), theprompt-cache lines when the route reports any, followed by a per-category breakdown:-System prompt, System tools, Project context, Skills, and Messages.+System prompt, System tools, Project context, Skills, and Messages. Below it, **Project+instructions** lists each instructions file the project context loaded, and marks an `AGENTS.md`+or `CLAUDE.md` read because its folder has no `JAN.md` (see+[Project Config](/docs/agent/project-config#agentsmd-and-claudemd)).Press <kbd>Esc</kbd>, <kbd>q</kbd>, or <kbd>Ctrl</kbd>+<kbd>C</kbd> to close; closing nevercancels the turn.diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdxindex cbf74d55d..ab8175aa4 100644--- a/docs/src/pages/docs/agent/project-config.mdx+++ b/docs/src/pages/docs/agent/project-config.mdx@@ -70,6 +70,39 @@ of task belongs in a [skill](/docs/agent/skills).Jan reads `JAN.md` from the project root and each of its ancestors; the nearest file wins. Write oneby hand or with `/init`.+### AGENTS.md and CLAUDE.md++Many repositories already keep instructions for other coding agents in `AGENTS.md`. Jan reads one+file per directory on that same walk:++1. `JAN.md`, if it is there and not empty. It always wins, so a repo with both files loads only+ `JAN.md`.+2. Otherwise `AGENTS.md`.+3. Otherwise `CLAUDE.md`, but only if you opt in to it.++A file already loaded under another name is skipped, so the common `ln -s AGENTS.md JAN.md` loads+once. Each file keeps its path in the prompt, so the model can see which one it got. When a+fallback is used, the startup note says so and `/context` lists it under **Project instructions**.+In a project that has `AGENTS.md` but no `JAN.md`, `/init` uses it as the starting point.++Configure it in `agent.toml`, or in `~/.jan/config.toml` for every project (the project wins):++```toml+[context]+fallback_files = ["AGENTS.md"] # the default+# fallback_files = ["AGENTS.md", "CLAUDE.md"] # also read CLAUDE.md+# fallback_files = [] # JAN.md only+```++Only `AGENTS.md` and `CLAUDE.md` are recognised. The files are re-read at the start of every run;+`/reload system-prompt` lists what the next run will load, with fallbacks marked.++<Callout type="warning">+A file written for another agent can mention that agent's own tools or commands. If Jan follows+something meant for another tool, write a `JAN.md` (it shadows the other file) or set+`fallback_files = []`.+</Callout>+## agent.toml```toml@@ -168,6 +201,12 @@ by default on the CLI.| `env_passthrough` | `[]` | Host environment variables the shell may inherit beyond the minimal base (exact names or a `*` wildcard). Merged with `~/.jan/config.toml`. A secret-looking name is never copied by a wildcard - see [The shell environment](/docs/agent/permissions#the-shell-environment) || `env_set` | `{}` | Explicit `key = "value"` pairs for the shell env, as a `[tools.env_set]` table. Wins over `env_passthrough` and the global value; the way to inject a secret-named variable on purpose |+### `[context]`++| Key | Default | Description |+| --- | --- | --- |+| `fallback_files` | `["AGENTS.md"]` | Instructions files read, in order, from a directory with no `JAN.md`. Only `AGENTS.md` and `CLAUDE.md` are recognised; `[]` reads `JAN.md` only. Falls back to `~/.jan/config.toml`'s `[context]`. See [AGENTS.md and CLAUDE.md](#agentsmd-and-claudemd) |+### `[prompt]`Which contributor to the system prompt may sit above the **cache line**. A provider reuses a requestdiff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 888e51206..955f046a3 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -66,7 +66,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-| `/effort [low\|medium\|high]` | Set reasoning effort. Bare: show current; `low` is faster, `high` thinks deeper || `/mcp` | List, toggle, add, edit, and remove MCP servers; Enter opens a server's detail screen, where you can list its tools and sign in to it || `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |-| `/reload [config\|plugin\|skills\|system-prompt]` | Re-read on-disk state into the running session without a restart (bare: all). `config` re-applies the project's `agent.toml` limits - `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `send_reasoning`, `[budget].max_tokens` - to the next run and lists what changed; the model, `[tools]`, `[provider]` and `[budget].max_usd` still need a restart. `plugin`/`skills` re-scan and rebuild the catalog, reporting added/removed/changed entries. `system-prompt` re-reads `JAN.md`, which applies on the next run |+| `/reload [config\|plugin\|skills\|system-prompt]` | Re-read on-disk state into the running session without a restart (bare: all). `config` re-applies the project's `agent.toml` limits - `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `send_reasoning`, `[budget].max_tokens` - to the next run and lists what changed; the model, `[tools]`, `[provider]` and `[budget].max_usd` still need a restart. `plugin`/`skills` re-scan and rebuild the catalog, reporting added/removed/changed entries. `system-prompt` re-reads the project instructions (`JAN.md`, or a `[context].fallback_files` entry such as `AGENTS.md` where a directory has none), which apply on the next run || `/login` | Sign in to Tokamak and save the API key || `/config` | View provider config (`~/.jan/config.toml`) || `/terminal-setup` | Configure this terminal so <kbd>Shift</kbd>+<kbd>Enter</kbd> inserts a newline and, on macOS, <kbd>Option</kbd>+<kbd>Delete</kbd> deletes a word. Writes the terminal's own config where it can (VS Code, kitty, Ghostty, tmux) and prints the manual step where it cannot. Idempotent |diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex b250c0807..1f8b2802d 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -33,63 +33,127 @@ notice reaches you as a `<SYSTEM>` note that resumes the conversation, so nothinstopping. Do not idle, poll a file in a loop, or narrate waiting: say what you started, then either \get on with unrelated work or finish the turn.";-/// The one instructions file Jan reads, discovered by walking from the project-/// root up to the filesystem root. Another agent's file (`AGENTS.md`,-/// `CLAUDE.md`) is deliberately not ingested: only what a user wrote for Jan ---/// by hand or through `/init` -- becomes authoritative project context.+/// The instructions file Jan reads first in every directory of the walk from+/// the project root up to the filesystem root. When a directory has a+/// non-empty one it wins outright: nothing else in that directory is read.+///+/// #8642 made `JAN.md` the only file ingested, so another agent's file never+/// became authoritative behind the user's back. #9079 keeps `JAN.md` primary+/// and adds a *fallback* for directories without one: the names in+/// `[context].fallback_files` (default `AGENTS.md`; `CLAUDE.md` is opt-in),+/// tried in order, one file per directory. `[]` restores JAN.md-only exactly.const CONTEXT_FILE_NAME: &str = "JAN.md";-/// Read every non-empty `JAN.md` from the project root up to the filesystem-/// root, nearest-first. Shared by the system-prompt builder and the CLI's-/// `/reload system-prompt` report (which needs paths and sizes, not the-/// wrapped block).-pub(crate) fn context_files(project_root: &Path) -> Vec<(std::path::PathBuf, String)> {- let mut files: Vec<(std::path::PathBuf, String)> = Vec::new();+/// One instructions file the walk picked: where it is, what it says, and+/// whether it is a fallback (not `JAN.md`), so a surface can say so.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ContextFile {+ pub path: std::path::PathBuf,+ pub content: String,+ pub fallback: bool,+}++/// Walk from `project_root` to the filesystem root and pick at most one+/// instructions file per directory: a non-empty `JAN.md`, else the first+/// non-empty name in `fallback_files`. A file whose canonical path was already+/// picked (a `sub/AGENTS.md -> ../JAN.md` symlink) is skipped, so the same text+/// is never loaded twice. Returned farthest-first, so the nearest -- most+/// specific -- instructions come last and take precedence.+///+/// Deterministic for a given tree and config: the order is the walk's, never a+/// directory listing's.+pub(crate) fn discover_context_files(+ project_root: &Path,+ fallback_files: &[String],+) -> Vec<ContextFile> {+ let mut files: Vec<ContextFile> = Vec::new();+ let mut seen: std::collections::HashSet<std::path::PathBuf> = Default::default();let mut dir = Some(project_root);while let Some(current) = dir {- let path = current.join(CONTEXT_FILE_NAME);- if let Ok(content) = std::fs::read_to_string(&path) {- if !content.trim().is_empty() {- files.push((path, content));+ let candidates = std::iter::once((CONTEXT_FILE_NAME, false))+ .chain(fallback_files.iter().map(|name| (name.as_str(), true)));+ for (name, fallback) in candidates {+ let path = current.join(name);+ let Ok(content) = std::fs::read_to_string(&path) else {+ continue;+ };+ if content.trim().is_empty() {+ continue;+ }+ // This directory is decided by the first usable file, even when it+ // turns out to be a duplicate: a JAN.md that links to an ancestor's+ // file must not let this directory's AGENTS.md in behind it.+ let canonical = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());+ if seen.insert(canonical) {+ files.push(ContextFile {+ path,+ content,+ fallback,+ });}+ break;}dir = current.parent();}- // Ancestors are collected nearest-first; reverse so the nearest (most- // specific) instructions appear last and take precedence.+ // Collected nearest-first; reverse so the nearest appears last.files.reverse();files}-/// Ingest `JAN.md` from the project root and its ancestors, wrapped in a-/// `<project_context>` block so the model treats them as authoritative project-/// instructions. Returns None when none exist.-pub(crate) fn load_context_files(project_root: &Path) -> Option<String> {- let files = context_files(project_root);+/// The instructions files this project loads under its resolved+/// `[context].fallback_files`, farthest-first. What `/context` and the startup+/// note report, and what [`load_context_files`] renders: one rule for all three.+pub(crate) fn project_context_files(project_root: &Path) -> Vec<ContextFile> {+ let fallback = crate::core::agent::project::context_fallback_files(project_root);+ discover_context_files(project_root, &fallback)+}++/// Render picked instruction files as the `<project_context>` block, or None+/// when there are none. Each file keeps its own `<project_instructions path=...>`+/// tag, so the model sees which file -- `JAN.md` or a fallback -- it got.+fn render_context_files(files: &[ContextFile]) -> Option<String> {if files.is_empty() {return None;}let mut block = String::from("<project_context>\n\nProject-specific instructions and guidelines:\n\n",);- for (path, content) in files {+ for file in files {block.push_str(&format!("<project_instructions path=\"{}\">\n{}\n</project_instructions>\n\n",- path.display(),- content.trim()+ file.path.display(),+ file.content.trim()));}block.push_str("</project_context>");Some(block)}+/// Ingest the project's instructions -- `JAN.md`, or a configured fallback where+/// a directory has none -- from the project root and its ancestors, wrapped in a+/// `<project_context>` block so the model treats them as authoritative project+/// instructions. Returns None when none exist.+pub(crate) fn load_context_files(project_root: &Path) -> Option<String> {+ render_context_files(&project_context_files(project_root))+}+/// Whether this project has usable instructions, by the same rule the system-/// prompt uses: a non-empty `JAN.md` at the root or in any ancestor. Drives the-/// `/init` invitation on the CLI splash, so an ancestor's file (a monorepo root)-/// correctly counts as already onboarded.-#[cfg(feature = "cli")]+/// prompt uses: a non-empty `JAN.md` (or fallback) at the root or in any+/// ancestor, so an ancestor's file (a monorepo root) counts as already+/// onboarded. The startup note reads [`project_context_files`] directly, since+/// it also names a fallback; this is the yes/no its tests pin.+#[cfg(all(test, feature = "cli"))]pub(crate) fn has_context_file(project_root: &Path) -> bool {- load_context_files(project_root).is_some()+ !project_context_files(project_root).is_empty()+}++/// Whether the project root itself has a non-empty `JAN.md`. `/init` uses it to+/// decide between writing one and reviewing one, since a fallback file (or an+/// ancestor's) is not the project's own.+#[cfg(feature = "cli")]+pub(crate) fn has_own_jan_md(project_root: &Path) -> bool {+ std::fs::read_to_string(project_root.join(CONTEXT_FILE_NAME))+ .is_ok_and(|content| !content.trim().is_empty())}/// Built-in guide teaching the model the skills/memory file conventions. Always@@ -610,6 +674,160 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ fn agents_only() -> Vec<String> {+ vec!["AGENTS.md".to_string()]+ }++ /// #9079: a directory with no JAN.md falls back to AGENTS.md, and the tag+ /// names the file so the model can tell which one it got.+ #[test]+ fn agents_md_is_read_where_there_is_no_jan_md() {+ let root = scratch_project("agentsfallback");+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ let files = discover_context_files(&root, &agents_only());+ assert_eq!(files.len(), 1);+ assert!(files[0].fallback);+ assert!(files[0].path.ends_with("AGENTS.md"));+ let block = render_context_files(&files).expect("block");+ assert!(block.contains("AGENTS_RULES"));+ assert!(block.contains("AGENTS.md\">"), "{block}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// One file per directory: a repo with both loads exactly what it loaded+ /// before the fallback existed.+ #[test]+ fn jan_md_wins_over_agents_md_in_the_same_directory() {+ let root = scratch_project("janwins");+ std::fs::write(root.join("JAN.md"), "JAN_RULES").unwrap();+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ std::fs::write(root.join("CLAUDE.md"), "CLAUDE_RULES").unwrap();+ let all = vec!["AGENTS.md".to_string(), "CLAUDE.md".to_string()];+ let block = render_context_files(&discover_context_files(&root, &all)).unwrap();+ let jan_only = render_context_files(&discover_context_files(&root, &[])).unwrap();+ assert_eq!(block, jan_only, "JAN.md must shadow every fallback");+ assert!(!block.contains("AGENTS_RULES") && !block.contains("CLAUDE_RULES"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// An empty JAN.md does not count, the same rule as before: the directory+ /// falls through to its AGENTS.md.+ #[test]+ fn an_empty_jan_md_falls_through_to_the_fallback() {+ let root = scratch_project("emptyjan");+ std::fs::write(root.join("JAN.md"), " \n").unwrap();+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ let files = discover_context_files(&root, &agents_only());+ assert_eq!(files.len(), 1);+ assert!(files[0].content.contains("AGENTS_RULES"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// `[]` is today's behaviour exactly, and CLAUDE.md is read only when listed.+ #[test]+ fn fallback_list_controls_what_is_read() {+ let root = scratch_project("fallbacklist");+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ std::fs::write(root.join("CLAUDE.md"), "CLAUDE_RULES").unwrap();+ assert!(discover_context_files(&root, &[]).is_empty());+ let agents = discover_context_files(&root, &agents_only());+ assert!(agents[0].content.contains("AGENTS_RULES"));+ let claude = discover_context_files(&root, &["CLAUDE.md".to_string()]);+ assert!(claude[0].content.contains("CLAUDE_RULES"));+ // Order is precedence within a directory.+ let both = vec!["CLAUDE.md".to_string(), "AGENTS.md".to_string()];+ let files = discover_context_files(&root, &both);+ assert_eq!(files.len(), 1);+ assert!(files[0].content.contains("CLAUDE_RULES"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Mixed monorepo: the root's JAN.md and a package's AGENTS.md both load,+ /// nearest last, each tagged with its own path.+ #[test]+ fn fallback_is_decided_per_directory() {+ let root = scratch_project("perdir");+ let nested = root.join("pkg");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(root.join("JAN.md"), "ROOT_JAN").unwrap();+ std::fs::write(root.join("AGENTS.md"), "ROOT_AGENTS").unwrap();+ std::fs::write(nested.join("AGENTS.md"), "PKG_AGENTS").unwrap();+ let files = discover_context_files(&nested, &agents_only());+ let texts: Vec<&str> = files.iter().map(|f| f.content.as_str()).collect();+ assert_eq!(texts, ["ROOT_JAN", "PKG_AGENTS"]);+ assert_eq!(+ files.iter().map(|f| f.fallback).collect::<Vec<_>>(),+ [false, true]+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The common `JAN.md -> AGENTS.md` symlink loads once, as JAN.md.+ #[cfg(unix)]+ #[test]+ fn a_symlinked_jan_md_loads_its_target_once() {+ let root = scratch_project("symlink");+ std::fs::write(root.join("AGENTS.md"), "SHARED_RULES").unwrap();+ std::os::unix::fs::symlink("AGENTS.md", root.join("JAN.md")).unwrap();+ let files = discover_context_files(&root, &agents_only());+ assert_eq!(files.len(), 1);+ assert!(!files[0].fallback);+ let block = render_context_files(&files).unwrap();+ assert_eq!(block.matches("SHARED_RULES").count(), 1);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A package whose AGENTS.md links to the root's file must not load the+ /// same text a second time.+ #[cfg(unix)]+ #[test]+ fn a_file_already_loaded_by_canonical_path_is_skipped() {+ let root = scratch_project("canonical");+ let nested = root.join("pkg");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(root.join("AGENTS.md"), "SHARED_RULES").unwrap();+ std::os::unix::fs::symlink("../AGENTS.md", nested.join("AGENTS.md")).unwrap();+ let files = discover_context_files(&nested, &agents_only());+ assert_eq!(files.len(), 1, "{files:?}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A project's `agent.toml` `[context]` is what `load_context_files` honours:+ /// `[]` turns the fallback off, and a name Jan does not know is ignored.+ #[test]+ fn agent_toml_context_section_configures_the_fallback() {+ let root = scratch_project("agenttoml");+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ std::fs::write(root.join("README.md"), "README_TEXT").unwrap();+ let store = crate::core::agent::project::store_root(&root);+ std::fs::create_dir_all(&store).unwrap();+ std::fs::write(store.join("agent.toml"), "[context]\nfallback_files = []\n").unwrap();+ assert!(load_context_files(&root).is_none());+ std::fs::write(+ store.join("agent.toml"),+ "[context]\nfallback_files = [\"README.md\", \"AGENTS.md\"]\n",+ )+ .unwrap();+ let block = load_context_files(&root).expect("AGENTS.md via agent.toml");+ assert!(block.contains("AGENTS_RULES"));+ assert!(!block.contains("README_TEXT"), "unknown names are never read");+ let _ = std::fs::remove_dir_all(&store);+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Unset everywhere: AGENTS.md is on, CLAUDE.md is not.+ #[test]+ fn the_default_fallback_is_agents_md_only() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let root = scratch_project("defaultfallback");+ assert_eq!(+ crate::core::agent::project::context_fallback_files(&root),+ ["AGENTS.md"]+ );+ let _ = std::fs::remove_dir_all(&root);+ });+ }+#[test]fn no_context_files_yields_none() {let root = scratch_project("noctx");diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex 366488ca5..15f97cb14 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -56,6 +56,13 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # Defaults to 👋; set "" for the plain# # throbber if your terminal draws tofu#+# [context]+# fallback_files = ["AGENTS.md"] # instructions files read where a folder+# # has no JAN.md (JAN.md always wins).+# # Default ["AGENTS.md"]; add "CLAUDE.md"+# # to opt in; [] reads JAN.md only. A+# # project's agent.toml [context] wins+## [providers.my-provider]# api_key = "sk-..."# base_url = "https://api.example.com/v1"@@ -153,10 +160,21 @@ struct GlobalConfigToml {/// but a human appending to the file would not.#[serde(default, skip_serializing_if = "Vec::is_empty")]hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,+ /// `[context]` -- the user-wide default for which instructions files are+ /// read where a directory has no `JAN.md`. A project's own `[context]`+ /// wins. See `project::context_fallback_files`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ context: Option<GlobalContextSection>,#[serde(default)]providers: HashMap<String, GlobalProviderEntry>,}+#[derive(Debug, Clone, Default, Deserialize, Serialize)]+struct GlobalContextSection {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ fallback_files: Option<Vec<String>>,+}+#[derive(Debug, Clone, Default, Deserialize, Serialize)]struct GlobalProviderEntry {#[serde(default, skip_serializing_if = "Option::is_none")]@@ -325,6 +343,16 @@ pub(crate) fn sandbox_setting() -> Option<bool> {load_raw().ok().and_then(|config| config.sandbox)}+/// `[context].fallback_files` from `~/.jan/config.toml`, or `None` when unset+/// or unreadable, so the project's `agent.toml` and then the built-in default+/// decide. Like the other preferences, a bad file never blocks a session.+pub(crate) fn context_fallback_files_setting() -> Option<Vec<String>> {+ load_raw()+ .ok()+ .and_then(|config| config.context)+ .and_then(|context| context.fallback_files)+}+/// Whether a session gets its own git worktree by default (`worktree` in/// `~/.jan/config.toml`). `None` when unset, so a project's `agent.toml` or the/// `--worktree` flag decides first. Unreadable config yields `None`, likediff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rsindex 4c9eaec8b..347eec468 100644--- a/src-tauri/src/core/agent/prefix_stability.rs+++ b/src-tauri/src/core/agent/prefix_stability.rs@@ -606,6 +606,96 @@ async fn compaction_breaks_the_prefix_exactly_once() {);}+/// #9079: a project whose instructions come from the `AGENTS.md` fallback+/// instead of `JAN.md`. The fixture pins `[context].fallback_files` in its own+/// agent.toml, so the result cannot depend on the developer's+/// `~/.jan/config.toml`.+fn agents_md_project(tag: &str, link_jan_md: bool) -> Project {+ let project = Project::new(tag);+ let root = project.root();+ let body = "# Project\n\nPrefix-stability fixture.\n";+ std::fs::remove_file(root.join("JAN.md")).unwrap();+ std::fs::write(root.join("AGENTS.md"), body).unwrap();+ if link_jan_md {+ #[cfg(unix)]+ std::os::unix::fs::symlink("AGENTS.md", root.join("JAN.md")).unwrap();+ #[cfg(not(unix))]+ std::fs::write(root.join("JAN.md"), body).unwrap();+ }+ let store = crate::core::agent::project::store_root(root);+ std::fs::write(+ store.join("agent.toml"),+ "[context]\nfallback_files = [\"AGENTS.md\"]\n",+ )+ .unwrap();+ project+}++/// #9079: the fallback file is part of the stable prefix like `JAN.md` is. The+/// same tree composes the same bytes, consecutive turns extend each other, and+/// the block names the file it came from.+#[test]+fn an_agents_md_fallback_keeps_the_prefix_stable() {+ let project = agents_md_project("agentsmd", false);+ let tools = advertised(&["read_file"]);++ let first = turn(project.root(), &[user("first question")], DAY, &tools);+ let again = turn(project.root(), &[user("first question")], DAY, &tools);+ assert_same_bytes(+ "the same AGENTS.md project must compose the same bytes",+ &first.body,+ &again.body,+ );++ let stable = first.messages[0]["content"]+ .as_str()+ .expect("message 0 is the stable prompt");+ assert!(stable.contains("<project_context>"));+ assert!(stable.contains("AGENTS.md\">"), "the tag names the fallback file");++ let mut history = first.messages.clone();+ history.push(assistant("first answer"));+ history.push(user("second question"));+ let second = turn(project.root(), &history, DAY, &tools);+ first.assert_extended_by("an AGENTS.md project on the next turn", &second);+}++/// #9079: the common `JAN.md -> AGENTS.md` symlink loads once, as `JAN.md`, so+/// the prefix is byte-identical to a project with a plain `JAN.md` of the same+/// text. Adopting the symlink costs no cache miss beyond the one edit.+#[test]+fn a_jan_md_symlink_to_agents_md_composes_like_a_plain_jan_md() {+ let plain = Project::new("plainjan");+ let linked = agents_md_project("linkedjan", true);+ let tools = advertised(&["read_file"]);+ let history = [user("a question")];++ let plain_turn = turn(plain.root(), &history, DAY, &tools);+ let linked_turn = turn(linked.root(), &history, DAY, &tools);+ // The working directory differs between the two roots; everything that+ // is the context block must not.+ let block = |request: &Request| {+ let stable = request.messages[0]["content"].as_str().unwrap().to_string();+ let start = stable.find("<project_context>").expect("a context block");+ let end = stable.find("</project_context>").expect("a closed block");+ let block = stable[start..end].to_string();+ block.replace(&request_root(request), "<root>")+ };+ fn request_root(request: &Request) -> String {+ let stable = request.messages[0]["content"].as_str().unwrap();+ let marker = "Current project directory: `";+ let at = stable.find(marker).unwrap() + marker.len();+ stable[at..at + stable[at..].find('`').unwrap()].to_string()+ }+ let linked_block = block(&linked_turn);+ assert_same_bytes(+ "a symlinked JAN.md must load once, as JAN.md",+ &block(&plain_turn),+ &linked_block,+ );+ assert_eq!(linked_block.matches("Prefix-stability fixture.").count(), 1);+}+/// The guard on the cache line: this list is every composer permitted to write/// above it.///diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex 3ea571687..95531eade 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -30,6 +30,8 @@ pub(crate) struct AgentToml {pub skills: SkillsSection,#[serde(default)]pub plugins: PluginsSection,+ #[serde(default)]+ pub context: ContextSection,/// `[[hooks]]` -- lifecycle commands this project runs around tool calls,/// prompts, sessions and compactions. An array of tables rather than a/// `[hooks]` map because several hooks may share one event.@@ -56,6 +58,52 @@ pub(crate) struct PromptSection {pub prefix_allow: Option<Vec<String>>,}+/// `[context]` — which instructions files Jan reads besides `JAN.md`.+#[derive(Debug, Clone, Default, Deserialize)]+pub(crate) struct ContextSection {+ /// Files read, in order, from a directory that has no non-empty `JAN.md`+ /// (#9079). Only `AGENTS.md` and `CLAUDE.md` are recognised. `None` defers to+ /// `~/.jan/config.toml`, then to [`DEFAULT_CONTEXT_FALLBACK_FILES`]; `[]`+ /// reads `JAN.md` only, which is the behaviour before the fallback existed.+ #[serde(default)]+ pub fallback_files: Option<Vec<String>>,+}++/// The fallback used when neither `agent.toml` nor `~/.jan/config.toml` sets+/// `[context].fallback_files`: the vendor-neutral `AGENTS.md`. `CLAUDE.md` is+/// opt-in, since it is usually written for one specific agent.+pub(crate) const DEFAULT_CONTEXT_FALLBACK_FILES: &[&str] = &["AGENTS.md"];++/// The fallback names Jan will ever read. Anything else in `fallback_files` is+/// dropped, so the list cannot be used to ingest arbitrary files.+pub(crate) const KNOWN_CONTEXT_FALLBACK_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"];++/// The resolved `[context].fallback_files` for `project_root`: the project's+/// `agent.toml` if it sets the key, else `~/.jan/config.toml`, else the+/// default. Unknown names and duplicates are dropped; order is kept, and it is+/// the precedence within a directory.+pub(crate) fn context_fallback_files(project_root: &Path) -> Vec<String> {+ let configured = load_agent_config(project_root)+ .ok()+ .and_then(|cfg| cfg.context.fallback_files)+ .or_else(crate::core::agent::global_config::context_fallback_files_setting);+ let names: Vec<String> = match configured {+ Some(list) => list,+ None => DEFAULT_CONTEXT_FALLBACK_FILES+ .iter()+ .map(|s| s.to_string())+ .collect(),+ };+ let mut out: Vec<String> = Vec::new();+ for name in names {+ let name = name.trim().to_string();+ if KNOWN_CONTEXT_FALLBACK_FILES.contains(&name.as_str()) && !out.contains(&name) {+ out.push(name);+ }+ }+ out+}+/// `[plugins]` — plugin installs and marketplace. Installed plugins live in/// `<store_root>/plugins/`; this section only carries configuration.#[derive(Debug, Clone, Default, Deserialize)]@@ -320,6 +368,12 @@ inject = "always"# Fallback for a future unclassified composer: tail (the default) or prefix.# No effect on current composers. Use prefix_allow to narrow today's prefix.# default = "tail"++# Instructions files read from a directory that has no JAN.md, in order. JAN.md+# always wins. Unset uses ~/.jan/config.toml, else ["AGENTS.md"]. Add+# "CLAUDE.md" to opt in to it; [] reads JAN.md only.+# [context]+# fallback_files = ["AGENTS.md"]"#;/// `~/.jan`, where every project's store lives. Test builds use a per-processdiff --git a/src-tauri/src/core/agent/prompt.rs b/src-tauri/src/core/agent/prompt.rsindex f4a6e9d9e..c4a5ebbfb 100644--- a/src-tauri/src/core/agent/prompt.rs+++ b/src-tauri/src/core/agent/prompt.rs@@ -153,7 +153,9 @@ impl Composer {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::ProjectContext => {+ "JAN.md (or its AGENTS.md fallback), 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)",diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex ba66a2ee6..995436706 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -5187,6 +5187,7 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {// the two would make the same non-ASCII text count differently depending// on which segment it landed in.let (mut prompt_bytes, mut context_bytes, mut skills_bytes) = (0usize, 0usize, 0usize);+ let mut instruction_files: Vec<(String, bool)> = Vec::new();if let (Some(args), Some(root)) = (args, root.as_deref()) {let full = crate::core::agent::r#loop::context_system_prompt_preview(args.system_prompt_override.as_deref(),@@ -5198,6 +5199,10 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {.unwrap_or_default();context_bytes =crate::core::agent::context::load_context_files(root).map_or(0, |s| s.len());+ instruction_files = crate::core::agent::context::project_context_files(root)+ .into_iter()+ .map(|file| (file.path.display().to_string(), file.fallback))+ .collect();skills_bytes = crate::core::agent::context::load_skills(root).map_or(0, |s| s.len())+ crate::core::agent::context::load_memory_catalog(root).map_or(0, |s| s.len());prompt_bytes = full.len().saturating_sub(context_bytes + skills_bytes);@@ -5295,6 +5300,7 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {session_prompt_tokens: snapshot.session_prompt_tokens,session_cached_tokens: snapshot.session_cached_tokens,session_cache_write_tokens: snapshot.session_cache_write_tokens,+ instruction_files,}}@@ -6735,6 +6741,10 @@ struct ContextReport {session_prompt_tokens: u64,session_cached_tokens: u64,session_cache_write_tokens: u64,+ /// The instructions files the project context loaded, farthest first, each+ /// with whether it is a fallback (`AGENTS.md`, `CLAUDE.md`) read because its+ /// directory has no `JAN.md` (#9079). Listed so a fallback is never silent.+ instruction_files: Vec<(String, bool)>,}impl ContextReport {@@ -6958,6 +6968,24 @@ fn cost_summary_line(report: &ContextReport) -> Option<String> {))}+/// Which instructions files the project context holds, for `/context`: a blank+/// separator, a heading, then one path per file, a fallback marked as such.+/// Empty when none loaded, so a project without instructions shows nothing.+fn instruction_file_lines(report: &ContextReport) -> Vec<String> {+ if report.instruction_files.is_empty() {+ return Vec::new();+ }+ let mut lines = vec![String::new(), "Project instructions".to_string()];+ for (path, fallback) in &report.instruction_files {+ lines.push(if *fallback {+ format!(" {path} (fallback: no JAN.md in that folder)")+ } else {+ format!(" {path}")+ });+ }+ lines+}+/// Plain `/context` summary: current usage and autocompaction threshold first,/// followed by seven equal-scale category bars./// The session half of a usage readout: the estimate, its model breakdown,@@ -7180,6 +7208,9 @@ fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {format_tokens(segment.tokens),))]);}+ for text in instruction_file_lines(report) {+ rows.push(vec![Span::styled(text, Style::new().dim())]);+ }return rows.into_iter().map(|spans| Line::from(clip_spans(spans, max)))@@ -7307,6 +7338,9 @@ fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {Span::raw(suffix),]);}+ for text in instruction_file_lines(report) {+ rows.push(vec![Span::styled(text, Style::new().dim())]);+ }rows.into_iter().map(|spans| Line::from(clip_spans(spans, max)))@@ -9503,8 +9537,8 @@ pub async fn run(}// Only when there is nothing to load: a project that already has JAN.md needs// no invitation, and the splash hint covers re-running /init deliberately.- if !crate::core::agent::context::has_context_file(&app.project_root) {- app.note("no JAN.md here — run /init to study this project and write one");+ if let Some(note) = project_instructions_note(&app.project_root) {+ app.note(¬e);}// A modified key the terminal is dropping looks like a bug in the composer,// so say so once, and only where a config file proves it is unconfigured@@ -12667,6 +12701,29 @@ multi-step recipe exists. Do not invent skills to fill space.\n\n\true beyond this session and not already stated in the code.\n\n\Then report what you wrote and why, briefly.";+/// The startup note about project instructions: an invitation to `/init` when+/// there are none, and a plain statement when the context came from a fallback+/// file (`AGENTS.md`) rather than `JAN.md`, so that choice is never silent+/// (#9079). `None` when every loaded file is a `JAN.md`: nothing to say.+fn project_instructions_note(project_root: &std::path::Path) -> Option<String> {+ let files = crate::core::agent::context::project_context_files(project_root);+ if files.is_empty() {+ return Some("no JAN.md here — run /init to study this project and write one".to_string());+ }+ let fallbacks: Vec<String> = files+ .iter()+ .filter(|file| file.fallback)+ .map(|file| file.path.display().to_string())+ .collect();+ if fallbacks.is_empty() {+ return None;+ }+ Some(format!(+ "project instructions from {} (no JAN.md there) · [context].fallback_files in agent.toml controls this",+ fallbacks.join(", ")+ ))+}+/// `/init`: hand the model the onboarding task as a user turn, so it runs with/// the normal toolset, permission gate, and transcript. The prompt body itself/// is hidden -- the note below is what the user asked for, the canned text is@@ -12678,13 +12735,51 @@ fn init_command(app: &mut App) {app.note("/init is only available once the run has finished");return;}- let existing = crate::core::agent::context::has_context_file(&app.project_root);- app.note(if existing {- "◈ init · reviewing JAN.md, skills, and memory for this project"- } else {- "◈ init · studying the project to write JAN.md, skills, and memory"- });- app.submit_user_hidden(INIT_PROMPT.to_string());+ let existing = crate::core::agent::context::has_own_jan_md(&app.project_root);+ let seed = (!existing)+ .then(|| init_seed_file(&app.project_root))+ .flatten();+ match (&seed, existing) {+ (_, true) => app.note("◈ init · reviewing JAN.md, skills, and memory for this project"),+ (Some(name), false) => app.note(&format!(+ "◈ init · writing JAN.md from this project's {name}, plus skills and memory"+ )),+ (None, false) => {+ app.note("◈ init · studying the project to write JAN.md, skills, and memory")+ }+ }+ let prompt = match seed {+ Some(name) => format!("{INIT_PROMPT}\n\n{}", init_seed_paragraph(&name)),+ None => INIT_PROMPT.to_string(),+ };+ app.submit_user_hidden(prompt);+}++/// The other agent's instructions file `/init` should start from, when the+/// project root has one and no `JAN.md` (#9079): `AGENTS.md`, else `CLAUDE.md`.+/// Both are offered regardless of `[context].fallback_files`, because this only+/// seeds a file the user then owns -- nothing is loaded from it by this choice.+fn init_seed_file(project_root: &std::path::Path) -> Option<String> {+ ["AGENTS.md", "CLAUDE.md"]+ .into_iter()+ .find(|name| {+ std::fs::read_to_string(project_root.join(name))+ .is_ok_and(|content| !content.trim().is_empty())+ })+ .map(str::to_string)+}++/// The `/init` addendum for a project that already keeps instructions for+/// another agent: build on them rather than writing from scratch, and drop what+/// was aimed at that agent -- the concern #8642 raised about ingesting it as is.+fn init_seed_paragraph(name: &str) -> String {+ format!(+ "This project has no `JAN.md` but has `{name}`, written for another coding agent. Read it \+first and use it as the starting point for `JAN.md`: keep the commands, architecture, and \+conventions that hold for any agent, and drop or rewrite anything aimed at that specific agent (its \+tool names, its CLI commands, its config files). Leave `{name}` itself unchanged. If the user would \+rather keep one file, mention that `ln -s {name} JAN.md` makes Jan read it directly."+ )}/// Manually compact the conversation: summarize older turns, keeping the recent@@ -14604,15 +14699,24 @@ fn reload_catalog(app: &mut App, plugins: bool, skills: bool) {fn reload_system_prompt(app: &mut App) {// Nothing caches the instructions across runs: the system prompt// (including this block and the skills catalog) is rebuilt from disk at- // the start of every run. Re-read now to confirm what the next run picks up.- let files = crate::core::agent::context::context_files(&app.project_root);+ // the start of every run. Re-read now to confirm what the next run picks up,+ // through the same discovery the prompt uses: JAN.md per directory, else a+ // `[context].fallback_files` entry (#9079), with that list re-resolved too.+ let files = crate::core::agent::context::project_context_files(&app.project_root);if files.is_empty() {- app.note("◈ reload · system-prompt · no JAN.md in this project or its ancestors");+ app.note(+ "◈ reload · system-prompt · no JAN.md or [context].fallback_files match in this project or its ancestors",+ );return;}app.note("◈ reload · system-prompt · re-read project instructions (applies next run)");- for (path, content) in &files {- app.system_detail_text(&format!(" {} ({} bytes)", path.display(), content.len()));+ for file in &files {+ let tag = if file.fallback { ", fallback" } else { "" };+ app.system_detail_text(&format!(+ " {} ({} bytes{tag})",+ file.path.display(),+ file.content.len()+ ));}}@@ -32560,6 +32664,7 @@ mod tests {session_prompt_tokens: 0,session_cached_tokens: 0,session_cache_write_tokens: 0,+ instruction_files: Vec::new(),}}@@ -37238,7 +37343,7 @@ mod tests {let (mut app, root) = skill_test_app("deploy", "How to deploy.");run_command(&mut app, "reload system-prompt", &no_mcp()).await;assert!(- transcript_text(&app).contains("no JAN.md in this project"),+ transcript_text(&app).contains("no JAN.md or [context].fallback_files match"),"empty project: {}",transcript_text(&app));@@ -37251,6 +37356,26 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// #9079 x #9077: `/reload system-prompt` goes through the fallback+ /// discovery, so a project with only AGENTS.md reports it (tagged), and a+ /// JAN.md added later shadows it.+ #[tokio::test]+ async fn reload_system_prompt_reads_agents_md_fallback() {+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");+ std::fs::write(root.join("AGENTS.md"), "# Agents\n\nUse make.\n").unwrap();+ run_command(&mut app, "reload system-prompt", &no_mcp()).await;+ let out = transcript_text(&app);+ assert!(out.contains("AGENTS.md") && out.contains("fallback"), "{out}");++ std::fs::write(root.join("JAN.md"), "# Rules\n").unwrap();+ let before = transcript_text(&app).len();+ run_command(&mut app, "reload system-prompt", &no_mcp()).await;+ let out = transcript_text(&app);+ let tail = &out[before..];+ assert!(tail.contains("JAN.md") && !tail.contains("AGENTS.md"), "{tail}");+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn reload_bare_covers_every_target() {let (mut app, root) = skill_test_app("deploy", "How to deploy.");@@ -38521,6 +38646,78 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// #9079: a fallback is never silent. No instructions invites `/init`; a+ /// JAN.md says nothing; an AGENTS.md fallback names the file it loaded.+ #[test]+ fn startup_note_names_an_agents_md_fallback() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let root =+ std::env::temp_dir().join(format!("jan_fallback_note_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ let none = super::project_instructions_note(&root).expect("an invitation");+ assert!(none.contains("/init"), "{none}");+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ let fallback = super::project_instructions_note(&root).expect("a fallback note");+ assert!(fallback.contains("AGENTS.md"), "{fallback}");+ assert!(fallback.contains("no JAN.md"), "{fallback}");+ std::fs::write(root.join("JAN.md"), "JAN_RULES").unwrap();+ assert_eq!(super::project_instructions_note(&root), None);+ let _ = std::fs::remove_dir_all(&root);+ });+ }++ /// `/context` lists the files the project context holds, marking a fallback.+ #[test]+ fn context_view_lists_instruction_files_and_marks_a_fallback() {+ let mut report = context_report(128_000, 16_000, [100, 100, 100, 100, 100]);+ assert!(!context_text(&report).contains("Project instructions"));+ report.instruction_files = vec![+ ("/repo/JAN.md".into(), false),+ ("/repo/pkg/AGENTS.md".into(), true),+ ];+ for width in [80usize, 30] {+ let text = context_lines(&report, width)+ .iter()+ .map(line_text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(text.contains("Project instructions"), "{text}");+ assert!(text.contains("/repo/JAN.md"), "{text}");+ assert!(text.contains("AGENTS.md"), "{text}");+ }+ assert!(context_text(&report).contains("AGENTS.md (fallback"));+ }++ /// #9079: `/init` in a project with AGENTS.md and no JAN.md builds on it+ /// rather than writing from scratch, and offers the symlink.+ #[test]+ fn init_starts_from_an_existing_agents_md() {+ let root = std::env::temp_dir().join(format!("jan_init_seed_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ assert_eq!(super::init_seed_file(&root), None);+ std::fs::write(root.join("CLAUDE.md"), "CLAUDE_RULES").unwrap();+ assert_eq!(super::init_seed_file(&root).as_deref(), Some("CLAUDE.md"));+ std::fs::write(root.join("AGENTS.md"), "AGENTS_RULES").unwrap();+ assert_eq!(super::init_seed_file(&root).as_deref(), Some("AGENTS.md"));++ let mut app = test_app();+ app.project_root = root.clone();+ super::init_command(&mut app);+ let sent = app.history.last().expect("user message").to_string();+ assert!(sent.contains("has `AGENTS.md`"), "{sent}");+ assert!(sent.contains("ln -s AGENTS.md JAN.md"), "{sent}");+ let text: String = row_lines(&app.transcript)+ .iter()+ .flat_map(|l| l.spans.clone())+ .map(|s| s.content.to_string())+ .collect();+ assert!(text.contains("from this project's AGENTS.md"), "{text}");+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn a_seeded_session_is_not_invited_to_type() {let mut app = test_app();