Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): move agent instructions to root JAN.md, add /init (#8642)
Akarshan Biswasf1dee5b541a0
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 8da688be4..09616094c 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -129,9 +129,9 @@ pub fn resolve_decision(if perms.is_denied(tool.name) {return Decision::HardDeny;}- // Only the agent's own skills/memory/AGENT.md are reachable under .jan/agent/.- // Any other path there (agent.toml, the dir listing) is off-limits to every- // tool, ahead of allow rules so an allowed tool name cannot bypass it.+ // Nothing under .jan/agent/ is reachable: skills/memory only through their+ // dedicated tools, agent.toml and the dir listing not at all. Checked ahead+ // of allow rules so an allowed tool name cannot bypass it.let hits_restricted = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())@@ -337,11 +337,11 @@ mod tests {&grants,);assert_eq!(d, Decision::HardDeny);- // AGENT.md remains readable.- std::fs::write(root.join(".jan/agent/AGENT.md"), b"x").unwrap();+ // The instructions file is an ordinary project file at the root.+ std::fs::write(root.join("JAN.md"), b"x").unwrap();let d = resolve_decision(lookup("read").unwrap(),- &json!({"path": ".jan/agent/AGENT.md"}),+ &json!({"path": "JAN.md"}),&root,&perms,&grants,diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 17e6ac419..460eb0103 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -1714,7 +1714,7 @@ mod tests {std::fs::create_dir_all(root.join(".jan/agent/threads/t1")).unwrap();std::fs::write(root.join(".jan/agent/threads/t1/thread.json"), b"{}").unwrap();std::fs::write(root.join(".jan/agent/agent.toml"), b"[tools]\n").unwrap();- std::fs::write(root.join(".jan/agent/AGENT.md"), b"instructions").unwrap();+ std::fs::write(root.join("JAN.md"), b"instructions").unwrap();std::fs::write(root.join("README.md"), b"x").unwrap();let out =execute_builtin(lookup("find").unwrap(), &json!({"pattern": "**/*"}), &root).await;@@ -1723,8 +1723,8 @@ mod tests {"should include project file: {out}");assert!(- out.contains(".jan/agent/AGENT.md"),- "AGENT.md is readable, should be listed: {out}"+ out.contains("JAN.md"),+ "the root instructions file is an ordinary project file: {out}");assert!(!out.contains("thread.json"),diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex 3be4c7165..0039810d1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -18,11 +18,12 @@ pub fn escapes_project(project_root: &Path, raw: &str) -> Result<bool, String> {Ok(!resolved.starts_with(&root))}-/// True iff `raw` resolves inside `<project_root>/.jan/agent/` to anything other-/// than the `AGENT.md` instructions file. The `skills/` and `memory/` workspaces-/// are reachable only through the dedicated skill_*/memory_* tools, never general-/// read/write/edit/ls/find/grep/bash; agent.toml and any other config are fully-/// off-limits. So the general filesystem tools see only AGENT.md under .jan/agent/.+/// True iff `raw` resolves inside `<project_root>/.jan/agent/`. The `skills/`+/// and `memory/` workspaces are reachable only through the dedicated+/// skill_*/memory_* tools, never general read/write/edit/ls/find/grep/bash;+/// agent.toml and any other config are fully off-limits. The project+/// instructions file is `<project_root>/JAN.md`, an ordinary project file, so+/// the whole agent dir is opaque to the general filesystem tools.pub fn is_restricted_agent_path(project_root: &Path, raw: &str) -> bool {let Ok(root) = project_root.canonicalize() else {return false;@@ -35,11 +36,7 @@ pub fn is_restricted_agent_path(project_root: &Path, raw: &str) -> bool {let Ok(resolved) = canonicalize_lenient(&abs) else {return false;};- let agent = root.join(".jan").join("agent");- if !resolved.starts_with(&agent) {- return false;- }- resolved != agent.join("AGENT.md")+ resolved.starts_with(root.join(".jan").join("agent"))}/// True iff a shell command references a restricted agent path (best-effort token@@ -156,12 +153,11 @@ mod tests {#[test]- fn restricted_agent_path_covers_config_but_not_approved_surface() {+ fn restricted_agent_path_covers_the_whole_agent_dir() {let root = unique_root();std::fs::create_dir_all(root.join(".jan/agent/skills")).unwrap();std::fs::create_dir_all(root.join(".jan/agent/memory")).unwrap();std::fs::write(root.join(".jan/agent/agent.toml"), b"x").unwrap();- std::fs::write(root.join(".jan/agent/AGENT.md"), b"x").unwrap();// Restricted: agent.toml, the agent dir listing, unknown config files.assert!(is_restricted_agent_path(&root, ".jan/agent/agent.toml"));assert!(is_restricted_agent_path(&root, "./.jan/agent/agent.toml"));@@ -175,9 +171,14 @@ mod tests {// are restricted from the general filesystem tools too.assert!(is_restricted_agent_path(&root, ".jan/agent/skills/deploy.md"));assert!(is_restricted_agent_path(&root, ".jan/agent/memory/notes.md"));- // Only AGENT.md and unrelated project files stay reachable.- assert!(!is_restricted_agent_path(&root, ".jan/agent/AGENT.md"));+ // Nothing under .jan/agent/ is reachable; the instructions file now+ // lives at the project root as JAN.md, an ordinary project file.+ assert!(is_restricted_agent_path(&root, ".jan/agent/AGENT.md"));+ assert!(!is_restricted_agent_path(&root, "JAN.md"));assert!(!is_restricted_agent_path(&root, "src/main.rs"));+ // The `.jan` dir itself is not restricted: threads and other project+ // state outside `agent/` were never part of this carve-out.+ assert!(!is_restricted_agent_path(&root, ".jan"));let _ = std::fs::remove_dir_all(&root);}@@ -194,10 +195,11 @@ mod tests {&root,"grep foo < .jan/agent/agent.toml"));- assert!(!command_touches_restricted_agent_path(+ assert!(command_touches_restricted_agent_path(&root,"cat .jan/agent/AGENT.md"));+ assert!(!command_touches_restricted_agent_path(&root, "cat JAN.md"));assert!(!command_touches_restricted_agent_path(&root, "ls -la src"));let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 393bc8c8d..383dd582c 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -25,25 +25,23 @@ missing output: when output is cut it always carries an explicit `[output truncaits absence means you have everything. A command's `[exit N]` line is the authoritative result -- \`[exit 0]` is success even if there is text on stderr (many tools write normal status there).";-/// Context-file names discovered by walking from the project root up to the-/// filesystem root, most general (top ancestor) first so the nearest file wins.-const CONTEXT_FILE_NAMES: &[&str] = &["AGENTS.md", "CLAUDE.md"];--/// Ingest project instruction files (`AGENTS.md` / `CLAUDE.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. At most one file per directory (first match by `CONTEXT_FILE_NAMES`).+/// 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.+const CONTEXT_FILE_NAME: &str = "JAN.md";++/// 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 mut files: Vec<(std::path::PathBuf, String)> = Vec::new();let mut dir = Some(project_root);while let Some(current) = dir {- for name in CONTEXT_FILE_NAMES {- let path = current.join(name);- if let Ok(content) = std::fs::read_to_string(&path) {- if !content.trim().is_empty() {- files.push((path, content));- }- break;+ 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));}}dir = current.parent();@@ -339,8 +337,8 @@ mod tests {let root = scratch_project("ctxfiles");let nested = root.join("sub");std::fs::create_dir_all(&nested).unwrap();- std::fs::write(root.join("AGENTS.md"), "ROOT_RULES").unwrap();- std::fs::write(nested.join("CLAUDE.md"), "NESTED_RULES").unwrap();+ std::fs::write(root.join("JAN.md"), "ROOT_RULES").unwrap();+ std::fs::write(nested.join("JAN.md"), "NESTED_RULES").unwrap();let block = load_context_files(&nested).expect("context block");assert!(block.starts_with("<project_context>"));diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex e2e26e216..2f6eef005 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -131,7 +131,6 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]# max_tokens = 4096 # cap on tokens the model generates per response (OpenAI max_tokens); omitted if unset# max_parallel_subagents = 10 # max concurrently-running subagents per run; extra dispatches queue FIFO# show_reasoning = false # expand reasoning in the transcript (Ctrl-O still toggles)-instructions_file = "AGENT.md"# Project-local provider override. Wins over ~/.jan/config.toml and any# provider inherited from Jan Desktop's settings.json. Most projects don't@@ -174,9 +173,6 @@ enabled = []inject = "always""#;-const AGENT_MD_TEMPLATE: &str =- "# Agent Instructions\n\nDescribe how this project's agent should behave.\n";-/// Path to `<project_root>/.jan/agent/agent.toml`.pub(crate) fn agent_toml_path(project_root: &Path) -> PathBuf {project_root.join(".jan").join("agent").join("agent.toml")@@ -240,10 +236,14 @@ pub(crate) fn permissions_from(cfg: &AgentToml) -> ToolPermissions {)}-/// Ensure a usable `.jan/agent/{agent.toml, AGENT.md, skills/, memory/}` exists-/// under `project_root`, creating only the pieces that don't already exist.+/// Ensure a usable `.jan/agent/{agent.toml, skills/, memory/}` exists under+/// `project_root`, creating only the pieces that don't already exist./// Idempotent and clobber-safe: preserves user edits on re-runs. Auto-managed/// on both the CLI and desktop agent-run paths (there is no explicit init step).+///+/// The project instructions file (`<project_root>/JAN.md`) is deliberately not+/// scaffolded: an empty placeholder costs prompt space and teaches nothing, so+/// it is written by `/init` or by hand.pub(crate) fn ensure_project(project_root: &Path) -> Result<PathBuf, String> {if !project_root.is_dir() {return Err(format!(@@ -262,11 +262,6 @@ pub(crate) fn ensure_project(project_root: &Path) -> Result<PathBuf, String> {std::fs::write(&toml_path, AGENT_TOML_TEMPLATE).map_err(|e| format!("Failed to write {}: {e}", toml_path.display()))?;}- let md_path = agent_dir.join("AGENT.md");- if !md_path.exists() {- std::fs::write(&md_path, AGENT_MD_TEMPLATE)- .map_err(|e| format!("Failed to write {}: {e}", md_path.display()))?;- }Ok(agent_dir)}@@ -450,12 +445,24 @@ mod tests {assert!(!root.exists(), "must not create the missing project dir");}+ /// The instructions file lives at the project root as `JAN.md` and is the+ /// user's (or `/init`'s) to create -- the scaffold must not plant an empty+ /// one under `.jan/agent/`, which nothing reads.+ #[test]+ fn ensure_does_not_scaffold_an_instructions_file() {+ let root = unique_root("no_instructions");+ let dir = ensure_project(&root).expect("ensure");+ assert!(!dir.join("AGENT.md").exists());+ assert!(!root.join("JAN.md").exists());+ assert!(!AGENT_TOML_TEMPLATE.contains("instructions_file"));+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn ensure_creates_artifacts_and_is_idempotent() {let root = unique_root("ensure");let dir = ensure_project(&root).expect("ensure");assert!(dir.join("agent.toml").exists());- assert!(dir.join("AGENT.md").exists());assert!(dir.join("skills").is_dir());assert!(dir.join("memory").is_dir());diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex be0355dee..9c69267de 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -5494,6 +5494,11 @@ const SLASH_COMMANDS: &[SlashCommand] = &[hint: "",description: "Clear the conversation",},+ SlashCommand {+ name: "/init",+ hint: "",+ description: "Study the project, then write JAN.md, skills, and memory",+ },SlashCommand {name: "/compact",hint: "",@@ -5663,6 +5668,7 @@ async fn run_command(app: &mut App, line: &str) {"config" => open_config_screen(app),"settings" => settings_command(app, arg),"goal" => goal_command(app, arg),+ "init" => init_command(app),"plan" => plan_command(app, arg),"todo" => todo_command(app, arg).await,"cancel" => cancel_command(app, arg),@@ -5671,6 +5677,45 @@ async fn run_command(app: &mut App, line: &str) {}}+/// The `/init` prompt. Onboarding a project means producing the three things a+/// later session reads back: the root `JAN.md` (ingested as project context),+/// skills for repeatable workflows, and memory for durable facts. Phrased as a+/// task for the model rather than executed here -- only the model can read the+/// project and judge what is worth writing down.+const INIT_PROMPT: &str = "Onboard yourself to this project so future sessions start informed.\n\n\+1. Study the project first. Read the README and any contributor docs, map the directory layout, and \+find the real build, test, lint, and type-check commands (from the manifests and CI config, not from \+guesswork). Note the conventions the code actually follows.\n\n\+2. Write `JAN.md` in the project root. It is the only instructions file loaded into your system \+prompt, and it is loaded every session, so it must earn its tokens: the commands to build/test/lint, \+the architecture a newcomer cannot infer from the tree, and the conventions worth enforcing. Skip \+anything obvious from a directory listing, and do not pad it. If `JAN.md` already exists, read it and \+correct what has drifted instead of rewriting it wholesale.\n\n\+3. Write skills with `skill_write` for the project's repeatable procedures -- releasing, running \+migrations, adding a module, debugging a subsystem -- one skill per procedure, only where a real \+multi-step recipe exists. Do not invent skills to fill space.\n\n\+4. Record durable project facts with `memory_write`: decisions, constraints, and gotchas that are \+true beyond this session and not already stated in the code.\n\n\+Then report what you wrote and why, briefly.";++/// `/init`: hand the model the onboarding task as an ordinary user turn, so it+/// runs with the normal toolset, permission gate, and transcript. Idle-only,+/// like the other commands that start a turn -- queueing it behind a running+/// turn would have it survey a project mid-change.+fn init_command(app: &mut App) {+ if app.status != Status::Idle {+ app.note("/init is only available while idle");+ return;+ }+ let existing = app.project_root.join("JAN.md").exists();+ 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(INIT_PROMPT.to_string());+}+/// Manually compact the conversation: summarize older turns, keeping the recent/// tail, then persist. Blocks the event loop for one model call; runs only while/// idle (the caller gates on `Status::Idle`).@@ -5799,7 +5844,6 @@ struct AgentSettingDef {enum AgentSettingKind {Int { default: Option<u64>, min: u64 },- Text { default: &'static str },/// Exact-match choice: Enter writes one of `options`, cleared field/// unsets. Covers the `read-only | deny | allow` and `always | relevance`/// toggles that hand-editing agent.toml previously required.@@ -5834,12 +5878,6 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[desc: "subagents that may run at once; extra dispatches queue FIFO",kind: AgentSettingKind::Int { default: Some(10), min: 1 },},- AgentSettingDef {- key: "instructions_file",- label: "instructions_file",- desc: "markdown injected into the system prompt",- kind: AgentSettingKind::Text { default: "AGENT.md" },- },AgentSettingDef {key: "budget.max_tokens",label: "budget.max_tokens",@@ -6025,13 +6063,6 @@ fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) {}}}- AgentSettingKind::Text { .. } => {- if prompt.input.trim().is_empty() {- None- } else {- Some(toml_edit::value(prompt.input.trim().to_string()))- }- }AgentSettingKind::Enum { options, default } => {let input = prompt.input.trim();if input.is_empty() {@@ -7811,7 +7842,6 @@ fn draw_settings_prompt(.unwrap_or_else(|| "unset".to_string());format!("default: {d} · valid: >= {min}")}- AgentSettingKind::Text { default } => format!("default: {default}"),AgentSettingKind::Enum { options, default } => {format!("default: {default} · valid: {}", options.join(" | "))}@@ -8051,9 +8081,6 @@ fn draw_picker(.unwrap_or_else(|| "unset".to_string());format!("default: {d} · valid: >= {min} · current: {current}")}- AgentSettingKind::Text { default } => {- format!("default: {default} · current: {current}")- }AgentSettingKind::Enum { options, default } => {format!("default: {default} · valid: {} · current: {current}",@@ -10884,6 +10911,30 @@ mod tests {assert!(text.contains("/login"), "{text}");}+ #[test]+ fn init_starts_a_turn_covering_all_three_artifacts() {+ let mut app = test_app();+ super::init_command(&mut app);+ assert!(app.want_start, "/init must start a turn");+ let sent = app.history.last().expect("user message").to_string();+ assert!(sent.contains("JAN.md"), "{sent}");+ assert!(sent.contains("skill_write"), "{sent}");+ assert!(sent.contains("memory_write"), "{sent}");+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }++ /// Surveying a project while a turn is mid-change would onboard against a+ /// moving target, so the command declines rather than queueing.+ #[test]+ fn init_declines_while_a_turn_is_running() {+ let mut app = test_app();+ app.status = Status::Running;+ super::init_command(&mut app);+ assert!(app.history.is_empty());+ assert!(app.message_queue.is_empty());+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }+#[test]fn successful_login_closes_the_prompt_and_adopts_a_runnable_model() {crate::core::agent::global_config::with_temp_home(|_| {@@ -11366,28 +11417,6 @@ mod tests {let _ = std::fs::remove_dir_all(&app.agent_dir);}- #[test]- fn settings_prompt_edits_text_key() {- let mut app = test_app();- std::fs::create_dir_all(&app.agent_dir).unwrap();- let toml_path = app.agent_dir.join("agent.toml");- std::fs::write(&toml_path, "[agent]\n").unwrap();-- let def = AGENT_SETTINGS- .iter()- .find(|d| d.key == "instructions_file")- .unwrap();- app.settings_prompt = Some(super::SettingsPrompt::new(def, None));- for ch in "AGENTS.md".chars() {- super::handle_settings_key(&mut app, key(KeyCode::Char(ch)), false);- }- super::handle_settings_key(&mut app, key(KeyCode::Enter), false);- assert!(app.settings_prompt.is_none());- let doc = std::fs::read_to_string(&toml_path).unwrap();- assert!(doc.contains("instructions_file = \"AGENTS.md\""), "{doc}");- let _ = std::fs::remove_dir_all(&app.agent_dir);- }-#[test]fn settings_prompt_edits_enum_key() {let mut app = test_app();diff --git a/web-app/src/lib/__tests__/skillStore.test.ts b/web-app/src/lib/__tests__/skillStore.test.tsindex 1c03c60fc..ec0813d13 100644--- a/web-app/src/lib/__tests__/skillStore.test.ts+++ b/web-app/src/lib/__tests__/skillStore.test.ts@@ -87,9 +87,9 @@ describe('skillStore', () => {})})- // agent_skill_write also runs ensure_project, scaffolding agent.toml and- // AGENT.md. The plugin owns no config format and cannot write them, so- // routing this through guest-js would silently drop the scaffold.+ // agent_skill_write also runs ensure_project, scaffolding agent.toml. The+ // plugin owns no config format and cannot write it, so routing this through+ // guest-js would silently drop the scaffold.it('writes through the core command so the project scaffold is preserved', async () => {await writeSkill(scope, 'lint', 'text')expect(invoke).toHaveBeenCalledWith('agent_skill_write', {diff --git a/web-app/src/lib/skillStore.ts b/web-app/src/lib/skillStore.tsindex 7c73835e4..4b59b6f0e 100644--- a/web-app/src/lib/skillStore.ts+++ b/web-app/src/lib/skillStore.ts@@ -24,7 +24,7 @@ export type { SkillMeta }** The project scope deliberately keeps using the core `agent_skill_*` commands* rather than the plugin's. They are not redundant: `agent_skill_write` also runs- * `ensure_project`, which scaffolds `agent.toml` and `AGENT.md`. That format is+ * `ensure_project`, which scaffolds `agent.toml`. That format is* owned by `core::agent::project`, and the plugin must not learn to write it --* owning no config format is what let the toolset be extracted at all. Routing* project writes through guest-js would silently drop the scaffold.