Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): move project state to ~/.jan/projects and scope memory (#9065)
Akarshan Biswas33e1276b48e1
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex 464775971..f7a2f92cb 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -31,7 +31,7 @@ jan <COMMAND>| Flag | Description || --- | --- |-| `--project <PATH>` | Project root containing `.jan/agent/agent.toml`. Defaults to `.` |+| `--project <PATH>` | Project root; its `agent.toml` lives in `~/.jan/projects/<slug>/`. Defaults to `.` || `--task <TEXT>` | Seed the session with a first message || `--model <ID>` | Model id, overriding `[agent].model` || `--image <PATH>` | Attach an image to the first message. Repeatable |@@ -62,8 +62,8 @@ jan --worktree # work in a dedicated checkout, not your<Callout type="warning">Tool calls are auto-approved by default, and shell commands are **not** sandboxed by default - an-approved command runs with your own access. The hard denies never lift: `.jan/agent/` internals,-anything in `[tools] deny`, and everything plan mode blocks. `--safe` adds the interactive approval+approved command runs with your own access. The hard denies never lift:+anything in `[tools] deny` and everything plan mode blocks. `--safe` adds the interactive approvalprompt; `--sandbox` adds OS confinement (bubblewrap, Seatbelt, or AppContainer). See[tool permissions](/docs/agent/permissions#the-shell-sandbox).</Callout>@@ -537,7 +537,7 @@ this document and `protocol/schema.json` in one job and fails on a diff.## `jan plugin`Manage project-local plugins without the interactive console. Plugin commands use-`.jan/agent/plugins/` under `--project` (default `.`) and print JSON for list, install, and search.+the `plugins/` folder of the project's store (`~/.jan/projects/<slug>/`) for `--project` (default `.`) and print JSON for list, install, and search.```bashjan plugin list@@ -712,7 +712,7 @@ See [MCP](/docs/agent/mcp).## `jan mcp serve`The other direction: serve Jan's own built-in tools to another MCP client. One project root, fixed-at startup; a path argument that escapes it is refused, and so is the project's hidden `.jan` state.+at startup; a path argument that escapes it is refused.```bashjan mcp serve --project . # stdio, for a client that spawns it as a childdiff --git a/docs/src/pages/docs/agent/hooks.mdx b/docs/src/pages/docs/agent/hooks.mdxindex eae56805e..121ac6396 100644--- a/docs/src/pages/docs/agent/hooks.mdx+++ b/docs/src/pages/docs/agent/hooks.mdx@@ -22,7 +22,7 @@ so nothing here is a new execution primitive.## A first hook-`.jan/agent/agent.toml`:+The project's `agent.toml` (in `~/.jan/projects/<slug>/`):```toml[[hooks]]@@ -62,7 +62,7 @@ Three sources, merged least specific first:1. an installed plugin's `<plugin>/hooks/hooks.json` - shipped by a third party2. `~/.jan/config.toml` `[[hooks]]` - this user, every project-3. `<project>/.jan/agent/agent.toml` `[[hooks]]` - this project+3. `~/.jan/projects/<slug>/agent.toml` `[[hooks]]` - this projectThey all run. Merge order is run order, so the project's hook runs last and its `context` answerlands nearest the call. The set is resolved once per run, so a hook file edited mid-run cannot@@ -176,14 +176,14 @@ And one that feeds the model a fact at the start of every turn:```bash#!/usr/bin/env bash-# .jan/agent/hooks/branch.sh+# scripts/branch.shprintf '{"context":"current branch: %s"}' "$(git rev-parse --abbrev-ref HEAD)"``````toml[[hooks]]event = "UserPromptSubmit"-command = "./.jan/agent/hooks/branch.sh"+command = "./scripts/branch.sh"````context` from `PreCompact` and `SessionEnd` is logged rather than delivered: a compaction is not a@@ -308,14 +308,14 @@ jan cli agent status --project ~/code/app"matcher": "bash","command": "./hooks/audit.sh","timeout_secs": 10,- "source": "/home/you/code/app/.jan/agent/plugins/auditor/hooks/hooks.json"+ "source": "/home/you/.jan/projects/app-1a2b3c4d/plugins/auditor/hooks/hooks.json"},{"event": "PostToolUse","matcher": "edit","command": "cargo fmt --quiet","timeout_secs": 60,- "source": "/home/you/code/app/.jan/agent/agent.toml"+ "source": "/home/you/.jan/projects/app-1a2b3c4d/agent.toml"}],"plugin_tools": [@@ -324,7 +324,7 @@ jan cli agent status --project ~/code/app"plugin": "release-tools","description": "Render the changelog between two tags","command": "./bin/changelog.sh",- "source": "/home/you/code/app/.jan/agent/plugins/release-tools"+ "source": "/home/you/.jan/projects/app-1a2b3c4d/plugins/release-tools"}]```diff --git a/docs/src/pages/docs/agent/index.mdx b/docs/src/pages/docs/agent/index.mdxindex 6da232669..4c244326b 100644--- a/docs/src/pages/docs/agent/index.mdx+++ b/docs/src/pages/docs/agent/index.mdx@@ -117,7 +117,7 @@ Desktop's [local API server](/docs/desktop/api-server), with `jan config set --b## Staying in controlThe agent edits files and runs commands without stopping to ask. File paths are checked against the-project root, and `.jan/agent/` internals and anything in `[tools] deny` are refused outright - but+project root, and anything in `[tools] deny` is refused outright - butshell commands are not sandboxed by default, so one runs with your own access.Three ways to change that:diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdxindex 24957c6c6..d79c925ef 100644--- a/docs/src/pages/docs/agent/mcp.mdx+++ b/docs/src/pages/docs/agent/mcp.mdx@@ -131,10 +131,10 @@ jan mcp serve --transport http # loopback Streamable HTTP; prints its URThe served tools run against **one project root**, fixed when the server starts, with the same pathconfinement and sandbox re-checks an in-agent call gets. A path argument that escapes that root is-refused, and so is anything inside the project's hidden `.jan` state.+refused.The default set touches no project file: file reading, search, the web tools, and the memory and-skill tools. Those last two do write, but only into the agent's own store under `.jan/agent` and+skill tools. Those last two do write, but only into the agent's own store under `~/.jan/projects/<slug>` andonly by sanitized name, so they can never reach a file in your project. Note that a skill writtenthis way is an instruction Jan's own agent may later read, so a peer you would not trust to writeinstructions should be narrowed with `--tool`.diff --git a/docs/src/pages/docs/agent/memory.mdx b/docs/src/pages/docs/agent/memory.mdxindex 74ecedbc1..696224658 100644--- a/docs/src/pages/docs/agent/memory.mdx+++ b/docs/src/pages/docs/agent/memory.mdx@@ -20,7 +20,8 @@ Good memory entries look like:## How it worksThe agent writes memory itself when it learns something durable, and reads it back into the system-prompt on later runs. It's scoped per project.+prompt on later runs. It's scoped per project, with a separate user scope for notes that apply+everywhere (see [Scopes](#scopes)).Three tools drive it, and only the write prompts for approval:@@ -34,8 +35,44 @@ Because writes prompt, nothing enters memory without you seeing it.## Where it lives-Under `<project>/.jan/agent/memory/`, as files. You can read them, edit them, delete them, or commit-them. Nothing is hidden in an opaque store.+As plain markdown files in your Jan home, outside the repository. You can read them, edit them, or+delete them. Nothing is hidden in an opaque store.++```+~/.jan/+|-- MEMORY.md # root index: user notes + one line per project with memory+|-- memory/<name>.md # user-wide notes, every project+`-- projects/<slug>/+ |-- MEMORY.md # index of this project's notes+ `-- memory/<name>.md # this project's notes+```++Each `MEMORY.md` is generated: it is rebuilt on every `memory_write` and delete, so don't edit it by+hand - your changes would be overwritten. See [Project Config](/docs/agent/project-config) for how+`<slug>` is chosen.++## Scopes++Memory names are scoped:++| Name | Refers to | Writable |+| --- | --- | --- |+| `name` | A note in this project | Yes |+| `user:name` | A user-wide note in `~/.jan/memory/`, for preferences that apply to every project | Yes |+| `project:<slug>` | Another project's `MEMORY.md` index | No |+| `project:<slug>/name` | One note from another project | No |++`memory_read` accepts all four. `memory_write` to another project is refused, so a session can only+change its own project's notes and your user notes.++The system prompt's **Available Memories** block lists this project's notes, your user notes, and+pointers to other projects that have memory, which the agent opens with `project:<slug>` only when+relevant. To keep other projects out of the prompt and refuse `project:` reads, set this in+`~/.jan/config.toml`:++```toml+memory_cross_project = false # default: true+```Retrieval is backed by the same store Jan Desktop uses for memory, so a fact learned in one isavailable in the other.@@ -54,14 +91,14 @@ README is noise; a note about the thing that surprised someone is worth keeping.If the agent has stored something wrong, delete the file. There's no special command for it - theyare just files.-## Memory and AGENT.md+## Memory and JAN.mdThey overlap, and the distinction is who writes them:| | Written by | Best for || --- | --- | --- |-| `AGENT.md` | You | Rules you want followed every time |+| `JAN.md` | You | Rules you want followed every time || Memory | The agent | Facts it discovered and shouldn't have to rediscover |If you find yourself correcting the same thing repeatedly, promote it into-[`AGENT.md`](/docs/agent/project-config#agentmd) where it's guaranteed to be in the prompt.+[`JAN.md`](/docs/agent/project-config#janmd) where it's guaranteed to be in the prompt.diff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdxindex f4b19c303..5654e8e3d 100644--- a/docs/src/pages/docs/agent/permissions.mdx+++ b/docs/src/pages/docs/agent/permissions.mdx@@ -53,7 +53,7 @@ above.## Project policy-`.jan/agent/agent.toml` sets what a project exposes:+The project's `agent.toml` (in `~/.jan/projects/<slug>/`) sets what a project exposes:```toml[tools]@@ -90,6 +90,13 @@ directory, and reaches the network only if allowed. Reads are looser: the CLI keso `git` and `ssh` credential helpers work (`[tools].allow_home_read`, set it to `false` to closethat), while the desktop masks it entirely.+While the sandbox is on, Jan's own home, `~/.jan`, is hidden from every tool and from the shell,+even when you run `jan` from your home directory. It holds `config.toml` (provider keys and hooks)+and each project's `agent.toml`, memory and threads, so no approval can open it: file tools refuse+the path, `ls`, `find` and `grep` leave it out, and the shell sees an empty directory. The agent+still reaches memory and skills through its `memory_*` and `skill_*` tools. A git worktree Jan+created under `~/.jan/worktrees/` stays reachable, because it is the project being worked on.+Whether it is on depends on the surface:| Surface | Sandbox | Can it be changed? |@@ -118,7 +125,7 @@ jan --no-sandbox # this session only, overriding a setting below``````toml-# .jan/agent/agent.toml - for everyone who checks this project out+# ~/.jan/projects/<slug>/agent.toml - every session in this project[tools]sandbox = true```@@ -152,7 +159,7 @@ rely on (a proxy setting, `git` config, a toolchain home) will not see it.Two keys widen it, without giving up the default:```toml-# .jan/agent/agent.toml (per project) or ~/.jan/config.toml (all projects)+# ~/.jan/projects/<slug>/agent.toml (per project) or ~/.jan/config.toml (all projects)[tools]# Host variables the shell may inherit. Exact names or a "*" wildcard.env_passthrough = ["SSH_AUTH_SOCK", "GIT_*", "http_proxy", "https_proxy"]@@ -178,7 +185,7 @@ command has whatever network access you do. The two surfaces default differently| Surface | How to set network access | Default || --- | --- | --- || Desktop chat agent | The chat-screen tools toggle (`agent_tools`). Per session, in the UI | Off |-| `jan cli` code-screen agent | `[tools].allow_network` in `.jan/agent/agent.toml` | On |+| `jan cli` code-screen agent | `[tools].allow_network` in the project's `agent.toml` | On |The split is deliberate. The desktop chat agent is ephemeral, so it stays offline unless you opt in.The CLI is a coding agent in your own project, where one that cannot `curl`, `git fetch`, or install@@ -202,7 +209,7 @@ Approval prompts are opt-in: by default every call above is auto-approved. Start`jan --safe` to be asked instead. See [run modes](/docs/agent/run-modes).<Callout type="info">-Auto-approval only removes the prompt. The `.jan/agent/` restriction, the path checks, and-`[tools] deny` all still apply, as does the shell sandbox where it is on - but on the CLI it is off-by default, so auto-approved shell commands run with your own access unless you turn it on.+Auto-approval only removes the prompt. The path checks and `[tools] deny` all still apply, as does+the shell sandbox where it is on - but on the CLI it is off by default, so auto-approved shell+commands run with your own access unless you turn it on.</Callout>diff --git a/docs/src/pages/docs/agent/plugins.mdx b/docs/src/pages/docs/agent/plugins.mdxindex 6334755be..0b49b1dd2 100644--- a/docs/src/pages/docs/agent/plugins.mdx+++ b/docs/src/pages/docs/agent/plugins.mdx@@ -17,7 +17,7 @@ runs commands later, once a session uses it.## Where they live```-<project>/.jan/agent/plugins/+~/.jan/projects/<slug>/plugins/└── release-tools/├── plugin.toml # optional TOML metadata├── .claude-plugin/@@ -127,7 +127,7 @@ metadata is handled honestly:[Subagents](/docs/agent/subagents#tool-permissions))Plugin agents are read-only: `create_subagent` refuses the plugin scope, and a subagent defined in-`.jan/agent/subagents/` shadows a plugin agent of the same name.+the project's `subagents/` shadows a plugin agent of the same name.## Managingdiff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdxindex 261959388..211a62d37 100644--- a/docs/src/pages/docs/agent/project-config.mdx+++ b/docs/src/pages/docs/agent/project-config.mdx@@ -1,27 +1,35 @@---title: Project Config-description: AGENT.md and agent.toml - per-project instructions, model, budget, and tool policy.-keywords: [Jan, Jan Agent, agent.toml, AGENT.md, project config, instructions, budget]+description: JAN.md and agent.toml - per-project instructions, model, budget, and tool policy.+keywords: [Jan, Jan Agent, agent.toml, JAN.md, project config, instructions, budget]---import { Callout } from 'nextra/components'# Project Config-Each project gets a `.jan/agent/` directory holding how the agent should behave there.+Each project gets a store under `~/.jan/projects/` holding how the agent should behave there. The+project directory itself holds only `JAN.md`.```your-project/-└── .jan/- └── agent/- ├── agent.toml # model, budget, tool policy- ├── AGENT.md # instructions for the agent- ├── threads/ # saved sessions- ├── skills/ # reusable procedures- ├── memory/ # durable facts- └── subagents/ # reusable subagent definitions+`-- JAN.md # instructions for the agent++~/.jan/projects/<name>-<hash>/+|-- project.json # which directory this store belongs to+|-- agent.toml # model, budget, tool policy+|-- threads/ # saved sessions+|-- skills/ # reusable procedures+|-- MEMORY.md # generated index of memory/+|-- memory/ # durable facts+|-- plugins/ # installed plugins+`-- subagents/ # reusable subagent definitions```+The store name (the `<slug>` in these docs) is the project directory's name plus a short hash of+its full path. A linked git+worktree maps to its main checkout, so both share one store.+It's created on first use. To scaffold it up front without starting a session:```bash@@ -29,11 +37,19 @@ jan cli agent status --project .```<Callout type="tip">-Commit `agent.toml`, `AGENT.md`, `skills/`, and `subagents/` so the whole team gets the same agent.-Add `threads/` to `.gitignore` - those are personal transcripts.+Commit `JAN.md` so the whole team gets the same instructions. It is the only file Jan keeps in the+project; everything in the store is per user and stays out of your repository.</Callout>-## AGENT.md+## Where state lives / migration++Older versions kept this state inside the project, in `<project>/.jan/agent/`. When Jan starts in a+workspace that still has one, it moves `.jan/agent` into the project's store automatically and says+so. It never merges: if the store already has content, the old folder is left alone with a warning,+for you to merge or delete by hand. Any other files in `.jan/` are left in place and listed. A+workspace that is your home directory is skipped, since its `.jan` is the user-wide `~/.jan`.++## JAN.mdPlain markdown, injected into the system prompt on every run. The highest-leverage file here.@@ -51,7 +67,8 @@ This is a Rust workspace. `cargo test` must pass before you call anything done.Write it as rules, not prose. Things that are true every time belong here; a procedure for one kindof task belongs in a [skill](/docs/agent/skills).-Point at a different file with `instructions_file` if you already keep conventions somewhere else.+Jan reads `JAN.md` from the project root and each of its ancestors; the nearest file wins. Write one+by hand or with `/init`.## agent.toml@@ -66,7 +83,6 @@ Point at a different file with `instructions_file` if you already keep conventio# show_reasoning = false # unfold thinking blocks in the transcript (Ctrl-O still toggles)# send_reasoning = true # resend prior reasoning to the model; false drops it from the request# worktree = true # give each session its own git checkout instead of editing this one-instructions_file = "AGENT.md"# [provider]# name = "openai"@@ -110,7 +126,6 @@ inject = "always"| `show_reasoning` | `false` | Unfold model reasoning (`<thinking>`) blocks in the transcript instead of folding them to a summary row. <kbd>Ctrl</kbd>+<kbd>O</kbd> still toggles a folded block || `send_reasoning` | `true` | Resend a prior turn's reasoning to the model with the conversation. Set `false` for an upstream that rejects the field (e.g. Groq), or to keep chains of thought out of the context budget || `worktree` | `false` | Run each session in its own git worktree under `~/.jan/worktrees`, on a `jan/agent/` branch, instead of editing this checkout. Overridden by `--worktree` / `--no-worktree`. See [Sessions](/docs/agent/sessions) |-| `instructions_file` | `AGENT.md` | Markdown injected into the system prompt |### `[provider]`@@ -140,8 +155,8 @@ ceiling was crossed, and carries on, tool calls included. For a hard bound on an### `[tools]`See [Tool permissions](/docs/agent/permissions#project-policy). `sandbox` is how a project requires-[shell confinement](/docs/agent/permissions#the-shell-sandbox) for everyone who checks it out; it is-off by default on the CLI.+[shell confinement](/docs/agent/permissions#the-shell-sandbox) for every session in it; it is off+by default on the CLI.| Key | Default | Description || --- | --- | --- |diff --git a/docs/src/pages/docs/agent/providers.mdx b/docs/src/pages/docs/agent/providers.mdxindex bf56351b7..3fde3dd0c 100644--- a/docs/src/pages/docs/agent/providers.mdx+++ b/docs/src/pages/docs/agent/providers.mdx@@ -139,9 +139,10 @@ models = ["gpt-4o"]# compaction_ratio = 0.6```-<Callout type="warning">-That file usually gets committed. Prefer leaving `api_key` out of it and keeping the key in-`~/.jan/config.toml` or the environment.+<Callout type="info">+`agent.toml` lives in the project's store under `~/.jan/projects/`, outside the repository, so it is+never committed. Keeping `api_key` in `~/.jan/config.toml` or the environment still leaves one+place to rotate it.</Callout>## Removing onediff --git a/docs/src/pages/docs/agent/run-modes.mdx b/docs/src/pages/docs/agent/run-modes.mdxindex 17ab7324c..2286cfb70 100644--- a/docs/src/pages/docs/agent/run-modes.mdx+++ b/docs/src/pages/docs/agent/run-modes.mdx@@ -30,7 +30,6 @@ established the `bash` tool refuses to run at all. It can also be turned on permSome things are denied outright and no mode lifts them:-- `.jan/agent/` internals, so the agent cannot rewrite its own permissions- anything listed in `[tools] deny` in `agent.toml`- every write and command while plan mode is ondiff --git a/docs/src/pages/docs/agent/sessions.mdx b/docs/src/pages/docs/agent/sessions.mdxindex 7e13876c1..e004d82a8 100644--- a/docs/src/pages/docs/agent/sessions.mdx+++ b/docs/src/pages/docs/agent/sessions.mdx@@ -9,7 +9,7 @@ import { Callout } from 'nextra/components'# SessionsA session is one conversation with the agent. Sessions are saved per project, under-`.jan/agent/threads`, so a project's history stays with the project.+`~/.jan/projects/<slug>/threads`, outside the repository.Because they're per project, resuming from a different directory finds nothing - that's expected,not a bug.@@ -100,7 +100,7 @@ jan --no-worktree # override a persistent settingPersistently:```toml-# .jan/agent/agent.toml - for everyone who checks this project out+# ~/.jan/projects/<slug>/agent.toml - every session in this project[agent]worktree = true```@@ -177,7 +177,8 @@ jan cli threads delete <ID>## What's stored-Under `<project>/.jan/agent/`:+Under the project's store, `~/.jan/projects/<slug>/` (see+[Project Config](/docs/agent/project-config)):| Path | Contents || --- | --- |@@ -185,5 +186,5 @@ Under `<project>/.jan/agent/`:| `memory/` | Durable facts, see [Memory](/docs/agent/memory) || `skills/` | Reusable procedures, see [Skills](/docs/agent/skills) |-Add `threads/` to `.gitignore` - those are personal transcripts. `agent.toml`, `AGENT.md`, and-`skills/` are worth committing.+None of it lives in your repository, so there is nothing to gitignore. The only file Jan keeps in+the project is `JAN.md`.diff --git a/docs/src/pages/docs/agent/skills.mdx b/docs/src/pages/docs/agent/skills.mdxindex b158ff46c..442c957bb 100644--- a/docs/src/pages/docs/agent/skills.mdx+++ b/docs/src/pages/docs/agent/skills.mdx@@ -17,7 +17,7 @@ task calls for it, so a large library of skills doesn't crowd the context window## Where they live```-<project>/.jan/agent/skills/+~/.jan/projects/<slug>/skills/├── release/│ └── SKILL.md # folder form, can bundle scripts alongside└── add-migration.md # flat form@@ -96,15 +96,15 @@ the `nightly` channel only - the same project files, through the same directory.in one shows up in the other.</Callout>-## Skills, AGENT.md, and memory+## Skills, JAN.md, and memoryThree places that shape behaviour, easily confused:| | Scope | Loaded || --- | --- | --- |-| [`AGENT.md`](/docs/agent/project-config#agentmd) | Rules for everything the agent does here | Always |+| [`JAN.md`](/docs/agent/project-config#janmd) | Rules for everything the agent does here | Always || Skills | A specific procedure | On demand, when relevant || [Memory](/docs/agent/memory) | Facts the agent learned | Recalled as needed |-Rule of thumb: if it applies to every task, it belongs in `AGENT.md`. If it applies to one kind of+Rule of thumb: if it applies to every task, it belongs in `JAN.md`. If it applies to one kind oftask, make it a skill.diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 780c269c7..b91d6d11d 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -69,7 +69,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-| `/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 |-| `/settings [max_parallel_subagents N]` | Edit settings in an interactive menu - the project's `agent.toml` (`[agent]` knobs `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `instructions_file`, `[budget]` limits, the `[tools]` / `[skills]` toggles) and user-wide `~/.jan/config.toml` keys such as `wave` and `ask_timeout_secs` in the one list (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets - except `wave`, where an empty field is the "no sweep" value and `x` restores the default 👋). The leading `providers` row opens a manager for OpenAI-compatible providers in `~/.jan/config.toml`: `a` adds, Enter edits, `d` twice deletes. `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run, except cosmetic ones like `wave` that apply immediately |+| `/settings [max_parallel_subagents N]` | Edit settings in an interactive menu - the project's `agent.toml` (`[agent]` knobs `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `[budget]` limits, the `[tools]` / `[skills]` toggles) and user-wide `~/.jan/config.toml` keys such as `wave` and `ask_timeout_secs` in the one list (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets - except `wave`, where an empty field is the "no sweep" value and `x` restores the default 👋). The leading `providers` row opens a manager for OpenAI-compatible providers in `~/.jan/config.toml`: `a` adds, Enter edits, `d` twice deletes. `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run, except cosmetic ones like `wave` that apply immediately |See [Providers](/docs/agent/providers), [MCP](/docs/agent/mcp), [Plugins](/docs/agent/plugins), and[Keybindings](/docs/agent/keybindings#shiftenter-and-the-option-key).diff --git a/docs/src/pages/docs/agent/subagents.mdx b/docs/src/pages/docs/agent/subagents.mdxindex 31233ffaa..c7989d428 100644--- a/docs/src/pages/docs/agent/subagents.mdx+++ b/docs/src/pages/docs/agent/subagents.mdx@@ -108,8 +108,8 @@ costs you only its final answer.Definitions are TOML files, merged from two scopes:```-~/.jan/agent/subagents/<name>.toml # user scope, available everywhere-<project>/.jan/agent/subagents/<name>.toml # project scope, shareable via git+~/.jan/agent/subagents/<name>.toml # user scope, available everywhere+~/.jan/projects/<slug>/subagents/<name>.toml # project scope, this project only```The two are merged, and the project scope shadows the user scope by name - so a project can@@ -138,8 +138,8 @@ Create a subagent called "reviewer" that reviews diffs for correctnessand never edits files.```-That writes to the project scope by default, so it can be committed and shared. Ask for the user-scope to keep it to yourself.+That writes to the project scope by default, so it applies only in this project. Ask for the user+scope to use it everywhere.Once saved, refer to it by name and it picks up its stored prompt and permissions.diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 4b71bde12..3c51661bb 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -57,7 +57,7 @@ to opt out of both.",struct Cli {#[command(subcommand)]command: Option<Commands>,- /// Project root containing .jan/agent/agent.toml (bare TUI only)+ /// Project root (its agent.toml lives in ~/.jan/projects/<slug>/) (bare TUI only)#[arg(long, default_value = ".")]project: String,/// Optional first message to seed the chat with (bare TUI only)@@ -142,7 +142,7 @@ impl SandboxArgs {}/// Session-resume selection, shared by the bare TUI and `jan cli agent run`.-/// Threads are per-project (`<project>/.jan/agent/threads`), so resuming from a+/// Threads are per-project (`~/.jan/projects/<slug>/threads`), so resuming from a/// different working directory simply finds nothing there.#[derive(Args)]struct ResumeArgs {@@ -443,7 +443,7 @@ impl ProviderArgs {enum AgentCommands {/// Run the agent loop to completion, or to a --max-turns capRun {- /// Project root containing .jan/agent/agent.toml+ /// Project root (its agent.toml lives in ~/.jan/projects/<slug>/)#[arg(long, default_value = ".")]project: String,/// The task/prompt for the agent@@ -492,7 +492,7 @@ enum AgentCommands {},/// Run a single turn (debugging)Step {- /// Project root containing .jan/agent/agent.toml+ /// Project root (its agent.toml lives in ~/.jan/projects/<slug>/)#[arg(long, default_value = ".")]project: String,/// The task/prompt for the agent@@ -510,7 +510,7 @@ enum AgentCommands {},/// Print resolved project config and available providers as JSONStatus {- /// Project root containing .jan/agent/agent.toml+ /// Project root (its agent.toml lives in ~/.jan/projects/<slug>/)#[arg(long, default_value = ".")]project: String,#[command(flatten)]diff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rsindex a02aa8a2e..5bed875b8 100644--- a/src-tauri/jan-cli/tests/agent_rpc.rs+++ b/src-tauri/jan-cli/tests/agent_rpc.rs@@ -58,6 +58,11 @@ fn provider(tokens: usize, token_bytes: usize) -> String {}/// A scratch directory of our own, so the two tests never share a `~/.jan`.+/// The project's store as the binary resolves it under the test's `HOME`.+fn store(home: &Path, project: &Path) -> PathBuf {+ tauri_plugin_agent_tools::workspace::project_store_in(&home.join(".jan"), project)+}+fn scratch(name: &str) -> PathBuf {let dir = std::env::temp_dir().join(format!("jan-rpc-{name}-{}", std::process::id()));std::fs::create_dir_all(dir.join("home")).unwrap();@@ -243,8 +248,8 @@ fn rpc_serves_a_session_lifecycle_after_the_handshake() {assert_eq!(terminal["params"]["stopReason"], "completed");assert!(saw_text, "the real provider's streamed token reaches RPC");assert!(- project- .join(".jan/agent/threads")+ store(&home, &project)+ .join("threads").join(&session_id).exists(),"completed non-ephemeral turn persists under its RPC session id"@@ -328,7 +333,7 @@ fn failed_fork_does_not_close_other_sessions() {rpc.handshake();let project = scratch.join("project");let session_id = rpc.start_session(&project);- std::fs::write(project.join(".jan/agent/agent.toml"), "[agent\n").unwrap();+ std::fs::write(store(&home, &project).join("agent.toml"), "[agent\n").unwrap();let failure = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":4,"method":"session/fork","params":{"sessionId":session_id}}));assert_eq!(failure["id"], 4);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex b7b4b0bf5..b63a473f3 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -80,8 +80,8 @@ pub struct ToolResult {/// The permanent store root holding `memory/` and `skills/`.////// `project` is an explicit override and is currently always `None`: the desktop-/// has no project picker yet. Once one lands, a project's own co-located store-/// (`<project>/.jan/agent`) layers on top of this one; see the memory-scope TODO.+/// has no project picker yet. Once one lands, a project's own store+/// (`~/.jan/projects/<slug>`) layers on top of this one; see the memory-scope TODO.fn resolve_store(data_folder: &str, project: Option<&str>) -> PathBuf {match project.map(str::trim).filter(|p| !p.is_empty()) {Some(p) => workspace::project_store(Path::new(p)),@@ -582,6 +582,7 @@ pub async fn start_monitor(project_root: root,scratch_root: Some(scratch),mask_root: Some(PathBuf::from(&data_folder)),+ hidden_root: workspace::hidden_root(true),read_roots,write_roots,allow_network: allow_network.unwrap_or(false),@@ -869,6 +870,9 @@ async fn execute_tool_inner();let tool = lookup(&name).ok_or_else(|| AgentToolsError::from(format!("unknown built-in tool '{name}'")))?;+ // The desktop always sandboxes, and an attached project folder can be the+ // user's home, which puts the CLI's `~/.jan` inside it.+ let hidden = workspace::hidden_root(true);match gate::resolve_decision(tool,@@ -878,22 +882,18 @@ async fn execute_tool_inner(scratch: Some(&scratch),read_roots: &read_roots,write_roots: &write_roots,- hide_jan: true,+ hidden_root: hidden.as_deref(),},&ToolPermissions::default(),&SessionGrants::default(),) {Decision::Allow => {}- Decision::HardDeny(gate::DenyReason::Hidden) => {- return Err(format!(- "tool '{name}' is denied: {} is the agent's own state directory and is hidden",- crate::tools::sandbox::JAN_DIR- )- .into());- }Decision::HardDeny(gate::DenyReason::Policy) => {return Err(format!("tool '{name}' is denied by policy").into());}+ Decision::HardDeny(gate::DenyReason::Hidden) => {+ return Err(format!("tool '{name}' is denied: the Jan home (~/.jan) is hidden").into());+ }// An exec prompt asks the user to vouch for a command that could reach// anything. Under an enforcing sandbox it cannot: writes stay in the// thread workspace and $HOME is unreadable, so the containment the prompt@@ -976,6 +976,7 @@ async fn execute_tool_inner(.with_scratch_root(&scratch).with_read_roots(&read_roots).with_write_roots(&write_roots)+ .with_hidden_root(hidden.as_deref()).with_thread_id(Some(&thread_id)).with_screenshot_backend(screenshot_backend);if let Some(sp) = skill_project.as_deref() {@@ -1180,10 +1181,10 @@ mod tests {}#[test]- fn explicit_project_uses_its_co_located_store() {+ fn explicit_project_uses_its_project_store() {assert_eq!(resolve_store("/data", Some("/repo")),- Path::new("/repo/.jan/agent")+ workspace::project_store(Path::new("/repo")));// Blank is treated as absent, not as the filesystem root.assert_eq!(@@ -1745,35 +1746,6 @@ mod tests {let _ = std::fs::remove_dir_all(&data);}- #[tokio::test]- async fn agent_config_surface_is_hard_denied() {- let data = unique_data_folder();- let df = data.to_string_lossy().to_string();- thread_workspace_path(df.clone(), T1.into()).await.unwrap();-- let err = execute_tool(- df.clone(),- T1.into(),- None,- "read".to_string(),- json!({"path": ".jan/agent/agent.toml"}),- None,- None,- None,- None,- None,- None,- )- .await- .expect_err("agent config must be hard-denied");- assert!(- err.message.contains("is hidden"),- "unexpected: {}",- err.message- );- let _ = std::fs::remove_dir_all(&data);- }-#[tokio::test]async fn unknown_tool_is_rejected() {let data = unique_data_folder();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md b/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.mdindex db8629b87..f3171e472 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/default_jan_skill.md@@ -12,34 +12,35 @@ Run `jan` in a folder. That CWD is the project root; `--project DIR` selects ano## Project filesJan reads non-empty `JAN.md` files from the project root and its ancestors. The nearest file wins.-Jan creates this separate state tree on first use:+`JAN.md` is the only file Jan keeps in the project; commit it to share instructions.+Everything else is per-user state under `~/.jan/`, created on first use.++## User files```text-<project>/-|-- JAN.md # always-loaded project instructions-`-- .jan/- `-- agent/+~/.jan/+|-- config.toml # CLI provider configuration and credentials+|-- MEMORY.md # generated index: user notes + projects with memory+|-- memory/ # user-wide notes (`user:<name>`), every project+`-- projects/+ `-- <name>-<hash>/ # one per project directory (git worktrees share it)+ |-- project.json # which directory this store belongs to|-- agent.toml # model, provider, budget, tools, skills+ |-- MEMORY.md # generated index of this project's notes+ |-- memory/ # durable project facts|-- skills/| `-- <name>/| `-- SKILL.md # procedure, plus optional scripts/templates- |-- memory/ # durable project facts+ |-- plugins/|-- threads/ # saved conversations`-- subagents/ # reusable agent definitions````agent.toml` has `[agent]`, `[provider]`, `[budget]`, `[tools]`, and `[skills]` sections.-A simple skill can be `skills/<name>.md`. Commit `JAN.md`, `agent.toml`, `skills/`, and-`subagents/`; gitignore `threads/`. Run `jan cli agent status --project .` to scaffold the tree.--## User-global files--`~/.jan/` is separate from a project's `.jan/`:--```text-~/.jan/-`-- config.toml # CLI provider configuration and credentials-```+A simple skill can be `skills/<name>.md`. Run `jan cli agent status --project .` to scaffold+the store. A project that still has a `.jan/` folder from an older Jan is moved into+`~/.jan/projects/` automatically the next time Jan starts in it.+`memory_cross_project = false` in `config.toml` hides other projects' memory from the agent.Jan Desktop stores its settings and shared MCP configuration under the platform support folder:diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rsindex e65a248d9..4bad107e1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs@@ -1,9 +1,17 @@-//! Long-term agent memory: flat `<name>.md` notes under `<store_root>/memory/`.+//! Long-term agent memory: `<name>.md` notes under `<store_root>/memory/`,+//! indexed by a generated `<store_root>/MEMORY.md`.//!//! Every function takes a store root rather than a project root, so the same-//! implementation serves the desktop's permanent store in the Jan data folder and-//! a project's co-located `<project>/.jan/agent` store. Memory deliberately-//! outlives the ephemeral per-thread sandbox the filesystem tools run in.+//! implementation serves the desktop's permanent store in the Jan data folder,+//! a project's store under `~/.jan/projects/<slug>`, and the user-wide store at+//! `~/.jan` itself (whose `MEMORY.md` is the root index: user notes plus one+//! pointer per project). Memory deliberately outlives the ephemeral per-thread+//! sandbox the filesystem tools run in.+//!+//! The indexes are generated from the notes on every write, never hand-edited,+//! so they cannot drift from what is on disk. [`Scopes`] resolves the names the+//! `memory_*` tools accept: `note` (this project), `user:note`, and, read-only,+//! `project:<slug>` / `project:<slug>/note` for another project.//!//! This is the store the `memory_*` built-in tools read and write, and the same//! one the management commands expose, so both share one implementation. It is@@ -15,10 +23,16 @@use std::path::{Path, PathBuf};-use crate::workspace::{store_dir, workspace_filename};+use crate::workspace::{project_meta, projects_dir, store_dir, workspace_filename};const KIND: &str = "memory";+/// The generated index at the top of every store.+pub const INDEX_FILE: &str = "MEMORY.md";++const USER_PREFIX: &str = "user:";+const PROJECT_PREFIX: &str = "project:";+/// `<store_root>/memory`.pub fn memory_dir(store_root: &Path) -> PathBuf {store_dir(store_root, KIND)@@ -134,8 +148,9 @@ pub fn catalog(store: &Path) -> Vec<CatalogEntry> {notes}-/// Create or overwrite a note. Returns the filename written, so callers can-/// phrase their own result message. Parent directories are created as needed.+/// Create or overwrite a note and regenerate the store's index. Returns the+/// filename written, so callers can phrase their own result message. Parent+/// directories are created as needed.pub async fn write(store: &Path, name: &str, content: &str) -> Result<String, String> {let file = workspace_filename(name)?;let dir = memory_dir(store);@@ -145,19 +160,302 @@ pub async fn write(store: &Path, name: &str, content: &str) -> Result<String, Sttokio::fs::write(dir.join(&file), content).await.map_err(|e| format!("ERROR: {e}"))?;+ write_index(store);Ok(file)}-/// Delete a note. Idempotent: a missing note is Ok.+/// Delete a note and regenerate the store's index. Idempotent: a missing note+/// is Ok.pub async fn delete(store: &Path, name: &str) -> Result<(), String> {let target = target(store, name)?;match tokio::fs::remove_file(&target).await {- Ok(()) => Ok(()),+ Ok(()) => {+ write_index(store);+ Ok(())+ }Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),Err(e) => Err(format!("ERROR: {e}")),}}+/// `- `<prefix><name>` - summary` rows, one per note.+fn note_rows(prefix: &str, notes: &[CatalogEntry]) -> Vec<String> {+ notes+ .iter()+ .map(|n| {+ if n.summary.is_empty() {+ format!("- `{prefix}{}` - no summary", n.name)+ } else {+ format!("- `{prefix}{}` - {}", n.name, n.summary)+ }+ })+ .collect()+}++/// A project store's `MEMORY.md`: one row per note. Empty when it has none.+pub fn project_index(store: &Path) -> String {+ let rows = note_rows("", &catalog(store));+ if rows.is_empty() {+ return String::new();+ }+ format!("# Project memory\n\n{}\n", rows.join("\n"))+}++/// Regenerate `<store>/MEMORY.md` from the notes. Best-effort: an index that+/// fails to write is rebuilt on the next write, and the prompt never reads it.+pub fn write_index(store: &Path) {+ let path = store.join(INDEX_FILE);+ let body = project_index(store);+ if body.is_empty() {+ let _ = std::fs::remove_file(&path);+ } else {+ let _ = std::fs::write(&path, body);+ }+}++/// One other project, as the root index points at it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectPointer {+ pub slug: String,+ /// The project directory the store belongs to, when it recorded one.+ pub path: Option<String>,+ pub notes: usize,+}++/// Every project store under `<jan_home>/projects` that holds at least one+/// note, except `exclude` (the current project). Sorted by slug.+pub fn project_pointers(jan_home: &Path, exclude: Option<&Path>) -> Vec<ProjectPointer> {+ let Ok(rd) = std::fs::read_dir(projects_dir(jan_home)) else {+ return Vec::new();+ };+ let mut out: Vec<ProjectPointer> = rd+ .flatten()+ .filter(|e| e.path().is_dir())+ .filter(|e| exclude != Some(e.path().as_path()))+ .filter_map(|e| {+ let slug = e.file_name().to_str()?.to_string();+ if slug.starts_with('.') {+ return None;+ }+ let notes = catalog(&e.path()).len();+ (notes > 0).then(|| ProjectPointer {+ slug,+ path: project_meta(&e.path()),+ notes,+ })+ })+ .collect();+ out.sort_by(|a, b| a.slug.cmp(&b.slug));+ out+}++fn pointer_rows(pointers: &[ProjectPointer]) -> Vec<String> {+ pointers+ .iter()+ .map(|p| {+ let plural = if p.notes == 1 { "note" } else { "notes" };+ match &p.path {+ Some(path) => format!("- `{PROJECT_PREFIX}{}` - {path} ({} {plural})", p.slug, p.notes),+ None => format!("- `{PROJECT_PREFIX}{}` - ({} {plural})", p.slug, p.notes),+ }+ })+ .collect()+}++/// The root `~/.jan/MEMORY.md`: user-wide notes, then (when `cross_project`) a+/// pointer to every project with memory. Empty when there is nothing to list.+pub fn root_index(jan_home: &Path, cross_project: bool) -> String {+ let mut sections = Vec::new();+ let user = note_rows(USER_PREFIX, &catalog(jan_home));+ if !user.is_empty() {+ sections.push(format!("## User notes (all projects)\n\n{}", user.join("\n")));+ }+ if cross_project {+ let projects = pointer_rows(&project_pointers(jan_home, None));+ if !projects.is_empty() {+ sections.push(format!("## Projects\n\n{}", projects.join("\n")));+ }+ }+ if sections.is_empty() {+ return String::new();+ }+ format!("# Memory\n\n{}\n", sections.join("\n\n"))+}++/// Regenerate the root index. Best-effort, like [`write_index`].+pub fn write_root_index(jan_home: &Path, cross_project: bool) {+ let path = jan_home.join(INDEX_FILE);+ let body = root_index(jan_home, cross_project);+ if body.is_empty() {+ let _ = std::fs::remove_file(&path);+ } else if std::fs::create_dir_all(jan_home).is_ok() {+ let _ = std::fs::write(&path, body);+ }+}++/// The memory a run can reach, and how scoped names resolve against it.+#[derive(Debug, Clone, Copy)]+pub struct Scopes<'a> {+ /// The current store: unprefixed names read and write here.+ pub store: &'a Path,+ /// `~/.jan`, holding the user-wide notes and every project's store. `None`+ /// on the desktop, whose store is the data folder's and has no user scope.+ pub home: Option<&'a Path>,+ /// Whether other projects are listed and readable.+ pub cross_project: bool,+}++/// Where a scoped name points.+#[derive(Debug, PartialEq, Eq)]+struct Resolved {+ store: PathBuf,+ /// `None` for `project:<slug>`, which names that project's index.+ note: Option<String>,+ /// Only the current project's and the user's notes are writable; another+ /// project's memory is that project's to curate.+ writable: bool,+}++impl<'a> Scopes<'a> {+ /// Scopes with only the current store (the desktop, and tests).+ pub fn store_only(store: &'a Path) -> Self {+ Self {+ store,+ home: None,+ cross_project: false,+ }+ }++ fn home(&self) -> Result<&'a Path, String> {+ self.home+ .ok_or_else(|| "ERROR: this session has no user or cross-project memory".to_string())+ }++ fn resolve(&self, name: &str) -> Result<Resolved, String> {+ let name = name.trim();+ if let Some(note) = name.strip_prefix(USER_PREFIX) {+ return Ok(Resolved {+ store: self.home()?.to_path_buf(),+ note: Some(note.to_string()),+ writable: true,+ });+ }+ let Some(rest) = name.strip_prefix(PROJECT_PREFIX) else {+ return Ok(Resolved {+ store: self.store.to_path_buf(),+ note: Some(name.to_string()),+ writable: true,+ });+ };+ let (slug, note) = match rest.split_once('/') {+ Some((slug, note)) => (slug, Some(note.to_string())),+ None => (rest, None),+ };+ if slug.is_empty() || slug.contains(['/', '\\']) || slug.contains("..") {+ return Err(format!("ERROR: invalid project '{slug}'"));+ }+ let store = projects_dir(self.home()?).join(slug);+ if store == self.store {+ return Ok(Resolved {+ store,+ note,+ writable: true,+ });+ }+ if !self.cross_project {+ return Err(+ "ERROR: cross-project memory is off (memory_cross_project = false in ~/.jan/config.toml)"+ .to_string(),+ );+ }+ if !store.is_dir() {+ return Err(format!("ERROR: no project '{slug}'"));+ }+ Ok(Resolved {+ store,+ note,+ writable: false,+ })+ }++ /// Read a note, or with `project:<slug>` that project's index.+ pub async fn read(&self, name: &str) -> Result<String, String> {+ let target = self.resolve(name)?;+ match target.note {+ Some(note) => read(&target.store, ¬e).await,+ None => {+ let index = project_index(&target.store);+ Ok(if index.is_empty() {+ "(no memory notes)".to_string()+ } else {+ index+ })+ }+ }+ }++ /// Write a note in the current project or the user scope, then refresh the+ /// root index so its pointers stay current. Returns the path written,+ /// relative to its store's parent scope, for the tool result.+ pub async fn write(&self, name: &str, content: &str) -> Result<String, String> {+ let target = self.resolve(name)?;+ let Some(note) = target.note.filter(|_| target.writable) else {+ return Err(format!(+ "ERROR: '{name}' is read-only: write to this project's notes (`name`) or your own (`user:name`)"+ ));+ };+ let file = write(&target.store, ¬e, content).await?;+ if let Some(home) = self.home {+ write_root_index(home, self.cross_project);+ }+ let is_user = self.home.is_some_and(|h| target.store == h);+ Ok(if is_user { format!("{USER_PREFIX}{file}") } else { file })+ }++ /// The current project's note names, then the user's as `user:<name>`.+ pub async fn list(&self) -> Vec<String> {+ let mut names = list(self.store).await;+ if let Some(home) = self.home {+ names.extend(list(home).await.into_iter().map(|n| format!("{USER_PREFIX}{n}")));+ }+ names+ }++ /// The prompt's memory block: this project's index, then the user's notes+ /// and (when `cross_project`) pointers to other projects. `None` when there+ /// is nothing to show. Rendered from the notes, not from the `MEMORY.md`+ /// files, so a stale or hand-edited index can never reach the model.+ pub fn prompt_block(&self) -> Option<String> {+ let mut sections = Vec::new();+ let project = note_rows("", &catalog(self.store));+ if !project.is_empty() {+ sections.push(format!("## This project\n\n{}", project.join("\n")));+ }+ if let Some(home) = self.home {+ let user = note_rows(USER_PREFIX, &catalog(home));+ if !user.is_empty() {+ sections.push(format!("## User notes (all projects)\n\n{}", user.join("\n")));+ }+ if self.cross_project {+ let others = pointer_rows(&project_pointers(home, Some(self.store)));+ if !others.is_empty() {+ sections.push(format!(+ "## Other projects\n\nRead-only. `memory_read` a project to see its notes; only open one when it is relevant.\n\n{}",+ others.join("\n")+ ));+ }+ }+ }+ if sections.is_empty() {+ return None;+ }+ Some(format!(+ "# Available Memories\n\nDurable facts recorded in earlier sessions. Read a note's full contents with `memory_read` when it is relevant to the current task.\n\n{}",+ sections.join("\n\n")+ ))+ }+}+#[cfg(test)]mod tests {use super::*;@@ -265,4 +563,115 @@ mod tests {assert!(catalog(&root).is_empty());let _ = std::fs::remove_dir_all(&root);}++ fn scopes_fixture() -> (PathBuf, PathBuf, PathBuf) {+ let home = unique_root();+ let current = projects_dir(&home).join("app-1");+ let other = projects_dir(&home).join("lib-2");+ std::fs::create_dir_all(¤t).unwrap();+ std::fs::create_dir_all(memory_dir(&other)).unwrap();+ std::fs::write(memory_dir(&other).join("api.md"), "Lib API is frozen.").unwrap();+ std::fs::write(other.join("project.json"), "{\"path\": \"/src/lib\"}").unwrap();+ (home, current, other)+ }++ #[tokio::test]+ async fn write_generates_the_store_index_and_delete_removes_it() {+ let root = unique_root();+ write(&root, "prefs", "# Prefs\nKeep it minimal.").await.unwrap();+ let index = std::fs::read_to_string(root.join(INDEX_FILE)).unwrap();+ assert!(index.contains("- `prefs` - Keep it minimal."), "{index}");++ delete(&root, "prefs").await.unwrap();+ assert!(!root.join(INDEX_FILE).exists(), "an empty store has no index");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn scoped_names_route_to_user_and_project_stores() {+ let (home, current, _other) = scopes_fixture();+ let scopes = Scopes {+ store: ¤t,+ home: Some(&home),+ cross_project: true,+ };++ assert_eq!(scopes.write("local", "Here.").await.unwrap(), "local.md");+ assert_eq!(scopes.write("user:prefs", "Everywhere.").await.unwrap(), "user:prefs.md");+ assert!(memory_dir(¤t).join("local.md").is_file());+ assert!(memory_dir(&home).join("prefs.md").is_file());+ assert_eq!(scopes.read("user:prefs").await.unwrap(), "Everywhere.");+ assert_eq!(scopes.list().await, vec!["local", "user:prefs"]);++ // Another project is readable, index and note, but never writable.+ assert!(scopes.read("project:lib-2").await.unwrap().contains("`api`"));+ assert_eq!(scopes.read("project:lib-2/api").await.unwrap(), "Lib API is frozen.");+ assert!(scopes.write("project:lib-2/api", "x").await.unwrap_err().contains("read-only"));+ assert!(scopes.read("project:nope/api").await.is_err());+ assert!(scopes.read("project:../x/api").await.is_err());++ // The root index lists user notes and points at projects with memory.+ let root = std::fs::read_to_string(home.join(INDEX_FILE)).unwrap();+ assert!(root.contains("- `user:prefs` - Everywhere."), "{root}");+ assert!(root.contains("- `project:lib-2` - /src/lib (1 note)"), "{root}");+ assert!(root.contains("- `project:app-1`"), "{root}");+ let _ = std::fs::remove_dir_all(&home);+ }++ #[tokio::test]+ async fn cross_project_off_hides_and_refuses_other_projects() {+ let (home, current, _other) = scopes_fixture();+ let scopes = Scopes {+ store: ¤t,+ home: Some(&home),+ cross_project: false,+ };+ assert!(scopes.read("project:lib-2/api").await.unwrap_err().contains("cross-project"));+ // The current project stays addressable by its own slug.+ scopes.write("mine", "ok").await.unwrap();+ assert_eq!(scopes.read("project:app-1/mine").await.unwrap(), "ok");+ assert!(!scopes.prompt_block().unwrap().contains("lib-2"));+ assert!(!root_index(&home, false).contains("lib-2"));+ let _ = std::fs::remove_dir_all(&home);+ }++ #[tokio::test]+ async fn a_store_only_scope_has_no_user_or_project_names() {+ let root = unique_root();+ let scopes = Scopes::store_only(&root);+ assert!(scopes.write("user:x", "y").await.is_err());+ assert!(scopes.read("project:a/b").await.is_err());+ scopes.write("x", "y").await.unwrap();+ assert_eq!(scopes.list().await, vec!["x"]);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn prompt_block_opens_this_project_and_points_at_the_rest() {+ let (home, current, _other) = scopes_fixture();+ std::fs::create_dir_all(memory_dir(¤t)).unwrap();+ std::fs::write(memory_dir(¤t).join("build.md"), "Use yarn.").unwrap();+ std::fs::create_dir_all(memory_dir(&home)).unwrap();+ std::fs::write(memory_dir(&home).join("style.md"), "Be terse.").unwrap();++ let block = Scopes {+ store: ¤t,+ home: Some(&home),+ cross_project: true,+ }+ .prompt_block()+ .unwrap();+ assert!(block.starts_with("# Available Memories"));+ let this = block.find("## This project").unwrap();+ let user = block.find("## User notes").unwrap();+ let others = block.find("## Other projects").unwrap();+ assert!(this < user && user < others, "{block}");+ assert!(block.contains("- `build` - Use yarn."));+ assert!(block.contains("- `user:style` - Be terse."));+ assert!(block.contains("`project:lib-2` - /src/lib (1 note)"));+ assert!(!block.contains("project:app-1"), "the current project is not a pointer");+ assert!(!block.contains("Lib API is frozen."), "bodies stay out of the prompt");+ let _ = std::fs::remove_dir_all(&home);+ }+}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 9b82dc1c5..1e291cb0b 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@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};use crate::permissions::ToolPermissions;use crate::tools::cmdscan::{normalize, scan_command, CommandScan};use crate::tools::sandbox::{- command_touches_hidden_jan_path, escapes_read_roots, escapes_write_roots, is_hidden_jan_path,+ command_touches_hidden_root, escapes_read_roots, escapes_write_roots, in_hidden_root,};use crate::tools::{BuiltinTool, Capability};@@ -113,7 +113,7 @@ impl SessionGrants {pub enum DenyReason {/// `[tools] deny` in agent.toml names this tool.Policy,- /// The call reaches `<project>/.jan`, which is hidden from every tool.+ /// The call reaches the Jan home (`~/.jan`), hidden from every tool.Hidden,}@@ -124,7 +124,7 @@ pub enum Decision {Prompt(PromptKind),}-/// Filesystem roots and hiding policy used when gating a tool call.+/// Filesystem roots used when gating a tool call.#[derive(Debug, Clone, Copy)]pub struct GateContext<'a> {/// The project root: paths inside it are the agent's own workspace.@@ -136,8 +136,12 @@ pub struct GateContext<'a> {/// The subset of `read_roots` the caller marked writable: writes inside one/// are ordinary in-project writes rather than escapes.pub write_roots: &'a [PathBuf],- /// Hide the agent's own `.jan` state (skills/memory/config) from general tools.- pub hide_jan: bool,+ /// The Jan home (`~/.jan`: `config.toml` with keys and hooks, every+ /// project's store). Set while the shell is sandboxed; paths and commands+ /// reaching it are refused outright, wherever it sits relative to the+ /// project (running in `$HOME` puts it inside). See+ /// [`crate::tools::sandbox::in_hidden_root`] for the worktree exception.+ pub hidden_root: Option<&'a Path>,}/// Decide how a built-in tool call should be gated, combining the static@@ -157,27 +161,23 @@ pub fn resolve_decision(if perms.is_denied(tool.name) {return Decision::HardDeny(DenyReason::Policy);}- // Nothing under .jan is reachable while hidden: skills/memory only through- // their dedicated tools, config, threads and the dir listing not at all.- // Checked ahead of allow rules so an allowed tool name cannot bypass it.- // The whole check is skipped when not hiding, so an unconfined CLI run can- // read and edit its own `.jan` like any other project state.- let hits_hidden = ctx.hide_jan- && tool.path_args.iter().any(|key| {+ // Ahead of allow rules and session grants, so neither an allowed tool name+ // nor a routine "allow writes" approval reaches keys, hooks or the agent's+ // own permissions.+ if let Some(hidden) = ctx.hidden_root {+ let hits_path = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())- .map(|p| is_hidden_jan_path(ctx.project_root, p))- .unwrap_or(false)+ .is_some_and(|p| in_hidden_root(ctx.project_root, ctx.scratch, hidden, p))});- let exec_hits_hidden = ctx.hide_jan- && tool.capability == Capability::Exec- && args- .get("command")- .and_then(|v| v.as_str())- .map(|c| command_touches_hidden_jan_path(ctx.project_root, c))- .unwrap_or(false);- if hits_hidden || exec_hits_hidden {- return Decision::HardDeny(DenyReason::Hidden);+ let hits_command = tool.capability == Capability::Exec+ && args+ .get("command")+ .and_then(|v| v.as_str())+ .is_some_and(|c| command_touches_hidden_root(ctx.project_root, ctx.scratch, hidden, c));+ if hits_path || hits_command {+ return Decision::HardDeny(DenyReason::Hidden);+ }}if perms.is_allowed(tool.name) {return Decision::Allow;@@ -294,7 +294,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -316,7 +316,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -339,7 +339,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -363,7 +363,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -376,114 +376,92 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// Regression for the #9065 review: with `$HOME` as the project, the Jan+ /// home is inside it, and neither default permissions, a session Write+ /// grant nor an allow-all policy may reach its keys, hooks or the agent's+ /// own permissions.#[test]- fn agent_config_is_off_limits_to_every_tool() {- let root = unique_root();- std::fs::create_dir_all(root.join(".jan/agent")).unwrap();- std::fs::write(root.join(".jan/agent/agent.toml"), b"[tools]\n").unwrap();- let perms = ToolPermissions::allow_all();- let grants = SessionGrants::default();- // Read/ls/find/grep and write/edit all hard-deny on agent.toml.- for tool in ["read", "ls", "find", "grep", "write", "edit"] {- let d = resolve_decision(- lookup(tool).unwrap(),- &json!({ "path": ".jan/agent/agent.toml" }),- &GateContext {- project_root: &root,- scratch: None,- read_roots: &[],- write_roots: &[],- hide_jan: true,- },- &perms,- &grants,- );- assert_eq!(- d,- Decision::HardDeny(DenyReason::Hidden),- "{tool} on agent.toml must be denied"- );+ fn the_jan_home_is_refused_when_the_project_is_home() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(jan.join("projects/home-1")).unwrap();+ std::fs::write(jan.join("config.toml"), b"[providers]\n").unwrap();+ std::fs::write(jan.join("projects/home-1/agent.toml"), b"[tools]\n").unwrap();+ let ctx = GateContext {+ project_root: &home,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let mut granted = SessionGrants::default();+ granted.grant(PromptKind::Write);+ granted.grant_command("cat ~/.jan/config.toml");+ let hidden = Decision::HardDeny(DenyReason::Hidden);+ let cases = [+ ("read", json!({"path": ".jan/config.toml"})),+ ("write", json!({"path": ".jan/projects/home-1/agent.toml", "content": ""})),+ ("edit", json!({"path": ".jan/config.toml"})),+ ("ls", json!({"path": ".jan"})),+ ("grep", json!({"pattern": "key", "path": ".jan"})),+ ("bash", json!({"command": "cat ~/.jan/config.toml"})),+ ];+ for perms in [ToolPermissions::default(), ToolPermissions::allow_all()] {+ for (tool, args) in &cases {+ let d = resolve_decision(lookup(tool).unwrap(), args, &ctx, &perms, &granted);+ assert_eq!(d, hidden, "{tool} {args}");+ }}- // bash referencing it is denied too.- let d = resolve_decision(- lookup("bash").unwrap(),- &json!({"command": "cat .jan/agent/agent.toml"}),- &GateContext {- project_root: &root,- scratch: None,- read_roots: &[],- write_roots: &[],- hide_jan: true,- },- &perms,- &grants,- );- assert_eq!(d, Decision::HardDeny(DenyReason::Hidden));- // The instructions file is an ordinary project file at the root.- std::fs::write(root.join("JAN.md"), b"x").unwrap();+ // The rest of the home is an ordinary project.+ std::fs::write(home.join("notes.txt"), b"x").unwrap();let d = resolve_decision(lookup("read").unwrap(),- &json!({"path": "JAN.md"}),- &GateContext {- project_root: &root,- scratch: None,- read_roots: &[],- write_roots: &[],- hide_jan: true,- },- &perms,- &grants,+ &json!({"path": "notes.txt"}),+ &ctx,+ &ToolPermissions::default(),+ &SessionGrants::default(),);assert_eq!(d, Decision::Allow);- let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&home);}+ /// The Jan home is refused from any project, not only when it is inside:+ /// an escaping read of `~/.jan/config.toml` must not reach a prompt.#[test]- fn hidden_jan_is_reachable_when_not_hiding() {- let root = unique_root();- std::fs::create_dir_all(root.join(".jan/agent")).unwrap();- std::fs::write(root.join(".jan/agent/agent.toml"), b"[tools]\n").unwrap();- let perms = ToolPermissions::allow_all();- let grants = SessionGrants::default();- // With hiding off, paths and commands under `.jan` take the ordinary- // capability path instead of the hard deny (here an in-project read- // allows; the write prompts like any in-project write).- for tool in ["read", "ls", "find", "grep", "write", "edit"] {- let d = resolve_decision(- lookup(tool).unwrap(),- &json!({ "path": ".jan/agent/agent.toml" }),- &GateContext {- project_root: &root,- scratch: None,- read_roots: &[],- write_roots: &[],- hide_jan: false,- },- &perms,- &grants,- );- assert_ne!(- d,- Decision::HardDeny(DenyReason::Hidden),- "{tool} must not hard-deny .jan when not hiding"- );- }- // bash referencing it is a normal exec prompt, not a hidden deny.+ fn the_jan_home_is_refused_from_an_ordinary_project() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let ctx = GateContext {+ project_root: &project,+ scratch: None,+ read_roots: &[],+ write_roots: &[],+ hidden_root: Some(&jan),+ };+ let config = jan.join("config.toml");let d = resolve_decision(- lookup("bash").unwrap(),- &json!({"command": "cat .jan/agent/agent.toml"}),- &GateContext {- project_root: &root,- scratch: None,- read_roots: &[],- write_roots: &[],- hide_jan: false,- },- &perms,- &grants,+ lookup("read").unwrap(),+ &json!({"path": config.to_str().unwrap()}),+ &ctx,+ &ToolPermissions::allow_all(),+ &SessionGrants::default(),);- assert_ne!(d, Decision::HardDeny(DenyReason::Hidden));- let _ = std::fs::remove_dir_all(&root);+ assert_eq!(d, Decision::HardDeny(DenyReason::Hidden));+ // Unset (sandbox off) leaves the ordinary escape rules in charge.+ let open = GateContext { hidden_root: None, ..ctx };+ let d = resolve_decision(+ lookup("read").unwrap(),+ &json!({"path": config.to_str().unwrap()}),+ &open,+ &ToolPermissions::default(),+ &SessionGrants::default(),+ );+ assert_eq!(d, Decision::Prompt(PromptKind::ReadEscape));+ let _ = std::fs::remove_dir_all(&home);}#[test]@@ -499,7 +477,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -521,7 +499,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -555,7 +533,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -571,7 +549,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -601,7 +579,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -631,7 +609,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -657,7 +635,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -673,7 +651,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -682,43 +660,6 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}- #[test]- fn general_tools_cannot_reach_skills_memory_or_config() {- let root = unique_root();- let perms = ToolPermissions::allow_all();- let grants = SessionGrants::default();- // skills/ and memory/ are reachable only via the dedicated tools; general- // read/write/edit/ls/find/grep hard-deny there, same as agent.toml.- let paths = [- ".jan/agent/skills/deploy.md",- ".jan/agent/memory/notes.md",- ".jan/agent/agent.toml",- ];- for tool in ["read", "ls", "find", "grep", "write", "edit"] {- for path in paths {- let d = resolve_decision(- lookup(tool).unwrap(),- &json!({ "path": path }),- &GateContext {- project_root: &root,- scratch: None,- read_roots: &[],- write_roots: &[],- hide_jan: true,- },- &perms,- &grants,- );- assert_eq!(- d,- Decision::HardDeny(DenyReason::Hidden),- "{tool} on {path} must be denied"- );- }- }- let _ = std::fs::remove_dir_all(&root);- }-#[test]fn workspace_tools_auto_allow_but_deny_still_wins() {let root = unique_root();@@ -733,7 +674,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -751,7 +692,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&denied,&grants,@@ -773,7 +714,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -795,7 +736,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -818,7 +759,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -841,7 +782,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -863,7 +804,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -887,7 +828,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -911,7 +852,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -933,7 +874,7 @@ mod tests {scratch: None,read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -961,7 +902,7 @@ mod tests {scratch: None,read_roots: &roots,write_roots: &[],- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -976,7 +917,7 @@ mod tests {scratch: None,read_roots: &roots,write_roots: &[],- hide_jan: true,+ hidden_root: None,},&ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),&grants,@@ -1007,7 +948,7 @@ mod tests {scratch: None,read_roots: &roots,write_roots: &roots,- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -1022,7 +963,7 @@ mod tests {scratch: None,read_roots: &roots,write_roots: &roots,- hide_jan: true,+ hidden_root: None,},&perms,&grants,@@ -1048,7 +989,7 @@ mod tests {scratch: None,read_roots: &roots,write_roots: &[],- hide_jan: true,+ hidden_root: None,},&ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),&SessionGrants::default(),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 8f7a28ef6..ddbd2e5a8 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@@ -14,7 +14,7 @@ use crate::skills;use crate::tools::jail;use crate::tools::proc;use crate::tools::sandbox::{- escapes_write_roots, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,+ escapes_write_roots, hidden_under, in_scratch, lexical_normalize, resolve_path,scratch_display_path, symlink_escapes_any_root,};use crate::tools::{BuiltinTool, ImageContentPart, ScreenshotBackend, ToolContext};@@ -209,7 +209,7 @@ async fn execute_text(// deliberately do not, which is what keeps an attached folder// readable and unwritable."read" => read(args, project_root, scratch, ctx.read_roots).await.0,- "ls" => ls(args, project_root, scratch, ctx.sandbox, ctx.read_roots).await,+ "ls" => ls(args, project_root, scratch, ctx.read_roots, ctx.hidden_root).await,"write" => {write(args,@@ -231,13 +231,13 @@ async fn execute_text(.await}"bash" => bash(args, ctx).await,- "find" => find(args, project_root, scratch, ctx.sandbox, ctx.read_roots).await,- "grep" => grep(args, project_root, scratch, ctx.sandbox, ctx.read_roots).await,+ "find" => find(args, project_root, scratch, ctx.read_roots, ctx.hidden_root).await,+ "grep" => grep(args, project_root, scratch, ctx.read_roots, ctx.hidden_root).await,// Memory and skills live in the store root, not the sandbox: they must// outlive the conversation the filesystem tools are scoped to.- "memory_list" => memory_list(ctx.store_root).await,- "memory_read" => memory_read(args, ctx.store_root).await,- "memory_write" => memory_write(args, ctx.store_root).await,+ "memory_list" => memory_list(ctx.memory_scopes()).await,+ "memory_read" => memory_read(args, ctx.memory_scopes()).await,+ "memory_write" => memory_write(args, ctx.memory_scopes()).await,// Skills go through the skills module so the tool honors the folder form// (`<name>/SKILL.md`) and frontmatter, matching what the UI writes."skill_list" => skill_list(ctx),@@ -527,28 +527,28 @@ fn skill_write(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {/// The memory tools delegate to `crate::memory` so the built-ins and the/// management commands share one implementation.-async fn memory_list(store: &Path) -> String {- memory::list(store).await.join("\n")+async fn memory_list(scopes: memory::Scopes<'_>) -> String {+ scopes.list().await.join("\n")}-async fn memory_read(args: &serde_json::Value, store: &Path) -> String {+async fn memory_read(args: &serde_json::Value, scopes: memory::Scopes<'_>) -> String {let Some(name) = arg_str(args, "name") else {return "ERROR: missing required argument 'name'".to_string();};- match memory::read(store, name).await {+ match scopes.read(name).await {Ok(content) => content,Err(e) => e,}}-async fn memory_write(args: &serde_json::Value, store: &Path) -> String {+async fn memory_write(args: &serde_json::Value, scopes: memory::Scopes<'_>) -> String {let Some(name) = arg_str(args, "name") else {return "ERROR: missing required argument 'name'".to_string();};let Some(content) = arg_str(args, "content") else {return "ERROR: missing required argument 'content'".to_string();};- match memory::write(store, name, content).await {+ match scopes.write(name, content).await {Ok(file) => format!("Wrote {} bytes to memory/{file}", content.len()),Err(e) => e,}@@ -644,8 +644,8 @@ async fn ls(args: &serde_json::Value,root: &Path,scratch: Option<&Path>,- hide_jan: bool,read_roots: &[PathBuf],+ hidden: Option<&Path>,) -> String {let path = arg_str(args, "path").unwrap_or(".");let limit = arg_u64(args, "limit")@@ -660,14 +660,14 @@ async fn ls(Ok(rd) => rd,Err(e) => return format!("ERROR: {e}"),};+ // Omitted, not reported-then-denied: an entry the agent can never open is+ // only an invitation to try.+ let skip = hidden.and_then(|h| hidden_under(&target, h));let mut names: Vec<String> = Vec::new();loop {match entries.next_entry().await {Ok(Some(entry)) => {- // Hidden state is omitted, not reported-then-denied: an entry the- // agent can never open is only an invitation to try. Skipped when- // not hiding, so an unconfined CLI run sees its own `.jan`.- if hide_jan && is_hidden_jan_path(root, &entry.path().to_string_lossy()) {+ if skip.as_deref() == Some(entry.path().as_path()) {continue;}let mut name = entry.file_name().to_string_lossy().into_owned();@@ -816,16 +816,12 @@ pub(crate) fn confined_shell(let root = ctx.project_root;let mut policy =jail::Policy::new(root, ctx.allow_network).with_home_readonly(ctx.home_readonly);- // While the shell is sandboxed, hide the project's own `.jan` state directory- // from it (see [`Policy::with_hide_root`]). When the shell runs unconfined the- // hide is both pointless (there is no OS mount to layer it on) and wrong- // (the agent should see its own state), so it is only applied when sandboxed.- if ctx.sandbox {- policy = policy.with_hide_root(&root.join(crate::tools::sandbox::JAN_DIR));- }if let Some(mask) = ctx.mask_root {policy = policy.with_mask_root(mask);}+ if let Some(hide) = ctx.hidden_root {+ policy = policy.with_hide_root(hide);+ }if let Some(scratch) = ctx.scratch_root {policy = policy.with_scratch_root(scratch);}@@ -1594,8 +1590,8 @@ async fn find(args: &serde_json::Value,root: &Path,scratch: Option<&Path>,- hide_jan: bool,read_roots: &[PathBuf],+ hidden: Option<&Path>,) -> String {let pattern = arg_str(args, "pattern").map(String::from);let path = arg_str(args, "path").unwrap_or(".").to_string();@@ -1606,7 +1602,7 @@ async fn find(if symlink_escapes_any_root(root, scratch, read_roots, &base) {return format!("ERROR: refused to search through a symlink out of the workspace: {path}");}- let root_owned = root.to_path_buf();+ let skip = hidden.and_then(|h| hidden_under(&base, h));let Some(pattern) = pattern else {return "ERROR: missing required argument 'pattern'".to_string();@@ -1625,15 +1621,13 @@ async fn find(for entry in WalkBuilder::new(&base).hidden(false).require_git(false)+ .filter_entry(move |e| skip.as_deref() != Some(e.path())).build().flatten(){if entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {continue;}- if hide_jan && is_hidden_jan_path(&root_owned, &entry.path().to_string_lossy()) {- continue;- }let rel = rel_to(&base, entry.path());if pat.matches_with(&rel, opts) {matches.push(rel);@@ -1656,8 +1650,8 @@ async fn grep(args: &serde_json::Value,root: &Path,scratch: Option<&Path>,- hide_jan: bool,read_roots: &[PathBuf],+ hidden: Option<&Path>,) -> String {let pattern = arg_str(args, "pattern").map(String::from);let path = arg_str(args, "path").unwrap_or(".").to_string();@@ -1676,6 +1670,7 @@ async fn grep(let scratch_owned = scratch.map(Path::to_path_buf);// Owned for the blocking walk closure, which outlives this frame.let roots_owned = read_roots.to_vec();+ let skip = hidden.and_then(|h| hidden_under(&base, h));let Some(pattern) = pattern else {return "ERROR: missing required argument 'pattern'".to_string();@@ -1757,6 +1752,7 @@ async fn grep(for entry in WalkBuilder::new(&base).hidden(false).require_git(false)+ .filter_entry(move |e| skip.as_deref() != Some(e.path())).build().flatten(){@@ -1780,9 +1776,6 @@ async fn grep({continue;}- if hide_jan && is_hidden_jan_path(&root_owned, &entry.path().to_string_lossy()) {- continue;- }if !search_file(entry.path(), &base) {break;}@@ -1824,10 +1817,9 @@ mod tests {// the skill whitelist, stay readable. Tests that do care build a// `ToolContext` and call `super::*` directly.//- // They co-locate the store inside the root (`<root>/.jan/agent`), the layout- // a project uses, so the memory/skill tests keep asserting against paths- // relative to their one temp dir. The desktop's split roots are covered in- // `workspace` and `commands`.+ // They use the project's store (`workspace::project_store`, under a test+ // temp home), the layout the CLI uses. The desktop's split roots are+ // covered in `workspace` and `commands`.async fn execute_builtin(tool: &BuiltinTool, args: &serde_json::Value, root: &Path) -> String {let store = crate::workspace::project_store(root);super::execute_builtin(tool, args, &ToolContext::new(root, &store, &[]))@@ -2778,7 +2770,7 @@ mod tests {scratch: Some(&scratch),read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&crate::permissions::ToolPermissions::default(),&crate::tools::gate::SessionGrants::default(),@@ -2810,7 +2802,7 @@ mod tests {scratch: Some(&scratch),read_roots: &[],write_roots: &[],- hide_jan: true,+ hidden_root: None,},&crate::permissions::ToolPermissions::default(),&crate::tools::gate::SessionGrants::default(),@@ -2848,43 +2840,45 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}- /// Hidden means absent from the listing, not present-but-unopenable: an- /// entry the agent can never read is only an invitation to try.+ /// With `$HOME` as the project, a walk of `.` would otherwise read the Jan+ /// home: the gate only sees the `.` argument, so the walks skip it too.#[tokio::test]- async fn ls_omits_the_hidden_jan_dir() {- let root = unique_root();- std::fs::create_dir_all(root.join(".jan/agent")).unwrap();- std::fs::write(root.join("src.rs"), b"x").unwrap();- std::fs::write(root.join("JAN.md"), b"x").unwrap();- let out = execute_builtin(lookup("ls").unwrap(), &json!({}), &root).await;- assert!(out.contains("src.rs"), "unexpected: {out}");- assert!(out.contains("JAN.md"), "unexpected: {out}");- assert!(- !out.contains(".jan/"),- "must not list the agent state dir: {out}"- );- let _ = std::fs::remove_dir_all(&root);- }-- /// When the shell is unconfined (CLI with --no-sandbox) the `.jan` directory- /// is ordinary project state and is listed, not hidden.- #[tokio::test]- async fn ls_lists_the_jan_dir_when_unconfined() {- let root = unique_root();- std::fs::create_dir_all(root.join(".jan/agent")).unwrap();- std::fs::write(root.join(".jan/agent/agent.toml"), b"[tools]\n").unwrap();- std::fs::write(root.join("src.rs"), b"x").unwrap();- let store = crate::workspace::project_store(&root);- let ctx = ToolContext::new(&root, &store, &[]).with_sandbox(false);- let out = super::execute_builtin(lookup("ls").unwrap(), &json!({}), &ctx)- .await- .0;- assert!(out.contains("src.rs"), "unexpected: {out}");- assert!(- out.contains(".jan/"),- "must list .jan when unconfined: {out}"- );- let _ = std::fs::remove_dir_all(&root);+ async fn walks_skip_the_jan_home_inside_the_project() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(jan.join("projects/p-1")).unwrap();+ std::fs::write(jan.join("config.toml"), b"api_key = SECRET_MARKER").unwrap();+ std::fs::write(jan.join("projects/p-1/agent.toml"), b"SECRET_MARKER").unwrap();+ std::fs::write(home.join("notes.txt"), b"SECRET_MARKER").unwrap();+ std::fs::write(home.join(".janitor"), b"SECRET_MARKER").unwrap();+ let store = crate::workspace::project_store(&home);+ let ctx = ToolContext::new(&home, &store, &[]).with_hidden_root(Some(&jan));+ let run = |tool: &'static str, args: serde_json::Value| {+ let ctx = ctx.clone();+ async move { super::execute_builtin(lookup(tool).unwrap(), &args, &ctx).await.0 }+ };+ for path in [".", "./"] {+ let ls = run("ls", json!({"path": path})).await;+ assert!(ls.contains("notes.txt") && ls.contains(".janitor"), "{ls}");+ assert!(!ls.lines().any(|l| l == ".jan/"), "{ls}");+ let find = run("find", json!({"pattern": "**/*", "path": path})).await;+ assert!(find.contains("notes.txt"), "{find}");+ assert!(!find.contains("config.toml") && !find.contains("agent.toml"), "{find}");+ let grep = run("grep", json!({"pattern": "SECRET_MARKER", "path": path})).await;+ assert!(grep.contains("notes.txt") && grep.contains(".janitor"), "{grep}");+ assert!(!grep.contains("config.toml") && !grep.contains("agent.toml"), "{grep}");+ }+ // Unset (sandbox off), the home is walked like any other directory.+ let open = ToolContext::new(&home, &store, &[]);+ let grep = super::execute_builtin(+ lookup("grep").unwrap(),+ &json!({"pattern": "SECRET_MARKER"}),+ &open,+ )+ .await+ .0;+ assert!(grep.contains("config.toml"), "{grep}");+ let _ = std::fs::remove_dir_all(&home);}#[tokio::test]@@ -2909,73 +2903,6 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}- #[tokio::test]- async fn find_does_not_leak_the_hidden_jan_tree() {- let root = unique_root();- 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();- // Directly under `.jan`, outside `agent/`: hidden by the same rule.- std::fs::write(root.join(".jan/stray.txt"), b"x").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;- assert!(- out.contains("README.md"),- "should include project file: {out}"- );- assert!(- out.contains("JAN.md"),- "the root instructions file is an ordinary project file: {out}"- );- assert!(- !out.contains("thread.json"),- "must not leak thread storage: {out}"- );- assert!(- !out.contains("agent.toml"),- "must not leak agent config: {out}"- );- assert!(- !out.contains("stray.txt"),- "the whole .jan dir is hidden, not just agent/: {out}"- );- let _ = std::fs::remove_dir_all(&root);- }-- #[tokio::test]- async fn grep_does_not_leak_hidden_jan_contents() {- let root = unique_root();- std::fs::create_dir_all(root.join(".jan/agent/threads/t1")).unwrap();- std::fs::write(- root.join(".jan/agent/threads/t1/messages.jsonl"),- b"SECRET_MARKER thread content",- )- .unwrap();- std::fs::write(root.join(".jan/agent/agent.toml"), b"SECRET_MARKER config").unwrap();- std::fs::write(root.join("README.md"), b"SECRET_MARKER readme").unwrap();- let out = execute_builtin(- lookup("grep").unwrap(),- &json!({"pattern": "SECRET_MARKER"}),- &root,- )- .await;- assert!(- out.contains("README.md"),- "should match project file: {out}"- );- assert!(- !out.contains("messages.jsonl"),- "must not grep thread storage: {out}"- );- assert!(- !out.contains("agent.toml"),- "must not grep agent config: {out}"- );- let _ = std::fs::remove_dir_all(&root);- }-#[tokio::test]async fn grep_regex_and_literal_and_ignore_case() {let root = unique_root();@@ -3601,7 +3528,8 @@ mod tests {assert!(w.starts_with("Wrote"), "unexpected: {w}");// Landed at the canonical workspace path.assert_eq!(- std::fs::read_to_string(root.join(".jan/agent/memory/drift.md")).unwrap(),+ std::fs::read_to_string(crate::workspace::project_store(&root).join("memory/drift.md"))+ .unwrap(),"553 behind");@@ -3629,7 +3557,9 @@ mod tests {.await;assert!(w.contains("deploy"), "unexpected: {w}");// New skills are written as the folder form `<name>/SKILL.md`.- assert!(root.join(".jan/agent/skills/deploy/SKILL.md").exists());+ assert!(crate::workspace::project_store(&root)+ .join("skills/deploy/SKILL.md")+ .exists());// skill_read returns the body on demand (progressive disclosure).let r = execute_builtin(diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex eee6732ce..d079bc319 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -13,9 +13,6 @@//! interpreter, loader, and libraries.//! - writes: the thread workspace and a private temp dir, nothing else.//! - network: denied unless explicitly allowed.-//! - the agent's own `<workspace>/.jan` state directory is hidden even though it-//! sits inside the workspace ([`Policy::hide_root`]); AppContainer is the one-//! backend that cannot express it.//!//! AppContainer is stricter than that on reads: it can only read what grants//! `ALL APPLICATION PACKAGES`, which covers the system directories a process@@ -75,11 +72,6 @@ pub struct Policy {/// masking it would hide the very files the agent works on.pub mask_root: Option<PathBuf>,pub allow_network: bool,- /// A path *inside* the workspace to hide from the shell: the agent's own- /// `<project>/.jan` state directory. The workspace bind/allow makes the whole- /// project reachable, so hiding it needs a rule layered on top -- see- /// [`Policy::with_hide_root`].- pub hide_root: Option<PathBuf>,/// Expose `$HOME` to the sandboxed shell read-only instead of hiding it./// The CLI turns this on so helpers that read the user's home (`git`/`ssh`/// credential helpers, `~/.ssh/config`, `~/.netrc`) work, while writes stay@@ -103,6 +95,10 @@ pub struct Policy {/// allowed) read-write in the same position as `read_roots`; an entry/// present in both lists is bound once, writable.pub write_roots: Vec<PathBuf>,+ /// The Jan home (`~/.jan`), hidden from the shell wherever it sits: under a+ /// read-only `$HOME`, inside the workspace (running in `$HOME`), or around+ /// it (a Jan worktree in `~/.jan/worktrees/`). See [`Policy::with_hide_root`].+ pub hide_root: Option<PathBuf>,}impl Policy {@@ -111,14 +107,34 @@ impl Policy {workspace: workspace.to_path_buf(),mask_root: None,allow_network,- hide_root: None,home_readonly: false,scratch_root: None,read_roots: Vec::new(),write_roots: Vec::new(),+ hide_root: None,}}+ /// Hide `hide_root` from the sandboxed shell. The gate's token scan of the+ /// command string is best-effort; this is what makes the directory+ /// unreachable to the spellings a scan cannot see (`cd ~; cat .jan/*`, a+ /// script the shell writes and runs). Not enforced on AppContainer, where+ /// carving a subpath back out of a granted folder would mean writing a deny+ /// ACE onto the user's directory; there the scan stands alone.+ pub fn with_hide_root(mut self, hide_root: &Path) -> Self {+ self.hide_root = Some(hide_root.to_path_buf());+ self+ }++ /// True when a bind of the workspace or an attached root would re-expose the+ /// hidden directory, so it has to be masked again after those binds.+ fn hide_under_a_bind(&self, hide: &Path) -> bool {+ std::iter::once(&self.workspace)+ .chain(&self.read_roots)+ .chain(&self.write_roots)+ .any(|root| hide.starts_with(root) && hide != root)+ }+/// Attach read-only roots. See [`Policy::read_roots`] for why their bind/// order relative to the masks and the workspace is load-bearing.pub fn with_read_roots(mut self, read_roots: Vec<PathBuf>) -> Self {@@ -141,18 +157,6 @@ impl Policy {self}- /// Hide `hide_root` from the sandboxed shell. Applied after the workspace is- /// bound/allowed, so it wins over it: the gate's token scan of the command- /// string is best-effort, and this is what makes `.jan` unreachable to the- /// spellings a scan cannot see (`cd .jan`, `$(echo ...)`, a script the shell- /// writes and runs). Not enforced on AppContainer, where the workspace is- /// granted by an ACE and carving a subpath back out would mean writing a deny- /// ACE onto the user's directory; there the scan stands alone.- pub fn with_hide_root(mut self, hide_root: &Path) -> Self {- self.hide_root = Some(hide_root.to_path_buf());- self- }-/// Expose `$HOME` read-only instead of masking it. See [`Policy::home_readonly`].pub fn with_home_readonly(mut self, home_readonly: bool) -> Self {self.home_readonly = home_readonly;@@ -399,6 +403,11 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {if let Some(mask) = &policy.mask_root {push(&mut args, &["--tmpfs", &mask.to_string_lossy()]);}+ // The Jan home, masked with the others: before the binds below, so a+ // workspace living under it (a Jan worktree) is punched back through.+ if let Some(hide) = &policy.hide_root {+ push(&mut args, &["--tmpfs", &hide.to_string_lossy()]);+ }// Between the masks above and the workspace below, and that position is the// enforcement: after the `$HOME`/data-folder tmpfs so a project living under@@ -424,12 +433,9 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {}push(&mut args, &["--bind", &ws, &ws]);- // After the workspace bind, so it is not shadowed by it: an empty tmpfs where- // the agent's own state directory sits. Mounted unconditionally rather than- // only when the directory exists, so a `.jan` created while the sandbox runs- // cannot be read back by the next command in the same shell. Writes into it- // are discarded with the sandbox (and hard-denied at the tool layer anyway).- if let Some(hide) = &policy.hide_root {+ // And again after, when a bind contains it (running in `$HOME`): the+ // workspace bind would otherwise shadow the mask above and re-expose it.+ if let Some(hide) = policy.hide_root.as_deref().filter(|h| policy.hide_under_a_bind(h)) {push(&mut args, &["--tmpfs", &hide.to_string_lossy()]);}push(&mut args, &["--chdir", &ws]);@@ -465,6 +471,11 @@ fn seatbelt_program() -> &'static str {}}+/// Seatbelt rules hiding the Jan home; where they go in the profile decides+/// whether they win over the workspace allow (see [`seatbelt_policy`]).+const HIDE_RULES: &str = "(deny file-read* (subpath (param \"HIDE_ROOT\")))\n\+ (deny file-write* (subpath (param \"HIDE_ROOT\")))\n";+/// Seatbelt profile. `(deny default)` closes everything, then each section opens/// the narrowest thing that works. Later rules win, which is what lets the/// workspace be re-allowed after `$HOME` is denied (or, with `home_readonly`,@@ -502,6 +513,16 @@ pub fn seatbelt_policy(policy: &Policy) -> String {if policy.mask_root.is_some() {p.push_str("(deny file-read* (subpath (param \"MASK_ROOT\")))\n");}+ // Later rules win. Denied here, before the allows below, when the+ // workspace lives under the Jan home (a worktree) so it is read back; when+ // the home lies inside an allowed root instead, the deny goes last.+ let hide_last = policy+ .hide_root+ .as_deref()+ .is_some_and(|h| policy.hide_under_a_bind(h));+ if policy.hide_root.is_some() && !hide_last {+ p.push_str(HIDE_RULES);+ }p.push_str("(allow file-read* (subpath (param \"WORKSPACE\")))\n\; Writes: the workspace and the temp dir, nothing else.\n\@@ -538,13 +559,8 @@ pub fn seatbelt_policy(policy: &Policy) -> String {(allow file-write* (subpath (param \"WRITE_ROOT_{i}\")))\n"));}- // Last, so it wins over the workspace allow above: the agent's own state- // directory is neither readable nor writable, however the command spells it.- if policy.hide_root.is_some() {- p.push_str(- "(deny file-read* (subpath (param \"HIDE_ROOT\")))\n\- (deny file-write* (subpath (param \"HIDE_ROOT\")))\n",- );+ if hide_last {+ p.push_str(HIDE_RULES);}if policy.allow_network {p.push_str(@@ -576,15 +592,15 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {if let Some(mask) = &policy.mask_root {args.push(format!("-DMASK_ROOT={}", mask.to_string_lossy()));}+ if let Some(hide) = &policy.hide_root {+ args.push(format!("-DHIDE_ROOT={}", hide.to_string_lossy()));+ }for (i, root) in policy.read_roots.iter().enumerate() {args.push(format!("-DREAD_ROOT_{i}={}", root.to_string_lossy()));}for (i, root) in policy.write_roots.iter().enumerate() {args.push(format!("-DWRITE_ROOT_{i}={}", root.to_string_lossy()));}- if let Some(hide) = &policy.hide_root {- args.push(format!("-DHIDE_ROOT={}", hide.to_string_lossy()));- }args.push(format!("-DTMPDIR={}",std::env::temp_dir().to_string_lossy()@@ -717,6 +733,56 @@ mod tests {args.join(" ")}+ /// Running in `$HOME`: the Jan home is inside the workspace, so the+ /// workspace bind would shadow the first mask; a second one must follow.+ #[test]+ fn bwrap_hides_the_jan_home_after_a_workspace_that_contains_it() {+ let ws = "/home/u";+ let hide = "/home/u/.jan";+ let text = joined(&bwrap_args(+ &Policy::new(Path::new(ws), false).with_hide_root(Path::new(hide)),+ &cfg(),+ ));+ let bind = text.find(&format!("--bind {ws} {ws}")).expect("bind");+ let last = text.rfind(&format!("--tmpfs {hide}")).expect("mask");+ assert!(bind < last, "the mask must follow the workspace bind: {text}");+ }++ /// A Jan worktree lives under the home: the mask goes before the workspace+ /// bind only, or it would hide the tree the agent is working in.+ #[test]+ fn bwrap_hides_the_jan_home_before_a_workspace_inside_it() {+ let ws = "/home/u/.jan/worktrees/r-1/feat";+ let hide = "/home/u/.jan";+ let text = joined(&bwrap_args(+ &Policy::new(Path::new(ws), false).with_hide_root(Path::new(hide)),+ &cfg(),+ ));+ let bind = text.find(&format!("--bind {ws} {ws}")).expect("bind");+ let mask = format!("--tmpfs {hide} ");+ assert_eq!(text.matches(&mask).count(), 1, "{text}");+ assert!(text.find(&mask).unwrap() < bind, "{text}");+ assert!(!joined(&bwrap_args(&policy(), &cfg())).contains(".jan"));+ }++ #[test]+ fn seatbelt_orders_the_jan_home_deny_by_where_the_workspace_is() {+ let deny = "(deny file-read* (subpath (param \"HIDE_ROOT\")))";+ let allow = "(allow file-read* (subpath (param \"WORKSPACE\")))";+ let home = Policy::new(Path::new("/Users/u"), false).with_hide_root(Path::new("/Users/u/.jan"));+ let p = seatbelt_policy(&home);+ assert!(p.find(allow).unwrap() < p.find(deny).unwrap(), "{p}");+ assert!(p.contains("(deny file-write* (subpath (param \"HIDE_ROOT\")))"));+ let wt = Policy::new(Path::new("/Users/u/.jan/worktrees/r/f"), false)+ .with_hide_root(Path::new("/Users/u/.jan"));+ let p = seatbelt_policy(&wt);+ assert!(p.find(deny).unwrap() < p.find(allow).unwrap(), "{p}");+ // The path travels as a -D parameter, never interpolated into the profile.+ assert!(!p.contains("/Users/u/.jan"), "{p}");+ assert!(joined(&seatbelt_args(&wt, &cfg())).contains("-DHIDE_ROOT=/Users/u/.jan"));+ assert!(!seatbelt_policy(&policy()).contains("HIDE_ROOT"));+ }+#[test]fn bwrap_mounts_root_read_only_before_layering_on_it() {let args = bwrap_args(&policy(), &cfg());@@ -758,26 +824,6 @@ mod tests {assert!(ro.contains(&ro_bind), "{ro}");}- /// The workspace bind makes the whole project reachable, so the mask must be- /// layered on after it or it would be shadowed and silently do nothing.- #[test]- fn bwrap_hides_the_agent_state_dir_after_binding_the_workspace() {- let ws = "/data/agent-workspace/threads/t1";- let hide = format!("{ws}/.jan");- let text = joined(&bwrap_args(- &policy().with_hide_root(Path::new(&hide)),- &cfg(),- ));- let bind = text.find(&format!("--bind {ws} {ws}")).expect("bind");- let tmpfs = text.find(&format!("--tmpfs {hide}")).expect("hide tmpfs");- assert!(- bind < tmpfs,- "the mask must follow the workspace bind: {text}"- );- // Unset by default, so nothing is hidden where no state dir is named.- assert!(!joined(&bwrap_args(&policy(), &cfg())).contains(".jan"));- }-/// The bind order *is* the enforcement, on both sides: after the `$HOME`/// tmpfs so a folder living under the home is punched back through the mask,/// and before the workspace bind so a read root can never shadow the only@@ -909,25 +955,6 @@ mod tests {.any(|a| a.contains("READ_ROOT")));}- #[test]- fn seatbelt_denies_the_agent_state_dir_last() {- let hide = "/data/agent-workspace/threads/t1/.jan";- let p = policy().with_hide_root(Path::new(hide));- let profile = seatbelt_policy(&p);- let allow = profile- .find("(allow file-read* (subpath (param \"WORKSPACE\")))")- .expect("workspace allow");- let deny = profile- .find("(deny file-read* (subpath (param \"HIDE_ROOT\")))")- .expect("hide deny");- assert!(allow < deny, "later rules win, so the deny must come last");- assert!(profile.contains("(deny file-write* (subpath (param \"HIDE_ROOT\")))"));- // The path travels as a -D parameter, never interpolated into the profile.- assert!(!profile.contains(hide), "{profile}");- assert!(joined(&seatbelt_args(&p, &cfg())).contains(&format!("-DHIDE_ROOT={hide}")));- assert!(!seatbelt_policy(&policy()).contains("HIDE_ROOT"));- }-#[test]fn bwrap_denies_network_unless_allowed() {let denied = joined(&bwrap_args(&policy(), &cfg()));diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 882b10952..dec1aa56b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -84,6 +84,13 @@ pub struct ToolContext<'a> {/// every surface with no folder attached. Skill *writes* and all memory ops/// still target `store_root`; only skill reads consult this overlay.pub skill_project_root: Option<&'a Path>,+ /// `~/.jan`, reached by the `memory_*` tools as the `user:` scope and as+ /// the parent of other projects' stores. `None` (the desktop) confines+ /// memory to `store_root`.+ pub memory_home: Option<&'a Path>,+ /// Whether other projects' memory is listed in the prompt and readable as+ /// `project:<slug>`. Only meaningful with `memory_home`.+ pub cross_project: bool,pub enabled_skills: &'a [String],pub allow_network: bool,/// When set, `write`/`edit` re-canonicalize the target and refuse a path@@ -95,6 +102,10 @@ pub struct ToolContext<'a> {/// where it sits outside the workspace (the desktop). `None` on the CLI,/// where the project itself is the workspace.pub mask_root: Option<&'a Path>,+ /// The Jan home, hidden from `ls`/`find`/`grep` walks and the sandboxed+ /// shell. Set with [`Self::with_hidden_root`] from+ /// [`crate::workspace::hidden_root`]; the gate refuses direct paths to it.+ pub hidden_root: Option<&'a Path>,/// Expose `$HOME` to the sandboxed shell read-only (the CLI) instead of/// hiding it (the desktop). Passed through to the `bash` sandbox policy.pub home_readonly: bool,@@ -189,10 +200,13 @@ impl std::fmt::Debug for ToolContext<'_> {.field("project_root", &self.project_root).field("store_root", &self.store_root).field("skill_project_root", &self.skill_project_root)+ .field("memory_home", &self.memory_home)+ .field("cross_project", &self.cross_project).field("enabled_skills", &self.enabled_skills).field("allow_network", &self.allow_network).field("confine_writes", &self.confine_writes).field("mask_root", &self.mask_root)+ .field("hidden_root", &self.hidden_root).field("home_readonly", &self.home_readonly).field("scratch_root", &self.scratch_root).field("sandbox", &self.sandbox)@@ -324,10 +338,13 @@ impl<'a> ToolContext<'a> {project_root,store_root,skill_project_root: None,+ memory_home: None,+ cross_project: false,enabled_skills,allow_network: false,confine_writes: false,mask_root: None,+ hidden_root: None,home_readonly: false,scratch_root: None,sandbox: true,@@ -399,6 +416,23 @@ impl<'a> ToolContext<'a> {self}+ /// Give the `memory_*` tools the user scope and, when `cross_project`, the+ /// other projects under `home`. See [`crate::memory::Scopes`].+ pub fn with_memory_home(mut self, home: &'a Path, cross_project: bool) -> Self {+ self.memory_home = Some(home);+ self.cross_project = cross_project;+ self+ }++ /// The memory scopes this context's `memory_*` tools resolve names in.+ pub fn memory_scopes(&self) -> crate::memory::Scopes<'a> {+ crate::memory::Scopes {+ store: self.store_root,+ home: self.memory_home,+ cross_project: self.cross_project,+ }+ }+/// Skill stores in precedence order for discovery and `skill_read`: the/// project overlay (when attached) on top of the permanent store.pub fn skill_roots(&self) -> Vec<&Path> {@@ -458,6 +492,12 @@ impl<'a> ToolContext<'a> {self}+ /// Hide the Jan home from walks and the shell. See [`Self::hidden_root`].+ pub fn with_hidden_root(mut self, hidden_root: Option<&'a Path>) -> Self {+ self.hidden_root = hidden_root;+ self+ }+/// Expose `$HOME` to the sandboxed shell read-only. See [`Self::home_readonly`].pub fn with_home_readonly(mut self, home_readonly: bool) -> Self {self.home_readonly = home_readonly;@@ -556,7 +596,7 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[capability: Capability::Exec,path_args: &[],},- // Dedicated skill/memory tools. They operate on `.jan/agent/{skills,memory}/`+ // Dedicated skill/memory tools. They operate on the store's `{skills,memory}/`// by name (never a path), so they are always workspace-scoped and never// prompt. `path_args` is empty: there is no path to sandbox-check.BuiltinTool {@@ -604,7 +644,7 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[},];-/// Tools that act only on the agent's own `.jan/agent/{skills,memory}/`+/// Tools that act only on the agent's own store `{skills,memory}/`/// workspace. They are auto-allowed by the gate (no prompt), since a sanitized/// name can never escape the workspace. `deny` in agent.toml still overrides.pub fn is_workspace_tool(name: &str) -> bool {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rsindex 2f3c8d916..3b06ce403 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs@@ -59,6 +59,7 @@ pub struct MonitorCtx {pub project_root: PathBuf,pub scratch_root: Option<PathBuf>,pub mask_root: Option<PathBuf>,+ pub hidden_root: Option<PathBuf>,pub read_roots: Vec<PathBuf>,pub write_roots: Vec<PathBuf>,pub allow_network: bool,@@ -72,6 +73,7 @@ impl MonitorCtx {project_root: ctx.project_root.to_path_buf(),scratch_root: ctx.scratch_root.map(Path::to_path_buf),mask_root: ctx.mask_root.map(Path::to_path_buf),+ hidden_root: ctx.hidden_root.map(Path::to_path_buf),read_roots: ctx.read_roots.to_vec(),write_roots: ctx.write_roots.to_vec(),allow_network: ctx.allow_network,@@ -89,7 +91,8 @@ impl MonitorCtx {.with_home_readonly(self.home_readonly).with_sandbox(self.sandbox).with_read_roots(&self.read_roots)- .with_write_roots(&self.write_roots);+ .with_write_roots(&self.write_roots)+ .with_hidden_root(self.hidden_root.as_deref());if let Some(mask) = &self.mask_root {ctx = ctx.with_mask_root(mask);}@@ -589,6 +592,7 @@ mod tests {project_root: root.to_path_buf(),scratch_root: None,mask_root: None,+ hidden_root: None,read_roots: Vec::new(),write_roots: Vec::new(),allow_network: false,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 f345902d0..2a25f9fdc 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@@ -244,44 +244,73 @@ fn tmp_relative(raw: &str) -> Option<String> {Some(raw.strip_prefix("/tmp/")?.to_string())}-/// The agent's own state directory inside a project. Hidden wholesale rather-/// than per-subdirectory: it holds `agent.toml`, the skills/memory workspaces-/// (reachable only through the dedicated skill_*/memory_* tools), and the thread-/// store with the conversation's own transcripts. None of it is project source,-/// so a listing that shows it is noise at best and a self-referential read at-/// worst -- and anything added under it later is hidden by construction.-pub const JAN_DIR: &str = ".jan";--/// True iff `raw` resolves inside `<project_root>/.jan`. Hidden paths are not-/// merely denied: `ls`/`find`/`grep` omit them from their output, so the agent-/// never sees the directory exists. The project instructions file is-/// `<project_root>/JAN.md`, an ordinary project file, and is unaffected.-pub fn is_hidden_jan_path(project_root: &Path, raw: &str) -> bool {- let Ok(root) = project_root.canonicalize() else {+/// True iff `raw` resolves inside `hidden` (the Jan home, `~/.jan`), which holds+/// `config.toml` with provider keys and hooks plus every project's store. The+/// memory/skill tools reach the store by name and never come through here.+///+/// One exception: a project that itself lives under `hidden` (a Jan worktree in+/// `~/.jan/worktrees/`) is the agent's working tree, so paths inside it stay+/// reachable. The home itself as the project grants nothing.+pub fn in_hidden_root(project_root: &Path, scratch: Option<&Path>, hidden: &Path, raw: &str) -> bool {+ let Ok(hidden) = canonicalize_lenient(hidden) else {return false;};- let abs = if Path::new(raw).is_absolute() {- PathBuf::from(raw)- } else {- root.join(raw)- };- let Ok(resolved) = canonicalize_lenient(&abs) else {+ let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, scratch, raw)) else {return false;};- resolved.starts_with(root.join(JAN_DIR))+ if !resolved.starts_with(&hidden) {+ return false;+ }+ match project_root.canonicalize() {+ Ok(root) if root != hidden && root.starts_with(&hidden) => !resolved.starts_with(&root),+ _ => true,+ }}-/// True iff a shell command references a hidden path (best-effort token scan).-/// Splits on whitespace and shell metacharacters and checks each token so-/// `cat .jan/agent/agent.toml` and its quoted/redirected variants are caught.-/// Best-effort is enough only because the OS sandbox masks the directory too-/// (see [`super::jail::Policy::hide_root`]); this check exists to turn an-/// evasion-free attempt into a clear error instead of an empty directory.-pub fn command_touches_hidden_jan_path(project_root: &Path, command: &str) -> bool {+/// True iff a shell command names a path inside `hidden` (best-effort token+/// scan). `~` and `$HOME` are expanded, since `cat ~/.jan/config.toml` is the+/// obvious spelling. Best-effort is enough only because the OS sandbox masks+/// the directory too (see [`super::jail::Policy::hide_root`]); this turns a+/// plain attempt into a clear refusal instead of an empty directory.+pub fn command_touches_hidden_root(+ project_root: &Path,+ scratch: Option<&Path>,+ hidden: &Path,+ command: &str,+) -> bool {+ let home = hidden.parent().map(|h| h.to_string_lossy().into_owned());command- .split(|c: char| c.is_whitespace() || ";|&><()\"'`".contains(c))+ .split(|c: char| c.is_whitespace() || ";|&><()\"'`=".contains(c)).filter(|t| !t.is_empty())- .any(|t| is_hidden_jan_path(project_root, t))+ .any(|t| {+ let expanded = match &home {+ Some(home) => expand_home(t, home),+ None => t.to_string(),+ };+ in_hidden_root(project_root, scratch, hidden, &expanded)+ })+}++fn expand_home(token: &str, home: &str) -> String {+ for prefix in ["${HOME}", "$HOME", "~"] {+ if let Some(rest) = token.strip_prefix(prefix) {+ if rest.is_empty() || rest.starts_with('/') {+ return format!("{home}{rest}");+ }+ }+ }+ token.to_string()+}++/// `hidden` spelled under `base`, the way a directory walk rooted at `base`+/// names its entries, or `None` when the walk cannot reach it. Lets `ls`,+/// `find` and `grep` skip the Jan home with a prefix test per entry instead of+/// canonicalizing every file they visit.+pub fn hidden_under(base: &Path, hidden: &Path) -> Option<PathBuf> {+ let base_canon = base.canonicalize().ok()?;+ let hidden_canon = canonicalize_lenient(hidden).ok()?;+ let rest = hidden_canon.strip_prefix(&base_canon).ok()?;+ Some(base.join(rest))}/// True when `target` *claims* to be inside a trusted root but resolves outside@@ -462,63 +491,6 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}- #[test]- fn hidden_path_covers_the_whole_jan_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::create_dir_all(root.join(".jan/agent/threads/t1")).unwrap();- std::fs::write(root.join(".jan/agent/agent.toml"), b"x").unwrap();- // Config, the agent dir listing, unknown config files.- assert!(is_hidden_jan_path(&root, ".jan/agent/agent.toml"));- assert!(is_hidden_jan_path(&root, "./.jan/agent/agent.toml"));- assert!(is_hidden_jan_path(- &root,- root.join(".jan/agent/agent.toml").to_str().unwrap()- ));- assert!(is_hidden_jan_path(&root, ".jan/agent"));- assert!(is_hidden_jan_path(&root, ".jan/agent/secrets.env"));- // skills/ and memory/ are reachable only via the dedicated tools, so they- // are hidden from the general filesystem tools too.- assert!(is_hidden_jan_path(&root, ".jan/agent/skills/deploy.md"));- assert!(is_hidden_jan_path(&root, ".jan/agent/memory/notes.md"));- assert!(is_hidden_jan_path(&root, ".jan/agent/AGENT.md"));- // The whole `.jan` dir is hidden, not just `agent/`: the thread store- // holds the running conversation's own transcripts, and future state- // added beside it is covered without another carve-out.- assert!(is_hidden_jan_path(&root, ".jan"));- assert!(is_hidden_jan_path(&root, ".jan/agent/threads/t1"));- // Ordinary project files, including the instructions file, are untouched.- assert!(!is_hidden_jan_path(&root, "JAN.md"));- assert!(!is_hidden_jan_path(&root, "src/main.rs"));- // A sibling whose name merely starts with `.jan` is not inside it.- assert!(!is_hidden_jan_path(&root, ".janitor"));- let _ = std::fs::remove_dir_all(&root);- }-- #[test]- fn command_scan_flags_hidden_paths() {- let root = unique_root();- std::fs::create_dir_all(root.join(".jan/agent")).unwrap();- std::fs::write(root.join(".jan/agent/agent.toml"), b"x").unwrap();- assert!(command_touches_hidden_jan_path(- &root,- "cat .jan/agent/agent.toml"- ));- assert!(command_touches_hidden_jan_path(- &root,- "grep foo < .jan/agent/agent.toml"- ));- assert!(command_touches_hidden_jan_path(- &root,- "cat .jan/agent/AGENT.md"- ));- assert!(command_touches_hidden_jan_path(&root, "ls -la .jan"));- assert!(!command_touches_hidden_jan_path(&root, "cat JAN.md"));- assert!(!command_touches_hidden_jan_path(&root, "ls -la src"));- let _ = std::fs::remove_dir_all(&root);- }-/// A symlink planted in the scratch (the shell can create one: `/tmp` is/// the scratch bind) must not turn `/tmp/...` into a way out. Clamping `..`/// is not enough -- the link is a single component that resolves elsewhere.@@ -815,4 +787,78 @@ mod tests {let _ = std::fs::remove_dir_all(&repo);let _ = std::fs::remove_dir_all(&ws);}++ /// The home-as-project case from the #9065 review: the Jan home sits inside+ /// the project, and everything under it is hidden, not just config.toml.+ #[test]+ fn the_jan_home_is_hidden_when_the_project_contains_it() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(jan.join("projects/p-1/memory")).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ assert!(in_hidden_root(&home, None, &jan, ".jan/config.toml"));+ assert!(in_hidden_root(&home, None, &jan, "./.jan/../.jan/config.toml"));+ assert!(in_hidden_root(&home, None, &jan, jan.join("config.toml").to_str().unwrap()));+ assert!(in_hidden_root(&home, None, &jan, ".jan"));+ assert!(in_hidden_root(&home, None, &jan, ".jan/projects/p-1/agent.toml"));+ // Not yet existing files are hidden too, so a write cannot create one.+ assert!(in_hidden_root(&home, None, &jan, ".jan/hooks.toml"));+ assert!(!in_hidden_root(&home, None, &jan, "JAN.md"));+ assert!(!in_hidden_root(&home, None, &jan, ".janitor"));+ let _ = std::fs::remove_dir_all(&home);+ }++ /// A Jan worktree is the agent's own working tree even though it lives+ /// under `~/.jan`; the rest of the home stays hidden from it.+ #[test]+ fn a_worktree_inside_the_jan_home_keeps_its_own_tree() {+ let home = unique_root();+ let jan = home.join(".jan");+ let wt = jan.join("worktrees/repo-1/feature");+ std::fs::create_dir_all(&wt).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ assert!(!in_hidden_root(&wt, None, &jan, "src/main.rs"));+ assert!(!in_hidden_root(&wt, None, &jan, wt.to_str().unwrap()));+ assert!(in_hidden_root(&wt, None, &jan, "../../../config.toml"));+ assert!(in_hidden_root(&wt, None, &jan, jan.join("config.toml").to_str().unwrap()));+ let _ = std::fs::remove_dir_all(&home);+ }++ #[test]+ fn command_scan_expands_home_spellings() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ std::fs::write(jan.join("config.toml"), b"k").unwrap();+ let project = home.join("proj");+ std::fs::create_dir_all(&project).unwrap();+ for cmd in [+ "cat ~/.jan/config.toml",+ "cat $HOME/.jan/config.toml",+ "grep key < ${HOME}/.jan/config.toml",+ "cat ../.jan/config.toml",+ "F=~/.jan/config.toml",+ ] {+ assert!(command_touches_hidden_root(&project, None, &jan, cmd), "{cmd}");+ }+ let abs = format!("cat '{}'", jan.join("config.toml").display());+ assert!(command_touches_hidden_root(&project, None, &jan, &abs));+ assert!(!command_touches_hidden_root(&project, None, &jan, "cat ~/.bashrc"));+ assert!(!command_touches_hidden_root(&project, None, &jan, "ls -la src"));+ let _ = std::fs::remove_dir_all(&home);+ }++ #[test]+ fn hidden_under_spells_the_home_the_way_a_walk_does() {+ let home = unique_root();+ let jan = home.join(".jan");+ std::fs::create_dir_all(&jan).unwrap();+ assert_eq!(hidden_under(&home, &jan), Some(home.join(".jan")));+ let dot = home.join(".");+ assert_eq!(hidden_under(&dot, &jan), Some(dot.join(".jan")));+ let other = home.join("proj");+ std::fs::create_dir_all(&other).unwrap();+ assert_eq!(hidden_under(&other, &jan), None);+ let _ = std::fs::remove_dir_all(&home);+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 4d4519215..ef9d78e41 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -113,7 +113,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "memory_list",- "description": "List the names of your project memory notes (durable facts stored across sessions). No arguments.",+ "description": "List your memory notes (durable facts stored across sessions): this project's, then your user-wide ones as `user:<name>`. No arguments.","parameters": { "type": "object", "properties": {}, "required": [] }}}),@@ -121,11 +121,11 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "memory_read",- "description": "Read one of your project memory notes by name.",+ "description": "Read a memory note by name. `name` is this project's note, `user:name` a user-wide note, `project:<slug>` another project's index and `project:<slug>/name` one of its notes.","parameters": {"type": "object","properties": {- "name": { "type": "string", "description": "Note name (without the .md extension)." }+ "name": { "type": "string", "description": "Note name (without the .md extension), optionally scoped with `user:` or `project:<slug>/`." }},"required": ["name"]}@@ -135,11 +135,11 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "memory_write",- "description": "Create or overwrite a project memory note. Use for durable, non-obvious facts (decisions, conventions, preferences). Keep it short.",+ "description": "Create or overwrite a memory note. Use for durable, non-obvious facts (decisions, conventions, preferences). Keep it short. Plain `name` is this project's; `user:name` applies to every project (personal preferences, cross-project conventions).","parameters": {"type": "object","properties": {- "name": { "type": "string", "description": "Note name (without the .md extension); one topic per note." },+ "name": { "type": "string", "description": "Note name (without the .md extension); one topic per note. Prefix `user:` for a user-wide note." },"content": { "type": "string", "description": "Full Markdown content of the note." }},"required": ["name", "content"]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex 1b2b17769..e9f08c809 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -2,9 +2,9 @@//!//! **Store root** -- holds `memory/` and `skills/`. Long-term: memories and//! skills outlive any single conversation, so on the desktop this is a permanent-//! directory in the Jan data folder. A project (dev's layout, and the CLI agent)-//! co-locates its store at `<project>/.jan/agent` instead; both are just a store-//! root to everything downstream.+//! directory in the Jan data folder. A project (the CLI agent) keeps its store+//! at `~/.jan/projects/<slug>` instead; both are just a store root to+//! everything downstream.//!//! **Project root** -- the sandbox the filesystem tools (read/ls/find/grep, and//! later write/edit/bash) are confined to. On the desktop this is ephemeral and@@ -36,12 +36,174 @@ pub fn store_dir(store_root: &Path, kind: &str) -> PathBuf {store_root.join(kind)}-/// A project's co-located store root: `<project_root>/.jan/agent`.+/// Where projects' stores live under a Jan home: `<jan_home>/projects`.+const PROJECTS: &str = "projects";++/// The directory a project stored its state in before it moved out of the+/// project: `<project_root>/.jan`. Only the launch migration reads it.+pub const LEGACY_DIR: &str = ".jan";++/// `~/.jan`, the user-wide agent home, or `None` when the home directory is+/// unset or degenerate (a `/` home would put every project's state at the+/// filesystem root).+///+/// Test builds of this crate resolve a per-process temp directory instead, so+/// no test writes into the developer's real `~/.jan`.+pub fn jan_home() -> Option<PathBuf> {+ #[cfg(test)]+ {+ Some(std::env::temp_dir().join(format!("jan-test-home-{}", std::process::id())))+ }+ #[cfg(not(test))]+ {+ #[cfg(windows)]+ let raw = std::env::var_os("USERPROFILE");+ #[cfg(not(windows))]+ let raw = std::env::var_os("HOME");+ let home = PathBuf::from(raw?);+ if home.parent().is_none() || home.as_os_str().is_empty() {+ return None;+ }+ Some(home.join(".jan"))+ }+}++/// The directory every surface hides from the general tools and the sandboxed+/// shell: the Jan home, holding `config.toml` (provider keys, hooks) and every+/// project's store. Only while `sandbox` is on; an unconfined run is the user+/// opting out of containment. The memory/skill tools reach the store by name+/// and are unaffected.+pub fn hidden_root(sandbox: bool) -> Option<PathBuf> {+ if sandbox {+ jan_home()+ } else {+ None+ }+}++/// `<jan_home>/projects`.+pub fn projects_dir(jan_home: &Path) -> PathBuf {+ jan_home.join(PROJECTS)+}++/// FNV-1a of the path's bytes, 8 hex digits. `DefaultHasher` is explicitly not+/// stable across Rust releases, and a project must find its store (and a+/// session its worktree) again after a toolchain upgrade.+fn path_hash(path: &Path) -> String {+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ for byte in path.to_string_lossy().as_bytes() {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ format!("{hash:016x}")[..8].to_string()+}++/// Directory name for a path: its own name plus a hash of the whole path, so+/// two checkouts of the same project never share a directory.+pub fn path_slug(path: &Path) -> String {+ let name = path+ .file_name()+ .and_then(|n| n.to_str())+ .filter(|n| !n.is_empty())+ .unwrap_or("repo");+ format!("{name}-{}", path_hash(path))+}++/// The path a project's store is keyed on: the project root, canonicalized,+/// with a linked git worktree mapped back onto its main checkout.+///+/// Without the mapping, a session running in `~/.jan/worktrees/<slug>/<id>`+/// would get a fresh, empty store and lose the project's memory, skills and+/// config. A subdirectory of a worktree maps to the same subdirectory of the+/// main checkout. Read straight from the `.git` file rather than by running+/// `git`, because this runs on every store lookup.+pub fn project_key(project_root: &Path) -> PathBuf {+ let root = project_root+ .canonicalize()+ .unwrap_or_else(|_| project_root.to_path_buf());+ for top in root.ancestors() {+ let dot_git = top.join(".git");+ if dot_git.is_dir() {+ return root;+ }+ if !dot_git.is_file() {+ continue;+ }+ // A linked worktree's `.git` is `gitdir: <main>/.git/worktrees/<name>`.+ let main = std::fs::read_to_string(&dot_git).ok().and_then(|raw| {+ let gitdir = PathBuf::from(raw.trim().strip_prefix("gitdir:")?.trim());+ let gitdir = if gitdir.is_absolute() { gitdir } else { top.join(gitdir) };+ let worktrees = gitdir.parent()?;+ if worktrees.file_name()? != "worktrees" {+ return None;+ }+ let common = worktrees.parent()?;+ if common.file_name()? != ".git" {+ return None;+ }+ common.parent().map(Path::to_path_buf)+ });+ return match (main, root.strip_prefix(top)) {+ (Some(main), Ok(rel)) if rel.as_os_str().is_empty() => main,+ (Some(main), Ok(rel)) => main.join(rel),+ _ => root,+ };+ }+ root+}++/// A project's store root under a given Jan home:+/// `<jan_home>/projects/<slug>`.+pub fn project_store_in(jan_home: &Path, project_root: &Path) -> PathBuf {+ projects_dir(jan_home).join(path_slug(&project_key(project_root)))+}++/// A project's store root: `~/.jan/projects/<slug>`, holding `agent.toml`,+/// `memory/`, `skills/`, `subagents/`, `plugins/` and threads.///-/// This is dev's per-project layout and what the CLI agent uses, where memory-/// and skills live inside the project being worked on.+/// Kept outside the project so the agent's own state never sits in the tree+/// its tools work on (nothing to hide, nothing to gitignore). With no usable+/// home directory it falls back to the legacy in-project location so the agent+/// still works.pub fn project_store(project_root: &Path) -> PathBuf {- project_root.join(".jan").join("agent")+ project_store_at(jan_home().as_deref(), project_root)+}++/// [`project_store`] against an explicit Jan home, for callers that resolve the+/// home themselves (the app substitutes a temp home in its tests).+pub fn project_store_at(jan_home: Option<&Path>, project_root: &Path) -> PathBuf {+ match jan_home {+ Some(home) => project_store_in(home, project_root),+ None => legacy_project_store(project_root),+ }+}++/// Records which directory a store belongs to, since the slug alone only names+/// it. Read by the root memory index and by anything listing projects.+const PROJECT_META: &str = "project.json";++/// Record `project_root` in `<store>/project.json`. Rewritten only when it+/// changed, so a launch does not touch the file every time.+pub fn write_project_meta(store: &Path, project_root: &Path) -> std::io::Result<()> {+ let path = project_root.to_string_lossy().into_owned();+ if project_meta(store).as_deref() == Some(path.as_str()) {+ return Ok(());+ }+ std::fs::create_dir_all(store)?;+ let body = serde_json::json!({ "path": path });+ std::fs::write(store.join(PROJECT_META), format!("{body:#}\n"))+}++/// The project directory a store recorded, if any.+pub fn project_meta(store: &Path) -> Option<String> {+ let raw = std::fs::read_to_string(store.join(PROJECT_META)).ok()?;+ let value: serde_json::Value = serde_json::from_str(&raw).ok()?;+ value.get("path")?.as_str().map(str::to_string)+}++/// Where a project kept its store before the move: `<project_root>/.jan/agent`.+pub fn legacy_project_store(project_root: &Path) -> PathBuf {+ project_root.join(LEGACY_DIR).join("agent")}/// The desktop's permanent store root: `<jan_data_folder>/agent-workspace`.@@ -483,13 +645,39 @@ mod tests {);}- /// dev's layout: a project keeps its store inside itself.+ /// A project's store lives under the Jan home, never inside the project.#[test]- fn project_store_is_under_jan_agent() {- assert_eq!(- store_dir(&project_store(Path::new("/p")), "memory"),- Path::new("/p/.jan/agent/memory")- );+ fn project_store_is_under_jan_home_projects() {+ let home = Path::new("/home/u/.jan");+ let store = project_store_in(home, Path::new("/nonexistent/src/jan"));+ assert_eq!(store, Path::new("/home/u/.jan/projects/jan-f1654549"));+ assert!(!project_store(Path::new("/p")).starts_with("/p"));+ }++ /// The slug is persisted as a directory name, so it is a wire value: pin it+ /// rather than letting a refactor quietly orphan every existing store.+ #[test]+ fn the_slug_hash_is_pinned() {+ assert_eq!(path_slug(Path::new("/home/u/src/jan")), "jan-582afba2");+ }++ /// A session in a linked worktree must share its main checkout's store.+ #[test]+ fn a_linked_worktree_keys_on_its_main_checkout() {+ let base = unique_data_folder();+ let main = base.join("main");+ std::fs::create_dir_all(main.join(".git").join("worktrees").join("w1")).unwrap();+ std::fs::create_dir_all(main.join("sub")).unwrap();+ let wt = base.join("wt");+ std::fs::create_dir_all(wt.join("sub")).unwrap();+ let gitdir = main.canonicalize().unwrap().join(".git/worktrees/w1");+ std::fs::write(wt.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();++ let main_key = project_key(&main);+ assert_eq!(project_key(&wt), main_key);+ assert_eq!(project_key(&wt.join("sub")), project_key(&main.join("sub")));+ assert_ne!(project_key(&main.join("sub")), main_key);+ let _ = std::fs::remove_dir_all(&base);}/// The whole point of the split: a thread sandbox is a sibling of the store,diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rsindex 0f623371c..324c64f1c 100644--- a/src-tauri/src/core/agent/commands.rs+++ b/src-tauri/src/core/agent/commands.rs@@ -10,6 +10,7 @@ use crate::core::agent::git;use crate::core::agent::plugins;use crate::core::agent::project::{agent_toml_path, ensure_project, load_agent_config, set_skills_enabled_in_agent_toml,+ store_root,};use crate::core::agent::skill_hub;use crate::core::agent::skills as agent_skills;@@ -24,21 +25,21 @@ fn ui_error(e: String) -> String {e.strip_prefix("ERROR: ").map(str::to_string).unwrap_or(e)}-/// List the skills under `<project>/.jan/agent/skills/` (folder `<name>/SKILL.md`+/// List the skills under `<store>/skills/` (folder `<name>/SKILL.md`/// and legacy flat `<name>.md`). These are the same skills `load_skills` injects/// into the agent's system prompt; managing them here is CRUD over that/// directory. Read-only: returns empty when the project isn't scaffolded yet.#[tauri::command]pub async fn agent_skill_list(project: String) -> Result<Vec<SkillMeta>, String> {let root = std::path::PathBuf::from(&project);- Ok(skills::list_meta(&workspace::project_store(&root)))+ Ok(skills::list_meta(&store_root(&root)))}/// Read one skill's raw SKILL.md (frontmatter included) for the editor.#[tauri::command]pub async fn agent_skill_read(project: String, name: String) -> Result<String, String> {let root = std::path::PathBuf::from(&project);- skills::read_raw(&workspace::project_store(&root), &name).map_err(ui_error)+ skills::read_raw(&store_root(&root), &name).map_err(ui_error)}/// Create or overwrite a skill. New skills are written as `<name>/SKILL.md`;@@ -51,14 +52,14 @@ pub async fn agent_skill_write() -> Result<(), String> {let root = std::path::PathBuf::from(&project);ensure_project(&root)?;- skills::write(&workspace::project_store(&root), &name, &content).map_err(ui_error)+ skills::write(&store_root(&root), &name, &content).map_err(ui_error)}/// Delete a skill by name. Idempotent: a missing skill is treated as success.#[tauri::command]pub async fn agent_skill_delete(project: String, name: String) -> Result<(), String> {let root = std::path::PathBuf::from(&project);- skills::delete(&workspace::project_store(&root), &name).map_err(ui_error)+ skills::delete(&store_root(&root), &name).map_err(ui_error)}/// List the skills available on Anthropic's public skill hub (name + purpose).@@ -84,7 +85,7 @@ pub async fn agent_skill_hub_import(Some(p) => {let root = std::path::PathBuf::from(&p);ensure_project(&root)?;- workspace::project_store(&root)+ store_root(&root)}None => {let data = data_folder@@ -136,7 +137,7 @@ pub async fn agent_skill_invoke(.map_err(ui_error)}-/// List installed plugins under `<project>/.jan/agent/plugins/` with metadata+/// List installed plugins under `<store>/plugins/` with metadata/// and skill counts.#[tauri::command]pub async fn agent_plugin_list(project: String) -> Result<Vec<plugins::InstalledPlugin>, String> {diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex e9cbcdda5..f9c6888b4 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -11,7 +11,7 @@use std::path::Path;use crate::core::agent::prompt::{Composer, Placement, PromptPolicy};-use tauri_plugin_agent_tools::{memory, workspace};+use tauri_plugin_agent_tools::memory;/// Default persona used only when no assistant instructions are supplied, so a/// bare project run still opens with a role statement instead of "# Working@@ -226,29 +226,20 @@ Shell: `{shell}`{scratch_line}")}-/// A catalog of curated memory notes (names + one-line summaries), injected so-/// the model can read a note on demand with `memory_read`. None when no note-/// exists. Mirrors `load_skills`: progressive disclosure, not full bodies.+/// The memory index (names + one-line summaries), injected so the model can+/// read a note on demand with `memory_read`: this project's notes, the user's+/// `user:` notes, and pointers to other projects when cross-project memory is+/// on. The same content as the generated `MEMORY.md` files, rendered from the+/// notes. None when there is nothing to show. Progressive disclosure, not+/// full bodies.pub(crate) fn load_memory_catalog(project_root: &Path) -> Option<String> {- let entries = memory::catalog(&workspace::project_store(project_root));- if entries.is_empty() {- return None;+ let (store, home, cross_project) = crate::core::agent::project::memory_roots(project_root);+ memory::Scopes {+ store: &store,+ home: home.as_deref(),+ cross_project,}- let list = entries- .iter()- .map(|entry| {- let (name, description) = (&entry.name, &entry.summary);- if description.is_empty() {- format!("- `{name}` - no summary")- } else {- format!("- `{name}` - {description}")- }- })- .collect::<Vec<_>>()- .join("\n");- Some(format!(- "# Available Memories\n\nDurable facts recorded in this project. Read a note's full contents with `memory_read` when it is relevant to the current task.\n\n{list}"- ))+ .prompt_block()}/// Everything the prompt-block composers read.@@ -391,17 +382,20 @@ mod tests {fn scratch_project(tag: &str) -> PathBuf {let n = COUNTER.fetch_add(1, Ordering::SeqCst);- std::env::temp_dir().join(format!("jan_ctx_test_{tag}_{n}"))+ let root = std::env::temp_dir().join(format!("jan_ctx_test_{tag}_{n}"));+ let _ = std::fs::remove_dir_all(crate::core::agent::project::store_root(&root));+ std::fs::create_dir_all(&root).unwrap();+ root}fn write_skill(root: &Path, name: &str, body: &str) {- let dir = root.join(".jan").join("agent").join("skills");+ let dir = crate::core::agent::project::store_root(root).join("skills");std::fs::create_dir_all(&dir).unwrap();std::fs::write(dir.join(name), body).unwrap();}fn write_memory(root: &Path, name: &str, body: &str) {- let dir = root.join(".jan").join("agent").join("memory");+ let dir = crate::core::agent::project::store_root(root).join("memory");std::fs::create_dir_all(&dir).unwrap();std::fs::write(dir.join(name), body).unwrap();}diff --git a/src-tauri/src/core/agent/default_skill.md b/src-tauri/src/core/agent/default_skill.mdindex f1a9fc55d..22f5b35bd 100644--- a/src-tauri/src/core/agent/default_skill.md+++ b/src-tauri/src/core/agent/default_skill.md@@ -39,6 +39,12 @@ would otherwise forget.- `memory_write` (name, content) - create or update a note (same nameoverwrites). Prefer one topic per note with a descriptive name; keep it short.+Names are scoped. A plain `name` is this project's note. `user:name` is a+user-wide note that applies to every project: use it for personal preferences+and conventions that are not specific to this codebase. `project:<slug>` reads+another project's index and `project:<slug>/name` one of its notes; those are+read-only, so open one only when it is relevant.+Record a memory when you learn something durable and non-obvious. Remove factsthat become wrong by overwriting the note. Do not record transient details thatonly matter to the current turn. The "Available Memories" section of yourdiff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex c8c13793f..d478980fb 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -349,16 +349,16 @@ pub struct PendingSubagent {pub phase: u32,}-/// If `path` targets a file in the agent's skill or memory workspace, return the-/// kind (`"skill"`/`"memory"`) and the item name (file stem). None otherwise.+/// If `path` targets a file in a project's skill or memory store+/// (`~/.jan/projects/<slug>/{skills,memory}/...`), return the kind+/// (`"skill"`/`"memory"`) and the item name (file stem). None otherwise.fn classify_agent_path(path: &str) -> Option<(&'static str, String)> {+ const PROJECTS: &str = ".jan/projects/";let norm = path.replace('\\', "/");- for (needle, kind) in [- (".jan/agent/skills/", "skill"),- (".jan/agent/memory/", "memory"),- ] {- if let Some(idx) = norm.find(needle) {- let rest = &norm[idx + needle.len()..];+ let after = &norm[norm.find(PROJECTS)? + PROJECTS.len()..];+ let (_slug, inside) = after.split_once('/')?;+ for (prefix, kind) in [("skills/", "skill"), ("memory/", "memory")] {+ if let Some(rest) = inside.strip_prefix(prefix) {if rest.is_empty() || rest.ends_with('/') {return Some((kind, String::new()));}@@ -838,11 +838,11 @@ pub(crate) mod tests {#[test]fn describe_labels_fallback_path_ops() {assert_eq!(- describe_tool_call("read", &json!({"path": ".jan/agent/skills/deploy.md"})),+ describe_tool_call("read", &json!({"path": "/home/u/.jan/projects/app-1/skills/deploy.md"})),"Reading skill: deploy");assert_eq!(- describe_tool_call("write", &json!({"path": ".jan/agent/memory/decisions.md"})),+ describe_tool_call("write", &json!({"path": "/home/u/.jan/projects/app-1/memory/decisions.md"})),"Updating memory: decisions");}diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rsindex 0bb3cb238..a020f1614 100644--- a/src-tauri/src/core/agent/git.rs+++ b/src-tauri/src/core/agent/git.rs@@ -102,6 +102,20 @@ pub(crate) fn snapshot_ref(thread_id: &str) -> String {format!("refs/jan/agent/snapshots/{thread_id}")}+/// True when git tracks any file under `path` (a directory in a work tree).+/// `false` outside a repo, for an untracked or ignored directory, and when `git`+/// is not installed -- callers use it to avoid deleting files a team shares.+pub(crate) fn tracks_any(path: &Path) -> bool {+ let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else {+ return false;+ };+ let dir = dir.to_string_lossy();+ let name = name.to_string_lossy();+ git(&["-C", &dir, "ls-files", "--", &name])+ .map(|out| !out.is_empty())+ .unwrap_or(false)+}+/// The repository top-level for `path`, or `None` when `path` is not inside a/// git work tree (workspace-restore is unavailable then; the agent still edits/// in place). Also `None` when `git` is not installed.diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex cece0fe19..366488ca5 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -13,7 +13,7 @@ use crate::core::state::ProviderConfig;const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# Applies to every project unless overridden by that project's-# .jan/agent/agent.toml [provider] section.+# agent.toml [provider] section (~/.jan/projects/<project>/agent.toml).## default_model = "my-model" # used when no --model / agent.toml model is set# smol_model = "my-fast-model" # fast model for the `smol` role (/goal evaluation);@@ -47,6 +47,9 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # On by default# claude_code_alias = false # allow Jan to reuse Claude Code's# # keychain login; on by default+# memory_cross_project = false # hide other projects' memory from the+# # agent (the root ~/.jan/MEMORY.md lists+# # them by default)# wave = "👋" # sweep this glyph along the working row# # instead of the static throbber. Up to# # 3 characters ("🍌", "~", "👁️👄👁️").@@ -114,6 +117,11 @@ struct GlobalConfigToml {/// on; set false to keep Jan from reading or refreshing that credential.#[serde(default, skip_serializing_if = "Option::is_none")]claude_code_alias: Option<bool>,+ /// List other projects' memory in the prompt and let the agent read it as+ /// `project:<slug>`. `None` = the default, on. Off keeps each project's+ /// memory to itself (user-wide `user:` notes still apply everywhere).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ memory_cross_project: Option<bool>,/// Glyph swept along the working row while a turn runs, in place of the/// static Braille throbber. Absent = `WAVE_DEFAULT`; `""` = off, the/// throbber. See `wave_glyph` for why those are two different things.@@ -366,6 +374,18 @@ pub(crate) fn think_tags_enabled() -> bool {.unwrap_or(true)}+/// Whether other projects' memory is listed and readable+/// (`memory_cross_project` in `~/.jan/config.toml`), defaulting to on.+/// Unreadable config yields the default, like the other preferences.+// Test builds pin cross-project memory off (see `project::memory_roots`).+#[cfg_attr(test, allow(dead_code))]+pub(crate) fn memory_cross_project_enabled() -> bool {+ load_raw()+ .ok()+ .and_then(|config| config.memory_cross_project)+ .unwrap_or(true)+}+/// Whether the TUI streams reasoning into its live tail while folding is on/// (`stream_reasoning` in `~/.jan/config.toml`), defaulting to on. `false` keeps/// a folded block off screen entirely, leaving the header badge to stand for it.diff --git a/src-tauri/src/core/agent/hooks_config.rs b/src-tauri/src/core/agent/hooks_config.rsindex ba30d35f1..dba4094a5 100644--- a/src-tauri/src/core/agent/hooks_config.rs+++ b/src-tauri/src/core/agent/hooks_config.rs@@ -12,7 +12,7 @@//!//! 1. installed plugins' `hooks/hooks.json` (shipped by a third party)//! 2. `~/.jan/config.toml` `[[hooks]]` (this user, every project)-//! 3. `<project>/.jan/agent/agent.toml` `[[hooks]]` (this project)+//! 3. `~/.jan/projects/<slug>/agent.toml` `[[hooks]]` (this project)//!//! A deny is not a precedence question: `run_hooks` stops at the *first* hook//! that denies, so any layer can veto a call and no later layer can overturn@@ -158,7 +158,7 @@ mod tests {}fn write_agent_toml(root: &Path, body: &str) {- let dir = root.join(".jan").join("agent");+ let dir = crate::core::agent::project::store_root(root);std::fs::create_dir_all(&dir).unwrap();std::fs::write(dir.join("agent.toml"), body).unwrap();}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex bc330bc45..75503d5d9 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -518,10 +518,13 @@ struct SubagentContext {struct CompositeToolInvoker {mcp: McpToolInvoker,project_root: std::path::PathBuf,- /// Where `memory/` and `skills/` live. Co-located with the project here, so- /// the on-disk layout is unchanged; the desktop points this at its permanent- /// store instead.+ /// Where `memory/` and `skills/` live: the project's store under+ /// `~/.jan/projects`. The desktop points this at its permanent store.store_root: std::path::PathBuf,+ /// `~/.jan`, for the `user:` memory scope and other projects' stores.+ memory_home: Option<std::path::PathBuf>,+ /// Whether other projects' memory is readable (`memory_cross_project`).+ cross_project: bool,/// `[skills].enabled`, resolved once per run. The toolset owns no config/// format, so the whitelist is injected rather than re-read per tool call.enabled_skills: Vec<String>,@@ -535,6 +538,10 @@ struct CompositeToolInvoker {/// Whether `bash` is confined at all. Resolved once per run by/// [`resolve_sandbox`]; always true on the desktop.sandbox: bool,+ /// The Jan home, refused to the general tools and masked from the shell+ /// while sandboxed (`project::hidden_root`). Kept beside `sandbox` and set+ /// with it, so the two cannot disagree.+ hidden_root: Option<std::path::PathBuf>,/// Session-scoped scratch directory the shell and the filesystem tools share/// (see `workspace::scratch_dir`), so `bash` scratch files persist across/// calls for the whole run. Created at run start and wiped at run end.@@ -896,14 +903,19 @@ impl CompositeToolInvoker {}fn tool_context(&self) -> tauri_plugin_agent_tools::tools::ToolContext<'_> {- tauri_plugin_agent_tools::tools::ToolContext::new(+ let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(&self.project_root,&self.store_root,&self.enabled_skills,- )- .with_network(self.allow_network)+ );+ let ctx = match self.memory_home.as_deref() {+ Some(home) => ctx.with_memory_home(home, self.cross_project),+ None => ctx,+ };+ ctx.with_network(self.allow_network).with_home_readonly(self.allow_home_read).with_sandbox(self.sandbox)+ .with_hidden_root(self.hidden_root.as_deref()).with_scratch_root(&self.scratch_root).with_env_passthrough(&self.env_passthrough).with_env_set(&self.env_set)@@ -1587,15 +1599,13 @@ fn denied_by_policy_msg(name: &str, project_root: &std::path::Path) -> String {)}-/// Message for a call that reached the hidden agent state directory. Says the-/// path does not exist *for the agent* and that retrying is pointless: pointing-/// at a deny list would send the model reading a file that is hidden too.+/// Refusal for a path or command reaching the Jan home. Structural, not a+/// policy the user edits, so it points at the dedicated tools instead.fn hidden_path_msg(name: &str) -> String {format!(- "ERROR: tool '{name}' refused: '{}' is the agent's own state directory and is not part of \- the project. It is hidden from every tool -- do not try to reach it another way. Skills \- and memory are available through the skill_*/memory_* tools.",- tauri_plugin_agent_tools::tools::sandbox::JAN_DIR+ "ERROR: tool '{name}' refused: the Jan home (~/.jan) holds the agent's own \+ configuration and state and is hidden from every tool -- do not try to reach it \+ another way. Skills and memory are available through the skill_*/memory_* tools.")}@@ -2100,14 +2110,13 @@ impl ToolInvoker for CompositeToolInvoker {// read-only or writable root to attach.read_roots: &[],write_roots: &[],- hide_jan: self.sandbox,+ hidden_root: self.hidden_root.as_deref(),},&self.permissions,&snapshot,);// Auto-approval suppresses every prompt (sandbox escape, write, exec) but- // still honors HardDeny, so the hidden `.jan` invariant (while the shell- // is sandboxed) and explicit agent.toml denies hold.+ // still honors HardDeny, so explicit agent.toml denies hold.let decision = match decision {Decision::Prompt(_) if self.auto_approve => Decision::Allow,other => other,@@ -2121,10 +2130,13 @@ impl ToolInvoker for CompositeToolInvoker {// and builds the context inside.let root = self.project_root.clone();let store = self.store_root.clone();+ let memory_home = self.memory_home.clone();+ let cross_project = self.cross_project;let enabled = self.enabled_skills.clone();let allow_network = self.allow_network;let allow_home_read = self.allow_home_read;let sandbox = self.sandbox;+ let hidden = self.hidden_root.clone();let scratch = self.scratch_root.clone();// Hooks come along: a read is still a tool call, and a// PreToolUse policy that stopped applying to whatever happened@@ -2133,10 +2145,16 @@ impl ToolInvoker for CompositeToolInvoker {let planning = self.run_mode == crate::core::agent::plan::RunMode::Plan;let hook_sink = self.hook_sink();read_futures.push(async move {- let ctx = ToolContext::new(&root, &store, &enabled)+ let ctx = ToolContext::new(&root, &store, &enabled);+ let ctx = match memory_home.as_deref() {+ Some(home) => ctx.with_memory_home(home, cross_project),+ None => ctx,+ };+ let ctx = ctx.with_network(allow_network).with_home_readonly(allow_home_read).with_sandbox(sandbox)+ .with_hidden_root(hidden.as_deref()).with_scratch_root(&scratch).with_hooks(&hooks, planning, Some(hook_sink));let (text, diff, images) = execute_builtin_with_diff(tool, &args, &ctx).await;@@ -3221,13 +3239,18 @@ async fn orchestrate_inner(if settings.sandbox {tauri_plugin_agent_tools::workspace::ensure_scratch_dir_path(&scratch_root).await?;}+ let (store_root, memory_home, cross_project) =+ crate::core::agent::project::memory_roots(root);let tools = CompositeToolInvoker {mcp: mcp_tools,- store_root: tauri_plugin_agent_tools::workspace::project_store(root),+ store_root,+ memory_home,+ cross_project,enabled_skills: settings.enabled_skills,allow_network: settings.allow_network,allow_home_read: settings.allow_home_read,sandbox: settings.sandbox,+ hidden_root: crate::core::agent::project::hidden_root(settings.sandbox),scratch_root: scratch_root.clone(),env_passthrough: settings.env_passthrough,env_set: settings.env_set,@@ -3559,7 +3582,7 @@ pub(crate) async fn compact_history(// are resolved here.if let Some(root) = args.project_root.as_deref() {let hooks = crate::core::agent::hooks_config::resolve_hooks(root);- let store = tauri_plugin_agent_tools::workspace::project_store(root);+ let store = crate::core::agent::project::store_root(root);let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(root, &store, &[]).with_sandbox(effective_sandbox(root)).with_hooks(&hooks, false, None);@@ -5090,7 +5113,7 @@ mod tests {#[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");+ let agent_dir = crate::core::agent::project::store_root(&root);std::fs::create_dir_all(&agent_dir).expect("agent dir");std::fs::write(agent_dir.join("agent.toml"),@@ -5141,7 +5164,7 @@ mod tests {#[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");+ let agent_dir = crate::core::agent::project::store_root(&root);std::fs::create_dir_all(&agent_dir).expect("agent dir");std::fs::write(agent_dir.join("agent.toml"),@@ -7695,12 +7718,15 @@ mod tests {) -> CompositeToolInvoker {CompositeToolInvoker {sandbox: true,+ hidden_root: crate::core::agent::project::hidden_root(true),mcp: McpToolInvoker {tool_to_server: HashMap::new(),mcp_servers: Arc::new(Mutex::new(HashMap::new())),mcp_settings: Arc::new(Mutex::new(McpSettings::default())),},- store_root: tauri_plugin_agent_tools::workspace::project_store(&root),+ store_root: crate::core::agent::project::store_root(&root),+ memory_home: None,+ cross_project: false,enabled_skills: Vec::new(),allow_network: DEFAULT_ALLOW_NETWORK,allow_home_read: DEFAULT_ALLOW_HOME_READ,@@ -7765,6 +7791,7 @@ mod tests {// plugin-tool wiring, not about a sandbox backend or a prompt that has// no one to answer it.invoker.sandbox = false;+ invoker.hidden_root = None;invoker.auto_approve = true;invoker.hooks = hooks;invoker.plugin_tools = plugin_tools;@@ -8166,6 +8193,7 @@ mod tests {let (tx, rx) = mpsc::unbounded_channel();let mut invoker = build_prompting_invoker(root, tx, PermissionRegistry::default());invoker.sandbox = false;+ invoker.hidden_root = None;invoker.auto_approve = true;invoker.host_tools = tools;(invoker, rx)@@ -8852,7 +8880,7 @@ mod tests {.unwrap().as_nanos()));- let agent_dir = root.join(".jan").join("agent");+ let agent_dir = crate::core::agent::project::store_root(&root);std::fs::create_dir_all(&agent_dir).expect("create agent dir");let write = |body: &str| {@@ -9813,6 +9841,7 @@ mod tests {invoker.auto_approve = true;// Bare shell: this exercises the loop wiring, not the jail.invoker.sandbox = false;+ invoker.hidden_root = None;let out = invoker.invoke(&[monitor_call(@@ -9873,6 +9902,7 @@ mod tests {let mut invoker = build_prompting_invoker(root.clone(), tx, registry);invoker.auto_approve = true;invoker.sandbox = false;+ invoker.hidden_root = None;invoker.monitors_outlive_run = true;let out = invokerdiff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 3b36fd969..e75c9440d 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -48,6 +48,7 @@ pub mod reminder;pub mod session;pub mod skill_hub;pub mod skills;+pub mod store_migration;pub mod subagent;pub mod todo;pub mod transcript;diff --git a/src-tauri/src/core/agent/plugin_commands.rs b/src-tauri/src/core/agent/plugin_commands.rsindex d8cb896e6..b74c405a9 100644--- a/src-tauri/src/core/agent/plugin_commands.rs+++ b/src-tauri/src/core/agent/plugin_commands.rs@@ -385,19 +385,19 @@ mod tests {let cmd_dir = plugins_dir(&root).join("release").join("commands");std::fs::create_dir_all(&cmd_dir).unwrap();std::fs::write(cmd_dir.join("prepare.md"), "body").unwrap();- std::fs::create_dir_all(root.join(".jan").join("agent")).unwrap();+ std::fs::create_dir_all(crate::core::agent::project::store_root(&root)).unwrap();// With the command disabled (not in the whitelist), invocation errors,// matching the skill path.std::fs::write(- root.join(".jan").join("agent").join("agent.toml"),+ crate::core::agent::project::store_root(&root).join("agent.toml"),"[skills]\nenabled = [\"some-other\"]\n",).unwrap();assert!(build_message(&root, "prepare", "").is_err());// A command enabled by name resolves.std::fs::write(- root.join(".jan").join("agent").join("agent.toml"),+ crate::core::agent::project::store_root(&root).join("agent.toml"),"[skills]\nenabled = [\"prepare\"]\n",).unwrap();diff --git a/src-tauri/src/core/agent/plugins.rs b/src-tauri/src/core/agent/plugins.rsindex 87996df34..29c681ed8 100644--- a/src-tauri/src/core/agent/plugins.rs+++ b/src-tauri/src/core/agent/plugins.rs@@ -1,5 +1,5 @@//! Plugin install/removal and marketplace search. A plugin is a directory-//! `.jan/agent/plugins/<name>/` cloned from a git repository, so installing+//! `~/.jan/projects/<slug>/plugins/<name>/` cloned from a git repository, so installing//! from GitHub (or any git host) is just `git clone`. No lockfile or registry//! file: an installed plugin is a directory, removed by deleting it. Installing//! never executes plugin code — a plugin carries skills (instructions) plus andiff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rsindex f68628c17..4c9eaec8b 100644--- a/src-tauri/src/core/agent/prefix_stability.rs+++ b/src-tauri/src/core/agent/prefix_stability.rs@@ -178,20 +178,22 @@ impl Project {COUNTER.fetch_add(1, Ordering::SeqCst)));let _ = std::fs::remove_dir_all(&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::create_dir_all(&root).unwrap();+ let store = crate::core::agent::project::store_root(&root);+ std::fs::create_dir_all(store.join("skills")).unwrap();+ std::fs::create_dir_all(store.join("memory")).unwrap();std::fs::write(root.join("JAN.md"),"# Project\n\nPrefix-stability fixture.\n",).unwrap();std::fs::write(- root.join(".jan/agent/skills/example.md"),+ store.join("skills/example.md"),"---\nname: example\ndescription: An example skill\n---\n\nSkill body.\n",).unwrap();std::fs::write(- root.join(".jan/agent/memory/note.md"),+ store.join("memory/note.md"),"A durable fact about the fixture project.\n\nLonger detail.\n",).unwrap();diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex 4129c7852..3ea571687 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -1,4 +1,5 @@-//! `agent.toml` project config parsing and `.jan/agent/` scaffolding.+//! `agent.toml` project config parsing and store scaffolding+//! (`~/.jan/projects/<slug>/`).use std::collections::BTreeMap;use std::path::{Path, PathBuf};@@ -56,7 +57,7 @@ pub(crate) struct PromptSection {}/// `[plugins]` — plugin installs and marketplace. Installed plugins live in-/// `.jan/agent/plugins/`; this section only carries configuration.+/// `<store_root>/plugins/`; this section only carries configuration.#[derive(Debug, Clone, Default, Deserialize)]pub(crate) struct PluginsSection {/// URL of a JSON marketplace index (`[{ name, description, repo, ref? }]`).@@ -321,9 +322,84 @@ inject = "always"# default = "tail""#;-/// Path to `<project_root>/.jan/agent/agent.toml`.+/// `~/.jan`, where every project's store lives. Test builds use a per-process+/// temp directory so no test reads or writes the developer's real `~/.jan`;+/// the plugin's own `cfg(test)` override is not active when this crate+/// compiles it as a dependency.+pub(crate) fn jan_home() -> Option<PathBuf> {+ #[cfg(test)]+ {+ Some(std::env::temp_dir().join(format!("jan-app-test-home-{}", std::process::id())))+ }+ #[cfg(not(test))]+ {+ tauri_plugin_agent_tools::workspace::jan_home()+ }+}++/// The Jan home the general tools and the sandboxed shell may not reach while+/// `sandbox` is on (see `workspace::hidden_root`). Resolved through [`jan_home`]+/// so tests hide their temp home, not the developer's.+pub(crate) fn hidden_root(sandbox: bool) -> Option<PathBuf> {+ if sandbox {+ jan_home()+ } else {+ None+ }+}++/// A project's store root, `~/.jan/projects/<slug>`: `agent.toml`, `memory/`,+/// `skills/`, `subagents/`, `plugins/` and the TUI's threads. The one place the+/// app resolves it; the project directory itself holds only `JAN.md`.+pub(crate) fn store_root(project_root: &Path) -> PathBuf {+ tauri_plugin_agent_tools::workspace::project_store_at(jan_home().as_deref(), project_root)+}++/// Move a legacy `<project>/.jan/agent` into [`store_root`] when the workspace+/// still has a `.jan` directory. Called once per launch, before anything reads+/// the store; returns a line for the surface to show, if any.+///+/// Once per project per process: later calls are free and return `None`, so+/// every entry point can call it without re-reporting.+pub(crate) fn migrate_legacy_store(project_root: &Path) -> Option<String> {+ use std::collections::HashSet;+ use std::sync::Mutex;+ static SEEN: Mutex<Option<HashSet<PathBuf>>> = Mutex::new(None);+ {+ let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());+ if !seen.get_or_insert_with(HashSet::new).insert(project_root.to_path_buf()) {+ return None;+ }+ }+ let home = jan_home()?;+ let store = store_root(project_root);+ let outcome =+ crate::core::agent::store_migration::migrate_on_launch(project_root, &store, Some(&home));+ if matches!(outcome, crate::core::agent::store_migration::Outcome::Moved { .. }) {+ // A migrated store has notes but no indexes yet, and the root index+ // should point at it straight away.+ let _ = tauri_plugin_agent_tools::workspace::write_project_meta(&store, project_root);+ tauri_plugin_agent_tools::memory::write_index(&store);+ let (_, _, cross_project) = memory_roots(project_root);+ tauri_plugin_agent_tools::memory::write_root_index(&home, cross_project);+ }+ outcome.message()+}++/// The memory a run in `project_root` reaches, as owned paths: the project's+/// store, and `~/.jan` for the user scope and other projects. Tests get no+/// cross-project listing, so one test's notes never reach another's prompt.+pub(crate) fn memory_roots(project_root: &Path) -> (PathBuf, Option<PathBuf>, bool) {+ #[cfg(test)]+ let cross = false;+ #[cfg(not(test))]+ let cross = crate::core::agent::global_config::memory_cross_project_enabled();+ (store_root(project_root), jan_home(), cross)+}++/// Path to `<store_root>/agent.toml`.pub(crate) fn agent_toml_path(project_root: &Path) -> PathBuf {- project_root.join(".jan").join("agent").join("agent.toml")+ store_root(project_root).join("agent.toml")}/// Load + parse agent.toml. Err if missing or malformed (path included in message).@@ -419,8 +495,8 @@ pub(crate) fn permissions_from(cfg: &AgentToml) -> ToolPermissions {)}-/// Ensure a usable `.jan/agent/{agent.toml, skills/, memory/}` exists under-/// `project_root`, creating only the pieces that don't already exist.+/// Ensure a usable `{agent.toml, skills/, memory/}` exists in the project's+/// store (see [`store_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).///@@ -434,7 +510,13 @@ pub(crate) fn ensure_project(project_root: &Path) -> Result<PathBuf, String> {project_root.display()));}- let agent_dir = project_root.join(".jan").join("agent");+ // Before scaffolding, or an empty new store would turn the move into a+ // conflict. A no-op after the first call for this project; the CLI already+ // ran it (and reported it) when it resolved the project.+ if let Some(note) = migrate_legacy_store(project_root) {+ log::info!("Agent: {note}");+ }+ let agent_dir = store_root(project_root);std::fs::create_dir_all(agent_dir.join("skills")).map_err(|e| format!("Failed to create skills dir: {e}"))?;std::fs::create_dir_all(agent_dir.join("memory"))@@ -445,6 +527,8 @@ 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()))?;}+ // Best-effort: only the memory index's project pointers read it.+ let _ = tauri_plugin_agent_tools::workspace::write_project_meta(&agent_dir, project_root);Ok(agent_dir)}@@ -547,19 +631,20 @@ mod tests {root}- /// `ensure_project` scaffolds `.jan/agent/{skills,memory}` by hand, while the- /// toolset resolves those same directories through `workspace::project_store`.- /// Nothing but this test ties the two together, and if they ever drift a- /// user's existing skills and memories simply stop being found.+ /// `ensure_project` scaffolds `{skills,memory}` in the store, while the+ /// toolset reads those same directories through the store root it is+ /// handed. If the two ever drift a user's skills and memories stop being+ /// found. The store must also never land inside the project.#[test]fn scaffolded_dirs_match_the_toolset_store_layout() {use tauri_plugin_agent_tools::workspace;let root = unique_root("store_layout");- ensure_project(&root).expect("scaffold project");+ let store = ensure_project(&root).expect("scaffold project");- let store = workspace::project_store(&root);- assert_eq!(store, root.join(".jan").join("agent"));+ assert_eq!(store, store_root(&root));+ assert!(!store.starts_with(&root), "the store must live outside the project");+ assert!(!root.join(".jan").exists(), "nothing is written into the project");assert!(tauri_plugin_agent_tools::skills::skills_dir(&store).is_dir(),"skills dir the toolset reads is not the one ensure_project created"@@ -573,7 +658,7 @@ mod tests {}fn write_agent_toml(root: &Path, body: &str) {- let dir = root.join(".jan").join("agent");+ let dir = crate::core::agent::project::store_root(root);std::fs::create_dir_all(&dir).expect("create agent dir");std::fs::write(dir.join("agent.toml"), body).expect("write agent.toml");}@@ -632,7 +717,7 @@ mod tests {/// 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.+ /// one in the store, which nothing reads.#[test]fn ensure_does_not_scaffold_an_instructions_file() {let root = unique_root("no_instructions");diff --git a/src-tauri/src/core/agent/skill_hub.rs b/src-tauri/src/core/agent/skill_hub.rsindex a95007937..9a023ac2b 100644--- a/src-tauri/src/core/agent/skill_hub.rs+++ b/src-tauri/src/core/agent/skill_hub.rs@@ -1,6 +1,6 @@//! Import skills from Anthropic's public skill hub (github.com/anthropics/skills).//! Skills live at `skills/<name>/SKILL.md` with optional bundled files; import-//! copies the whole folder into the project's `.jan/agent/skills/<name>/`.+//! copies the whole folder into the project store's `skills/<name>/`.//!//! All network I/O goes through the backend (no CORS/CSP limits) using the git//! tree API (1 request to enumerate paths) plus raw.githubusercontent.com for@@ -103,7 +103,7 @@ pub async fn list() -> Result<Vec<HubSkill>, String> {}/// Download one hub skill (SKILL.md + every bundled file) into the project's-/// `.jan/agent/skills/<name>/`, replacing any existing skill of the same name.+/// `<store>/skills/<name>/`, replacing any existing skill of the same name.////// Atomic on failure: every file is fetched into memory first, and only once all/// downloads succeed is the destination cleared and rewritten — a mid-downloaddiff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rsindex b4eaabd97..5e82cea38 100644--- a/src-tauri/src/core/agent/skills.rs+++ b/src-tauri/src/core/agent/skills.rs@@ -21,9 +21,9 @@ use serde::Deserialize;use tauri_plugin_agent_tools::skills::{DEFAULT_JAN_SKILL, DEFAULT_JAN_SKILL_NAME};use tauri_plugin_agent_tools::workspace::workspace_filename;-/// `<project_root>/.jan/agent/skills`.+/// `<store_root>/skills`, in the project's store (see `project::store_root`).pub(crate) fn skills_dir(root: &Path) -> PathBuf {- root.join(".jan").join("agent").join("skills")+ crate::core::agent::project::store_root(root).join("skills")}/// One skill on disk, located by its identity name (folder name or flat stem).@@ -203,14 +203,14 @@ pub(crate) fn scan_skill_dir(dir: &Path) -> Vec<SkillEntry> {out}-/// All project skills (`.jan/agent/skills`), sorted by name.+/// All project skills (`<store_root>/skills`), sorted by name.pub(crate) fn discover(root: &Path) -> Vec<SkillEntry> {scan_skill_dir(&skills_dir(root))}-/// The plugins directory `.jan/agent/plugins`.+/// The plugins directory `<store_root>/plugins`.pub(crate) fn plugins_dir(root: &Path) -> PathBuf {- root.join(".jan").join("agent").join("plugins")+ crate::core::agent::project::store_root(root).join("plugins")}/// Recursively yield every `*.md` file under `dir`, skipping dotfiles and@@ -930,7 +930,7 @@ mod tests {// Unknown or disabled skills are rejected.assert!(build_invocation_message(&root, "nope", "").is_err());std::fs::write(- root.join(".jan").join("agent").join("agent.toml"),+ crate::core::agent::project::store_root(&root).join("agent.toml"),"[skills]\nenabled = [\"other\"]\n",).unwrap();diff --git a/src-tauri/src/core/agent/store_migration.rs b/src-tauri/src/core/agent/store_migration.rsnew file mode 100644index 000000000..489f2e313--- /dev/null+++ b/src-tauri/src/core/agent/store_migration.rs@@ -0,0 +1,364 @@+//! One-time move of a project's agent state out of the project.+//!+//! Before issue #388 the agent kept everything at `<project>/.jan/agent`+//! (`agent.toml`, memory, skills, subagents, plugins, threads). It now lives in+//! `~/.jan/projects/<slug>` (see `project::store_root`). This runs at launch+//! and does nothing unless the workspace still has a `.jan` directory, so a+//! migrated or fresh project pays one `stat`.+//!+//! Never merges: when both locations already hold state the legacy folder is+//! left alone and the caller reports it, because silently picking a winner+//! would throw away whichever side lost.++use std::path::{Path, PathBuf};++use tauri_plugin_agent_tools::workspace::{legacy_project_store, LEGACY_DIR};++/// What a launch-time migration did, for the surface to report.+#[derive(Debug, PartialEq, Eq)]+pub enum Outcome {+ /// No `<project>/.jan` directory: nothing to do (the common case).+ Absent,+ /// The legacy store was moved to `to`. `leftover` lists entries in+ /// `<project>/.jan` other than `agent/`, which were not ours to move.+ Moved { to: PathBuf, leftover: Vec<String> },+ /// Both the legacy and the new store hold state; nothing was touched.+ Conflict { from: PathBuf, to: PathBuf },+ /// Git tracks files under the legacy store (a team sharing skills through+ /// the repo). Moving it would show up as deleted files and take the shared+ /// copy away from everyone else, so it is left for the user to decide.+ Tracked { from: PathBuf, to: PathBuf },+ /// `<project>/.jan` exists but is not a project store we recognise (for+ /// instance it is the user's global `~/.jan` because the workspace is the+ /// home directory). Left alone.+ Skipped,+}++impl Outcome {+ /// One line for the TUI or stderr, or `None` when there is nothing to say.+ pub fn message(&self) -> Option<String> {+ match self {+ Outcome::Absent | Outcome::Skipped => None,+ Outcome::Moved { to, leftover } if leftover.is_empty() => {+ Some(format!("moved project agent state to {}", to.display()))+ }+ Outcome::Moved { to, leftover } => Some(format!(+ "moved project agent state to {}; left {} in {LEGACY_DIR}/ untouched",+ to.display(),+ leftover.join(", ")+ )),+ Outcome::Conflict { from, to } => Some(format!(+ "found agent state in both {} and {}; using the latter. Merge or delete {} by hand",+ from.display(),+ to.display(),+ from.display()+ )),+ Outcome::Tracked { from, to } => Some(format!(+ "{} is tracked by git, so it was not moved; Jan now reads {}. Copy what you \+ need there, then remove {} from the repo",+ from.display(),+ to.display(),+ from.display()+ )),+ }+ }+}++/// Move `<project>/.jan/agent` to `store` when the workspace still has one.+///+/// `jan_home` is the global `~/.jan`; a workspace whose `.jan` *is* that+/// directory (running in `$HOME`) is skipped rather than having the user's+/// config swallowed. Crash-safe: the tree is copied to a temp sibling of+/// `store` and renamed into place before the source is deleted, so an+/// interrupted run leaves the legacy copy intact and simply retries next time.+pub fn migrate_on_launch(project_root: &Path, store: &Path, jan_home: Option<&Path>) -> Outcome {+ let legacy_dir = project_root.join(LEGACY_DIR);+ if !legacy_dir.is_dir() {+ return Outcome::Absent;+ }+ if let Some(home) = jan_home {+ if same_path(&legacy_dir, home) {+ return Outcome::Skipped;+ }+ }+ let legacy = legacy_project_store(project_root);+ if !legacy.is_dir() {+ return Outcome::Skipped;+ }+ if crate::core::agent::git::tracks_any(&legacy) {+ return Outcome::Tracked {+ from: legacy,+ to: store.to_path_buf(),+ };+ }+ if has_entries(store) {+ return Outcome::Conflict {+ from: legacy,+ to: store.to_path_buf(),+ };+ }+ if let Err(e) = move_tree(&legacy, store) {+ log::warn!(+ "Agent: could not move {} to {}: {e}",+ legacy.display(),+ store.display()+ );+ return Outcome::Skipped;+ }+ let leftover = remaining_entries(&legacy_dir);+ if leftover.is_empty() {+ let _ = std::fs::remove_dir(&legacy_dir);+ }+ Outcome::Moved {+ to: store.to_path_buf(),+ leftover,+ }+}++fn same_path(a: &Path, b: &Path) -> bool {+ match (a.canonicalize(), b.canonicalize()) {+ (Ok(a), Ok(b)) => a == b,+ _ => false,+ }+}++fn has_entries(dir: &Path) -> bool {+ std::fs::read_dir(dir)+ .map(|mut rd| rd.next().is_some())+ .unwrap_or(false)+}++fn remaining_entries(dir: &Path) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .map(|rd| {+ rd.flatten()+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .collect()+ })+ .unwrap_or_default();+ names.sort();+ names+}++/// Put `from` at `to` (which must not hold anything): a rename when both sit on+/// one filesystem, otherwise copy to a temp sibling, rename that into place,+/// then delete the source.+fn move_tree(from: &Path, to: &Path) -> std::io::Result<()> {+ let parent = to+ .parent()+ .ok_or_else(|| std::io::Error::other("store has no parent directory"))?;+ std::fs::create_dir_all(parent)?;+ // An empty store directory (a scaffold from an earlier launch that found+ // nothing to migrate) would make the rename fail.+ let _ = std::fs::remove_dir(to);+ if std::fs::rename(from, to).is_ok() {+ return Ok(());+ }+ let staging = parent.join(format!(+ ".migrating-{}-{}",+ std::process::id(),+ to.file_name().and_then(|n| n.to_str()).unwrap_or("store")+ ));+ let _ = std::fs::remove_dir_all(&staging);+ copy_tree(from, &staging)?;+ std::fs::rename(&staging, to)?;+ std::fs::remove_dir_all(from)+}++/// Recursive copy that recreates symlinks as symlinks instead of following them,+/// so a link inside the store cannot pull an arbitrary tree into `~/.jan`.+fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {+ std::fs::create_dir_all(to)?;+ for entry in std::fs::read_dir(from)? {+ let entry = entry?;+ let src = entry.path();+ let dst = to.join(entry.file_name());+ let kind = entry.file_type()?;+ if kind.is_dir() {+ copy_tree(&src, &dst)?;+ } else if kind.is_symlink() {+ copy_link(&src, &dst)?;+ } else {+ std::fs::copy(&src, &dst)?;+ }+ }+ Ok(())+}++#[cfg(unix)]+fn copy_link(src: &Path, dst: &Path) -> std::io::Result<()> {+ std::os::unix::fs::symlink(std::fs::read_link(src)?, dst)+}++// Creating a symlink on Windows needs a privilege most users lack, and a store+// has no reason to contain one; skip it rather than fail the whole move.+#[cfg(not(unix))]+fn copy_link(src: &Path, _dst: &Path) -> std::io::Result<()> {+ log::warn!("Agent: skipped symlink {} while migrating", src.display());+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn legacy_project(dir: &Path) -> PathBuf {+ let project = dir.join("project");+ let agent = project.join(".jan").join("agent");+ std::fs::create_dir_all(agent.join("memory")).unwrap();+ std::fs::create_dir_all(agent.join("threads")).unwrap();+ std::fs::write(agent.join("agent.toml"), "[agent]\nmodel = \"m\"\n").unwrap();+ std::fs::write(agent.join("memory").join("note.md"), "remember").unwrap();+ std::fs::write(agent.join("threads").join("t1.json"), "{}").unwrap();+ project+ }++ #[test]+ fn a_workspace_without_jan_is_left_alone() {+ let dir = tempfile::tempdir().unwrap();+ let store = dir.path().join("home/projects/p-1");+ let out = migrate_on_launch(dir.path(), &store, None);+ assert_eq!(out, Outcome::Absent);+ assert!(!store.exists(), "no migration must not create the store");+ assert!(out.message().is_none());+ }++ #[test]+ fn legacy_state_moves_and_the_jan_dir_goes_away() {+ let dir = tempfile::tempdir().unwrap();+ let project = legacy_project(dir.path());+ let store = dir.path().join("home/projects/p-1");++ let out = migrate_on_launch(&project, &store, None);+ assert_eq!(+ out,+ Outcome::Moved {+ to: store.clone(),+ leftover: vec![]+ }+ );+ assert_eq!(std::fs::read_to_string(store.join("memory/note.md")).unwrap(), "remember");+ assert!(store.join("threads/t1.json").is_file());+ assert!(store.join("agent.toml").is_file());+ assert!(!project.join(".jan").exists());+ assert!(out.message().unwrap().contains("moved project agent state"));++ // A second launch finds nothing to do.+ assert_eq!(migrate_on_launch(&project, &store, None), Outcome::Absent);+ }++ #[test]+ fn an_empty_scaffolded_store_does_not_count_as_a_conflict() {+ let dir = tempfile::tempdir().unwrap();+ let project = legacy_project(dir.path());+ let store = dir.path().join("home/projects/p-1");+ std::fs::create_dir_all(&store).unwrap();+ assert!(matches!(+ migrate_on_launch(&project, &store, None),+ Outcome::Moved { .. }+ ));+ assert!(store.join("agent.toml").is_file());+ }++ #[test]+ fn existing_state_on_both_sides_is_a_conflict_and_nothing_moves() {+ let dir = tempfile::tempdir().unwrap();+ let project = legacy_project(dir.path());+ let store = dir.path().join("home/projects/p-1");+ std::fs::create_dir_all(&store).unwrap();+ std::fs::write(store.join("agent.toml"), "new").unwrap();++ let out = migrate_on_launch(&project, &store, None);+ assert!(matches!(out, Outcome::Conflict { .. }));+ assert_eq!(std::fs::read_to_string(store.join("agent.toml")).unwrap(), "new");+ assert!(project.join(".jan/agent/agent.toml").is_file());+ assert!(out.message().unwrap().contains("both"));+ }++ #[test]+ fn unrelated_entries_in_jan_are_kept_and_reported() {+ let dir = tempfile::tempdir().unwrap();+ let project = legacy_project(dir.path());+ std::fs::write(project.join(".jan").join("other.txt"), "x").unwrap();+ let store = dir.path().join("home/projects/p-1");++ let out = migrate_on_launch(&project, &store, None);+ assert_eq!(+ out,+ Outcome::Moved {+ to: store.clone(),+ leftover: vec!["other.txt".to_string()]+ }+ );+ assert!(project.join(".jan/other.txt").is_file());+ assert!(!project.join(".jan/agent").exists());+ }++ /// Running in `$HOME` makes `<workspace>/.jan` the global Jan home, which+ /// holds `config.toml` and every other project's store.+ #[test]+ fn the_global_jan_home_is_never_migrated() {+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path().join(".jan");+ std::fs::create_dir_all(home.join("agent").join("subagents")).unwrap();+ let store = home.join("projects").join("u-1");++ let out = migrate_on_launch(dir.path(), &store, Some(&home));+ assert_eq!(out, Outcome::Skipped);+ assert!(home.join("agent/subagents").is_dir());+ assert!(!store.exists());+ }++ #[test]+ fn a_jan_dir_without_an_agent_store_is_skipped() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join(".jan")).unwrap();+ let store = dir.path().join("home/projects/p-1");+ assert_eq!(migrate_on_launch(dir.path(), &store, None), Outcome::Skipped);+ assert!(dir.path().join(".jan").is_dir());+ }++ /// A team that commits `.jan/agent/skills` shares them through the repo;+ /// moving them would delete tracked files for everyone.+ #[test]+ fn a_legacy_store_tracked_by_git_is_not_moved() {+ let dir = tempfile::tempdir().unwrap();+ let project = legacy_project(dir.path());+ let git = |args: &[&str]| {+ let ok = std::process::Command::new("git")+ .arg("-C")+ .arg(&project)+ .args(args)+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false);+ assert!(ok, "git {args:?}");+ };+ git(&["init", "-q"]);+ let store = dir.path().join("home/projects/p-1");+ // Untracked, it moves as usual; nothing is lost.+ let untracked = dir.path().join("untracked");+ copy_tree(&project, &untracked).unwrap();+ git(&["add", ".jan/agent/agent.toml"]);++ let out = migrate_on_launch(&project, &store, None);+ assert!(matches!(out, Outcome::Tracked { .. }), "{out:?}");+ assert!(project.join(".jan/agent/agent.toml").is_file());+ assert!(!store.exists());+ assert!(out.message().unwrap().contains("tracked by git"));+ assert!(matches!(+ migrate_on_launch(&untracked, &store, None),+ Outcome::Moved { .. }+ ));+ }++ #[test]+ fn copy_fallback_preserves_the_tree() {+ let dir = tempfile::tempdir().unwrap();+ let project = legacy_project(dir.path());+ let staging = dir.path().join("copy");+ copy_tree(&legacy_project_store(&project), &staging).unwrap();+ assert!(staging.join("memory/note.md").is_file());+ assert!(staging.join("threads/t1.json").is_file());+ }+}diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex d59c8d1c9..3e4e70a89 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1,8 +1,8 @@//! Subagent definitions and their two-scope registry. A subagent is a named,//! reusable system prompt + default tool allowlist that the main agent can//! dispatch a nested, isolated run against (see `dispatch_subagent`). Definitions-//! live as `<scope>/.jan/agent/subagents/<name>.toml`, merged from the user scope-//! (`~/.jan/agent/subagents/`) and the project scope (`<project>/.jan/agent/+//! live as `<scope>/subagents/<name>.toml`, merged from the user scope+//! (`~/.jan/agent/subagents/`) and the project scope (`~/.jan/projects/<slug>///! subagents/`); the project scope shadows the user scope by name.use std::path::{Path, PathBuf};@@ -18,7 +18,8 @@ use tauri_plugin_agent_tools::tools::spill::{use tauri_plugin_agent_tools::workspace;/// Directory name holding `<name>.toml` definitions, under both a project's-/// `.jan/agent/` and the desktop's permanent store.+/// store (`~/.jan/projects/<slug>/`), `~/.jan/agent/` and the desktop's+/// permanent store.const SUBAGENTS: &str = "subagents";#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]@@ -79,9 +80,9 @@ pub fn user_subagents_dir() -> Option<PathBuf> {dirs::home_dir().map(|h| h.join(".jan").join("agent").join(SUBAGENTS))}-/// `<project_root>/.jan/agent/subagents/`.+/// `<store_root>/subagents/`, in the project's store (see `project::store_root`).pub fn project_subagents_dir(project_root: &Path) -> PathBuf {- project_root.join(".jan").join("agent").join(SUBAGENTS)+ crate::core::agent::project::store_root(project_root).join(SUBAGENTS)}/// The desktop's single subagent directory:diff --git a/src-tauri/src/core/cli/mcp_serve.rs b/src-tauri/src/core/cli/mcp_serve.rsindex d98c237e6..3db68c945 100644--- a/src-tauri/src/core/cli/mcp_serve.rs+++ b/src-tauri/src/core/cli/mcp_serve.rs@@ -39,6 +39,10 @@ fn options_for(project: &str, flags: &ServeFlags) -> Result<ServeOptions, Stringlet root = PathBuf::from(project).canonicalize().map_err(|e| format!("Cannot resolve project '{project}': {e}"))?;+ // stdout is the MCP channel, so the notice goes to stderr.+ if let Some(note) = crate::core::agent::project::migrate_legacy_store(&root) {+ eprintln!("({note})");+ }let settings = crate::core::agent::project::run_settings(&root);let mut opts = ServeOptions::new(root);opts.enabled_skills = settings.enabled_skills;@@ -110,7 +114,10 @@ mod tests {assert_eq!(opts.served, ServedTools::default());assert!(opts.sandbox, "sandbox stays on unless agent.toml says otherwise");assert!(!opts.allow_network);- assert_eq!(opts.store_root, opts.project_root.join(".jan").join("agent"));+ assert_eq!(+ opts.store_root,+ crate::core::agent::project::store_root(&opts.project_root)+ );let opts = options_for(&project,@@ -130,7 +137,7 @@ mod tests {#[test]fn agent_toml_tool_settings_are_honored() {let dir = tempfile::tempdir().expect("tempdir");- let agent_dir = dir.path().join(".jan").join("agent");+ let agent_dir = crate::core::agent::project::store_root(dir.path());std::fs::create_dir_all(&agent_dir).expect("mkdir");std::fs::write(agent_dir.join("agent.toml"),diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex cb63d6581..ac07d58bd 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -53,7 +53,7 @@ use crate::core::threads::{// ── Thread operations ──────────────────────────────────────────────────────/// List thread metadata under `<base>/threads/`. `base` is the Jan data folder-/// (desktop store) or a project's `.jan/agent` dir (TUI store).+/// (desktop store) or a project's store `~/.jan/projects/<slug>` (TUI store).pub fn list_threads_in(base: &std::path::Path) -> Result<Vec<serde_json::Value>, String> {use std::fs;@@ -379,7 +379,7 @@ pub fn cli_save_thread(/// Persist a TUI `/model` choice to the project's `agent.toml` `[agent].model`,/// so it is remembered on the next session (agent.toml wins over the desktop-/// default in the model-resolution order). `agent_dir` is `<project>/.jan/agent`.+/// default in the model-resolution order). `agent_dir` is the project's store.pub fn cli_set_project_model(agent_dir: &std::path::Path, model: &str) -> Result<(), String> {set_model_in_agent_toml(&agent_dir.join("agent.toml"), model)}@@ -850,10 +850,27 @@ fn resolve_cost_ceiling(/// working-directory block, so a bare "." must become the real cwd rather than/// being sent to the model as-is. Falls back to the raw (possibly relative)/// path if canonicalization fails (e.g. the directory doesn't exist yet).+///+/// Every CLI entry point resolves its project here, so this is also where a+/// legacy `<project>/.jan` is moved into the project's store: before anything+/// reads it, and only when the workspace still has one. The notice is kept for+/// the surface to show (see [`take_migration_notice`]).fn resolve_project_root(project: &str) -> PathBuf {- PathBuf::from(project)+ let root = PathBuf::from(project).canonicalize()- .unwrap_or_else(|_| PathBuf::from(project))+ .unwrap_or_else(|_| PathBuf::from(project));+ if let Some(note) = crate::core::agent::project::migrate_legacy_store(&root) {+ log::info!("Agent: {note}");+ *MIGRATION_NOTICE.lock().unwrap_or_else(|e| e.into_inner()) = Some(note);+ }+ root+}++static MIGRATION_NOTICE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);++/// The launch migration's one-line report, handed out once.+pub(crate) fn take_migration_notice() -> Option<String> {+ MIGRATION_NOTICE.lock().unwrap_or_else(|e| e.into_inner()).take()}/// Resolved-config + provider snapshot for `jan cli agent status`.@@ -1786,6 +1803,9 @@ fn prepare_agent_run(resume.as_ref(),)?;let project_root = resolve_project_root(project);+ if let Some(note) = take_migration_notice() {+ eprintln!("({note})");+ }if let Some(note) = session.workspace_note.as_deref() {eprintln!("({note})");}@@ -2725,15 +2745,16 @@ pub async fn cli_agent_ui(},resume.as_ref(),)?;- // TUI threads persist under the project's .jan/agent dir, separate from the- // desktop store, so continuing here never mutates desktop threads.+ // TUI threads persist in the project's store, separate from the desktop+ // store, so continuing here never mutates desktop threads.let agent_dir = agent_dir_for(&project_root);tui::run(session, agent_dir, project_root, task, images, resume).await}-/// Where the TUI persists a project's threads (`<project>/.jan/agent`).+/// Where the TUI persists a project's threads: the project's store,+/// `~/.jan/projects/<slug>` (see `project::store_root`).pub fn agent_dir_for(project_root: &std::path::Path) -> PathBuf {- project_root.join(".jan").join("agent")+ crate::core::agent::project::store_root(project_root)}/// Render one `StreamEvent` for the terminal. Content tokens go to stdout so adiff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 8b250423b..ba28ac168 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -1916,7 +1916,8 @@ struct App {last_esc: Option<Instant>,/// User-message index chosen in the rewind picker, carried into the scope step.rewind_target: Option<usize>,- /// Project `.jan/agent` dir where this TUI's threads are saved/listed.+ /// The project's store (`~/.jan/projects/<slug>`) where this TUI's threads+ /// are saved/listed.agent_dir: std::path::PathBuf,/// OpenAI-shaped conversation history sent with each run.history: Vec<serde_json::Value>,@@ -9454,6 +9455,9 @@ pub async fn run((false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)".to_string(),};app.push_session_banner(!seeded);+ if let Some(note) = super::take_migration_notice() {+ app.note(¬e);+ }if let Some(note) = workspace_note {app.note(¬e);}@@ -11831,7 +11835,7 @@ impl SlashCatalog {/// One row of the slash-command popup: a built-in command, an installed/// plugin command (`<plugin>/commands/<name>.md`), or an installed project-/// skill (`.jan/agent/skills/<name>/SKILL.md`) offered by name so `/deploy`+/// skill (`<store>/skills/<name>/SKILL.md`) offered by name so `/deploy`/// behaves like a command the user can tab-complete and run.#[derive(Clone)]enum SlashMatch {@@ -12801,7 +12805,7 @@ struct AgentSettingDef {/// looking for a knob: they want the setting, not the file it lives in.#[derive(Clone, Copy, PartialEq, Eq)]enum SettingScope {- /// This project's `.jan/agent/agent.toml`, under `[agent]` unless the key+ /// This project's `agent.toml` (in its store), under `[agent]` unless the key/// names its own section.Project,/// The user-wide `~/.jan/config.toml`, at the document root.@@ -14250,7 +14254,7 @@ fn cancel_command(app: &mut App, arg: &str) {));}-/// `/plugin` handler: manage plugins installed under `.jan/agent/plugins/`.+/// `/plugin` handler: manage plugins installed under the project store's `plugins/`./// - `/plugin` or `/plugin list` — installed plugins + the skills they ship/// - `/plugin install <spec>` — git URL (optionally `#ref`) or a name/// from the configured `[plugins] marketplace`@@ -20368,7 +20372,7 @@ mod tests {/// App whose project has one installed skill `<name>/SKILL.md` with the/// given frontmatter description, so slash-popup and dispatch tests run- /// against a real `.jan/agent/skills/` tree. Returns the temp project+ /// against a real `<store>/skills/` tree. Returns the temp project/// root for cleanup.fn skill_test_app(name: &str, description: &str) -> (App, std::path::PathBuf) {skill_test_app_fm(name, description, "")@@ -20386,7 +20390,8 @@ mod tests {std::process::id(),uuid::Uuid::new_v4()));- let agent_dir = root.join(".jan/agent");+ std::fs::create_dir_all(&root).unwrap();+ let agent_dir = crate::core::agent::project::store_root(&root);std::fs::create_dir_all(agent_dir.join("skills").join(name)).unwrap();std::fs::write(agent_dir.join("skills").join(name).join("SKILL.md"),@@ -35505,6 +35510,7 @@ mod tests {project_root: root.to_path_buf(),scratch_root: None,mask_root: None,+ hidden_root: None,read_roots: Vec::new(),write_roots: Vec::new(),allow_network: false,@@ -36412,7 +36418,8 @@ mod tests {#[test]fn slash_popup_uses_startup_catalog_after_files_change() {let (mut app, root) = skill_test_app("deploy", "How to deploy.");- std::fs::remove_dir_all(root.join(".jan/agent/skills/deploy")).unwrap();+ let store = crate::core::agent::project::store_root(&root);+ std::fs::remove_dir_all(store.join("skills/deploy")).unwrap();app.input = "/dep".into();assert_eq!(names(&app), vec!["/deploy".to_string()]);@@ -36426,7 +36433,7 @@ mod tests {// Whitelist a different skill: deploy must vanish from the popup,// matching the user-side catalog semantics.std::fs::write(- root.join(".jan/agent/agent.toml"),+ crate::core::agent::project::store_root(&root).join("agent.toml"),"[agent]\n[skills]\nenabled = [\"other\"]\n",).unwrap();@@ -36502,8 +36509,8 @@ mod tests {/// A plugin with one folder skill under the app's project root.fn plugin_skill_in_app(root: &std::path::Path, plugin: &str, name: &str, description: &str) {- let dir = root- .join(".jan/agent/plugins")+ let dir = crate::core::agent::project::store_root(root)+ .join("plugins").join(plugin).join("skills").join(name);@@ -36517,8 +36524,8 @@ mod tests {/// A plugin with one command prompt template under the app's project root.fn plugin_command_in_app(root: &std::path::Path, plugin: &str, name: &str, content: &str) {- let dir = root- .join(".jan/agent/plugins")+ let dir = crate::core::agent::project::store_root(root)+ .join("plugins").join(plugin).join("commands");std::fs::create_dir_all(&dir).unwrap();@@ -36570,7 +36577,8 @@ mod tests {app.input = "/feature".into();assert!(names(&app).contains(&"/feature-dev".to_string()));- std::fs::remove_file(root.join(".jan/agent/plugins/feature-dev/commands/feature-dev.md"))+ let store = crate::core::agent::project::store_root(&root);+ std::fs::remove_file(store.join("plugins/feature-dev/commands/feature-dev.md")).unwrap();app.input = "/fea".into();app.reset_slash_hint();diff --git a/src-tauri/src/core/cli/worktree.rs b/src-tauri/src/core/cli/worktree.rsindex 991edbb53..6f632b1e9 100644--- a/src-tauri/src/core/cli/worktree.rs+++ b/src-tauri/src/core/cli/worktree.rs@@ -13,7 +13,7 @@//! is looking at, which must be their decision rather than ours.//!//! The checkout lives under `~/.jan/worktrees/<repo-slug>/<id>`, outside the-//! repository. Inside it (`<project>/.jan/agent/worktrees/...`) the agent's own+//! repository. Inside it (`<project>/worktrees/...`) the agent's own//! `find`/`grep`/`bash` would walk into a second copy of the tree whenever a//! session ran in the main checkout, and `git clean` would delete it.//!@@ -56,27 +56,11 @@ pub fn worktrees_root() -> Result<PathBuf, String> {Ok(crate::core::agent::global_config::global_jan_dir()?.join("worktrees"))}-/// FNV-1a, so the slug for a path is the same in every build. `DefaultHasher`-/// is explicitly not stable across Rust releases, and a session must find its-/// checkout again after a toolchain upgrade.-fn path_hash(path: &Path) -> String {- let mut hash: u64 = 0xcbf2_9ce4_8422_2325;- for byte in path.to_string_lossy().as_bytes() {- hash ^= u64::from(*byte);- hash = hash.wrapping_mul(0x0000_0100_0000_01b3);- }- format!("{hash:016x}")[..8].to_string()-}-/// Directory name for a repository: its own name plus a hash of its path, so two-/// checkouts of the same project do not share a worktree directory.+/// checkouts of the same project do not share a worktree directory. The same+/// slug keys the project's store under `~/.jan/projects`.pub fn repo_slug(repo: &Path) -> String {- let name = repo- .file_name()- .and_then(|n| n.to_str())- .filter(|n| !n.is_empty())- .unwrap_or("repo");- format!("{name}-{}", path_hash(repo))+ tauri_plugin_agent_tools::workspace::path_slug(repo)}/// Branch a session's worktree is checked out on. Namespaced under `jan/agent/`diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rsindex ab8425879..f3d9082c5 100644--- a/src-tauri/src/core/mcp/server/mod.rs+++ b/src-tauri/src/core/mcp/server/mod.rs@@ -89,7 +89,7 @@ pub struct ServeOptions {/// The one project root the served tools are confined to.pub project_root: PathBuf,/// Where `memory/` and `skills/` live; normally- /// `workspace::project_store(project_root)`.+ /// `project::store_root(project_root)`.pub store_root: PathBuf,/// The `[skills].enabled` whitelist; empty means every skill.pub enabled_skills: Vec<String>,@@ -104,10 +104,10 @@ pub struct ServeOptions {}impl ServeOptions {- /// Defaults for a project root: its co-located store, the read-only served+ /// Defaults for a project root: its store under `~/.jan/projects`, the read-only served/// set, sandbox on.pub fn new(project_root: PathBuf) -> Self {- let store_root = tauri_plugin_agent_tools::workspace::project_store(&project_root);+ let store_root = crate::core::agent::project::store_root(&project_root);Self {project_root,store_root,@@ -122,16 +122,21 @@ impl ServeOptions {/// The MCP server: Jan's built-in toolset behind a `ServerHandler`.///-/// Cheap to clone (one `Arc`), which is what the Streamable HTTP transport needs-/// -- it builds a fresh handler per session from a factory.+/// Cheap to clone (an `Arc` and one path), which is what the Streamable HTTP+/// transport needs -- it builds a fresh handler per session from a factory.#[derive(Debug, Clone)]pub struct JanToolServer {opts: Arc<ServeOptions>,+ /// The Jan home, refused to every served tool whether or not `bash` is+ /// sandboxed: a served client is a program, not a user at the terminal,+ /// and there is no one here to approve reaching keys or hooks.+ hidden_root: Option<std::path::PathBuf>,}impl JanToolServer {pub fn new(opts: ServeOptions) -> Self {Self {+ hidden_root: crate::core::agent::project::hidden_root(true),opts: Arc::new(opts),}}@@ -191,6 +196,7 @@ impl JanToolServer {).with_network(self.opts.allow_network).with_sandbox(self.opts.sandbox)+ .with_hidden_root(self.hidden_root.as_deref()).with_confined_writes(true);if let Some(scratch) = self.opts.scratch_root.as_deref() {ctx = ctx.with_scratch_root(scratch);@@ -229,9 +235,7 @@ impl JanToolServer {scratch: self.opts.scratch_root.as_deref(),read_roots: &[],write_roots: &[],- // The agent's own `.jan` state is never reachable as a path;- // memory and skills are served through their own tools.- hide_jan: true,+ hidden_root: self.hidden_root.as_deref(),},&Default::default(),&SessionGrants::default(),@@ -244,8 +248,8 @@ impl JanToolServer {Decision::HardDeny(DenyReason::Hidden) => {return (format!(- "ERROR: tool '{name}' was refused: the path is inside the agent's \- hidden .jan state. Use the memory_* and skill_* tools instead."+ "ERROR: tool '{name}' was refused: the Jan home (~/.jan) is hidden. \+ Use the memory_* and skill_* tools instead."),Vec::new(),)diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rsindex 478d675ed..68d936695 100644--- a/src-tauri/src/core/mcp/server/tests.rs+++ b/src-tauri/src/core/mcp/server/tests.rs@@ -206,6 +206,42 @@ async fn escaping_read_path_is_refused() {assert!(!content.contains("classified"));}+/// Served from the user's home, the Jan home sits inside the root. It is+/// refused even with the shell unsandboxed (as `options` sets it), because a+/// served client has no one to ask.+#[tokio::test]+async fn the_jan_home_is_refused_even_unsandboxed() {+ let Some(jan) = crate::core::agent::project::jan_home() else {+ return;+ };+ let home = jan.parent().expect("jan home has a parent").to_path_buf();+ std::fs::create_dir_all(jan.join("projects/home-1")).expect("mkdir");+ std::fs::write(jan.join("config.toml"), "api_key = \"classified\"").expect("write");+ std::fs::write(jan.join("projects/home-1/agent.toml"), "[tools]").expect("write");+ let mut opts = options(&home);+ opts.served.allow_write = true;+ let server = JanToolServer::new(opts);+ for (tool, args) in [+ ("read", serde_json::json!({ "path": jan.join("config.toml").to_string_lossy() })),+ ("grep", serde_json::json!({ "pattern": "classified", "path": jan.to_string_lossy() })),+ (+ "write",+ serde_json::json!({+ "path": jan.join("projects/home-1/agent.toml").to_string_lossy(),+ "content": "[tools]\nallow = [\"bash\"]"+ }),+ ),+ ] {+ let (content, _) = server.dispatch(tool, &args).await;+ assert!(content.contains("Jan home"), "{tool}: {content}");+ assert!(!content.contains("classified"), "{tool}: {content}");+ }+ assert_eq!(+ std::fs::read_to_string(jan.join("projects/home-1/agent.toml")).unwrap(),+ "[tools]"+ );+}+#[tokio::test]async fn escaping_write_path_is_refused_even_when_write_is_served() {let dir = tempfile::tempdir().expect("tempdir");@@ -225,19 +261,6 @@ async fn escaping_write_path_is_refused_even_when_write_is_served() {assert!(!target.exists());}-#[tokio::test]-async fn hidden_jan_state_is_refused() {- let dir = tempfile::tempdir().expect("tempdir");- std::fs::create_dir_all(dir.path().join(".jan/agent")).expect("mkdir");- std::fs::write(dir.path().join(".jan/agent/agent.toml"), "x = 1").expect("write fixture");- let server = JanToolServer::new(options(dir.path()));- let (content, _) = server- .dispatch("read", &serde_json::json!({ "path": ".jan/agent/agent.toml" }))- .await;- assert!(content.starts_with("ERROR"), "{content}");- assert!(content.contains("hidden .jan state"), "{content}");-}-#[tokio::test]async fn in_project_write_runs_once_opted_in() {let dir = tempfile::tempdir().expect("tempdir");diff --git a/web-app/src/hooks/useSkills.ts b/web-app/src/hooks/useSkills.tsindex 4ab77fd63..84754a827 100644--- a/web-app/src/hooks/useSkills.ts+++ b/web-app/src/hooks/useSkills.ts@@ -53,8 +53,8 @@ const useSkillsVersion = create<{ v: number; bump: () => void }>((set) => ({/*** CRUD over the agent's skills. The permanent store in the Jan data folder is* always listed -- it is what the Cowork agent's `skill_*` tools read by- * default -- and with a `folder` its co-located store- * (`<folder>/.jan/agent/skills`) layers on top, a project skill shadowing a+ * default -- and with a `folder` its project store+ * (`~/.jan/projects/<slug>/skills`) layers on top, a project skill shadowing a* same-named global one (#8879). Each returned skill carries its `origin` so* `read`/`write`/`remove` target the store it lives in; a brand-new skill lands* in the folder's store when one is attached, else the permanent store. Thediff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 24c95f59e..d1004db70 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -265,7 +265,7 @@ export async function executeAgentTool(* folder). Off by default, so chat's attachment stays read-only. */projectWritable = false,/**- * A project folder whose co-located skills (`<folder>/.jan/agent/skills`)+ * A project folder whose project-store skills (`~/.jan/projects/<slug>/skills`)* layer on top of the permanent store for `skill_list`/`skill_read`, so an* attached folder's skills reach the agent alongside the global ones (#8879).* Cowork passes its attached folder; chat leaves it unset, keeping its skillsdiff --git a/web-app/src/lib/skillStore.ts b/web-app/src/lib/skillStore.tsindex 5dbca1cf5..1c4190f13 100644--- a/web-app/src/lib/skillStore.ts+++ b/web-app/src/lib/skillStore.ts@@ -20,7 +20,7 @@ export type { SkillMeta }** - `store` -- the desktop's permanent store in the Jan data folder, managed* from Settings. Reached through the plugin's guest-js.- * - `project` -- a project's co-located `<folder>/.jan/agent`, managed from the+ * - `project` -- the folder's project store `~/.jan/projects/<slug>`, managed from the* code screen.** The project scope deliberately keeps using the core `agent_skill_*` commands