Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent)!: agent-managed memory with a bounded, cache-stable index (#9497)
Akarshan Biswasc15a946f55be
diff --git a/docs/src/pages/docs/agent/adk-runtime.mdx b/docs/src/pages/docs/agent/adk-runtime.mdxindex 903c1eddd..b44ebb113 100644--- a/docs/src/pages/docs/agent/adk-runtime.mdx+++ b/docs/src/pages/docs/agent/adk-runtime.mdx@@ -20,8 +20,8 @@ conversations, a Stop button, tool approval, or recovery from a failure.- Wait for a turn to finish before starting another. One runtime runs one active turn at a time.- Use `ephemeral: true` / `ephemeral=True` when the conversation should not be saved. Its answersare also kept out of automatic memory recall, so one session's answers never reach a later- session in the same `cwd`. [Memory notes](/docs/agent/memory) written with `memory_write` in- other sessions are still listed in its prompt.+ session in the same `cwd`. [Memory notes](/docs/agent/memory) written with the `memory` tool+ in other sessions are still listed in its prompt.Always arrange cleanup, including on errors. In JavaScript, put `await runtime.close()` in a`finally` block. In Python, use `with JanRuntime.start() as runtime:`. Thediff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex f7ce4ed19..bc9b694c4 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -479,7 +479,7 @@ The `initialize` result carries the same `input_content_parts` object `init` doeThe `item/*` payload contains the existing `StreamEvent` object unchanged. A client can also call `session/list`, `session/resume`, `session/fork`, `session/archive`, `turn/steer`, `turn/interrupt` and `permission/respond {requestId,decision}`. Session ids address this **process**, not another RPC process. `turn/interrupt` closes the turn with one `turn/completed` carrying `stopReason: "interrupted"`, and puts that record on the wire before it answers the request. A client that closes stdin ends the process, and the turn that is still running is closed with `stopReason: "interrupted"` before it exits. An outstanding permission request is never granted - closing the channel is not an approval, and the gate's fallback for a request that is dropped without an answer is denial. Only one turn is active per process; a second `turn/start` returns `-32001` with `data.retryable: true` rather than silently queueing it, and so does a `turn/start` arriving while the output queue has no room left for the terminal record - the turn is refused instead of accepted and then lost. `turn/completed.stopReason` is the turn's outcome (`completed`, `error`, `interrupted`), not the upstream finish reason: that one is the `stop_reason` inside `item/done`. Transport errors (`-32700` malformed JSON, `-32600` invalid request, `-32601` unknown method, `-32602` bad params) differ from an agent failure reported by `turn/completed` with `stopReason: "error"`.-Input frames are capped at 16 MiB and the writer queue holds at most 1025 records. If a client stops reading, the queue stops growing and the turn ends with a terminal overload outcome rather than the run accumulating deltas without bound; the process stays alive while the writer is blocked on the full stdout pipe, and that outcome is delivered as soon as the client reads again. The server exits when stdin closes, or when a later record finds the client gone. `--max-turns` is a one-shot flag rather than a session setting: an RPC turn runs until it finishes or a client sends `turn/interrupt`. `ephemeral: true` skips thread persistence and automatic memory recall: the session neither indexes its answers nor has earlier answers recalled into its prompt. Memory notes written with `memory_write` still apply. Host tools are declared on `session/start` (`tools`, `builtins`) and answered with `tool/respond`; see [Protocol](./protocol#rpc-host-tools). The `schema` command below documents the older `stream-json` channel, while `rpc-schema` describes this RPC envelope, accepted requests and event types. RPC clients use `turn/completed`, not the process exit code, to classify an individual turn.+Input frames are capped at 16 MiB and the writer queue holds at most 1025 records. If a client stops reading, the queue stops growing and the turn ends with a terminal overload outcome rather than the run accumulating deltas without bound; the process stays alive while the writer is blocked on the full stdout pipe, and that outcome is delivered as soon as the client reads again. The server exits when stdin closes, or when a later record finds the client gone. `--max-turns` is a one-shot flag rather than a session setting: an RPC turn runs until it finishes or a client sends `turn/interrupt`. `ephemeral: true` skips thread persistence and automatic memory recall: the session neither indexes its answers nor has earlier answers recalled into its prompt. Memory notes written with the `memory` tool still apply. Host tools are declared on `session/start` (`tools`, `builtins`) and answered with `tool/respond`; see [Protocol](./protocol#rpc-host-tools). The `schema` command below documents the older `stream-json` channel, while `rpc-schema` describes this RPC envelope, accepted requests and event types. RPC clients use `turn/completed`, not the process exit code, to classify an individual turn.### `schema`diff --git a/docs/src/pages/docs/agent/hooks.mdx b/docs/src/pages/docs/agent/hooks.mdxindex 1554761b4..e4c60c152 100644--- a/docs/src/pages/docs/agent/hooks.mdx+++ b/docs/src/pages/docs/agent/hooks.mdx@@ -107,8 +107,8 @@ command = "logger -t jan 'agent session finished'"| `timeout_secs` | Seconds before the hook is killed. Defaults to 60 |`matcher` is only consulted for the two tool events - a session-lifecycle hook has no tool name to-match and always fires. It is an ordinary glob, so `*write*` catches `write`, `memory_write` and-`skill_write`, while `edit` catches only `edit`. An invalid glob is dropped at load with a notice+match and always fires. It is an ordinary glob, so `*write*` catches `write` and `skill_write`,+while `edit` catches only `edit`. An invalid glob is dropped at load with a noticerather than kept: a pattern that cannot parse can only ever answer "no", which reads exactly like ahook written for a tool that was never called.@@ -142,6 +142,11 @@ for `bash` no longer matches it; change it to `shell`. A `bash` matcher is reporCLI when a run starts, and by the desktop app under each shell call. A script's `tool_name` checkcannot be detected, so search your hooks for it.+The memory tools `memory_write`, `memory_read` and `memory_list` are now one tool, `memory`. A+matcher that names an old one (or a glob such as `memory_*`) still applies, to every `memory` op, and+is reported the same way; rename it to `memory`. So does a broader glob that used to catch one, such+as `*write*`: it keeps guarding `memory` (every op) and is reported. A script that tests `tool_name` for an old name needs the same change.+## The answerWhatever the command writes to stdout, up to 64KB.diff --git a/docs/src/pages/docs/agent/memory.mdx b/docs/src/pages/docs/agent/memory.mdxindex 71e01998e..856969af4 100644--- a/docs/src/pages/docs/agent/memory.mdx+++ b/docs/src/pages/docs/agent/memory.mdx@@ -1,7 +1,7 @@---title: Memory-description: Durable facts the agent keeps about your project, stored as files you can read and edit.-keywords: [Jan, Jan Agent, memory, durable facts, project memory, recall]+description: Durable facts the agent keeps and curates about your project, stored as files you can read and edit.+keywords: [Jan, Jan Agent, memory, durable facts, project memory, recall, memory tidy, auto-tidy]---import { Callout } from 'nextra/components'@@ -23,15 +23,27 @@ The agent writes memory itself when it learns something durable, and reads it baprompt on later runs. It's scoped per project, with a separate user scope for notes that applyeverywhere (see [Scopes](#scopes)).-Three tools drive it, and only the write prompts for approval:+One `memory` tool drives it, with an `op`. Memory belongs to the agent, so no op asks for+approval, in the TUI, headless runs or ACP:-| Tool | Approval |-| --- | --- |-| `memory_list` | No |-| `memory_read` | No |-| `memory_write` | Yes |+| `op` | Arguments | What it does |+| --- | --- | --- |+| `view` | `name`? | No name: the full index. A folder (`tui/`): its notes. A note: its content. If a note and a folder share a name, `tui` is the note and `tui/` the folder |+| `search` | `query` | Keyword search over titles and bodies, archived notes included |+| `write` | `name`, `title`, `content` | Create or overwrite; the title is the note's first line |+| `edit` | `name`, `old`, `new` | Replace one exact, unique piece of text |+| `delete` | `name` | Remove the note and its index line |+| `move` | `name`, `to` | Rename a note or move it into (or out of) a folder in one step; content, front matter and recency are kept. Fails if `to` exists |++A `deny = ["memory"]` entry in `agent.toml` turns the tool off.++`view` and `search` calls in one turn run in parallel. Changes (`write`, `edit`, `delete`, `move`)+to one store apply one at a time, whoever makes them (the agent, a tidy, the desktop app), so two+edits of the same note never lose one: the second sees the first's result, and an `edit` whose text+is gone by then fails with `not found` instead of overwriting.-Because writes prompt, nothing enters memory without you seeing it.+Memory belongs to the main agent only. [Subagents](/docs/agent/subagents#isolation) get no `memory`+tool and no memory index, so the main agent passes them any remembered fact they need in the task.## Where it lives@@ -44,13 +56,61 @@ delete them. Nothing is hidden in an opaque store.|-- 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+ `-- memory/+ |-- <name>.md # this project's notes+ |-- <folder>/<name>.md # grouped notes, one folder level+ `-- .meta.json # last read / last written times (drives index order)+```++A note's first line is its **title**, the only part of it the index shows. A note may open with+front matter; `status: done` there **archives** it:++```markdown+---+status: done+---+PR 9102 merged: subagent steering+...```-Each `MEMORY.md` is generated: it is rebuilt on every `memory_write` and delete, so don't edit it by+An archived note stays readable and searchable but is never listed, which is how finished work+(merged PRs, closed issues, past reviews) leaves the prompt without being lost.++Because the index is built for you, `index` and `MEMORY` are reserved note names (in any folder, any+case): a new note named like that is refused.++Each `MEMORY.md` is generated: it is rebuilt on every write, edit and delete, so don't edit it byhand - your changes would be overwritten. See [Project Config](/docs/agent/project-config) for how`<slug>` is chosen.+Notes written by an older Jan are migrated once, the first time a session starts on the store: a+note whose first line starts with `DONE` or `OBSOLETE` is archived, recency is seeded from file+times, and nothing is renamed or deleted.++## The index in the prompt++The system prompt's **Available Memories** block is the index, titles only, and it is capped at+about **1,500 tokens** however many notes a project has:++1. This project's notes, most recently used first. A folder takes one line (`tui/ (18 notes)`).+2. Your user notes, then one pointer per other project with memory.+3. Whatever does not fit becomes a single line: `+N more ... memory view lists everything`.++The agent opens a note (or a folder) by name with `view`, so the index only has to say what exists.+When a write leaves the index near its budget, the tool result says so, which is the agent's cue to+archive or merge.++The index is a **snapshot taken when the session starts**. Writing, editing or deleting a note+mid-session never changes the system prompt, so the cached prompt prefix survives memory updates.+Changes made since the snapshot, by the agent or by a tidy, are listed in a short+`Memory changes this session: + new, ~ changed, - deleted` block after the conversation instead+(a `move` shows as `- old` plus `+ new`).+The block is sent with the first request of every run and again after any successful `memory` call+that changed it, so a note written mid-run (in a headless `jan cli agent run` too, including+follow-ups sent with `--input-format stream-json`) reaches the model's next request. The+snapshot is retaken on `/new`, `/clear`, `/resume`, and after a compaction. A fork continues its+source session, so it keeps the source's snapshot.+## ScopesMemory names are scoped:@@ -62,9 +122,12 @@ Memory names are scoped:| `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+`view` accepts all four. Writing, editing or deleting in another project is refused, so a session can onlychange its own project's notes and your user notes.+In [plan mode](/docs/agent/run-modes#plan-mode) memory is read-only: `view` and `search` work, and+`write`, `edit`, `move` and `delete` are refused.+The system prompt's **Available Memories** block lists this project's notes, your user notes, andpointers to other projects that have memory, which the agent opens with `project:<slug>` only whenrelevant. To keep other projects out of the prompt and refuse `project:` reads, set this in@@ -88,8 +151,43 @@ vice versa.Memory works when it's small and specific. A note that restates what any reader would see from theREADME 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 - they-are just files.+The tool tells the agent to reconcile rather than append: search for an existing note before+writing, update it instead of adding a near-duplicate, delete a note a newer fact supersedes, and+archive finished work. If the agent has stored something wrong, tell it, or delete the file yourself -+they are just files.++## Tidying++A tidy is a cheap subagent (on the [`smol` model](/docs/agent/subagents#choosing-a-subagents-model))+that reads the notes in its own context and is deliberately conservative: it archives only notes whose+own content says the work is finished (merged, released, closed, obsolete), merges only clear+duplicates, deletes only notes a newer one supersedes, groups notes with `move`, never writes index+or overview notes, and leaves a note alone when unsure. It reports what it changed as one line in the console, for example+`memory tidied: archived pr-9102; merged tui-scroll into tui/scroll` (with more than three changes,+counts instead: `memory tidied: archived 12, moved 5`; the full list is in the tidy's subagent row). The main conversation never+loads the notes, and the tidy never asks for permission. It is the only subagent with memory.++- **At most 30 changes per tidy.** The tidy's `memory` tool refuses any write, edit, delete or move+ past the 30th, so a tidy that misjudges the store can only misjudge that many notes. When the cap is+ hit the console note says `cap reached (30 changes)`; run `/memory tidy` again to continue.+- **No lost edits.** A tidy works in the background while you and the agent keep going. Its `memory`+ tool refuses to overwrite, move or delete a note that changed since the tidy last viewed it, so+ it must read the note again first and an edit made meanwhile is never overwritten.+- **`/memory tidy`** runs one now. Bare `/memory` shows the index size against its budget.+- **Auto-tidy** runs one in the background when the index no longer fits its budget. It is checked+ each time a turn finishes (cheaply: the index is only rebuilt when a note changed), so a store that+ outgrows its budget mid-session is tidied at that turn's end. It runs at most once per session+ (`/new`, `/clear` and `/resume` start a new session; a fork does not), so a store a tidy cannot+ shrink is never retried in a loop. It never blocks your turn,+ never starts a model turn of its own, and never rewrites this session's prompt: what it changed+ shows up in the memory-changes block. An automatic tidy that changed nothing stays silent.++Auto-tidy is on by default. To turn it off, use `/settings` (`memory_auto_tidy`) or set this in+`~/.jan/config.toml`; `/memory tidy` keeps working either way:++```toml+memory_auto_tidy = false # default: true+```## Memory and AGENTS.mddiff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdxindex 7a21628f7..3c2a46c78 100644--- a/docs/src/pages/docs/agent/permissions.mdx+++ b/docs/src/pages/docs/agent/permissions.mdx@@ -32,10 +32,15 @@ Every tool maps to one capability, and approval applies at that level rather tha| Capability | Tools | Default || --- | --- | --- |-| Read | `read`, `ls`, `find`, `grep`, `web_search`, `web_fetch`, `memory_read`, `memory_list`, `skill_read`, `skill_list` | Allowed |-| Write | `write`, `edit`, `memory_write`, `skill_write` | Prompts |+| Read | `read`, `ls`, `find`, `grep`, `web_search`, `web_fetch`, `skill_read`, `skill_list` | Allowed |+| Write | `write`, `edit` | Prompts || Exec | `shell` | Prompts |+The agent's own stores never prompt: every `memory` op (view, search, write, edit, move, delete) and+`skill_write` act only on the agent's notes and skills by name, never on a project file, so they are+allowed without asking. A `deny` entry in `agent.toml` still removes them, and in plan mode only+`view` and `search` run. See [Memory](/docs/agent/memory).+So approving `a` on a shell command allows further shell commands, not just that one. That's thetrade for not being asked twenty times during a test loop - and the reason to prefer `y` when youonly meant one.@@ -89,6 +94,12 @@ each such `[tools]` entry when a run starts (the desktop app does not read `[toosurface refuses a subagent whose `allowed_tools` still says `bash`. `jan mcp serve --tool bash`says so too.+The memory tools `memory_write`, `memory_read` and `memory_list` are now one tool, `memory`. An old+name in `allow`, `deny` or a hook matcher keeps applying, to the whole `memory` tool: a+`deny = ["memory_write"]` now denies every memory op, reads included. The same holds for a broader+glob that used to catch an old name: `deny = ["*write*"]` still denies `memory`. The `jan` CLI+reports each such entry when a run starts; rename an old name to `memory`.+## The shell sandboxJan can run shell commands under OS confinement - bubblewrap on Linux, Seatbelt on macOS,diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdxindex c85176f46..df63651bd 100644--- a/docs/src/pages/docs/agent/project-config.mdx+++ b/docs/src/pages/docs/agent/project-config.mdx@@ -249,7 +249,7 @@ prefix_allow = ["assistant_instructions", "guidelines", "skills", "tool_schemas"| Key | Default | Description || --- | --- | --- || `prefix_allow` | unset | Contributor ids allowed above the cache line. Unset keeps the placement each contributor declares in code; setting it narrows the prefix to exactly the ids listed. An id that names nothing is an error, not a silent no-op |-| `default` | `"tail"` | Placement for a contributor neither the list nor the code classifies. A contributor that varies within a session stays in the tail whatever this says, and listing one (`memory_recall`, `plan_addendum`, `todo_addendum`) in `prefix_allow` fails the run instead of costing a cache miss per turn |+| `default` | `"tail"` | Placement for a contributor neither the list nor the code classifies. A contributor that varies within a session stays in the tail whatever this says, and listing one (`memory_changes`, `memory_recall`, `plan_addendum`, `todo_addendum`) in `prefix_allow` fails the run instead of costing a cache miss per turn |All current contributors either declare their placement or vary, so changing `default` alone hasno effect today. Use `prefix_allow` to narrow the current prefix. The tool schemas are a request@@ -261,7 +261,7 @@ jan cli agent status # the resolved placement of every contributor, and whyContributor ids: `assistant_instructions`, `guidelines`, `working_directory`, `runtime_environment`,`session_start`, `subagent_guide`, `skill_guide`, `web_tools_guide`, `project_context`, `skills`,-`memory_catalog`, `tool_schemas`, `memory_recall`, `plan_addendum`, `todo_addendum`.+`memory_catalog`, `tool_schemas`, `memory_changes`, `memory_recall`, `plan_addendum`, `todo_addendum`.`session_start` is the date and git branch taken once when the session starts ("Session start date","Starting branch"); it stays fixed for the session so it can sit above the cache line. See[Context and Compaction](/docs/agent/context) for what the split buys.diff --git a/docs/src/pages/docs/agent/run-modes.mdx b/docs/src/pages/docs/agent/run-modes.mdxindex b4e5b742b..b5066dbd5 100644--- a/docs/src/pages/docs/agent/run-modes.mdx+++ b/docs/src/pages/docs/agent/run-modes.mdx@@ -61,7 +61,10 @@ the prompt, so it is denied and the run stalls on its first write.## Plan mode-Read-only. The agent investigates and proposes, but every write and command is blocked.+Read-only. The agent investigates and proposes, but every write and command is blocked. That+includes memory: the agent can `view` and `search` its notes, but writing, editing, moving or+deleting one is refused until you leave plan mode, an automatic memory tidy waits, and+`/memory tidy` is refused too. A tidy already running when you enter plan mode is stopped.```bashjan --plandiff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdxindex 3413dbb99..853dc6c63 100644--- a/docs/src/pages/docs/agent/slash-commands.mdx+++ b/docs/src/pages/docs/agent/slash-commands.mdx@@ -52,6 +52,7 @@ See [Sessions](/docs/agent/sessions).| `/plan [exit\|text]` | Enter read-only plan mode, optionally with a first message || `/todo [add [phase\|] text \| clear]` | Open the todo editor, append an item, or drop all || `/compact` | Summarize older turns to free up context |+| `/memory [tidy]` | Bare: the memory index size against its prompt budget. `tidy`: archive finished work, merge duplicates and delete stale notes in a background subagent, then report what changed (see [Memory](/docs/agent/memory#tidying)) || `/context` | Show what is filling the context window, by category. Opens a readout docked above the input, live while the turn keeps running; Esc or `q` closes it || `/usage [session\|run\|account\|daily\|requests\|limits\|<execution-id>]` | Bare: an overview of both answers -- this session's estimate over your account's recorded spend, each labelled with its source and never added together. The session half draws immediately; the account half fills in when the read lands, or says why it could not. `session` shows the local estimate alone: total tokens and estimated cost, then the costliest models behind it, priced from what the provider publishes (a model it publishes no price for is listed as such rather than counted as free); `m` expands the model list past the top few. The other views read what the provider actually recorded, each leading with the figure it was opened for -- account spend, the newest day, whether spending is allowed -- with breakdowns folded behind the same `m`. Reported amounts print exactly as the provider sent them, so they never read as a local estimate. Same docked readout as `/context`, and only one is open at a time; the input field is inactive while it is up || `/cancel [N]` | Cancel queued messages. Bare: all, or an index |diff --git a/docs/src/pages/docs/agent/subagents.mdx b/docs/src/pages/docs/agent/subagents.mdxindex 9eced846f..1abdf4371 100644--- a/docs/src/pages/docs/agent/subagents.mdx+++ b/docs/src/pages/docs/agent/subagents.mdx@@ -152,6 +152,11 @@ Subagents also cannot:- dispatch subagents of their own (no recursion)- read or change the main agent's todo list- ask you an interactive question+- use [memory](/docs/agent/memory): they get no `memory` tool and no memory index in their prompt++Memory stays with the main agent. When a subagent needs something the main agent remembers, the main+agent puts that fact in the task, and it records anything worth keeping from the subagent's answer+itself. That keeps one curator for memory instead of several writers it never sees.They *can* request permission for a write or a command. Those prompts surface in your console,labelled with which subagent asked.@@ -284,6 +289,10 @@ A subagent gets the session's full toolset unless something narrows it, and it iEither way it can only ever reach a subset of what the parent could reach, so delegation cannot beused to escape your project's [tool policy](/docs/agent/permissions#project-policy).+`memory` is never a tool a subagent can be given: it is left out of the `allowed_tools` choices, and a+definition or dispatch that names it still gets a subagent without it. The only subagent with memory+is Jan's own [tidy](/docs/agent/memory#tidying) run, which cannot be dispatched by the agent.+One exception: `skill_list` and `skill_read` are always available to a subagent, whatever itsallowlist says. Skills are how a subagent executes its procedure, and plugin `agents/*.md` filesnever list them, so a narrowed toolset keeps the read side - a subagent can always load the skillsdiff --git a/docs/src/pages/docs/desktop/cowork.mdx b/docs/src/pages/docs/desktop/cowork.mdxindex 8666759af..e87bf0dc0 100644--- a/docs/src/pages/docs/desktop/cowork.mdx+++ b/docs/src/pages/docs/desktop/cowork.mdx@@ -107,7 +107,8 @@ Use **Plan** first if you want to review the proposed work before allowing editsClick **Plan** beside the message input, or type `/plan`, to ask Jan to planbefore making changes. In Plan mode, Jan can read files, search, and research,-but cannot edit files or run shell commands.+but cannot edit files or run shell commands. It can read its memory but not+change it.Review the proposed steps and answer any questions. When Jan offers a plan,you can choose:diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex a263f6431..f635172f0 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2646,6 +2646,16 @@ dependencies = ["autocfg",]+[[package]]+name = "fs4"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5"+dependencies = [+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "fs_extra"version = "1.3.0"@@ -7970,6 +7980,7 @@ dependencies = ["base64 0.22.1","block2","cairo-rs",+ "fs4","gio","glib 0.18.5","glob",diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lockindex ec40a6216..0a62e8ea9 100644--- a/src-tauri/jan-cli/Cargo.lock+++ b/src-tauri/jan-cli/Cargo.lock@@ -1851,6 +1851,16 @@ dependencies = ["percent-encoding",]+[[package]]+name = "fs4"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5"+dependencies = [+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "fs_extra"version = "1.3.0"@@ -5349,6 +5359,7 @@ name = "tauri-plugin-agent-tools"version = "0.8.3"dependencies = ["base64 0.22.1",+ "fs4","glob","ignore","nix 0.30.1",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex 499f50ee9..f56eca83f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -45,6 +45,9 @@ tauri = [[dependencies]base64 = "0.22"+# Advisory file locks (flock / LockFileEx) that serialize memory store changes+# across processes: the desktop app and the jan CLI share one store.+fs4 = "1"# Pure Rust, no GUI linkage; used by the webview screenshot path and harmless in# the CLI graph.png = "0.17"diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 5a0bb35a7..3bcdf389e 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -78,19 +78,17 @@ pub struct ToolResult {pub images: Vec<ImageContentPart>,}-/// `content` plus, on a shell call, a line per hook matcher that still names-/// the shell's old name. The CLI reports hook load notices once at run start;-/// this surface has no run around a call, so they ride on the shell call-/// itself -- exactly the call the stale hook no longer guards.-fn with_renamed_shell_notices(+/// `content` plus a line per hook matcher that still names `tool` by an old+/// name (`bash`, `memory_write`, ...). The CLI reports hook load notices once+/// at run start; this surface has no run around a call, so they ride on the+/// call of the tool the stale matcher meant.+fn with_renamed_tool_notices(tool: &str,mut content: String,hooks: &crate::tools::hooks::HookSet,) -> String {- if tool == crate::tools::SHELL_TOOL {- for notice in hooks.renamed_shell_notices() {- content.push_str(&format!("\n[hook config: {notice}]"));- }+ for notice in hooks.renamed_notices(tool) {+ content.push_str(&format!("\n[hook config: {notice}]"));}content}@@ -301,14 +299,12 @@ pub async fn memory_write(content: String,) -> Result<(), AgentToolsError> {let data_folder = workspace::host_data_folder(&data_folder);- memory::write(- &resolve_store(&data_folder, project.as_deref()),- &name,- &content,- )- .await- .map(|_| ())- .map_err(Into::into)+ let store = resolve_store(&data_folder, project.as_deref());+ let _lock = memory::lock_changes(&store).await;+ memory::write(&store, &name, &content)+ .await+ .map(|_| ())+ .map_err(Into::into)}/// Name + summary + mtime for every memory note, name-sorted. This is the@@ -336,9 +332,9 @@ pub async fn memory_delete(name: String,) -> Result<(), AgentToolsError> {let data_folder = workspace::host_data_folder(&data_folder);- memory::delete(&resolve_store(&data_folder, project.as_deref()), &name)- .await- .map_err(Into::into)+ let store = resolve_store(&data_folder, project.as_deref());+ let _lock = memory::lock_changes(&store).await;+ memory::delete(&store, &name).await.map_err(Into::into)}/// OpenAI-shaped function schemas for every built-in tool. The frontend picks@@ -1047,7 +1043,7 @@ async fn execute_tool_inner(ctx = ctx.with_output_sink(sink);}let (content, diff, images) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;- let content = with_renamed_shell_notices(tool.name, content, &hooks);+ let content = with_renamed_tool_notices(tool.name, content, &hooks);let is_error = handlers::tool_result_failed(tool, &content);Ok(ToolResult {content,@@ -1542,12 +1538,32 @@ mod tests {}],Path::new("config.toml"),);- let out = with_renamed_shell_notices("shell", "ok\n[exit 0]".into(), &hooks);+ let out = with_renamed_tool_notices("shell", "ok\n[exit 0]".into(), &hooks);assert!(out.starts_with("ok\n[exit 0]\n[hook config: "), "{out}");assert!(out.contains("now `shell`"), "{out}");- assert_eq!(with_renamed_shell_notices("read", "x".into(), &hooks), "x");+ assert_eq!(with_renamed_tool_notices("read", "x".into(), &hooks), "x");+ assert_eq!(with_renamed_tool_notices("memory", "x".into(), &hooks), "x");let none = crate::tools::hooks::HookSet::new();- assert_eq!(with_renamed_shell_notices("shell", "x".into(), &none), "x");+ assert_eq!(with_renamed_tool_notices("shell", "x".into(), &none), "x");+ }++ /// The same for a matcher on an old memory tool name, under memory calls.+ #[test]+ fn an_old_memory_hook_matcher_is_reported_under_memory_calls() {+ let mut hooks = crate::tools::hooks::HookSet::new();+ hooks.extend_from(+ vec![crate::tools::hooks::HookEntry {+ event: "PreToolUse".into(),+ matcher: Some("memory_read".into()),+ command: "guard".into(),+ timeout_secs: None,+ }],+ Path::new("config.toml"),+ );+ let out = with_renamed_tool_notices("memory", "Drift".into(), &hooks);+ assert!(out.starts_with("Drift\n[hook config: "), "{out}");+ assert!(out.contains("`memory_read`"), "{out}");+ assert_eq!(with_renamed_tool_notices("shell", "x".into(), &hooks), "x");}/// The network flag has to survive the whole IPC -> ToolContext -> jail path.@@ -1726,8 +1742,8 @@ mod tests {df.clone(),T1.into(),None,- "memory_write".into(),- json!({"name": "prefs", "content": "user likes tabs"}),+ "memory".into(),+ json!({"op": "write", "name": "prefs", "content": "user likes tabs"}),None,None,None,@@ -1748,8 +1764,8 @@ mod tests {df.clone(),T2.into(),None,- "memory_read".into(),- json!({"name": "prefs"}),+ "memory".into(),+ json!({"op": "view", "name": "prefs"}),None,None,None,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 1f14aac68..5b2f63073 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@@ -54,6 +54,10 @@ skill folders are followed. Run `jan cli agent status --project .` to scaffoldthe 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.+Memory is curated by the agent with one `memory` tool (view/search/write/edit/delete/move; no prompts).+The in-prompt index is capped at ~1,500 tokens; `status: done` front matter archives a note.+`/memory tidy` tidies it in a background subagent (at most 30 changes per tidy), and `memory_auto_tidy = false` in `config.toml`+turns off the automatic tidy that runs once a session when the index is over budget.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 4bad107e1..0e4c23f71 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs@@ -1,5 +1,5 @@-//! Long-term agent memory: `<name>.md` notes under `<store_root>/memory/`,-//! indexed by a generated `<store_root>/MEMORY.md`.+//! Long-term agent memory: Markdown notes under `<store_root>/memory/`, owned+//! and curated by the agent, and 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,@@ -8,95 +8,285 @@//! 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.+//! A note is `memory/<name>.md`, and a name may carry one folder level+//! (`tui/scroll` is `memory/tui/scroll.md`), so related notes collapse to one+//! index line. A note may open with front matter (`---` ... `---`); its first+//! body line is the title the index shows. `status: done` in the front matter+//! archives a note: it stays readable and searchable but is never listed.//!-//! 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-//! unrelated to the vector-db recall index, which is keyed by project and-//! populated by a separate indexing path.+//! The index is a pointer chain, titles only, under a fixed token budget+//! ([`INDEX_BUDGET_TOKENS`]): root user notes and project pointers first, then+//! this project's notes by most recent use, folders collapsed to one line, and+//! a single overflow line for whatever does not fit. Recency lives in a side+//! file (`memory/.meta.json`), so reading a note never touches its mtime.+//!+//! [`Scopes`] resolves the names the `memory` tool accepts: `note` or+//! `folder/note` (this project), `user:note`, and, read-only, `project:<slug>`+//! / `project:<slug>/note` for another project.//!//! Error strings carry the `ERROR:` prefix the tool protocol expects; the//! command layer strips it for display.+use std::collections::{BTreeMap, HashMap};use std::path::{Path, PathBuf};-use crate::workspace::{project_meta, projects_dir, store_dir, workspace_filename};+use crate::workspace::{is_windows_device_name, project_meta, projects_dir, store_dir};const KIND: &str = "memory";/// The generated index at the top of every store.pub const INDEX_FILE: &str = "MEMORY.md";+/// Last-read / last-written times per note, kept beside the notes so a read+/// never rewrites a note's mtime.+const META_FILE: &str = ".meta.json";++/// Marks a store whose notes were brought to the titled format, so the+/// migration runs once.+const MIGRATED_FILE: &str = ".migrated";++/// Lock files that serialize a store's changes and its side file updates+/// across processes; see [`lock_changes`] and [`update_meta`].+const CHANGE_LOCK_FILE: &str = ".lock";+const META_LOCK_FILE: &str = ".meta.lock";+const USER_PREFIX: &str = "user:";const PROJECT_PREFIX: &str = "project:";+/// The token budget for the whole in-prompt memory section.+pub const INDEX_BUDGET_TOKENS: usize = 1_500;++/// Chars per token for budgeting. Conservative for English Markdown, so the+/// real token count lands under the budget rather than over it.+const CHARS_PER_TOKEN: usize = 4;++/// The share of the budget past which `write` warns that the index is filling.+const NEAR_BUDGET_PERCENT: usize = 85;++/// Longest title the index shows; a longer first line is cut.+const MAX_TITLE_CHARS: usize = 100;++/// Most lines a `search` returns.+const MAX_SEARCH_HITS: usize = 30;+/// `<store_root>/memory`.pub fn memory_dir(store_root: &Path) -> PathBuf {store_dir(store_root, KIND)}+/// Validate a note name and return its path relative to `memory/`. One+/// optional folder level; each part non-empty, with no traversal, separators+/// beyond the one `/`, or leading dot (which would hide it from listings).+///+/// The same rules hold on every OS, so a name accepted on one works on all and+/// the Windows ones are testable anywhere: no `:` (a drive prefix such as+/// `C:/x` makes `join` leave the store, and `note:s` names an NTFS stream), no+/// NUL, no device name (`nul`, `com1`), and the result must be plain relative+/// components only.+fn note_relpath(name: &str) -> Result<PathBuf, String> {+ let trimmed = name.trim();+ let stem = trimmed.strip_suffix(".md").unwrap_or(trimmed);+ let parts: Vec<&str> = stem.split('/').collect();+ let valid = |part: &str| {+ !part.is_empty()+ && !part.contains(['\\', ':', '\0'])+ && !part.contains("..")+ && !part.starts_with('.')+ && part.trim() == part+ && !is_windows_device_name(part)+ };+ let invalid = || {+ format!(+ "ERROR: invalid name '{name}' (use `note` or `folder/note`: no `..`, no leading `.`, no `:` or `\\`, one folder level)"+ )+ };+ if parts.len() > 2 || !parts.iter().all(|p| valid(p)) {+ return Err(invalid());+ }+ // Appended, not `set_extension`: that replaces whatever follows the last+ // dot, so `release.v1` would land on (and overwrite) `release.md`.+ let mut path: PathBuf = parts[..parts.len() - 1].iter().collect();+ path.push(format!("{}.md", parts[parts.len() - 1]));+ if !path.components().all(|c| matches!(c, std::path::Component::Normal(_))) {+ return Err(invalid());+ }+ Ok(path)+}++/// Note stems the harness's own index files would be confused with: a note+/// named `index` or `MEMORY` reads as an index the agent maintains, and the+/// harness builds the index itself (`MEMORY.md`, the prompt section).+const RESERVED_STEMS: [&str; 2] = ["index", "memory"];++/// [`note_relpath`] for a note about to be created: also refuses a name that+/// collides with the harness index ([`RESERVED_STEMS`], any case, any folder).+fn new_note_relpath(name: &str) -> Result<PathBuf, String> {+ let rel = note_relpath(name)?;+ let stem = rel.file_stem().and_then(|s| s.to_str()).unwrap_or_default();+ if RESERVED_STEMS.iter().any(|r| stem.eq_ignore_ascii_case(r)) {+ return Err(format!(+ "ERROR: '{name}' is reserved: the harness builds the memory index itself, so do not write index or overview notes"+ ));+ }+ Ok(rel)+}++/// Most mutations (write, edit, delete, move) one memory tidy may make. Past+/// it the tool refuses further changes, so a tidy that misjudges the store+/// can only misjudge this many notes.+pub const TIDY_MAX_CHANGES: usize = 30;++/// A run's allowance of memory mutations, enforced by the tool rather than+/// asked of the model. Shared by every call of one run; counts what it let+/// through and what it refused, so the caller can report a cap that was hit.+///+/// It also remembers what the run last saw of each note (a content hash per+/// file), because the run that holds one -- a tidy -- works in the background+/// beside the main agent on the same store: a whole-file `write`, a `move` or+/// a `delete` made from a copy the main agent has since changed would lose+/// that change, so it is refused until the note is viewed again.+#[derive(Debug)]+pub struct ChangeBudget {+ max: usize,+ used: std::sync::atomic::AtomicUsize,+ refused: std::sync::atomic::AtomicUsize,+ seen: std::sync::Mutex<HashMap<PathBuf, u64>>,+}++impl ChangeBudget {+ pub fn new(max: usize) -> Self {+ Self {+ max,+ used: Default::default(),+ refused: Default::default(),+ seen: Default::default(),+ }+ }++ fn seen(&self) -> std::sync::MutexGuard<'_, HashMap<PathBuf, u64>> {+ self.seen.lock().unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ /// Record that the run now knows `path` as `content`.+ pub(crate) fn saw(&self, path: &Path, content: &str) {+ self.seen().insert(path.to_path_buf(), content_hash(content));+ }++ /// Forget `path`: it was deleted or moved away.+ pub(crate) fn forget(&self, path: &Path) {+ self.seen().remove(path);+ }++ /// Ok when the note at `path` is missing (nothing to clobber) or is still+ /// what the run last saw; else the refusal asking it to view `name` again.+ pub(crate) fn check_fresh(&self, path: &Path, name: &str) -> Result<(), String> {+ let Ok(current) = std::fs::read_to_string(path) else {+ return Ok(());+ };+ if self.seen().get(path) == Some(&content_hash(¤t)) {+ return Ok(());+ }+ Err(format!(+ "ERROR: '{name}' changed since you last viewed it (or you have not viewed it), so this change \+ could overwrite newer content. `view` it again and base the change on what it says now."+ ))+ }++ /// Take one change, or the refusal the tool returns once the cap is spent.+ pub(crate) fn take(&self) -> Result<(), String> {+ use std::sync::atomic::Ordering;+ let taken = self+ .used+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| (n < self.max).then_some(n + 1));+ if taken.is_ok() {+ return Ok(());+ }+ self.refused.fetch_add(1, Ordering::SeqCst);+ Err(format!(+ "ERROR: this tidy has reached its cap of {} memory changes; no further write, edit, delete or move is allowed. Stop changing notes and write your report, ending it with `cap reached`.",+ self.max+ ))+ }++ /// Give back a change whose operation failed after it was taken.+ pub(crate) fn refund(&self) {+ self.used.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ }++ /// Changes made so far.+ pub fn used(&self) -> usize {+ self.used.load(std::sync::atomic::Ordering::SeqCst)+ }++ /// Changes refused because the cap was spent.+ pub fn refused(&self) -> usize {+ self.refused.load(std::sync::atomic::Ordering::SeqCst)+ }+}+fn target(store_root: &Path, name: &str) -> Result<PathBuf, String> {- Ok(memory_dir(store_root).join(workspace_filename(name)?))+ Ok(memory_dir(store_root).join(note_relpath(name)?))}-/// Note names (file stems), sorted. A missing directory yields an empty list-/// rather than an error: a store with no memory yet is not a failure.-pub async fn list(store: &Path) -> Vec<String> {- let Ok(mut entries) = tokio::fs::read_dir(memory_dir(store)).await else {- return Vec::new();+/// The canonical name of a validated note name: no `.md`, trimmed.+fn canonical(name: &str) -> String {+ let trimmed = name.trim();+ trimmed.strip_suffix(".md").unwrap_or(trimmed).to_string()+}++/// One note as parsed from disk.+#[derive(Debug, Clone)]+struct Note {+ /// `note` or `folder/note`.+ name: String,+ title: String,+ done: bool,+ body: String,+ mtime_ms: u64,+}++/// Split optional front matter from a note: `(front matter lines, body)`.+fn split_front_matter(content: &str) -> (Vec<&str>, &str) {+ let Some(rest) = content.strip_prefix("---\n").or_else(|| content.strip_prefix("---\r\n")) else {+ return (Vec::new(), content);};- let mut names: Vec<String> = Vec::new();- while let Ok(Some(e)) = entries.next_entry().await {- let path = e.path();- if path.extension().and_then(|x| x.to_str()) == Some("md") {- if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {- names.push(stem.to_string());- }+ let mut offset = 0;+ for line in rest.split_inclusive('\n') {+ if line.trim_end() == "---" {+ let front = rest[..offset].lines().collect();+ return (front, &rest[offset + line.len()..]);}+ offset += line.len();}- names.sort();- names+ (Vec::new(), content)}-pub async fn read(store: &Path, name: &str) -> Result<String, String> {- let target = target(store, name)?;- tokio::fs::read_to_string(&target)- .await- .map_err(|e| format!("ERROR: {e}"))+/// Whether the note's front matter archives it (`status: done`).+fn is_done(content: &str) -> bool {+ split_front_matter(content).0.iter().any(|line| {+ line.split_once(':').is_some_and(|(k, v)| {+ k.trim() == "status" && v.trim().trim_matches(['"', '\'']).eq_ignore_ascii_case("done")+ })+ })}-/// A memory note's summary line: the first non-empty, non-heading body line,-/// capped. Mirrors skills' catalog: models see one line per note at session-/// start and load the rest on demand with `memory_read`.-fn describe(content: &str) -> String {- content+/// A note's title: the first non-empty body line, heading marks stripped,+/// capped at [`MAX_TITLE_CHARS`].+fn title_of(content: &str) -> String {+ let line = split_front_matter(content)+ .1.lines().map(str::trim)- .find(|l| !l.is_empty() && !l.starts_with('#'))- .map(|l| {- if l.chars().count() > 120 {- l.chars().take(120).collect::<String>()- } else {- l.to_string()- }- })+ .find(|l| !l.is_empty()).unwrap_or_default()-}--/// One catalog row: enough to advertise a note without shipping its body.-///-/// `mtime_ms` (Unix millis, 0 when the filesystem withholds it) lets callers-/// rank notes by recency - the desktop's chat digest and Cowork's catalog cap-/// both keep the newest notes when they cannot keep them all.-#[derive(Debug, Clone, PartialEq, serde::Serialize)]-#[serde(rename_all = "camelCase")]-pub struct CatalogEntry {- pub name: String,- pub summary: String,- pub mtime_ms: u64,+ .trim_start_matches('#')+ .trim();+ if line.chars().count() > MAX_TITLE_CHARS {+ let cut: String = line.chars().take(MAX_TITLE_CHARS - 3).collect();+ format!("{}...", cut.trim_end())+ } else {+ line.to_string()+ }}fn mtime_ms(path: &Path) -> u64 {@@ -108,68 +298,414 @@ fn mtime_ms(path: &Path) -> u64 {.unwrap_or(0)}-/// Memory notes worth advertising in the system prompt: name + summary line, in-/// name-sorted order, skipping notes with neither a name nor a summary. This is-/// the progressive-disclosure catalog - the model calls `memory_read` to load a-/// note on demand. Sync (std::fs) so the sync `context::load_memory_catalog`-/// can call it directly; the async `memory_*` tools share the same store.-pub fn catalog(store: &Path) -> Vec<CatalogEntry> {+fn now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}++/// Every `.md` note in a store, archived ones included, sorted by name. Sync+/// (std::fs) so the sync prompt composition can call it directly.+fn scan(store: &Path) -> Vec<Note> {let dir = memory_dir(store);+ let mut notes = Vec::new();+ let mut visit = |path: PathBuf, folder: Option<&str>| {+ if path.extension().and_then(|x| x.to_str()) != Some("md") {+ return;+ }+ let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {+ return;+ };+ if stem.starts_with('.') {+ return;+ }+ let Ok(body) = std::fs::read_to_string(&path) else {+ return;+ };+ let name = match folder {+ Some(folder) => format!("{folder}/{stem}"),+ None => stem.to_string(),+ };+ notes.push(Note {+ name,+ title: title_of(&body),+ done: is_done(&body),+ mtime_ms: mtime_ms(&path),+ body,+ });+ };let Ok(rd) = std::fs::read_dir(&dir) else {return Vec::new();};- let mut notes: Vec<CatalogEntry> = rd- .filter_map(|e| e.ok())- .filter_map(|e| {- let path = e.path();- if path.extension().and_then(|x| x.to_str()) != Some("md") {- return None;+ for entry in rd.flatten() {+ let path = entry.path();+ if path.is_dir() {+ let Some(folder) = path.file_name().and_then(|f| f.to_str()).map(str::to_string) else {+ continue;+ };+ if folder.starts_with('.') {+ continue;}- let name = path.file_stem().and_then(|s| s.to_str());- let body = std::fs::read_to_string(&path).ok();- match (name, body) {- (Some(name), Some(body)) => {- let summary = describe(&body);- if name.is_empty() && summary.is_empty() {- None- } else {- Some(CatalogEntry {- name: name.to_string(),- summary,- mtime_ms: mtime_ms(&path),- })+ if let Ok(inner) = std::fs::read_dir(&path) {+ for sub in inner.flatten() {+ if sub.path().is_file() {+ visit(sub.path(), Some(&folder));}}- _ => None,}- })- .collect();+ } else {+ visit(path, None);+ }+ }notes.sort_by(|a, b| a.name.cmp(&b.name));notes}-/// 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)?;+/// Recency per note: the later of its last read and last write, in Unix ms.+#[derive(Debug, Default, Clone, PartialEq, serde::Serialize, serde::Deserialize)]+struct Meta {+ #[serde(default)]+ notes: BTreeMap<String, NoteMeta>,+}++#[derive(Debug, Default, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]+struct NoteMeta {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ read_ms: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ written_ms: Option<u64>,+}++impl NoteMeta {+ fn last_used(&self) -> u64 {+ self.read_ms.max(self.written_ms).unwrap_or(0)+ }+}++/// The recency side file: empty when it does not exist yet, `None` when it+/// exists but cannot be read or parsed. A caller about to save must not treat+/// `None` as empty, or one bad read would wipe every note's recency.+fn load_meta(store: &Path) -> Option<Meta> {+ match std::fs::read_to_string(memory_dir(store).join(META_FILE)) {+ Ok(raw) => serde_json::from_str(&raw).ok(),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(Meta::default()),+ Err(_) => None,+ }+}++/// Process-wide locks of one kind, one per store directory.+type StoreLocks<L> = std::sync::OnceLock<std::sync::Mutex<HashMap<PathBuf, std::sync::Arc<L>>>>;++fn store_lock<L: Default>(locks: &'static StoreLocks<L>, store: &Path) -> std::sync::Arc<L> {+ let locks = locks.get_or_init(Default::default);+ let mut locks = locks.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ locks.entry(memory_dir(store)).or_default().clone()+}++/// One lock per store directory, shared by every thread of the process: the+/// loop runs `memory` calls in parallel (it is a read-capability tool) and a+/// tidy subagent writes the same store as the main agent, so unserialized+/// read-modify-writes of the side file would drop each other's updates. Reads+/// update the side file too, so this is separate from (and taken inside)+/// [`lock_changes`], which only changes hold. [`update_meta`] adds the+/// cross-process half.+fn meta_lock(store: &Path) -> std::sync::Arc<std::sync::Mutex<()>> {+ static LOCKS: StoreLocks<std::sync::Mutex<()>> = std::sync::OnceLock::new();+ store_lock(&LOCKS, store)+}++/// Proof that the caller holds a store's change lock; see [`lock_changes`].+/// Dropping it releases the lock file before the in-process lock.+pub struct ChangeGuard {+ _file: Option<std::fs::File>,+ _held: tokio::sync::OwnedMutexGuard<()>,+}++/// Take the store's change lock, which every change to its notes (write, edit,+/// delete, move) holds for its whole read-modify-write. `memory` calls run in+/// parallel (the tool is classed `Read`), a tidy subagent changes the store+/// beside the main agent, the desktop changes it over IPC, and the desktop and+/// a `jan` process share the same stores: without one lock two edits of a note+/// would both read the old text and the later write would silently drop the+/// earlier edit. Async, because it is held across the file I/O; reads never+/// take it.+///+/// Threads of this process queue on an in-process mutex; its holder then+/// takes the store's lock file, which other processes contend for. The file+/// lock blocks in the OS, so it is taken on the blocking pool.+pub async fn lock_changes(store: &Path) -> ChangeGuard {+ let held = change_lock(store).lock_owned().await;+ let path = memory_dir(store).join(CHANGE_LOCK_FILE);+ let file = tokio::task::spawn_blocking(move || lock_file(&path)).await.ok().flatten();+ ChangeGuard { _file: file, _held: held }+}++/// Open (creating) a store's lock file; `None` when that fails. The store+/// directory is not created for it: a store that does not exist yet has no+/// note two processes could both edit.+fn open_lock_file(path: &Path) -> Option<std::fs::File> {+ std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(path)+ .ok()+}++/// The lock file at `path`, exclusively locked, waiting for another process+/// that holds it; the lock lasts until the file is dropped.+///+/// `None` when it cannot be made or locked (a read-only or missing store, a+/// filesystem without advisory locks): the caller then goes on under its+/// in-process lock alone, as before this lock existed. Failing the memory+/// operation instead would turn a store this process can still use into one+/// it cannot, to guard against a second process that is rarely there; the+/// migration keeps its re-read for that case (see [`archive_if_unchanged`]).+fn lock_file(path: &Path) -> Option<std::fs::File> {+ let file = open_lock_file(path)?;+ fs4::FileExt::lock(&file).ok()?;+ Some(file)+}++/// The lock [`lock_changes`] takes, for the sync [`migrate`] to try.+fn change_lock(store: &Path) -> std::sync::Arc<tokio::sync::Mutex<()>> {+ static LOCKS: StoreLocks<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();+ store_lock(&LOCKS, store)+}++/// Read, change and save the side file under the store's lock. Best-effort:+/// losing a timestamp only reorders the index, it never loses a note. A side+/// file that fails to parse is left as it is rather than replaced with what+/// `update` made of an empty one.+///+/// Another process updates the side file too, so the in-process lock is+/// paired with a lock file of its own, not the change lock: reads update the+/// side file and must not wait out a long change. How long another process+/// holds it is out of this one's hands, so async callers go through+/// [`update_meta_async`], which waits on the blocking pool.+fn update_meta(store: &Path, update: impl FnOnce(&mut Meta) -> bool) {+ let lock = meta_lock(store);+ let _held = lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ let _file = lock_file(&memory_dir(store).join(META_LOCK_FILE));+ let Some(mut meta) = load_meta(store) else {+ return;+ };+ if update(&mut meta) {+ save_meta(store, &meta);+ }+}++/// [`update_meta`] off the async runtime: the lock file may be held by another+/// process (a suspended one, or one on a slow network filesystem), and a+/// worker parked on it would stall every task scheduled there.+async fn update_meta_async(+ store: &Path,+ update: impl FnOnce(&mut Meta) -> bool + Send + 'static,+) {+ let store = store.to_path_buf();+ let _ = tokio::task::spawn_blocking(move || update_meta(&store, update)).await;+}++/// Write the side file through a temp file in the same directory and a+/// rename, so a reader sees the old file or the new one, never half of one.+/// Called only under [`meta_lock`], which also keeps the temp name unique.+fn save_meta(store: &Path, meta: &Meta) {+ let dir = memory_dir(store);+ let Ok(raw) = serde_json::to_string_pretty(meta) else {+ return;+ };+ if std::fs::create_dir_all(&dir).is_err() {+ return;+ }+ let tmp = dir.join(format!("{META_FILE}.{}.tmp", std::process::id()));+ if std::fs::write(&tmp, raw).is_err() || std::fs::rename(&tmp, dir.join(META_FILE)).is_err() {+ let _ = std::fs::remove_file(&tmp);+ }+}++/// Bring a store's notes to the titled format, once.+///+/// Notes written before titles existed lead with whatever their author wrote,+/// which is already the title the index shows (the first body line), so they+/// are left as they are. A note that announces it is finished (`DONE.` or+/// `OBSOLETE` leading its first line) is archived with `status: done` front+/// matter. Seeds `.meta.json` from mtimes so recency survives the move. No note+/// is renamed or deleted. Idempotent and best-effort; a marker file records+/// that it ran.+///+/// It rewrites notes, so it holds the store's change lock like every other+/// change, its lock file included; a change in flight here or in another+/// process defers it to a later session start rather than blocking this one.+/// A store that cannot be locked across processes (see [`lock_file`]) is+/// migrated anyway, so each note is archived only while it still reads as+/// scanned (see [`archive_if_unchanged`]).+pub fn migrate(store: &Path) {let dir = memory_dir(store);- tokio::fs::create_dir_all(&dir)+ if !dir.is_dir() || dir.join(MIGRATED_FILE).exists() {+ return;+ }+ let Ok(_change_lock) = change_lock(store).try_lock_owned() else {+ return;+ };+ let file = open_lock_file(&dir.join(CHANGE_LOCK_FILE));+ if let Some(file) = &file {+ if let Err(fs4::TryLockError::WouldBlock) = fs4::FileExt::try_lock(file) {+ return;+ }+ }+ if dir.join(MIGRATED_FILE).exists() {+ return;+ }+ let notes = scan(store);+ update_meta(store, |meta| {+ for note in ¬es {+ meta.notes.entry(note.name.clone()).or_insert(NoteMeta {+ read_ms: None,+ written_ms: Some(note.mtime_ms),+ });+ }+ true+ });+ for note in notes {+ let first = split_front_matter(¬e.body)+ .1+ .lines()+ .map(str::trim)+ .find(|l| !l.is_empty())+ .unwrap_or_default()+ .to_string();+ let finished = first.starts_with("DONE") || first.starts_with("OBSOLETE");+ if finished && !note.done {+ if let Ok(path) = target(store, ¬e.name) {+ archive_if_unchanged(&path, ¬e.body);+ }+ }+ }+ let _ = std::fs::write(dir.join(MIGRATED_FILE), "1\n");+ write_index(store);+}++/// Archive the note at `path` when it still holds `scanned`; true when it+/// was written. The re-read is what keeps a change another process made+/// since the scan when the store could not be locked across processes:+/// writing the archived scanned copy would silently drop it.+/// A note changed meanwhile stays unarchived, which only leaves it listed.+fn archive_if_unchanged(path: &Path, scanned: &str) -> bool {+ match std::fs::read_to_string(path) {+ Ok(current) if current == scanned => std::fs::write(path, set_status_done(scanned)).is_ok(),+ _ => false,+ }+}++/// `content` with `status: done` in its front matter, added or replaced.+fn set_status_done(content: &str) -> String {+ let (front, body) = split_front_matter(content);+ let mut lines: Vec<String> = front+ .iter()+ .filter(|l| l.split_once(':').map_or(true, |(k, _)| k.trim() != "status"))+ .map(|l| l.to_string())+ .collect();+ lines.push("status: done".to_string());+ format!("---\n{}\n---\n{}", lines.join("\n"), body)+}++/// Every note name (stems, `folder/note` for a foldered one), sorted, archived+/// ones included. A missing directory yields an empty list rather than an+/// error: a store with no memory yet is not a failure.+pub async fn list(store: &Path) -> Vec<String> {+ let store = store.to_path_buf();+ tokio::task::spawn_blocking(move || scan(&store).into_iter().map(|n| n.name).collect())+ .await+ .unwrap_or_default()+}++/// A note's full content. Records the read in `.meta.json`.+pub async fn read(store: &Path, name: &str) -> Result<String, String> {+ let target = target(store, name)?;+ let content = tokio::fs::read_to_string(&target).await.map_err(|e| format!("ERROR: {e}"))?;- tokio::fs::write(dir.join(&file), content)+ let now = now_ms();+ let name = canonical(name);+ update_meta_async(store, move |meta| {+ meta.notes.entry(name).or_default().read_ms = Some(now);+ true+ })+ .await;+ Ok(content)+}++/// One catalog row: enough to advertise a note without shipping its body.+///+/// `mtime_ms` (Unix millis, 0 when the filesystem withholds it) lets callers+/// rank notes by recency - the desktop's chat digest and Cowork's catalog cap+/// both keep the newest notes when they cannot keep them all.+#[derive(Debug, Clone, PartialEq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CatalogEntry {+ pub name: String,+ pub summary: String,+ pub mtime_ms: u64,+}++/// The listed (not archived) notes: name + title, name-sorted. The desktop's+/// recall surface; the CLI prompt uses the budgeted index instead.+pub fn catalog(store: &Path) -> Vec<CatalogEntry> {+ scan(store)+ .into_iter()+ .filter(|n| !n.done)+ .map(|n| CatalogEntry {+ name: n.name,+ summary: n.title,+ mtime_ms: n.mtime_ms,+ })+ .collect()+}++/// Create or overwrite a note and regenerate the store's index. Returns the+/// path written relative to `memory/`, so callers can phrase their own result+/// message. Its folder is created as needed. The caller holds+/// [`lock_changes`] (as do [`delete`] and [`rename`]'s callers).+pub async fn write(store: &Path, name: &str, content: &str) -> Result<String, String> {+ let rel = if target(store, name)?.is_file() {+ note_relpath(name)?+ } else {+ new_note_relpath(name)?+ };+ let path = memory_dir(store).join(&rel);+ if let Some(parent) = path.parent() {+ tokio::fs::create_dir_all(parent)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ }+ tokio::fs::write(&path, content).await.map_err(|e| format!("ERROR: {e}"))?;+ let now = now_ms();+ let name = canonical(name);+ update_meta_async(store, move |meta| {+ meta.notes.entry(name).or_default().written_ms = Some(now);+ true+ })+ .await;write_index(store);- Ok(file)+ Ok(rel.to_string_lossy().replace('\\', "/"))}-/// Delete a note and regenerate the store's index. Idempotent: a missing note-/// is Ok.+/// Delete a note and regenerate the store's index; an emptied folder goes+/// with it. 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(()) => {+ if let Some(parent) = target.parent().filter(|p| *p != memory_dir(store)) {+ // Fails while anything is left in it, which is the point.+ let _ = tokio::fs::remove_dir(parent).await;+ }+ let name = canonical(name);+ update_meta_async(store, move |meta| meta.notes.remove(&name).is_some()).await;write_index(store);Ok(())}@@ -178,27 +714,139 @@ pub async fn delete(store: &Path, name: &str) -> Result<(), String> {}}-/// `- `<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)+/// Rename a note, into or out of a folder, in one step: the file is renamed+/// (content and front matter untouched) and its recency moves with it, so+/// reorganizing is not a write+delete pair that resets either. Refuses a+/// missing source, an existing destination and a reserved destination name.+/// Returns the destination relative to `memory/`, like [`write`].+pub async fn rename(store: &Path, from: &str, to: &str) -> Result<String, String> {+ let source = target(store, from)?;+ let rel = new_note_relpath(to)?;+ let dest = memory_dir(store).join(&rel);+ if !source.is_file() {+ return Err(format!("ERROR: no note '{from}' to move"));+ }+ if dest.exists() {+ return Err(format!(+ "ERROR: '{to}' already exists; merge with `edit` or `write`, then `delete` the other"+ ));+ }+ if let Some(parent) = dest.parent() {+ tokio::fs::create_dir_all(parent)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ }+ tokio::fs::rename(&source, &dest)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ if let Some(parent) = source.parent().filter(|p| *p != memory_dir(store)) {+ // Fails while anything is left in it, which is the point.+ let _ = tokio::fs::remove_dir(parent).await;+ }+ let (from, to) = (canonical(from), canonical(to));+ update_meta_async(store, move |meta| match meta.notes.remove(&from) {+ Some(recency) => {+ meta.notes.insert(to, recency);+ true+ }+ None => false,+ })+ .await;+ write_index(store);+ Ok(rel.to_string_lossy().replace('\\', "/"))+}++/// One line of an index: a note, or a folder collapsed to its count.+#[derive(Debug, Clone)]+enum Entry {+ Note { name: String, title: String },+ Folder { name: String, notes: usize },+}++impl Entry {+ fn line(&self, prefix: &str) -> String {+ match self {+ Entry::Note { name, title } if title.is_empty() => format!("- `{prefix}{name}`"),+ Entry::Note { name, title } => format!("- `{prefix}{name}` - {title}"),+ Entry::Folder { name, notes } => {+ let plural = if *notes == 1 { "note" } else { "notes" };+ format!("- `{prefix}{name}/` ({notes} {plural})")+ }+ }+ }+}++/// A store's listed notes as index entries, most recently used first: a+/// folder collapses to one entry, ranked by its most recent note.+fn entries(store: &Path) -> Vec<Entry> {+ let meta = load_meta(store).unwrap_or_default();+ let used = |n: &Note| {+ meta.notes+ .get(&n.name)+ .map(NoteMeta::last_used)+ .filter(|t| *t > 0)+ .unwrap_or(n.mtime_ms)+ };+ let mut ranked: Vec<(u64, Entry)> = Vec::new();+ let mut folders: HashMap<String, (u64, usize)> = HashMap::new();+ for note in scan(store).into_iter().filter(|n| !n.done) {+ let when = used(¬e);+ match note.name.split_once('/') {+ Some((folder, _)) => {+ let slot = folders.entry(folder.to_string()).or_default();+ slot.0 = slot.0.max(when);+ slot.1 += 1;}+ None => ranked.push((+ when,+ Entry::Note {+ name: note.name,+ title: note.title,+ },+ )),+ }+ }+ ranked.extend(+ folders+ .into_iter()+ .map(|(name, (when, notes))| (when, Entry::Folder { name, notes })),+ );+ // Newest first; ties by name, so equal timestamps still give stable bytes.+ ranked.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| entry_name(&a.1).cmp(entry_name(&b.1))));+ ranked.into_iter().map(|(_, e)| e).collect()+}++fn entry_name(entry: &Entry) -> &str {+ match entry {+ Entry::Note { name, .. } | Entry::Folder { name, .. } => name,+ }+}++/// A folder's listed notes, for `view` of a folder.+fn folder_entries(store: &Path, folder: &str) -> Vec<Entry> {+ scan(store)+ .into_iter()+ .filter(|n| !n.done && n.name.split_once('/').is_some_and(|(f, _)| f == folder))+ .map(|n| Entry::Note {+ name: n.name,+ title: n.title,}).collect()}-/// A project store's `MEMORY.md`: one row per note. Empty when it has none.+/// Notes a store archived (`status: done`), counted for the index footer.+fn archived_count(store: &Path) -> usize {+ scan(store).iter().filter(|n| n.done).count()+}++/// A project store's `MEMORY.md`: one line per note or folder. Empty when it+/// has nothing listed.pub fn project_index(store: &Path) -> String {- let rows = note_rows("", &catalog(store));- if rows.is_empty() {+ let lines: Vec<String> = entries(store).iter().map(|e| e.line("")).collect();+ if lines.is_empty() {return String::new();}- format!("# Project memory\n\n{}\n", rows.join("\n"))+ format!("# Project memory\n\n{}\n", lines.join("\n"))}/// Regenerate `<store>/MEMORY.md` from the notes. Best-effort: an index that@@ -223,7 +871,7 @@ pub struct ProjectPointer {}/// Every project store under `<jan_home>/projects` that holds at least one-/// note, except `exclude` (the current project). Sorted by slug.+/// listed 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();@@ -249,29 +897,25 @@ pub fn project_pointers(jan_home: &Path, exclude: Option<&Path>) -> Vec<ProjectPout}-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()+fn pointer_line(p: &ProjectPointer) -> String {+ 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),+ }}/// 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));+ let user: Vec<String> = entries(jan_home).iter().map(|e| e.line(USER_PREFIX)).collect();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));+ let projects: Vec<String> =+ project_pointers(jan_home, None).iter().map(pointer_line).collect();if !projects.is_empty() {sections.push(format!("## Projects\n\n{}", projects.join("\n")));}@@ -293,6 +937,55 @@ pub fn write_root_index(jan_home: &Path, cross_project: bool) {}}+/// Estimated tokens in `text`, rounded up.+pub fn estimate_tokens(text: &str) -> usize {+ text.chars().count().div_ceil(CHARS_PER_TOKEN)+}++fn content_hash(content: &str) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ content.hash(&mut h);+ h.finish()+}++/// A content hash per note in `store`, archived ones included (archiving is a+/// change worth reporting).+fn note_hashes(store: &Path, prefix: &str, out: &mut BTreeMap<String, u64>) {+ for note in scan(store) {+ out.insert(format!("{prefix}{}", note.name), content_hash(¬e.body));+ }+}++/// Feed every entry of a store's `memory/` (one folder level, like [`scan`])+/// into `h` by name, size and mtime, in a stable order.+fn stamp_store(store: &Path, h: &mut impl std::hash::Hasher) {+ use std::hash::Hash;+ let mut rows: Vec<(PathBuf, u64, u64)> = Vec::new();+ let mut push = |path: PathBuf| {+ let meta = std::fs::metadata(&path).ok();+ let len = meta.as_ref().map_or(0, std::fs::Metadata::len);+ rows.push((path.clone(), len, mtime_ms(&path)));+ };+ let Ok(rd) = std::fs::read_dir(memory_dir(store)) else {+ return;+ };+ for entry in rd.flatten() {+ let path = entry.path();+ if path.is_dir() {+ if let Ok(inner) = std::fs::read_dir(&path) {+ inner.flatten().for_each(|sub| push(sub.path()));+ }+ } else if !path.file_name().and_then(|f| f.to_str()).is_some_and(|f| f.starts_with('.')) {+ // Side files skipped: every read rewrites `.meta.json`, and+ // recency alone never moves the index over its budget.+ push(path);+ }+ }+ rows.sort();+ rows.hash(h);+}+/// The memory a run can reach, and how scoped names resolve against it.#[derive(Debug, Clone, Copy)]pub struct Scopes<'a> {@@ -314,8 +1007,13 @@ struct Resolved {/// Only the current project's and the user's notes are writable; another/// project's memory is that project's to curate.writable: bool,+ /// The prefix that names this store in results (`user:`, `project:x/`).+ prefix: String,}+/// The index header every rendering of the prompt section starts with.+const PROMPT_HEADER: &str = "# Available Memories\n\nYour memory index (titles only, as of session start). Open a note with `memory` op `view` and a `name`; `view` a folder (`name/`) to list its notes.";+impl<'a> Scopes<'a> {/// Scopes with only the current store (the desktop, and tests).pub fn store_only(store: &'a Path) -> Self {@@ -338,6 +1036,7 @@ impl<'a> Scopes<'a> {store: self.home()?.to_path_buf(),note: Some(note.to_string()),writable: true,+ prefix: USER_PREFIX.to_string(),});}let Some(rest) = name.strip_prefix(PROJECT_PREFIX) else {@@ -345,21 +1044,24 @@ impl<'a> Scopes<'a> {store: self.store.to_path_buf(),note: Some(name.to_string()),writable: true,+ prefix: String::new(),});};let (slug, note) = match rest.split_once('/') {- Some((slug, note)) => (slug, Some(note.to_string())),+ Some((slug, note)) => (slug, Some(note.to_string()).filter(|n| !n.is_empty())),None => (rest, None),};- if slug.is_empty() || slug.contains(['/', '\\']) || slug.contains("..") {+ if slug.is_empty() || slug.contains(['/', '\\', ':', '\0']) || slug.contains("..") {return Err(format!("ERROR: invalid project '{slug}'"));}let store = projects_dir(self.home()?).join(slug);+ let prefix = format!("{PROJECT_PREFIX}{slug}/");if store == self.store {return Ok(Resolved {store,note,writable: true,+ prefix,});}if !self.cross_project {@@ -375,85 +1077,418 @@ impl<'a> Scopes<'a> {store,note,writable: false,+ prefix,})}- /// Read a note, or with `project:<slug>` that project's index.- pub async fn read(&self, name: &str) -> Result<String, String> {+ fn writable(&self, name: &str) -> Result<(PathBuf, String, 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- })- }+ match target.note.filter(|_| target.writable) {+ Some(note) => Ok((target.store, note, target.prefix)),+ None => Err(format!(+ "ERROR: '{name}' is read-only: change this project's notes (`name`) or your own (`user:name`)"+ )),}}- /// 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 file a note name resolves to, when it names a single note (not+ /// `folder/` or a project index). It may not exist. A folder of the same+ /// name does not change it: write, edit, delete and move of `tui` act on+ /// `tui.md` whether or not `tui/` exists, so the file is what they guard.+ pub(crate) fn note_file(&self, name: &str) -> Option<PathBuf> {+ let target = self.resolve(name).ok()?;+ let note = target.note.filter(|n| !n.ends_with('/'))?;+ Some(memory_dir(&target.store).join(note_relpath(¬e).ok()?))}- /// 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}")));+ /// Take the change lock (see [`lock_changes`]) of the store `name` writes+ /// to; `None` when it names no store. Callers of [`Self::write`],+ /// [`Self::edit`], [`Self::delete`] and [`Self::rename`] hold it.+ pub async fn lock_changes(&self, name: &str) -> Option<ChangeGuard> {+ let target = self.resolve(name).ok()?;+ Some(lock_changes(&target.store).await)+ }++ /// `view`: no name is the full index; a folder (`tui/`, or `tui` when no+ /// note `tui` exists) lists its notes; a note returns its content;+ /// `project:<slug>` that project's index. When a note and a folder share a+ /// name, `tui` is the note and `tui/` the folder.+ pub async fn view(&self, name: Option<&str>) -> Result<String, String> {+ let Some(name) = name.map(str::trim).filter(|n| !n.is_empty()) else {+ return Ok(self.full_index());+ };+ let target = self.resolve(name)?;+ let Some(note) = target.note else {+ let index = project_index(&target.store);+ return Ok(if index.is_empty() {+ "(no memory notes)".to_string()+ } else {+ index+ });+ };+ let folder = note.trim_end_matches('/');+ let dir = memory_dir(&target.store);+ let is_folder = note.ends_with('/')+ || (!folder.contains('/')+ && dir.join(folder).is_dir()+ && !note_relpath(folder).is_ok_and(|rel| dir.join(rel).is_file()));+ if is_folder {+ let lines: Vec<String> = folder_entries(&target.store, folder)+ .iter()+ .map(|e| e.line(&target.prefix))+ .collect();+ return Ok(if lines.is_empty() {+ format!("(no listed notes in {folder}/)")+ } else {+ lines.join("\n")+ });}- names+ read(&target.store, ¬e).await}- /// 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> {+ /// Every listed note and pointer, with no budget: what `view` with no name+ /// returns when the in-prompt index had to cut some.+ fn full_index(&self) -> String {let mut sections = Vec::new();- let project = note_rows("", &catalog(self.store));+ let project: Vec<String> = entries(self.store).iter().map(|e| e.line("")).collect();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));+ let user: Vec<String> = entries(home).iter().map(|e| e.line(USER_PREFIX)).collect();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)));+ let others: Vec<String> = project_pointers(home, Some(self.store))+ .iter()+ .map(pointer_line)+ .collect();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")- ));+ sections.push(format!("## Other projects (read-only)\n\n{}", others.join("\n")));}}}+ let archived = archived_count(self.store);+ if archived > 0 {+ sections.push(format!(+ "{archived} archived (status: done) note(s) are not listed; `search` finds them."+ ));+ }if sections.is_empty() {- return None;+ return "(no memory notes)".to_string();+ }+ sections.join("\n\n")+ }++ /// `search`: case-insensitive keyword match over titles and bodies of this+ /// project's and the user's notes, archived ones included. Every word of+ /// `query` must appear in the note. Returns names and matching lines.+ pub fn search(&self, query: &str) -> Result<String, String> {+ let words: Vec<String> = query+ .split_whitespace()+ .map(str::to_lowercase)+ .collect();+ if words.is_empty() {+ return Err("ERROR: search needs a non-empty query".to_string());+ }+ let mut stores: Vec<(&Path, &str)> = vec![(self.store, "")];+ if let Some(home) = self.home {+ stores.push((home, USER_PREFIX));+ }+ let mut out: Vec<String> = Vec::new();+ let mut notes = 0usize;+ for (store, prefix) in stores {+ for note in scan(store) {+ let haystack = format!("{}\n{}", note.name, note.body).to_lowercase();+ if !words.iter().all(|w| haystack.contains(w.as_str())) {+ continue;+ }+ notes += 1;+ let archived = if note.done { " (archived)" } else { "" };+ out.push(format!("`{prefix}{}`{archived} - {}", note.name, note.title));+ for line in note.body.lines().map(str::trim) {+ let lower = line.to_lowercase();+ if !line.is_empty() && words.iter().any(|w| lower.contains(w.as_str())) {+ let cut: String = line.chars().take(160).collect();+ out.push(format!(" {cut}"));+ }+ }+ }+ }+ if notes == 0 {+ return Ok(format!("No notes match '{query}'."));+ }+ let total = out.len();+ out.truncate(MAX_SEARCH_HITS);+ if total > MAX_SEARCH_HITS {+ out.push(format!("... {} more matching lines; narrow the query", total - MAX_SEARCH_HITS));+ }+ Ok(out.join("\n"))+ }++ /// `write`: create or overwrite a note in the current project or the user+ /// scope, `title` as its first line. A `title` already leading `content`+ /// is not repeated. Returns the result line, with a warning when the+ /// in-prompt index is near or over its budget.+ pub async fn write(&self, name: &str, title: Option<&str>, content: &str) -> Result<String, String> {+ let (store, note, prefix) = self.writable(name)?;+ let content = with_title(title, content);+ let file = write(&store, ¬e, &content).await?;+ if let Some(home) = self.home {+ write_root_index(home, self.cross_project);}- 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")+ Ok(format!(+ "Wrote {} bytes to memory/{prefix}{file}{}",+ content.len(),+ self.budget_note()))}++ /// `edit`: replace the one exact occurrence of `old` with `new`.+ pub async fn edit(&self, name: &str, old: &str, new: &str) -> Result<String, String> {+ if old.is_empty() {+ return Err("ERROR: `old` must not be empty".to_string());+ }+ let (store, note, prefix) = self.writable(name)?;+ let path = target(&store, ¬e)?;+ let current = tokio::fs::read_to_string(&path)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ match current.matches(old).count() {+ 0 => return Err(format!("ERROR: `old` not found in '{name}'")),+ 1 => {}+ n => {+ return Err(format!(+ "ERROR: `old` matches {n} times in '{name}'; include more context to make it unique"+ ))+ }+ }+ let updated = current.replacen(old, new, 1);+ write(&store, ¬e, &updated).await?;+ if let Some(home) = self.home {+ write_root_index(home, self.cross_project);+ }+ let archived = if is_done(&updated) && !is_done(¤t) {+ " (archived: status: done)"+ } else {+ ""+ };+ Ok(format!("Edited memory/{prefix}{}{archived}", canonical(¬e)))+ }++ /// `delete`: remove a note and its index row. Deleting a missing note is+ /// reported, not an error, so a repeated tidy does not fail.+ pub async fn delete(&self, name: &str) -> Result<String, String> {+ let (store, note, prefix) = self.writable(name)?;+ let existed = target(&store, ¬e)?.is_file();+ delete(&store, ¬e).await?;+ if let Some(home) = self.home {+ write_root_index(home, self.cross_project);+ }+ Ok(if existed {+ format!("Deleted memory/{prefix}{}", canonical(¬e))+ } else {+ format!("No note '{name}' to delete")+ })+ }++ /// `move`: rename `name` to `to` (see [`rename`]). Both must be in the+ /// same writable scope: a move between this project and `user:` is a+ /// `write` there and a `delete` here.+ pub async fn rename(&self, name: &str, to: &str) -> Result<String, String> {+ let (store, note, prefix) = self.writable(name)?;+ let (to_store, to_note, _) = self.writable(to)?;+ if to_store != store {+ return Err(format!(+ "ERROR: '{name}' and '{to}' are in different scopes; `write` the note there and `delete` it here"+ ));+ }+ let file = rename(&store, ¬e, &to_note).await?;+ if let Some(home) = self.home {+ write_root_index(home, self.cross_project);+ }+ Ok(format!(+ "Moved memory/{prefix}{} to memory/{prefix}{}",+ canonical(¬e),+ file.trim_end_matches(".md")+ ))+ }++ /// `" Index: N/B tokens ..."` when the index is near or past its budget,+ /// else empty.+ fn budget_note(&self) -> String {+ let used = self.index_tokens();+ if used * 100 < INDEX_BUDGET_TOKENS * NEAR_BUDGET_PERCENT {+ return String::new();+ }+ format!(+ "\nNote: the memory index is ~{used} tokens against a {INDEX_BUDGET_TOKENS}-token budget; overflow is cut from the prompt. Archive finished work (`status: done`), merge duplicates, or move related notes into a folder."+ )+ }++ /// Estimated tokens of the full, unbudgeted index section.+ pub fn index_tokens(&self) -> usize {+ estimate_tokens(&format!("{PROMPT_HEADER}\n\n{}", self.full_index()))+ }++ /// Whether the unbudgeted index no longer fits the prompt budget: the+ /// signal auto-tidy runs on.+ pub fn over_budget(&self) -> bool {+ self.index_tokens() > INDEX_BUDGET_TOKENS+ }++ /// A cheap stamp of this project's and the user's notes, from file+ /// metadata alone (name, size, mtime; nothing is read): equal stamps mean+ /// [`Self::over_budget`] would answer as it did before, so a caller that+ /// asks every turn only pays for the full index when a note changed.+ /// Other projects are not stamped: they only add one pointer line each.+ pub fn stamp(&self) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ stamp_store(self.store, &mut h);+ if let Some(home) = self.home {+ stamp_store(home, &mut h);+ }+ self.cross_project.hash(&mut h);+ h.finish()+ }++ /// The list of `user:`/project notes with names and hashes, used to tell+ /// what changed between two points. See [`Self::fingerprint`].+ pub fn fingerprint(&self) -> BTreeMap<String, u64> {+ let mut out = BTreeMap::new();+ note_hashes(self.store, "", &mut out);+ if let Some(home) = self.home {+ note_hashes(home, USER_PREFIX, &mut out);+ }+ out+ }++ /// The prompt's memory section, never over [`INDEX_BUDGET_TOKENS`].+ ///+ /// Root user notes and other-project pointers first (they are few and they+ /// orient), then this project's notes by most recent use, folders collapsed+ /// to one line. Whatever does not fit becomes one overflow line pointing at+ /// `memory view`. Rendered from the notes, not from the `MEMORY.md` files,+ /// so a stale or hand-edited index can never reach the model. `None` when+ /// there is nothing to show.+ pub fn prompt_block(&self) -> Option<String> {+ let mut user: Vec<String> = Vec::new();+ let mut others: Vec<String> = Vec::new();+ if let Some(home) = self.home {+ user = entries(home).iter().map(|e| e.line(USER_PREFIX)).collect();+ if self.cross_project {+ others = project_pointers(home, Some(self.store))+ .iter()+ .map(pointer_line)+ .collect();+ }+ }+ let project = entries(self.store);+ if user.is_empty() && others.is_empty() && project.is_empty() {+ return None;+ }++ let budget = INDEX_BUDGET_TOKENS * CHARS_PER_TOKEN;+ // Reserved for the overflow line, so adding it can never break the budget.+ let reserve = 120;+ let mut used = PROMPT_HEADER.chars().count();+ let fits = |line: &str, used: &mut usize| {+ let cost = line.chars().count() + 1;+ if *used + cost + reserve > budget {+ return false;+ }+ *used += cost;+ true+ };+ let mut dropped: Vec<&Entry> = Vec::new();+ let mut dropped_lines = 0usize;+ let mut take = |lines: Vec<String>, header: &str, used: &mut usize| -> Vec<String> {+ let mut kept = Vec::new();+ if lines.is_empty() || !fits(header, used) {+ dropped_lines += lines.len();+ return kept;+ }+ for line in lines {+ if fits(&line, used) {+ kept.push(line);+ } else {+ dropped_lines += 1;+ }+ }+ kept+ };+ let user_header = "\n## User notes (all projects)\n";+ let others_header = "\n## Other projects (read-only: `view` `project:<slug>`)\n";+ let user = take(user, user_header, &mut used);+ let others = take(others, others_header, &mut used);+ let project_header = "\n## This project\n";+ let mut project_lines: Vec<String> = Vec::new();+ if !project.is_empty() && fits(project_header, &mut used) {+ for entry in &project {+ let line = entry.line("");+ if fits(&line, &mut used) {+ project_lines.push(line);+ } else {+ dropped.push(entry);+ }+ }+ } else {+ dropped.extend(project.iter());+ }++ let mut sections = vec![PROMPT_HEADER.to_string()];+ if !project_lines.is_empty() {+ sections.push(format!("## This project\n\n{}", project_lines.join("\n")));+ }+ if !user.is_empty() {+ sections.push(format!("## User notes (all projects)\n\n{}", user.join("\n")));+ }+ if !others.is_empty() {+ sections.push(format!(+ "## Other projects (read-only: `view` `project:<slug>`)\n\n{}",+ others.join("\n")+ ));+ }+ let more_notes: usize = dropped+ .iter()+ .map(|e| match e {+ Entry::Note { .. } => 1,+ Entry::Folder { notes, .. } => *notes,+ })+ .sum::<usize>()+ + dropped_lines;+ if more_notes > 0 {+ let folders = dropped+ .iter()+ .filter(|e| matches!(e, Entry::Folder { .. }))+ .count();+ sections.push(format!(+ "+{more_notes} more ({folders} folders) not shown: `memory` op `view` lists everything"+ ));+ }+ Some(sections.join("\n\n"))+ }+}++/// `content` led by `title` as its first body line, after any front matter.+/// A content that already opens with the title (or a heading of it) is kept.+fn with_title(title: Option<&str>, content: &str) -> String {+ let Some(title) = title.map(str::trim).filter(|t| !t.is_empty()) else {+ return content.to_string();+ };+ let title = title.lines().next().unwrap_or_default().trim();+ let (front, body) = split_front_matter(content);+ if title_of(body) == title_of(title) {+ return content.to_string();+ }+ let body = format!("{title}\n\n{}", body.trim_start_matches('\n'));+ if front.is_empty() {+ body+ } else {+ format!("---\n{}\n---\n{body}", front.join("\n"))+ }}#[cfg(test)]@@ -461,11 +1496,29 @@ mod tests {use super::*;use std::sync::atomic::{AtomicUsize, Ordering};+ /// Update one note's recency, synchronously.+ fn touch_meta(store: &Path, name: &str, update: impl FnOnce(&mut NoteMeta)) {+ update_meta(store, |meta| {+ update(meta.notes.entry(name.to_string()).or_default());+ true+ });+ }+static COUNTER: AtomicUsize = AtomicUsize::new(0);fn unique_root() -> PathBuf {let n = COUNTER.fetch_add(1, Ordering::SeqCst);- std::env::temp_dir().join(format!("jan_memory_test_{}_{}", std::process::id(), n))+ let root = std::env::temp_dir().join(format!("jan_memory_test_{}_{}", std::process::id(), n));+ // A test that panicked skips its cleanup and the sandbox reuses pids,+ // so a later run could otherwise start on a stale store.+ let _ = std::fs::remove_dir_all(&root);+ root+ }++ fn put(store: &Path, name: &str, body: &str) {+ let path = memory_dir(store).join(note_relpath(name).unwrap());+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, body).unwrap();}#[tokio::test]@@ -484,20 +1537,32 @@ mod tests {}#[tokio::test]- async fn list_is_sorted_and_ignores_non_markdown() {+ async fn list_is_sorted_and_ignores_non_markdown_and_the_side_files() {let root = unique_root();write(&root, "b", "b").await.unwrap();write(&root, "a", "a").await.unwrap();std::fs::write(memory_dir(&root).join("notes.txt"), "ignored").unwrap();+ assert!(memory_dir(&root).join(META_FILE).is_file(), "writes are timed");assert_eq!(list(&root).await, vec!["a", "b"]);let _ = std::fs::remove_dir_all(&root);}+ #[tokio::test]+ async fn folders_hold_one_level_of_notes() {+ let root = unique_root();+ assert_eq!(write(&root, "tui/scroll", "Scroll").await.unwrap(), "tui/scroll.md");+ assert_eq!(read(&root, "tui/scroll").await.unwrap(), "Scroll");+ assert_eq!(list(&root).await, vec!["tui/scroll"]);+ delete(&root, "tui/scroll").await.unwrap();+ assert!(!memory_dir(&root).join("tui").exists(), "an emptied folder goes too");+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn traversal_names_are_rejected() {let root = unique_root();- for bad in ["../escape", "sub/x", "..", "", "."] {+ for bad in ["../escape", "a/b/c", "..", "", ".", ".hidden", "a/.x", "a\\b", "/abs"] {assert!(write(&root, bad, "x").await.is_err(), "write {bad:?}");assert!(read(&root, bad).await.is_err(), "read {bad:?}");assert!(delete(&root, bad).await.is_err(), "delete {bad:?}");@@ -505,6 +1570,67 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A dot inside a name is part of the name: `release.v1` is its own note,+ /// never `release.md`, through every op and the migration.+ #[tokio::test]+ async fn dotted_names_never_collide_with_their_prefix() {+ let root = unique_root();+ write(&root, "release", "Release notes").await.unwrap();+ assert_eq!(write(&root, "release.v1", "V1").await.unwrap(), "release.v1.md");+ assert_eq!(write(&root, "grp/a.b", "AB").await.unwrap(), "grp/a.b.md");+ assert_eq!(read(&root, "release").await.unwrap(), "Release notes");+ assert_eq!(read(&root, "release.v1").await.unwrap(), "V1");+ assert_eq!(read(&root, "release.v1.md").await.unwrap(), "V1");+ assert_eq!(list(&root).await, vec!["grp/a.b", "release", "release.v1"]);+ assert_eq!(rename(&root, "release.v1", "release.v2").await.unwrap(), "release.v2.md");+ assert_eq!(read(&root, "release").await.unwrap(), "Release notes");+ assert!(rename(&root, "release.v2", "release").await.is_err(), "no overwrite");+ delete(&root, "release.v2").await.unwrap();+ assert_eq!(read(&root, "release").await.unwrap(), "Release notes");+ assert_eq!(list(&root).await, vec!["grp/a.b", "release"]);++ let store = unique_root();+ put(&store, "pr", "Open PR.");+ put(&store, "pr.9", "DONE. PR 9 merged.");+ migrate(&store);+ let dir = memory_dir(&store);+ assert_eq!(std::fs::read_to_string(dir.join("pr.md")).unwrap(), "Open PR.");+ assert!(is_done(&std::fs::read_to_string(dir.join("pr.9.md")).unwrap()));+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&store);+ }++ /// A name is confined to the store on every platform: no drive prefix,+ /// no colon (an NTFS stream, or a drive on Windows), no NUL, no device+ /// name. Checked on the name itself so the Windows rules hold everywhere.+ #[tokio::test]+ async fn names_that_could_leave_the_store_are_rejected_on_every_platform() {+ let root = unique_root();+ for bad in [+ "C:/escape", "C:escape", "c:", "a:b", "grp/a:stream", "note:$DATA", "a\0b",+ "nul", "CON", "com1", "grp/lpt1", "aux.v1", "//server/share",+ ] {+ assert!(note_relpath(bad).is_err(), "{bad:?}");+ assert!(write(&root, bad, "x").await.is_err(), "write {bad:?}");+ assert!(read(&root, bad).await.is_err(), "read {bad:?}");+ assert!(delete(&root, bad).await.is_err(), "delete {bad:?}");+ assert!(rename(&root, bad, "ok").await.is_err(), "move from {bad:?}");+ }+ put(&root, "ok", "fine");+ assert!(rename(&root, "ok", "C:/escape").await.is_err());+ assert_eq!(read(&root, "ok").await.unwrap(), "fine");+ let home = unique_root();+ let scopes = Scopes {+ store: &root,+ home: Some(&home),+ cross_project: true,+ };+ for bad in ["project:C:", "project:C:/x", "project:a:b/x", "user:C:/x"] {+ assert!(scopes.view(Some(bad)).await.unwrap_err().contains("invalid"), "{bad:?}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn read_missing_note_errors() {let root = unique_root();@@ -512,16 +1638,23 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[tokio::test]+ async fn a_read_is_timed_in_the_side_file_and_leaves_the_mtime_alone() {+ let root = unique_root();+ put(&root, "fact", "A fact.");+ let before = mtime_ms(&memory_dir(&root).join("fact.md"));+ read(&root, "fact").await.unwrap();+ assert_eq!(mtime_ms(&memory_dir(&root).join("fact.md")), before);+ assert!(load_meta(&root).unwrap().notes["fact"].read_ms.is_some());+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]- fn catalog_lists_sorted_notes_with_summaries() {+ fn catalog_lists_titles_and_skips_archived_notes() {let root = unique_root();- std::fs::create_dir_all(memory_dir(&root)).unwrap();- std::fs::write(- memory_dir(&root).join("decisions.md"),- "# Decisions\nWe use Yarn not npm.",- )- .unwrap();- std::fs::write(memory_dir(&root).join("prefs.md"), "Keep it minimal.").unwrap();+ put(&root, "decisions", "# Decisions\nWe use Yarn not npm.");+ put(&root, "prefs", "Keep it minimal.");+ put(&root, "old", "---\nstatus: done\n---\nShipped in 0.8.");std::fs::write(memory_dir(&root).join("notes.txt"), "ignored").unwrap();let notes = catalog(&root);@@ -529,39 +1662,41 @@ mod tests {.iter().map(|n| (n.name.as_str(), n.summary.as_str())).collect();- assert_eq!(- named,- vec![- ("decisions", "We use Yarn not npm."),- ("prefs", "Keep it minimal."),- ]- );- assert!(- notes.iter().all(|n| n.mtime_ms > 0),- "freshly written notes carry a real mtime: {notes:?}"- );+ assert_eq!(named, vec![("decisions", "Decisions"), ("prefs", "Keep it minimal.")]);+ assert!(notes.iter().all(|n| n.mtime_ms > 0), "{notes:?}");let _ = std::fs::remove_dir_all(&root);}#[test]- fn catalog_lists_notes_even_without_a_summary_line() {+ fn catalog_missing_dir_is_empty() {let root = unique_root();- std::fs::create_dir_all(memory_dir(&root)).unwrap();- std::fs::write(memory_dir(&root).join("empty.md"), " \n# Only headings\n").unwrap();+ assert!(catalog(&root).is_empty());+ }- // A curated note is worth advertising by name even if it has no prose.- let notes = catalog(&root);- assert_eq!(notes.len(), 1);- assert_eq!(notes[0].name, "empty");- assert_eq!(notes[0].summary, "");- let _ = std::fs::remove_dir_all(&root);+ #[test]+ fn front_matter_and_titles_parse() {+ assert!(is_done("---\nstatus: done\n---\nx"));+ assert!(is_done("---\ntags: a\nstatus: \"Done\"\n---\nx"));+ assert!(!is_done("status: done\nnot front matter"));+ assert!(!is_done("---\nstatus: active\n---\nx"));+ assert_eq!(title_of("---\nstatus: done\n---\n\n## Title here\nbody"), "Title here");+ assert_eq!(title_of(&"y".repeat(300)).chars().count(), MAX_TITLE_CHARS);+ assert_eq!(set_status_done("Body"), "---\nstatus: done\n---\nBody");+ assert_eq!(+ set_status_done("---\nstatus: open\nx: 1\n---\nBody"),+ "---\nx: 1\nstatus: done\n---\nBody"+ );}#[test]- fn catalog_missing_dir_is_empty() {- let root = unique_root();- assert!(catalog(&root).is_empty());- let _ = std::fs::remove_dir_all(&root);+ fn a_title_leads_the_note_once() {+ assert_eq!(with_title(Some("Build"), "Use yarn."), "Build\n\nUse yarn.");+ assert_eq!(with_title(Some("Build"), "# Build\nUse yarn."), "# Build\nUse yarn.");+ assert_eq!(with_title(None, "Use yarn."), "Use yarn.");+ assert_eq!(+ with_title(Some("Old"), "---\nstatus: done\n---\nGone."),+ "---\nstatus: done\n---\nOld\n\nGone."+ );}fn scopes_fixture() -> (PathBuf, PathBuf, PathBuf) {@@ -569,8 +1704,7 @@ mod tests {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();+ put(&other, "api", "Lib API is frozen.");std::fs::write(other.join("project.json"), "{\"path\": \"/src/lib\"}").unwrap();(home, current, other)}@@ -580,7 +1714,7 @@ mod tests {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}");+ assert!(index.contains("- `prefs` - Prefs"), "{index}");delete(&root, "prefs").await.unwrap();assert!(!root.join(INDEX_FILE).exists(), "an empty store has no index");@@ -588,7 +1722,7 @@ mod tests {}#[tokio::test]- async fn scoped_names_route_to_user_and_project_stores() {+ async fn every_op_routes_through_scoped_names() {let (home, current, _other) = scopes_fixture();let scopes = Scopes {store: ¤t,@@ -596,28 +1730,82 @@ mod tests {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"]);+ let w = scopes.write("local", Some("Local fact"), "Here.").await.unwrap();+ assert!(w.starts_with("Wrote") && w.contains("memory/local.md"), "{w}");+ let u = scopes.write("user:prefs", Some("Prefs"), "Everywhere.").await.unwrap();+ assert!(u.contains("memory/user:prefs.md"), "{u}");+ assert_eq!(scopes.view(Some("local")).await.unwrap(), "Local fact\n\nHere.");+ assert_eq!(scopes.view(Some("user:prefs")).await.unwrap(), "Prefs\n\nEverywhere.");++ // edit: exact, unique match only.+ scopes.edit("local", "Here.", "There.").await.unwrap();+ assert!(scopes.view(Some("local")).await.unwrap().ends_with("There."));+ assert!(scopes.edit("local", "missing", "x").await.unwrap_err().contains("not found"));+ scopes.write("dup", None, "a a").await.unwrap();+ assert!(scopes.edit("dup", "a", "b").await.unwrap_err().contains("2 times"));++ // search: titles and bodies, both scopes.+ let hits = scopes.search("everywhere").unwrap();+ assert!(hits.contains("`user:prefs` - Prefs"), "{hits}");+ assert!(hits.contains(" Everywhere."), "{hits}");+ assert!(scopes.search("nothing-like-this").unwrap().starts_with("No notes match"));++ // delete.+ assert!(scopes.delete("dup").await.unwrap().starts_with("Deleted"));+ assert!(scopes.delete("dup").await.unwrap().starts_with("No note"));// 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());+ assert!(scopes.view(Some("project:lib-2")).await.unwrap().contains("`api`"));+ assert_eq!(scopes.view(Some("project:lib-2/api")).await.unwrap(), "Lib API is frozen.");+ for op in [+ scopes.write("project:lib-2/api", None, "x").await,+ scopes.edit("project:lib-2/api", "Lib", "x").await,+ scopes.delete("project:lib-2/api").await,+ ] {+ assert!(op.unwrap_err().contains("read-only"));+ }+ assert!(scopes.view(Some("project:nope/api")).await.is_err());+ assert!(scopes.view(Some("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("- `user:prefs` - Prefs"), "{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 archived_notes_are_readable_and_searchable_but_never_listed() {+ let root = unique_root();+ let scopes = Scopes::store_only(&root);+ scopes.write("pr-1", Some("PR 1 merged"), "Shipped the parser.").await.unwrap();+ let edited = scopes.edit("pr-1", "PR 1 merged", "---\nstatus: done\n---\nPR 1 merged").await.unwrap();+ assert!(edited.contains("archived"), "{edited}");++ assert!(scopes.prompt_block().is_none(), "nothing listed");+ assert!(catalog(&root).is_empty());+ assert!(scopes.view(None).await.unwrap().contains("1 archived"));+ assert!(scopes.view(Some("pr-1")).await.unwrap().contains("Shipped the parser."));+ assert!(scopes.search("parser").unwrap().contains("`pr-1` (archived)"));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn a_folder_views_as_its_notes_and_collapses_in_the_index() {+ let root = unique_root();+ let scopes = Scopes::store_only(&root);+ scopes.write("tui/scroll", Some("Scroll fix"), "x").await.unwrap();+ scopes.write("tui/theme", Some("Theme"), "y").await.unwrap();+ let listed = scopes.view(Some("tui/")).await.unwrap();+ assert_eq!(listed, "- `tui/scroll` - Scroll fix\n- `tui/theme` - Theme");+ assert_eq!(scopes.view(Some("tui")).await.unwrap(), listed);+ let block = scopes.prompt_block().unwrap();+ assert!(block.contains("- `tui/` (2 notes)"), "{block}");+ assert!(!block.contains("Scroll fix"), "{block}");+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn cross_project_off_hides_and_refuses_other_projects() {let (home, current, _other) = scopes_fixture();@@ -626,10 +1814,10 @@ mod tests {home: Some(&home),cross_project: false,};- assert!(scopes.read("project:lib-2/api").await.unwrap_err().contains("cross-project"));+ assert!(scopes.view(Some("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");+ scopes.write("mine", None, "ok").await.unwrap();+ assert_eq!(scopes.view(Some("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);@@ -639,20 +1827,18 @@ mod tests {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"]);+ assert!(scopes.write("user:x", None, "y").await.is_err());+ assert!(scopes.view(Some("project:a/b")).await.is_err());+ scopes.write("x", None, "y").await.unwrap();+ assert_eq!(list(&root).await, vec!["x"]);let _ = std::fs::remove_dir_all(&root);}#[test]- fn prompt_block_opens_this_project_and_points_at_the_rest() {+ fn prompt_block_lists_this_project_then_the_user_then_pointers() {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();+ put(¤t, "build", "Use yarn.");+ put(&home, "style", "Be terse.");let block = Scopes {store: ¤t,@@ -674,4 +1860,303 @@ mod tests {let _ = std::fs::remove_dir_all(&home);}+ /// The acceptance fixture: 120+ notes stay within the token budget, the+ /// most recently used ones are the ones listed, and the rest collapse to+ /// one overflow line.+ #[test]+ fn a_large_store_stays_within_the_budget() {+ let (home, current, _other) = scopes_fixture();+ for i in 0..130 {+ put(+ ¤t,+ &format!("note-{i:03}"),+ &format!("Fact number {i}: a reasonably long title describing finished work on a merged pull request"),+ );+ }+ for i in 0..20 {+ put(¤t, &format!("pr/n{i}"), "A PR note.");+ }+ for i in 0..8 {+ put(&home, &format!("pref-{i}"), "A user-wide preference that applies everywhere.");+ }+ // The newest note by use sorts first.+ touch_meta(¤t, "note-000", |m| m.read_ms = Some(u64::MAX / 2));+ let scopes = Scopes {+ store: ¤t,+ home: Some(&home),+ cross_project: true,+ };+ let block = scopes.prompt_block().unwrap();+ let tokens = estimate_tokens(&block);+ assert!(tokens <= INDEX_BUDGET_TOKENS, "{tokens} tokens:\n{block}");+ assert!(scopes.over_budget(), "the unbudgeted index does not fit");+ assert!(block.contains("- `note-000` -"), "most recent use is kept");+ assert!(block.contains("- `user:pref-0`"), "user notes come first");+ assert!(block.contains("`project:lib-2`"), "pointers come first");+ let overflow = block.lines().last().unwrap();+ assert!(overflow.starts_with('+') && overflow.contains("`view`"), "{overflow}");+ assert_eq!(block, scopes.prompt_block().unwrap(), "deterministic bytes");+ let _ = std::fs::remove_dir_all(&home);+ }++ #[tokio::test]+ async fn write_warns_when_the_index_nears_its_budget() {+ let root = unique_root();+ let scopes = Scopes::store_only(&root);+ let quiet = scopes.write("one", Some("One"), "x").await.unwrap();+ assert!(!quiet.contains("budget"), "{quiet}");+ for i in 0..80 {+ put(&root, &format!("n{i}"), &"A long enough title for the index row ".repeat(2));+ }+ let loud = scopes.write("two", Some("Two"), "y").await.unwrap();+ assert!(loud.contains("token budget"), "{loud}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn migration_archives_finished_notes_once_and_loses_none() {+ let root = unique_root();+ put(&root, "live", "Still true.");+ put(&root, "merged", "DONE. PR 9 merged.");+ put(&root, "stale", "OBSOLETE as of 2026-09-25: replaced.");+ put(&root, "tui/x", "Folder note.");+ migrate(&root);+ assert_eq!(scan(&root).len(), 4, "no note is lost");+ assert!(is_done(&std::fs::read_to_string(memory_dir(&root).join("merged.md")).unwrap()));+ assert!(is_done(&std::fs::read_to_string(memory_dir(&root).join("stale.md")).unwrap()));+ let live = std::fs::read_to_string(memory_dir(&root).join("live.md")).unwrap();+ assert_eq!(live, "Still true.", "live notes are untouched");+ let names: Vec<String> = catalog(&root).into_iter().map(|e| e.name).collect();+ assert_eq!(names, vec!["live", "tui/x"]);+ assert!(load_meta(&root).unwrap().notes.contains_key("tui/x"), "recency is seeded");++ // Once: a note marked DONE later is the agent's business, not the migration's.+ put(&root, "later", "DONE. later");+ migrate(&root);+ assert!(!is_done(&std::fs::read_to_string(memory_dir(&root).join("later.md")).unwrap()));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The migration rewrites notes, so it runs under the store's change lock+ /// like every other change: while a change is in flight it waits for a+ /// later session instead of writing the body it scanned over it.+ #[tokio::test]+ async fn migration_never_runs_beside_an_in_flight_change() {+ let root = unique_root();+ put(&root, "merged", "DONE. PR 9 merged.");+ let held = lock_changes(&root).await;+ put(&root, "merged", "DONE. PR 9 merged.\n\nFollow-up: PR 10.");+ migrate(&root);+ let path = memory_dir(&root).join("merged.md");+ assert_eq!(+ std::fs::read_to_string(&path).unwrap(),+ "DONE. PR 9 merged.\n\nFollow-up: PR 10.",+ "untouched while a change holds the lock"+ );+ assert!(!memory_dir(&root).join(MIGRATED_FILE).exists(), "deferred, not done");+ drop(held);+ migrate(&root);+ let body = std::fs::read_to_string(&path).unwrap();+ assert!(is_done(&body) && body.ends_with("Follow-up: PR 10."), "{body}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Hold `name`'s file lock through a handle of its own, the way another+ /// process (the desktop beside a `jan`) would: flock and LockFileEx locks+ /// belong to an open file, so this one excludes the store's own.+ fn hold_as_another_process(root: &Path, name: &str) -> std::fs::File {+ std::fs::create_dir_all(memory_dir(root)).unwrap();+ let file = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(memory_dir(root).join(name))+ .unwrap();+ fs4::FileExt::lock(&file).unwrap();+ file+ }++ #[tokio::test]+ async fn a_change_waits_for_another_process_changing_the_store() {+ let root = unique_root();+ let other = hold_as_another_process(&root, CHANGE_LOCK_FILE);+ let waiting = tokio::spawn({+ let root = root.clone();+ async move { drop(lock_changes(&root).await) }+ });+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;+ assert!(!waiting.is_finished(), "took the lock another process holds");+ drop(other);+ tokio::time::timeout(std::time::Duration::from_secs(10), waiting)+ .await+ .expect("taken once the other process lets go")+ .unwrap();+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn migration_never_runs_beside_another_process_changing_the_store() {+ let root = unique_root();+ put(&root, "merged", "DONE. PR 9 merged.");+ let other = hold_as_another_process(&root, CHANGE_LOCK_FILE);+ migrate(&root);+ let path = memory_dir(&root).join("merged.md");+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "DONE. PR 9 merged.");+ assert!(!memory_dir(&root).join(MIGRATED_FILE).exists(), "deferred, not done");+ drop(other);+ migrate(&root);+ assert!(is_done(&std::fs::read_to_string(&path).unwrap()));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn a_recency_update_waits_for_another_process_updating_it() {+ let root = unique_root();+ let other = hold_as_another_process(&root, META_LOCK_FILE);+ let waiting = std::thread::spawn({+ let root = root.clone();+ move || touch_meta(&root, "a", |m| m.read_ms = Some(1))+ });+ std::thread::sleep(std::time::Duration::from_millis(300));+ assert!(!memory_dir(&root).join(META_FILE).exists(), "wrote under another's lock");+ drop(other);+ waiting.join().unwrap();+ assert_eq!(load_meta(&root).unwrap().notes["a"].read_ms, Some(1));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A read waiting on another process's recency lock must not park the+ /// runtime: on a single-threaded one, every other task would stall too.+ #[test]+ fn a_read_waiting_on_another_process_leaves_the_runtime_free() {+ let root = unique_root();+ put(&root, "a", "A");+ let other = hold_as_another_process(&root, META_LOCK_FILE);+ let (ticked, tick) = std::sync::mpsc::channel();+ let runtime = std::thread::spawn({+ let root = root.clone();+ move || {+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ rt.block_on(async {+ let reading = tokio::spawn(async move { read(&root, "a").await });+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;+ let _ = ticked.send(());+ reading.await.unwrap()+ })+ }+ });+ let free = tick.recv_timeout(std::time::Duration::from_secs(5)).is_ok();+ drop(other);+ assert_eq!(runtime.join().unwrap().unwrap(), "A");+ assert!(free, "the read parked the runtime on another process's lock");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A store whose lock file cannot be made (here: a directory squats on+ /// its name) still takes changes, under the in-process lock alone.+ #[tokio::test]+ async fn a_store_that_cannot_be_locked_still_takes_changes() {+ let root = unique_root();+ std::fs::create_dir_all(memory_dir(&root).join(CHANGE_LOCK_FILE)).unwrap();+ std::fs::create_dir_all(memory_dir(&root).join(META_LOCK_FILE)).unwrap();+ let held = lock_changes(&root).await;+ write(&root, "a", "one").await.unwrap();+ drop(held);+ assert_eq!(read(&root, "a").await.unwrap(), "one");+ assert!(load_meta(&root).unwrap().notes.contains_key("a"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// When the store cannot be locked across processes, a note changed on+ /// disk after the migration scanned it is left as it is now rather than+ /// replaced with the archived scanned copy.+ #[test]+ fn migration_archives_only_a_note_still_as_scanned() {+ let root = unique_root();+ put(&root, "merged", "DONE. PR 9 merged.\n\nFollow-up: PR 10.");+ let path = memory_dir(&root).join("merged.md");+ assert!(!archive_if_unchanged(&path, "DONE. PR 9 merged."));+ assert_eq!(+ std::fs::read_to_string(&path).unwrap(),+ "DONE. PR 9 merged.\n\nFollow-up: PR 10."+ );+ assert!(archive_if_unchanged(&path, "DONE. PR 9 merged.\n\nFollow-up: PR 10."));+ assert!(is_done(&std::fs::read_to_string(&path).unwrap()));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn concurrent_recency_updates_are_all_kept_and_leave_no_temp_file() {+ let root = unique_root();+ std::fs::create_dir_all(memory_dir(&root)).unwrap();+ let threads: Vec<_> = (0..8)+ .map(|t| {+ let root = root.clone();+ std::thread::spawn(move || {+ for i in 0..25 {+ touch_meta(&root, &format!("n{t}-{i}"), |m| m.read_ms = Some(1));+ }+ })+ })+ .collect();+ threads.into_iter().for_each(|t| t.join().unwrap());+ let meta = load_meta(&root).expect("parses");+ assert_eq!(meta.notes.len(), 200, "no update was lost");+ let leftovers: Vec<_> = std::fs::read_dir(memory_dir(&root))+ .unwrap()+ .flatten()+ .map(|e| e.file_name().to_string_lossy().to_string())+ .filter(|n| n != META_FILE && n != META_LOCK_FILE)+ .collect();+ assert!(leftovers.is_empty(), "{leftovers:?}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn a_corrupt_side_file_is_never_overwritten_with_empty_recency() {+ let root = unique_root();+ put(&root, "a", "one");+ let path = memory_dir(&root).join(META_FILE);+ std::fs::write(&path, "{\"notes\": {\"a\": {\"read_ms\": 5").unwrap();+ read(&root, "a").await.unwrap();+ write(&root, "b", "two").await.unwrap();+ delete(&root, "b").await.unwrap();+ rename(&root, "a", "c").await.unwrap();+ assert_eq!(+ std::fs::read_to_string(&path).unwrap(),+ "{\"notes\": {\"a\": {\"read_ms\": 5",+ "left for a human to repair, not wiped"+ );+ assert!(scan(&root).iter().any(|n| n.name == "c"), "the ops themselves still work");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn a_stamp_moves_with_the_notes_but_not_with_recency() {+ let root = unique_root();+ put(&root, "a", "one");+ let scopes = Scopes::store_only(&root);+ let before = scopes.stamp();+ assert_eq!(scopes.stamp(), before, "stable");+ touch_meta(&root, "a", |m| m.read_ms = Some(42));+ assert_eq!(scopes.stamp(), before, "a read changes nothing that counts");+ put(&root, "b", "two");+ assert_ne!(scopes.stamp(), before, "a new note does");+ let with_b = scopes.stamp();+ put(&root, "b", "two, longer");+ assert_ne!(scopes.stamp(), with_b, "so does a rewrite");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn a_fingerprint_changes_with_content_and_archiving() {+ let root = unique_root();+ put(&root, "a", "one");+ let scopes = Scopes::store_only(&root);+ let first = scopes.fingerprint();+ put(&root, "a", "---\nstatus: done\n---\none");+ assert_ne!(scopes.fingerprint(), first);+ let _ = std::fs::remove_dir_all(&root);+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rsindex e78ce260d..73ab9e692 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rs@@ -32,9 +32,16 @@ pub struct ToolPermissions {allow_write: Vec<Pattern>,}+/// Each pattern as written, plus `memory` for one that named the old memory+/// tools (see [`crate::tools::names_legacy_memory`]), so such a rule keeps+/// applying -- a deny to the whole tool, which is the conservative reading.fn compile(patterns: &[String]) -> Vec<Pattern> {patterns.iter()+ .flat_map(|p| {+ let alias = crate::tools::names_legacy_memory(p).then_some(crate::tools::MEMORY_TOOL);+ std::iter::once(p.as_str()).chain(alias)+ }).filter_map(|p| Pattern::new(p).ok()).collect()}@@ -65,6 +72,16 @@ impl ToolPermissions {}}+ /// These permissions with `name` denied as well: hidden from the tool list+ /// and refused at the gate, whatever the allow lists say. How a caller takes+ /// one tool away from a run (a subagent's memory) without a config edit.+ pub fn with_denied(mut self, name: &str) -> Self {+ if let Ok(pattern) = Pattern::new(&Pattern::escape(name)) {+ self.deny.push(pattern);+ }+ self+ }+pub fn is_denied(&self, name: &str) -> bool {self.deny.iter().any(|p| p.matches(name))}@@ -102,6 +119,34 @@ mod tests {items.iter().map(|v| v.to_string()).collect()}+ #[test]+ fn with_denied_takes_one_exact_tool_away_even_from_an_allow_list() {+ let perms = ToolPermissions::new(PermissionDefault::Allow, &s(&["memory"]), &[], &[])+ .with_denied("memory");+ assert!(perms.is_denied("memory"));+ assert!(!perms.is_denied("memory_extra"), "an exact name, not a prefix");+ assert!(!perms.is_denied("read"));+ }++ /// A rule on an old memory tool name still applies, to the one `memory`+ /// tool: a deny on `memory_read` denies every op rather than none.+ #[test]+ fn old_memory_tool_names_apply_to_the_memory_tool() {+ for old in ["memory_write", "memory_read", "memory_list", "memory_*"] {+ let perms = ToolPermissions::new(PermissionDefault::Allow, &[], &s(&[old]), &[]);+ assert!(perms.is_denied("memory"), "deny {old}");+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &s(&[old]), &[], &[]);+ assert!(perms.is_allowed("memory"), "allow {old}");+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &s(&[old]));+ assert!(perms.is_allowed("memory"), "allow_write {old}");+ }+ // A broad deny that used to catch `memory_write` keeps covering memory.+ let broad = ToolPermissions::new(PermissionDefault::Allow, &[], &s(&["*write*"]), &[]);+ assert!(broad.is_denied("memory"), "a deny on every write still reaches memory");+ let other = ToolPermissions::new(PermissionDefault::Allow, &[], &s(&["web_*"]), &[]);+ assert!(!other.is_denied("memory"), "a glob that never matched memory is left alone");+ }+#[test]fn read_only_advertises_unlisted_mcp_tools() {// read-only (the CLI default) must not suppress opaque MCP tools.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 a726f9055..c57d302a7 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@@ -782,10 +782,17 @@ mod tests {let root = unique_root();let grants = SessionGrants::default();let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);- for name in ["memory_read", "memory_write", "skill_write", "memory_list"] {+ // Every memory op, writes and deletes included: memory is the agent's.+ for (name, op) in [+ ("memory", "view"),+ ("memory", "write"),+ ("memory", "edit"),+ ("memory", "delete"),+ ("skill_write", ""),+ ] {let d = resolve_decision(lookup(name).unwrap(),- &json!({"name": "x", "content": "y"}),+ &json!({"op": op, "name": "x", "content": "y"}),&GateContext {project_root: &root,scratch: None,@@ -796,13 +803,13 @@ mod tests {&perms,&grants,);- assert_eq!(d, Decision::Allow, "{name} should auto-allow");+ assert_eq!(d, Decision::Allow, "{name} {op} should auto-allow");}// Explicit deny in agent.toml still overrides the auto-allow.let denied =- ToolPermissions::new(PermissionDefault::ReadOnly, &[], &s(&["memory_write"]), &[]);+ ToolPermissions::new(PermissionDefault::ReadOnly, &[], &s(&["memory"]), &[]);let d = resolve_decision(- lookup("memory_write").unwrap(),+ lookup("memory").unwrap(),&json!({"name": "x", "content": "y"}),&GateContext {project_root: &root,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 c3726f199..0fc8d6031 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@@ -245,9 +245,9 @@ async fn execute_text("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.memory_scopes()).await,- "memory_read" => memory_read(args, ctx.memory_scopes()).await,- "memory_write" => memory_write(args, ctx.memory_scopes()).await,+ crate::tools::MEMORY_TOOL => {+ memory_tool(args, ctx.memory_scopes(), ctx.memory_change_budget, ctx.plan_mode).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),@@ -517,32 +517,144 @@ 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(scopes: memory::Scopes<'_>) -> String {- scopes.list().await.join("\n")-}--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();+/// The `memory` tool delegates every op to `crate::memory`, so the built-in+/// and the management commands share one implementation. A `budget` (Jan's+/// tidy subagent) caps the mutations: each write, edit, delete and move takes+/// one change before it runs and gives it back if it changed nothing. In+/// `plan_mode` only `view` and `search` run: plan mode is read-only, and the+/// tool is classed `Read` (so the loop's capability check lets it through),+/// which makes this the one place that knows which ops change the store.+/// For the same reason every change holds the store's change lock from the+/// freshness check to its own bookkeeping, so changes batched in parallel, or+/// made by a tidy beside the main agent, apply one after another.+async fn memory_tool(+ args: &serde_json::Value,+ scopes: memory::Scopes<'_>,+ budget: Option<&memory::ChangeBudget>,+ plan_mode: bool,+) -> String {+ let need = |key: &str| {+ arg_str(args, key).ok_or_else(|| format!("ERROR: op needs the '{key}' argument"))};- match scopes.read(name).await {- Ok(content) => content,- Err(e) => e,+ let op = arg_str(args, "op");+ let mutates = matches!(op, Some("write" | "edit" | "delete" | "move"));+ if mutates && plan_mode {+ // Worded like the loop's plan-mode refusal, which telemetry reads as+ // a config refusal.+ return format!(+ "ERROR: tool 'memory' op '{}' unavailable in plan_mode_read_only (plan mode is read-only). \+ Only `view` and `search` work in plan mode; stage the memory change in the plan.",+ op.unwrap_or_default()+ );+ }+ let _change_lock = match (mutates, arg_str(args, "name")) {+ (true, Some(name)) => scopes.lock_changes(name).await,+ _ => None,+ };+ // A tidy runs beside the main agent: its whole-file changes must be based+ // on the note as it is now (see `ChangeBudget::check_fresh`). `edit` needs+ // no check, being an exact match against the current text.+ // Only a complete call is checked, so a missing argument is reported as+ // such rather than as a stale note.+ let complete = match op {+ Some("write") => arg_str(args, "content").is_some(),+ Some("move") => arg_str(args, "to").is_some(),+ Some("delete") => true,+ _ => false,+ };+ if let (Some(budget), Some(name), true) = (budget, arg_str(args, "name"), complete) {+ if let Some(Err(e)) = scopes.note_file(name).map(|path| budget.check_fresh(&path, name)) {+ return e;+ }+ }+ // An `edit` is safe from a stale copy, but its result is only the run's+ // view when the run was up to date before it: otherwise the note also+ // holds text the run never saw, and recording it would let a later+ // whole-file change drop that text unseen.+ let edit_was_fresh = match (budget, op, arg_str(args, "name")) {+ (Some(budget), Some("edit"), Some(name)) => scopes+ .note_file(name)+ .is_some_and(|path| budget.check_fresh(&path, name).is_ok()),+ _ => false,+ };+ if mutates {+ if let Some(Err(e)) = budget.map(memory::ChangeBudget::take) {+ return e;+ }+ }+ let result = match op {+ Some("view") => scopes.view(arg_str(args, "name")).await,+ Some("search") => match need("query") {+ Ok(query) => scopes.search(query),+ Err(e) => Err(e),+ },+ Some("write") => match (need("name"), need("content")) {+ (Ok(name), Ok(content)) => scopes.write(name, arg_str(args, "title"), content).await,+ (Err(e), _) | (_, Err(e)) => Err(e),+ },+ Some("edit") => match (need("name"), need("old"), need("new")) {+ (Ok(name), Ok(old), Ok(new)) => scopes.edit(name, old, new).await,+ (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(e),+ },+ Some("delete") => match need("name") {+ Ok(name) => scopes.delete(name).await,+ Err(e) => Err(e),+ },+ Some("move") => match (need("name"), need("to")) {+ (Ok(name), Ok(to)) => scopes.rename(name, to).await,+ (Err(e), _) | (_, Err(e)) => Err(e),+ },+ Some(other) => Err(format!(+ "ERROR: unknown memory op '{other}' (expected view, search, write, edit, delete or move)"+ )),+ None => Err("ERROR: missing required argument 'op'".to_string()),+ };+ // A refused or no-op change (a missing note to delete) spends nothing.+ let changed = matches!(&result, Ok(text) if !text.starts_with("No note"));+ if !changed && mutates {+ if let Some(budget) = budget {+ budget.refund();+ }}+ if let (Some(budget), Ok(text)) = (budget, &result) {+ remember_notes(budget, scopes, op, args, text, edit_was_fresh);+ }+ result.unwrap_or_else(|e| e)}-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();+/// Keep a budgeted run's view of the notes current after a successful op: a+/// viewed note as returned, a changed one as now on disk (its own change must+/// not read as someone else's), a moved or deleted one forgotten. An edit of+/// a note the run was not up to date with (`edit_was_fresh` false) leaves the+/// stale view in place, so the run must view it again before a whole-file+/// change.+fn remember_notes(+ budget: &memory::ChangeBudget,+ scopes: memory::Scopes<'_>,+ op: Option<&str>,+ args: &serde_json::Value,+ text: &str,+ edit_was_fresh: bool,+) {+ let file = |key: &str| arg_str(args, key).and_then(|name| scopes.note_file(name));+ let record = |path: &Path| match std::fs::read_to_string(path) {+ Ok(content) => budget.saw(path, &content),+ Err(_) => budget.forget(path),};- match scopes.write(name, content).await {- Ok(file) => format!("Wrote {} bytes to memory/{file}", content.len()),- Err(e) => e,+ match op {+ Some("view") => {+ if let Some(path) = file("name").filter(|p| p.is_file()) {+ budget.saw(&path, text);+ }+ }+ Some("write") => file("name").iter().for_each(|p| record(p)),+ Some("edit") if edit_was_fresh => file("name").iter().for_each(|p| record(p)),+ Some("move") => {+ file("name").iter().for_each(|p| budget.forget(p));+ file("to").iter().for_each(|p| record(p));+ }+ Some("delete") => file("name").iter().for_each(|p| budget.forget(p)),+ _ => {}}}@@ -2048,6 +2160,9 @@ mod tests {let dir =std::env::temp_dir().join(format!("jan_handlers_test_{}_{}", std::process::id(), n));std::fs::create_dir_all(&dir).expect("create test root");+ // The root's store lives in the Jan home, outside the root a test+ // removes, and a reused pid reuses the root: start it empty.+ let _ = std::fs::remove_dir_all(crate::workspace::project_store(&dir));dir}@@ -4094,33 +4209,381 @@ mod tests {);}+ /// #497 bug 3: the harness side of a conservative tidy, on a store modeled+ /// on the smoke test (neutral notes plus explicitly finished ones). The+ /// model's choices cannot be unit-tested; what is tested is what the+ /// harness enforces whatever the model does: `move` keeps a note's front+ /// matter and recency, an `index`/`MEMORY` note is refused, and a run with+ /// a change budget stops mutating at the cap and says so.#[tokio::test]- async fn memory_write_read_list_roundtrip() {+ async fn a_capped_tidy_moves_archives_and_stops_at_the_cap() {let root = unique_root();- let w = execute_builtin(- lookup("memory_write").unwrap(),- &json!({"name": "drift", "content": "553 behind"}),- &root,- )- .await;+ let store = crate::workspace::project_store(&root);+ let dir = store.join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ for i in 0..70 {+ std::fs::write(+ dir.join(format!("note-{i:03}.md")),+ format!("Note {i:03} about area {i} with a fairly long descriptive title\n\nBody {i}.\n"),+ )+ .unwrap();+ }+ for i in 0..10 {+ std::fs::write(+ dir.join(format!("shipped-{i:02}.md")),+ format!("PR {} merged and released, work finished\n\nNothing left.\n", 9100 + i),+ )+ .unwrap();+ }+ let budget = crate::memory::ChangeBudget::new(crate::memory::TIDY_MAX_CHANGES);+ let memory = lookup("memory").unwrap();+ let ctx = ToolContext::new(&root, &store, &[]).with_memory_change_budget(Some(&budget));+ let run = |args: serde_json::Value| {+ let ctx = ctx.clone();+ async move { super::execute_builtin(memory, &args, &ctx).await.0 }+ };++ // A tidy views what it changes (the tool refuses a whole-file change+ // to a note it has not seen; see the clobber test below).+ for i in 0..70 {+ run(json!({"op": "view", "name": format!("note-{i:03}")})).await;+ }+ // An archived note moved into a folder keeps its front matter. Viewed+ // first: an edit alone does not count as a view (see the edit test).+ run(json!({"op": "view", "name": "shipped-00"})).await;+ let a = run(json!({"op": "edit", "name": "shipped-00", "old": "PR 9100", "new": "---\nstatus: done\n---\nPR 9100"})).await;+ assert!(a.contains("archived"), "{a}");+ let m = run(json!({"op": "move", "name": "shipped-00", "to": "shipped/9100"})).await;+ assert_eq!(m, "Moved memory/shipped-00 to memory/shipped/9100", "{m}");+ let moved = std::fs::read_to_string(dir.join("shipped/9100.md")).unwrap();+ assert!(moved.starts_with("---\nstatus: done\n---\nPR 9100"), "{moved}");+ assert!(!dir.join("shipped-00.md").exists());+ let meta = std::fs::read_to_string(dir.join(".meta.json")).unwrap();+ assert!(meta.contains("shipped/9100") && !meta.contains("\"shipped-00\""), "{meta}");+ // A move onto an existing note, or of a missing one, changes nothing.+ assert!(run(json!({"op": "move", "name": "note-001", "to": "note-002"})).await.starts_with("ERROR"));+ assert!(run(json!({"op": "move", "name": "nope", "to": "x"})).await.starts_with("ERROR"));+ assert!(run(json!({"op": "move", "name": "note-001"})).await.contains("'to'"));++ // The harness builds the index; a note named like it is refused.+ for bad in ["index", "subsystems/index", "MEMORY", "tui/Memory", "INDEX.md"] {+ let w = run(json!({"op": "write", "name": bad, "content": "links"})).await;+ assert!(w.starts_with("ERROR") && w.contains("index"), "{bad}: {w}");+ let mv = run(json!({"op": "move", "name": "note-003", "to": bad})).await;+ assert!(mv.starts_with("ERROR"), "{bad}: {mv}");+ }++ // 2 changes so far; 28 more fit, then every mutation is refused.+ for i in 10..38 {+ let r = run(json!({"op": "move", "name": format!("note-{i:03}"), "to": format!("area/{i:03}")})).await;+ assert!(r.starts_with("Moved"), "{i}: {r}");+ }+ assert_eq!(budget.used(), 30);+ for args in [+ json!({"op": "edit", "name": "shipped-01", "old": "PR", "new": "---\nstatus: done\n---\nPR"}),+ json!({"op": "write", "name": "x", "content": "y"}),+ json!({"op": "delete", "name": "note-040"}),+ json!({"op": "move", "name": "note-041", "to": "area/041"}),+ ] {+ let r = run(args).await;+ assert!(r.starts_with("ERROR") && r.contains("30"), "{r}");+ }+ assert!(dir.join("note-040.md").exists() && dir.join("note-041.md").exists());+ assert_eq!(budget.refused(), 4);+ // Reads are never capped.+ assert!(run(json!({"op": "view", "name": "shipped-01"})).await.starts_with("PR 9101"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A tidy (the run holding a change budget) runs beside the main agent on+ /// the same store. A note the main agent changed after the tidy viewed it+ /// is not overwritten, moved or deleted from the tidy's stale copy: the+ /// tool refuses and asks for a fresh `view`. The tidy's own changes do not+ /// trip it, and the main agent (no budget) is never checked.+ #[tokio::test]+ async fn a_tidy_never_clobbers_a_note_changed_since_it_viewed_it() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let dir = store.join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ for name in ["a", "b", "c"] {+ std::fs::write(dir.join(format!("{name}.md")), format!("Note {name}")).unwrap();+ }+ let budget = crate::memory::ChangeBudget::new(crate::memory::TIDY_MAX_CHANGES);+ let tidy = ToolContext::new(&root, &store, &[]).with_memory_change_budget(Some(&budget));+ let main = ToolContext::new(&root, &store, &[]);+ async fn run(ctx: &ToolContext<'_>, args: serde_json::Value) -> String {+ let memory = lookup("memory").unwrap();+ super::execute_builtin(memory, &args, ctx).await.0+ }+ for name in ["a", "b", "c"] {+ run(&tidy, json!({"op": "view", "name": name})).await;+ }+ // The main agent edits all three after the tidy read them.+ for name in ["a", "b", "c"] {+ let e = run(&main, json!({"op": "edit", "name": name, "old": "Note", "new": "Edited note"})).await;+ assert!(e.starts_with("Edited"), "{e}");+ }+ for args in [+ json!({"op": "write", "name": "a", "content": "Merged from a stale copy"}),+ json!({"op": "move", "name": "b", "to": "grp/b"}),+ json!({"op": "delete", "name": "c"}),+ ] {+ let r = run(&tidy, args.clone()).await;+ assert!(r.starts_with("ERROR") && r.contains("changed") && r.contains("view"), "{args}: {r}");+ }+ for name in ["a", "b", "c"] {+ let body = std::fs::read_to_string(dir.join(format!("{name}.md"))).unwrap();+ assert_eq!(body, format!("Edited note {name}"), "the main agent's edit survived");+ }+ assert_eq!(budget.used(), 0, "a refused change spends nothing");+ // A fresh view lets the tidy go ahead, and its own changes do not trip+ // the guard on the next op.+ run(&tidy, json!({"op": "view", "name": "a"})).await;+ assert!(run(&tidy, json!({"op": "write", "name": "a", "content": "Merged"})).await.starts_with("Wrote"));+ assert!(run(&tidy, json!({"op": "move", "name": "a", "to": "grp/a"})).await.starts_with("Moved"));+ assert!(run(&tidy, json!({"op": "delete", "name": "grp/a"})).await.starts_with("Deleted"));+ // The main agent is never checked.+ assert!(run(&main, json!({"op": "write", "name": "b", "content": "Over"})).await.starts_with("Wrote"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Plan mode keeps memory readable and refuses every op that changes it,+ /// whatever surface called the tool.+ #[tokio::test]+ async fn plan_mode_refuses_memory_changes_but_not_reads() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let dir = store.join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("fact.md"), "A fact").unwrap();+ let hooks = crate::tools::hooks::HookSet::new();+ let memory = lookup("memory").unwrap();+ let ctx = ToolContext::new(&root, &store, &[]).with_hooks(&hooks, true, None);+ for args in [+ json!({"op": "write", "name": "new", "content": "x"}),+ json!({"op": "edit", "name": "fact", "old": "A", "new": "B"}),+ json!({"op": "delete", "name": "fact"}),+ json!({"op": "move", "name": "fact", "to": "moved"}),+ ] {+ let out = super::execute_builtin(memory, &args, &ctx).await.0;+ assert!(out.starts_with("ERROR:") && out.contains("plan mode is read-only"), "{out}");+ assert!(out.contains("view") && out.contains("search"), "{out}");+ }+ assert_eq!(std::fs::read_to_string(dir.join("fact.md")).unwrap(), "A fact");+ assert!(!dir.join("new.md").exists());+ assert_eq!(super::execute_builtin(memory, &json!({"op": "view", "name": "fact"}), &ctx).await.0, "A fact");+ let found = super::execute_builtin(memory, &json!({"op": "search", "query": "fact"}), &ctx).await.0;+ assert!(found.contains("`fact`"), "{found}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// `memory` is a read-capability tool, so the loop drives a batch of its+ /// calls together (`FuturesUnordered` in one task, as `join!` does here).+ /// Each edit is a read-modify-write of the note; without the store's+ /// change lock every edit read the same text and the last write won, so+ /// all but one edit were lost while every call reported success.+ #[tokio::test]+ async fn concurrent_memory_edits_on_one_note_all_apply() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let dir = store.join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("log.md"), "Log\n\nA0 B0 C0 D0\n").unwrap();+ let ctx = ToolContext::new(&root, &store, &[]);+ let memory = lookup("memory").unwrap();+ let edit = |old: &str, new: &str| {+ let args = json!({"op": "edit", "name": "log", "old": old, "new": new});+ let ctx = ctx.clone();+ async move { super::execute_builtin(memory, &args, &ctx).await.0 }+ };+ let (a, b, c, d) =+ tokio::join!(edit("A0", "A1"), edit("B0", "B1"), edit("C0", "C1"), edit("D0", "D1"));+ for r in [&a, &b, &c, &d] {+ assert!(r.starts_with("Edited"), "{r}");+ }+ let body = std::fs::read_to_string(dir.join("log.md")).unwrap();+ assert_eq!(body, "Log\n\nA1 B1 C1 D1\n", "no edit was lost");++ // Two edits of the same text: one applies, the other finds its `old`+ // gone and says so instead of overwriting the first.+ let (x, y) = tokio::join!(edit("A1", "X"), edit("A1", "Y"));+ let applied = [&x, &y].iter().filter(|r| r.starts_with("Edited")).count();+ assert_eq!(applied, 1, "{x} / {y}");+ let failed = if x.starts_with("Edited") { &y } else { &x };+ assert!(failed.starts_with("ERROR") && failed.contains("not found"), "{failed}");+ let body = std::fs::read_to_string(dir.join("log.md")).unwrap();+ let winner = if x.starts_with("Edited") { "X" } else { "Y" };+ assert_eq!(body, format!("Log\n\n{winner} B1 C1 D1\n"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Concurrent changes to different notes all land, and a write racing an+ /// edit of the same note leaves one of the two whole, never a mix.+ #[tokio::test]+ async fn concurrent_memory_changes_to_different_notes_all_land() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[]);+ let memory = lookup("memory").unwrap();+ let run = |args: serde_json::Value| {+ let ctx = ctx.clone();+ async move { super::execute_builtin(memory, &args, &ctx).await.0 }+ };+ let (a, b, c) = tokio::join!(+ run(json!({"op": "write", "name": "a", "content": "Note a"})),+ run(json!({"op": "write", "name": "b", "content": "Note b"})),+ run(json!({"op": "write", "name": "grp/c", "content": "Note c"})),+ );+ for r in [&a, &b, &c] {+ assert!(r.starts_with("Wrote"), "{r}");+ }+ let dir = store.join("memory");+ assert_eq!(std::fs::read_to_string(dir.join("a.md")).unwrap(), "Note a");+ assert_eq!(std::fs::read_to_string(dir.join("b.md")).unwrap(), "Note b");+ assert_eq!(std::fs::read_to_string(dir.join("grp/c.md")).unwrap(), "Note c");+ let index = std::fs::read_to_string(store.join(crate::memory::INDEX_FILE)).unwrap();+ assert!(index.contains("`a`") && index.contains("`b`") && index.contains("`grp/`"), "{index}");++ let (m, d) = tokio::join!(+ run(json!({"op": "move", "name": "a", "to": "grp/a"})),+ run(json!({"op": "delete", "name": "b"})),+ );+ assert!(m.starts_with("Moved") && d.starts_with("Deleted"), "{m} / {d}");+ let (w, e) = tokio::join!(+ run(json!({"op": "write", "name": "grp/c", "content": "Rewritten c"})),+ run(json!({"op": "edit", "name": "grp/c", "old": "Note", "new": "Edited"})),+ );+ assert!(w.starts_with("Wrote"), "{w}");+ // Either order ends with the write's text: an edit that ran first was+ // replaced whole, one that ran second found `Note` gone.+ assert!(e.starts_with("Edited") || e.contains("not found"), "{e}");+ let body = std::fs::read_to_string(dir.join("grp/c.md")).unwrap();+ assert_eq!(body, "Rewritten c");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A note may share its name with a folder (`tui.md` beside `tui/`, as a+ /// tidy grouping notes under a topic leaves it). The tidy's freshness+ /// guard still covers the note: `view` of `tui` opens the note (`tui/` is+ /// the folder), and a whole-file change from a copy the main agent has+ /// since edited is refused.+ #[tokio::test]+ async fn a_tidy_never_clobbers_a_note_that_shares_a_folders_name() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let dir = store.join("memory");+ std::fs::create_dir_all(dir.join("tui")).unwrap();+ std::fs::write(dir.join("tui.md"), "TUI overview").unwrap();+ std::fs::write(dir.join("tui/scroll.md"), "Scroll fix").unwrap();+ let budget = crate::memory::ChangeBudget::new(crate::memory::TIDY_MAX_CHANGES);+ let tidy = ToolContext::new(&root, &store, &[]).with_memory_change_budget(Some(&budget));+ let main = ToolContext::new(&root, &store, &[]);+ async fn run(ctx: &ToolContext<'_>, args: serde_json::Value) -> String {+ let memory = lookup("memory").unwrap();+ super::execute_builtin(memory, &args, ctx).await.0+ }+ assert_eq!(run(&tidy, json!({"op": "view", "name": "tui"})).await, "TUI overview");+ assert_eq!(run(&tidy, json!({"op": "view", "name": "tui/"})).await, "- `tui/scroll` - Scroll fix");+ let e = run(&main, json!({"op": "edit", "name": "tui", "old": "overview", "new": "overview, edited"})).await;+ assert!(e.starts_with("Edited"), "{e}");+ for args in [+ json!({"op": "write", "name": "tui", "content": "Stale merge"}),+ json!({"op": "move", "name": "tui", "to": "tui-old"}),+ json!({"op": "delete", "name": "tui"}),+ ] {+ let r = run(&tidy, args.clone()).await;+ assert!(r.starts_with("ERROR") && r.contains("changed"), "{args}: {r}");+ }+ assert_eq!(std::fs::read_to_string(dir.join("tui.md")).unwrap(), "TUI overview, edited");+ assert_eq!(budget.used(), 0);+ // Viewed again, the tidy may change it.+ run(&tidy, json!({"op": "view", "name": "tui"})).await;+ assert!(run(&tidy, json!({"op": "delete", "name": "tui"})).await.starts_with("Deleted"));+ assert!(dir.join("tui/scroll.md").exists(), "the folder is untouched");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// An exact `edit` needs no fresh view, but it must not count as one: a+ /// tidy that viewed `A`, then edited it after the main agent added `B`,+ /// has still never seen `B`, so a whole-file change after that edit is+ /// refused until it views the note again.+ #[tokio::test]+ async fn a_tidy_edit_never_marks_unseen_content_as_seen() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let dir = store.join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("log.md"), "Log\n\nA\n").unwrap();+ let budget = crate::memory::ChangeBudget::new(crate::memory::TIDY_MAX_CHANGES);+ let tidy = ToolContext::new(&root, &store, &[]).with_memory_change_budget(Some(&budget));+ let main = ToolContext::new(&root, &store, &[]);+ async fn run(ctx: &ToolContext<'_>, args: serde_json::Value) -> String {+ let memory = lookup("memory").unwrap();+ super::execute_builtin(memory, &args, ctx).await.0+ }+ run(&tidy, json!({"op": "view", "name": "log"})).await;+ let e = run(&main, json!({"op": "edit", "name": "log", "old": "A\n", "new": "A\nB\n"})).await;+ assert!(e.starts_with("Edited"), "{e}");+ let e = run(&tidy, json!({"op": "edit", "name": "log", "old": "A\n", "new": "A2\n"})).await;+ assert!(e.starts_with("Edited"), "{e}");+ for args in [+ json!({"op": "delete", "name": "log"}),+ json!({"op": "write", "name": "log", "content": "Log\n\nA2\n"}),+ json!({"op": "move", "name": "log", "to": "old-log"}),+ ] {+ let r = run(&tidy, args.clone()).await;+ assert!(r.starts_with("ERROR") && r.contains("changed"), "{args}: {r}");+ }+ assert_eq!(std::fs::read_to_string(dir.join("log.md")).unwrap(), "Log\n\nA2\nB\n");+ // A tidy that was up to date when it edited stays up to date.+ run(&tidy, json!({"op": "view", "name": "log"})).await;+ run(&tidy, json!({"op": "edit", "name": "log", "old": "A2", "new": "A3"})).await;+ assert!(run(&tidy, json!({"op": "delete", "name": "log"})).await.starts_with("Deleted"));+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Without a budget (the main agent) nothing is capped, and `move` works.+ #[tokio::test]+ async fn the_main_agent_moves_notes_uncapped() {+ let root = unique_root();+ let memory = lookup("memory").unwrap();+ for i in 0..40 {+ let w = execute_builtin(memory, &json!({"op": "write", "name": format!("n{i}"), "content": "x"}), &root).await;+ assert!(w.starts_with("Wrote"), "{w}");+ }+ let m = execute_builtin(memory, &json!({"op": "move", "name": "n1", "to": "grp/n1"}), &root).await;+ assert!(m.starts_with("Moved"), "{m}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn the_memory_tool_runs_every_op() {+ let root = unique_root();+ let memory = lookup("memory").unwrap();+ let run = |args: serde_json::Value| {+ let root = root.clone();+ async move { execute_builtin(memory, &args, &root).await }+ };+ let w = run(json!({"op": "write", "name": "drift", "title": "Drift", "content": "553 behind"})).await;assert!(w.starts_with("Wrote"), "unexpected: {w}");- // Landed at the canonical workspace path.+ // Landed at the canonical workspace path, title first.assert_eq!(std::fs::read_to_string(crate::workspace::project_store(&root).join("memory/drift.md")).unwrap(),- "553 behind"+ "Drift\n\n553 behind");-- let r = execute_builtin(- lookup("memory_read").unwrap(),- &json!({"name": "drift"}),- &root,- )- .await;- assert_eq!(r, "553 behind");-- let l = execute_builtin(lookup("memory_list").unwrap(), &json!({}), &root).await;- assert_eq!(l, "drift");+ assert_eq!(run(json!({"op": "view", "name": "drift"})).await, "Drift\n\n553 behind");+ assert!(run(json!({"op": "view"})).await.contains("- `drift` - Drift"));+ assert!(run(json!({"op": "search", "query": "553"})).await.contains("`drift`"));+ assert!(run(json!({"op": "edit", "name": "drift", "old": "553", "new": "554"})).await.starts_with("Edited"));+ assert!(run(json!({"op": "view", "name": "drift"})).await.ends_with("554 behind"));+ assert!(run(json!({"op": "delete", "name": "drift"})).await.starts_with("Deleted"));+ assert!(run(json!({"op": "view", "name": "drift"})).await.starts_with("ERROR"));+ assert!(run(json!({"op": "write", "name": "x"})).await.contains("'content'"));+ assert!(run(json!({"op": "rename"})).await.contains("unknown memory op"));+ assert!(run(json!({"op": "rename"})).await.contains("move"));+ assert!(run(json!({})).await.contains("'op'"));let _ = std::fs::remove_dir_all(&root);}@@ -4368,10 +4831,10 @@ mod tests {#[tokio::test]async fn workspace_name_rejects_traversal() {let root = unique_root();- for bad in ["../escape", "sub/x", "..", ""] {+ for bad in ["../escape", "a/b/c", "..", ""] {let out = execute_builtin(- lookup("memory_write").unwrap(),- &json!({"name": bad, "content": "x"}),+ lookup("memory").unwrap(),+ &json!({"op": "write", "name": bad, "content": "x"}),&root,).await;diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rsindex 802b3cd2e..256d45523 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs@@ -168,9 +168,11 @@ impl Hook {// An unparseable matcher cannot reach here: `HookSet::extend_from`// drops such an entry with a notice rather than letting it match// nothing forever.- glob::Pattern::new(&self.matcher)+ let matched = glob::Pattern::new(&self.matcher).map(|p| p.matches(tool_name))- .unwrap_or(false)+ .unwrap_or(false);+ // A matcher on the old memory tools guards the one that replaced them.+ matched || (tool_name == super::MEMORY_TOOL && super::names_legacy_memory(&self.matcher))}}@@ -202,9 +204,10 @@ pub struct HookSet {/// swallowed, because a hook that silently does not fire is worse than one/// that complains -- the user believes their policy is in force.load_notices: Vec<String>,- /// The subset of `load_notices` from [`super::renamed_shell_notice`].+ /// The subset of `load_notices` from [`super::renamed_tool_notice`],+ /// each with the current name of the tool its matcher meant.#[serde(skip)]- renamed_shell_notices: Vec<String>,+ renamed_notices: Vec<(&'static str, String)>,}impl HookSet {@@ -230,11 +233,16 @@ impl HookSet {&self.load_notices}- /// The load notices for matchers that still name the shell tool's old- /// name `bash`. Kept apart so a surface with no run start (the desktop's- /// per-call command) can put them on the shell call they no longer guard.- pub fn renamed_shell_notices(&self) -> &[String] {- &self.renamed_shell_notices+ /// The load notices for matchers that still name `tool` by an old name+ /// (`bash` for the shell, `memory_*` for memory). Kept apart so a surface+ /// with no run start (the desktop's per-call command) can put them on the+ /// call of the tool they meant.+ pub fn renamed_notices(&self, tool: &str) -> Vec<&str> {+ self.renamed_notices+ .iter()+ .filter(|(t, _)| *t == tool)+ .map(|(_, notice)| notice.as_str())+ .collect()}/// Append entries from one source, skipping any whose event name is not@@ -276,11 +284,17 @@ impl HookSet {));continue;}- // Kept as written, so it starts matching the moment it is renamed,- // but said out loud: a guard hook on `bash` no longer fires.+ // Kept as written and said out loud: a guard hook on `bash` no+ // longer fires, and one on an old memory name now guards every+ // `memory` op (see `Hook::matches`).let hook_where = format!("Hook {} matcher in {where_}", event.as_str());- if let Some(notice) = super::renamed_shell_notice(&matcher, &hook_where) {- self.renamed_shell_notices.push(notice.clone());+ if let Some(notice) = super::renamed_tool_notice(&matcher, &hook_where) {+ let tool = if super::names_legacy_memory(&matcher) {+ super::MEMORY_TOOL+ } else {+ super::SHELL_TOOL+ };+ self.renamed_notices.push((tool, notice.clone()));self.load_notices.push(notice);}self.hooks.push(Hook {@@ -697,7 +711,7 @@ mod tests {let matched = set.matching(HookEvent::PreToolUse, Some("edit"));assert_eq!(matched.len(), 1);assert_eq!(matched[0].command, "a");- let matched = set.matching(HookEvent::PreToolUse, Some("memory_write"));+ let matched = set.matching(HookEvent::PreToolUse, Some("skill_write"));assert_eq!(matched.len(), 1);assert_eq!(matched[0].command, "b");}@@ -718,10 +732,35 @@ mod tests {let notice = &set.load_notices()[0];assert!(notice.contains("PreToolUse matcher in hooks.json"), "{notice}");assert!(notice.contains("now `shell`"), "{notice}");- assert_eq!(set.renamed_shell_notices(), set.load_notices());+ let notices: Vec<&str> = set.load_notices().iter().map(String::as_str).collect();+ assert_eq!(set.renamed_notices("shell"), notices);assert_eq!(set.matching(HookEvent::PreToolUse, Some("shell")).len(), 1);}+ /// A matcher on an old memory tool name guards the `memory` tool, and is+ /// reported so the user renames it.+ #[test]+ fn an_old_memory_matcher_guards_the_memory_tool_and_is_reported() {+ let mut set = HookSet::new();+ set.extend_from(+ vec![+ entry("PreToolUse", Some("memory_write"), "guard"),+ entry("PostToolUse", Some("*write*"), "log"),+ entry("PostToolUse", Some("web_*"), "net"),+ ],+ Path::new("hooks.json"),+ );+ assert_eq!(set.matching(HookEvent::PreToolUse, Some("memory")).len(), 1);+ // A broad guard that caught `memory_write` keeps firing for memory.+ assert_eq!(set.matching(HookEvent::PostToolUse, Some("memory")).len(), 1);+ assert_eq!(set.load_notices().len(), 2, "{:?}", set.load_notices());+ let notice = &set.load_notices()[0];+ assert!(notice.contains("PreToolUse matcher in hooks.json names `memory_write`"), "{notice}");+ assert!(set.load_notices()[1].contains("`*write*`, which matched"), "{:?}", set.load_notices());+ assert_eq!(set.renamed_notices("memory").len(), 2);+ assert!(set.renamed_notices("shell").is_empty());+ }+#[test]fn merge_order_is_the_order_sources_were_added() {let mut set = HookSet::new();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 b3329325e..2bb180707 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@@ -97,13 +97,17 @@ pub struct ToolContext<'a> {/// the target of `skill_write` with `scope: "user"`. `None` on surfaces/// with no user scope, where that scope is refused.pub skill_user_root: Option<&'a Path>,- /// `~/.jan`, reached by the `memory_*` tools as the `user:` scope and as+ /// `~/.jan`, reached by the `memory` tool 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,+ /// The cap on memory mutations for this run: set only for Jan's memory+ /// tidy subagent, so a tidy that misjudges the store is bounded by the+ /// harness rather than by its prompt. `None` leaves memory uncapped.+ pub memory_change_budget: Option<&'a crate::memory::ChangeBudget>,pub enabled_skills: &'a [String],pub allow_network: bool,/// When set, `write`/`edit` re-canonicalize the target and refuse a path@@ -390,6 +394,7 @@ impl<'a> ToolContext<'a> {skill_user_root: None,memory_home: None,cross_project: false,+ memory_change_budget: None,enabled_skills,allow_network: false,confine_writes: false,@@ -500,7 +505,7 @@ impl<'a> ToolContext<'a> {self}- /// Give the `memory_*` tools the user scope and, when `cross_project`, the+ /// Give the `memory` tool 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);@@ -508,7 +513,16 @@ impl<'a> ToolContext<'a> {self}- /// The memory scopes this context's `memory_*` tools resolve names in.+ /// Cap this context's memory mutations (see [`Self::memory_change_budget`]).+ pub fn with_memory_change_budget(+ mut self,+ budget: Option<&'a crate::memory::ChangeBudget>,+ ) -> Self {+ self.memory_change_budget = budget;+ self+ }++ /// The memory scopes this context's `memory` tool resolves names in.pub fn memory_scopes(&self) -> crate::memory::Scopes<'a> {crate::memory::Scopes {store: self.store_root,@@ -689,21 +703,17 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[// 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.+ // One `memory` tool with an `op` (view/search/write/edit/delete/move). Classed+ // `Read` so plan mode keeps its reads and the parallel read path takes it: it+ // writes only the agent's own notes, which the user does not manage+ // (janhq/jan-internal#497). Plan mode's refusal of the changing ops is per+ // op, in the handler, which also serializes those ops on a per-store lock+ // so a parallel batch cannot lose one of two edits to a note.BuiltinTool {- name: "memory_list",- capability: Capability::Read,- path_args: &[],- },- BuiltinTool {- name: "memory_read",+ name: MEMORY_TOOL,capability: Capability::Read,path_args: &[],},- BuiltinTool {- name: "memory_write",- capability: Capability::Write,- path_args: &[],- },BuiltinTool {name: "skill_list",capability: Capability::Read,@@ -740,15 +750,16 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[pub fn is_workspace_tool(name: &str) -> bool {matches!(name,- "memory_list"- | "memory_read"- | "memory_write"- | "skill_list"+ MEMORY_TOOL | "skill_list"| "skill_read"| "skill_write")}+/// The single memory tool's name. Agent memory is the agent's to curate, so no+/// op on it ever prompts.+pub const MEMORY_TOOL: &str = "memory";+/// The shell tool's name. Not `bash`: on Windows it runs PowerShell or cmd/// (janhq/jan#9128).pub const SHELL_TOOL: &str = "shell";@@ -768,6 +779,46 @@ pub fn renamed_shell_notice(name: &str, where_: &str) -> Option<String> {})}+/// The memory tools' names before they became the one [`MEMORY_TOOL`].+const LEGACY_MEMORY_TOOLS: [&str; 3] = ["memory_write", "memory_read", "memory_list"];++/// Whether a user-written tool name or glob covered the old memory tools: it+/// matches one of their names (any case) but not `memory` itself. Unlike+/// `bash`, such an entry is carried over to `memory` -- a deny on+/// `memory_write` that stopped matching would hand the agent every op it used+/// to refuse -- and the whole tool is meant, since one tool now does what the+/// three did. That includes a broad glob such as `*write*`: a user who denied+/// every write with it would otherwise lose memory's coverage silently.+pub fn names_legacy_memory(pattern: &str) -> bool {+ let lower = pattern.trim().to_ascii_lowercase();+ glob::Pattern::new(&lower).is_ok_and(|p| {+ !p.matches(MEMORY_TOOL) && LEGACY_MEMORY_TOOLS.iter().any(|name| p.matches(name))+ })+}++/// The notice for a user-written tool name or pattern that names a tool by a+/// name it no longer has: the shell's `bash` (which now matches nothing) or an+/// old memory tool (which now applies to all of `memory`). Reported once, at+/// load. `where_` names the setting, e.g. "[tools] deny".+pub fn renamed_tool_notice(name: &str, where_: &str) -> Option<String> {+ renamed_shell_notice(name, where_).or_else(|| {+ names_legacy_memory(name).then(|| {+ let name = name.trim();+ if name.to_ascii_lowercase().starts_with("memory_") {+ format!(+ "{where_} names `{name}`, an old memory tool name: it now applies to the \+ whole `{MEMORY_TOOL}` tool (every op). Rename it to `{MEMORY_TOOL}`."+ )+ } else {+ format!(+ "{where_} has `{name}`, which matched an old memory tool name: it now \+ also applies to the whole `{MEMORY_TOOL}` tool (every op)."+ )+ }+ })+ })+}+pub fn lookup(name: &str) -> Option<&'static BuiltinTool> {BUILTIN_TOOLS.iter().find(|t| t.name == name)}@@ -811,6 +862,29 @@ mod tests {}}+ /// A pattern that meant the old memory tools maps to `memory`; one that+ /// already matches `memory`, or never named memory, does not.+ #[test]+ fn old_memory_tool_names_map_to_memory_and_are_reported() {+ for old in ["memory_write", "memory_read", "memory_list", "Memory_Write", "memory_*", " memory_read "] {+ assert!(names_legacy_memory(old), "{old}");+ let notice = renamed_tool_notice(old, "[tools] deny").expect("flagged");+ assert!(notice.contains(&format!("[tools] deny names `{}`", old.trim())), "{notice}");+ assert!(notice.contains("`memory`"), "{notice}");+ }+ // A broad glob that caught an old name keeps covering memory, and says so.+ for broad in ["*write*", "*_read", "*_LIST"] {+ assert!(names_legacy_memory(broad), "{broad}");+ let notice = renamed_tool_notice(broad, "[tools] deny").expect("flagged");+ assert!(notice.contains(&format!("`{broad}`, which matched")), "{notice}");+ }+ for other in ["memory", "memory*", "*", "skill_write", "mcp__x__memory_write", "read"] {+ assert!(!names_legacy_memory(other), "{other}");+ assert!(renamed_tool_notice(other, "x").is_none(), "{other}");+ }+ assert!(renamed_tool_notice("bash", "x").expect("shell").contains("now `shell`"));+ }+#[test]fn unknown_is_not_builtin() {assert!(lookup("nope").is_none());@@ -819,10 +893,10 @@ mod tests {#[test]fn builtin_count_matches_expected() {- // 8 coding tools + 6 dedicated skill/memory tools + 2 native web tools.+ // 8 coding tools + 3 skill tools + 1 memory tool + 2 native web tools.// `screenshot` (one of the coding tools) is desktop-only, so the headless// CLI build (`feature = "tauri"` off) has one fewer.- let expected = if cfg!(feature = "tauri") { 16 } else { 15 };+ let expected = if cfg!(feature = "tauri") { 14 } else { 13 };assert_eq!(BUILTIN_TOOLS.len(), expected);}@@ -838,7 +912,10 @@ mod tests {#[test]fn workspace_tools_are_classified() {- assert!(is_workspace_tool("memory_write"));+ assert!(is_workspace_tool("memory"));+ for gone in ["memory_list", "memory_read", "memory_write"] {+ assert!(lookup(gone).is_none(), "{gone} has no alias");+ }assert!(is_workspace_tool("skill_list"));assert!(!is_workspace_tool("write"));assert!(!is_workspace_tool("shell"));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 23a2495cd..daf261a47 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@@ -9,6 +9,10 @@use serde_json::{json, Value};+/// The `memory` tool's description: what it is for and the reconcile rule that+/// keeps the index small (janhq/jan-internal#497).+const MEMORY_DESCRIPTION: &str = "Your long-term memory: durable facts (decisions, conventions, preferences, gotchas) kept across sessions. It is yours to curate; no op asks the user. Before writing, `search` or `view` for an existing note on the topic and update it (`edit`, or `write` over it) rather than adding another. When a new fact supersedes a note, `delete` the old one. When work a note tracks is finished, archive it by adding front matter `status: done` (it stays readable and searchable but leaves the index). Group related notes in a folder with `move` (`name` to `tui/scroll`); never write an index or overview note, the index is built for you. Keep notes short; never store secrets or session-only state.";+/// The `bash` tool's description before any shell-specific note.const BASH_DESCRIPTION: &str = "Run a shell command in the project root. Returns combined stdout and stderr, followed by a final `[exit N]` line (or `[terminated by signal]`). Judge success by that exit code, not by whether there is text on stderr: many commands (e.g. `git push`) write normal status to stderr on success, so `[exit 0]` means it worked. The output is COMPLETE and verbatim: trust it and do not re-run a command to double-check. It is truncated only when it exceeds 2000 lines or 64KB, and only then is an explicit `[output truncated ...]` notice appended with a temp-file path holding the full output; when truncated the LAST lines are kept (so the final result and errors stay visible). Absent that notice, you have the full output.";@@ -154,37 +158,21 @@ pub fn builtin_tool_schemas() -> Vec<Value> {json!({"type": "function","function": {- "name": "memory_list",- "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": [] }- }- }),- json!({- "type": "function",- "function": {- "name": "memory_read",- "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), optionally scoped with `user:` or `project:<slug>/`." }- },- "required": ["name"]- }- }- }),- json!({- "type": "function",- "function": {- "name": "memory_write",- "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).",+ "name": super::MEMORY_TOOL,+ "description": MEMORY_DESCRIPTION,"parameters": {"type": "object","properties": {- "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." }+ "op": { "type": "string", "enum": ["view", "search", "write", "edit", "delete", "move"], "description": "view: the index (no name), a folder's notes (`folder/`), or a note's content. search: keyword search over titles and bodies, archived notes included. write: create or overwrite. edit: replace one exact, unique `old` with `new`. delete: remove a note. move: rename `name` to `to` (e.g. into a folder), keeping its content." },+ "name": { "type": "string", "description": "Note name without .md: `note` or `folder/note` (this project), `user:note` (every project), `project:<slug>` or `project:<slug>/note` (another project, read-only). Required for write, edit, delete and move. `index` and `MEMORY` are reserved: the index is built for you." },+ "to": { "type": "string", "description": "move: the new name, `note` or `folder/note`; must not exist yet." },+ "query": { "type": "string", "description": "search: words that must all appear in the note." },+ "title": { "type": "string", "description": "write: one-line title, stored as the note's first line and shown in the index." },+ "content": { "type": "string", "description": "write: the note's Markdown body. Front matter `status: done` archives it." },+ "old": { "type": "string", "description": "edit: exact text to replace; must occur exactly once." },+ "new": { "type": "string", "description": "edit: replacement text." }},- "required": ["name", "content"]+ "required": ["op"]}}}),@@ -408,6 +396,28 @@ mod tests {assert_eq!(once, twice);}+ /// One `memory` tool carries every op and the reconcile rule; the three+ /// old tools are gone with no aliases.+ #[test]+ fn memory_is_one_tool_with_six_ops_and_the_reconcile_rule() {+ let schemas = builtin_tool_schemas();+ let names: Vec<&str> = schemas.iter().filter_map(|s| s["function"]["name"].as_str()).collect();+ assert!(names.contains(&"memory"));+ assert!(!names.iter().any(|n| n.starts_with("memory_")), "{names:?}");+ let memory = schemas.iter().find(|s| s["function"]["name"] == "memory").unwrap();+ let params = &memory["function"]["parameters"];+ assert_eq!(params["required"], json!(["op"]));+ assert_eq!(+ params["properties"]["op"]["enum"],+ json!(["view", "search", "write", "edit", "delete", "move"])+ );+ assert!(params["properties"]["to"].is_object(), "move takes `to`");+ let description = memory["function"]["description"].as_str().unwrap();+ for rule in ["`search` or `view`", "`delete` the old one", "`status: done`", "no op asks the user"] {+ assert!(description.contains(rule), "{rule}: {description}");+ }+ }+/// A PowerShell or cmd host says so before the generic text, so the model/// reads it before writing a command; a POSIX host is unchanged.#[test]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex 931db886f..079b880cf 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -742,7 +742,7 @@ async fn sweep_workspaces_in(dir: PathBuf, keep: &[String]) -> Result<usize, Str/// Names Windows maps to a device in every directory, in any case and also/// with an extension (`nul.txt`). Checked on every OS so an id accepted on one/// works on all of them.-fn is_windows_device_name(name: &str) -> bool {+pub(crate) fn is_windows_device_name(name: &str) -> bool {let stem = name.split('.').next().unwrap_or(name).to_ascii_uppercase();match stem.as_bytes() {[a, b, c] => matches!(&[*a, *b, *c], b"CON" | b"PRN" | b"AUX" | b"NUL"),diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.mdindex f150ee41e..f50e6daed 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md@@ -19,6 +19,8 @@ Default permissions for the llamacpp plugin- `allow-engine-devices`- `allow-force-stop-engine`- `allow-engine-slots-idle`+- `allow-begin-engine-restart`+- `allow-end-engine-restart`- `allow-erase-thread-slot-state`- `allow-read-gguf-metadata`- `allow-find-gguf-tensors`@@ -33,6 +35,32 @@ Default permissions for the llamacpp plugin</tr>+<tr>+<td>++`llamacpp:allow-begin-engine-restart`++</td>+<td>++Enables the begin_engine_restart command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-begin-engine-restart`++</td>+<td>++Denies the begin_engine_restart command without any pre-configured scope.++</td>+</tr>+<tr><td>@@ -62,6 +90,32 @@ Denies the cleanup_llama_processes command without any pre-configured scope.<tr><td>+`llamacpp:allow-end-engine-restart`++</td>+<td>++Enables the end_engine_restart command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-end-engine-restart`++</td>+<td>++Denies the end_engine_restart command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-engine-devices`</td>diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.jsonindex 6f44e6164..5b48f185a 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json@@ -294,6 +294,18 @@"PermissionKind": {"type": "string","oneOf": [+ {+ "description": "Enables the begin_engine_restart command without any pre-configured scope.",+ "type": "string",+ "const": "allow-begin-engine-restart",+ "markdownDescription": "Enables the begin_engine_restart command without any pre-configured scope."+ },+ {+ "description": "Denies the begin_engine_restart command without any pre-configured scope.",+ "type": "string",+ "const": "deny-begin-engine-restart",+ "markdownDescription": "Denies the begin_engine_restart command without any pre-configured scope."+ },{"description": "Enables the cleanup_llama_processes command without any pre-configured scope.","type": "string",@@ -306,6 +318,18 @@"const": "deny-cleanup-llama-processes","markdownDescription": "Denies the cleanup_llama_processes command without any pre-configured scope."},+ {+ "description": "Enables the end_engine_restart command without any pre-configured scope.",+ "type": "string",+ "const": "allow-end-engine-restart",+ "markdownDescription": "Enables the end_engine_restart command without any pre-configured scope."+ },+ {+ "description": "Denies the end_engine_restart command without any pre-configured scope.",+ "type": "string",+ "const": "deny-end-engine-restart",+ "markdownDescription": "Denies the end_engine_restart command without any pre-configured scope."+ },{"description": "Enables the engine_devices command without any pre-configured scope.","type": "string",@@ -523,10 +547,10 @@"markdownDescription": "Denies the unload_llama_model command without any pre-configured scope."},{- "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`",+ "description": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-begin-engine-restart`\n- `allow-end-engine-restart`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`","type": "string","const": "default",- "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`"+ "markdownDescription": "Default permissions for the llamacpp plugin\n#### This default permission set includes:\n\n- `allow-cleanup-llama-processes`\n- `allow-load-llama-model`\n- `allow-unload-llama-model`\n- `allow-generate-api-key`\n- `allow-ensure-session-ready`\n- `allow-find-session-by-model`\n- `allow-get-loaded-models`\n- `allow-start-engine`\n- `allow-stop-engine`\n- `allow-get-engine-info`\n- `allow-get-engine-version`\n- `allow-reload-engine-models`\n- `allow-engine-devices`\n- `allow-force-stop-engine`\n- `allow-engine-slots-idle`\n- `allow-begin-engine-restart`\n- `allow-end-engine-restart`\n- `allow-erase-thread-slot-state`\n- `allow-read-gguf-metadata`\n- `allow-find-gguf-tensors`\n- `allow-is-model-supported`"}]}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 952f4ee1b..9a613e9a2 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -8,6 +8,7 @@//! placement, so "who writes above the cache line" is answered by config and by//! one exhaustive match rather than by whoever edited the builder last.+use std::collections::BTreeMap;use std::path::Path;use crate::core::agent::prompt::{Composer, Placement, PromptPolicy};@@ -246,7 +247,9 @@ other agent fits. Dispatch independent subagents in parallel when \their work doesn't depend on each other; each returns in the background and a note carries its answer when \it finishes. Once you delegate a task it belongs to that subagent -- do not do the same work yourself; \spend the wait on other steps, and only `await_subagent` when nothing else is left to do. Do inline work \-yourself for small, targeted tasks where delegating would cost more than it saves.";+yourself for small, targeted tasks where delegating would cost more than it saves. Subagents have no \+memory: no memory tool and no memory index. Put any fact from your memory that a subagent needs into its \+task, and record anything worth keeping from its answer yourself.";/// The `# Subagents` block: the guide, then the predefined agents the/// `dispatch_subagent` `agent` enum accepts, each with its model and purpose.@@ -341,7 +344,7 @@ Shell: `{shell}`{shell_note}{scratch_line}"}/// 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+/// view a note on demand with the `memory` tool: 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@@ -356,6 +359,99 @@ pub(crate) fn load_memory_catalog(project_root: &Path) -> Option<String> {.prompt_block()}+/// A content hash per writable note (this project's and the user's), read now.+fn memory_fingerprint(project_root: &Path) -> BTreeMap<String, u64> {+ let (store, home, cross_project) = crate::core::agent::project::memory_roots(project_root);+ memory::Scopes {+ store: &store,+ home: home.as_deref(),+ cross_project,+ }+ .fingerprint()+}++/// Most names the changes block spells out before it only counts the rest, so+/// a tidy that touched hundreds of notes cannot flood the tail.+const MAX_CHANGED_NAMES: usize = 20;++/// The memory index as the session started with it, and a fingerprint of the+/// notes it was rendered from.+///+/// The index sits above the cache line, so it is taken once per session rather+/// than per run: a note written mid-session would otherwise change the system+/// prompt, and a changed prompt is appended as a whole new system message+/// (`upstream::set_system_prompt`), resending every byte of it. What changed+/// since the snapshot is reported below the history instead (see+/// [`MemorySnapshot::changes_block`]). Refreshed only where the conversation+/// starts over anyway: `/new`, `/clear`, `/resume`, and after a compaction. A+/// fork continues its source session and keeps the source's snapshot.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct MemorySnapshot {+ block: Option<String>,+ fingerprint: BTreeMap<String, u64>,+}++impl MemorySnapshot {+ /// Render the index and fingerprint the notes of `project_root` now.+ ///+ /// Session start is also where a store written by an older Jan is brought+ /// to the titled format, once (a marker file makes later calls free), so+ /// the first index a session shows is already archived and titled.+ pub(crate) fn capture(project_root: &Path) -> Self {+ let (store, home, _) = crate::core::agent::project::memory_roots(project_root);+ memory::migrate(&store);+ if let Some(home) = home.as_deref() {+ memory::migrate(home);+ }+ Self {+ block: load_memory_catalog(project_root),+ fingerprint: memory_fingerprint(project_root),+ }+ }++ /// The memory section as the session's system prompt carries it.+ pub(crate) fn block(&self) -> Option<&str> {+ self.block.as_deref()+ }++ /// The `# Memory Changes` tail block: every note added (`+`), changed+ /// (`~`) or deleted (`-`) since the snapshot, by this run or any other+ /// (the tidy subagent, another session). `None` when nothing changed.+ pub(crate) fn changes_block(&self, project_root: &Path) -> Option<String> {+ memory_changes(&self.fingerprint, &memory_fingerprint(project_root))+ }+}++fn memory_changes(+ before: &BTreeMap<String, u64>,+ after: &BTreeMap<String, u64>,+) -> Option<String> {+ let mut changes: Vec<String> = Vec::new();+ for (name, hash) in after {+ match before.get(name) {+ None => changes.push(format!("+ {name}")),+ Some(old) if old != hash => changes.push(format!("~ {name}")),+ Some(_) => {}+ }+ }+ for name in before.keys().filter(|name| !after.contains_key(*name)) {+ changes.push(format!("- {name}"));+ }+ if changes.is_empty() {+ return None;+ }+ let total = changes.len();+ changes.truncate(MAX_CHANGED_NAMES);+ let more = match total - changes.len() {+ 0 => String::new(),+ n => format!(", and {n} more"),+ };+ Some(format!(+ "# Memory Changes\n\nMemory changes this session: {}{more}\nThe memory index in your system prompt is the session-start snapshot; read a changed note by name for its current content.",+ changes.join(", ")+ ))+}+/// Everything the prompt-block composers read.struct CompositionInputs<'a> {base: Option<&'a str>,@@ -363,6 +459,31 @@ struct CompositionInputs<'a> {scratch: Option<&'a Path>,subagents_enabled: bool,session_start: Option<&'a SessionStart>,+ memory: bool,+}++/// The skill/memory guide for a run that has memory, or only its skills half+/// for one that does not (a subagent): no memory instructions for a tool the+/// run was not given.+fn skill_guide(memory: bool) -> String {+ skill_guide_from(DEFAULT_SKILL_GUIDE, memory)+}++/// [`skill_guide`] over a given guide text. Line endings are normalized first:+/// a Windows checkout with `core.autocrlf` hands `include_str!` CRLF, and the+/// section split and heading swap below match on `\n`.+fn skill_guide_from(raw: &str, memory: bool) -> String {+ let normalized = raw.replace("\r\n", "\n");+ let guide = normalized.trim();+ if memory {+ return guide.to_string();+ }+ let skills = guide.split("\n## Memory").next().unwrap_or(guide).trim_end();+ skills.replacen(+ "# Skills and Project Memory\n\nYou are running as a project agent. This project keeps two kinds of durable\nnotes that you maintain: skills (reusable procedures) and memory (durable\nfacts). Manage both with the dedicated tools below. Do NOT use `shell`, `cat`,\n`ls`, or raw file paths for skills or memory; the tools handle location and\nnaming for you.",+ "# Skills\n\nYou are running as a project agent. Use the dedicated skill tools below; do NOT use\n`shell`, `cat`, `ls`, or raw file paths for skills. Memory belongs to the agent that\ndispatched you: anything you need from earlier sessions is in your task.",+ 1,+ )}/// The date and git branch a session started with, taken once and then carried@@ -377,14 +498,18 @@ struct CompositionInputs<'a> {pub(crate) struct SessionStart {date: String,branch: Option<String>,+ /// The memory index the session started with. `None` with no project, and+ /// in a fixed test snapshot, where the index is read live instead.+ memory: Option<MemorySnapshot>,}impl SessionStart {- /// Read the clock and `project_root`'s checkout now.+ /// Read the clock, `project_root`'s checkout and its memory now.pub(crate) fn capture(project_root: Option<&Path>) -> Self {Self {date: chrono::Local::now().format("%Y-%m-%d").to_string(),branch: project_root.and_then(crate::core::agent::git::current_branch),+ memory: project_root.map(MemorySnapshot::capture),}}@@ -393,6 +518,23 @@ impl SessionStart {Self {date: date.to_string(),branch: branch.map(str::to_string),+ memory: None,+ }+ }++ /// The session's memory snapshot, when it took one.+ pub(crate) fn memory(&self) -> Option<&MemorySnapshot> {+ self.memory.as_ref()+ }++ /// Re-take only the memory snapshot, keeping the date and branch: for a+ /// compaction, which starts the history over but not the session. The+ /// TUI is the only caller that compacts a session it keeps.+ #[cfg(feature = "cli")]+ pub(crate) fn with_fresh_memory(&self, project_root: &Path) -> Self {+ Self {+ memory: Some(MemorySnapshot::capture(project_root)),+ ..self.clone()}}@@ -453,15 +595,22 @@ fn render(composer: Composer, inputs: &CompositionInputs) -> Option<String> {}Composer::SessionStart => inputs.session_start.map(SessionStart::block),Composer::SubagentGuide => inputs.subagents_enabled.then(|| subagent_guide(inputs.project_root)),- Composer::SkillGuide => Some(DEFAULT_SKILL_GUIDE.trim().to_string()),+ Composer::SkillGuide => Some(skill_guide(inputs.memory)),Composer::WebToolsGuide => Some(WEB_TOOLS_GUIDE.to_string()),Composer::ProjectContext => load_context_files(inputs.project_root),Composer::Skills => load_skills(inputs.project_root),- Composer::MemoryCatalog => load_memory_catalog(inputs.project_root),+ // The session's snapshot when it has one, so a note written mid-session+ // never rewrites the prompt; read live only for a run with no session.+ Composer::MemoryCatalog if !inputs.memory => None,+ Composer::MemoryCatalog => match inputs.session_start.and_then(SessionStart::memory) {+ Some(snapshot) => snapshot.block().map(str::to_string),+ None => load_memory_catalog(inputs.project_root),+ },// Built where the request is assembled, because they need state the// composition has no access to: the tool array is a request field, and- // the last three read per-turn state (a query, the todo registry).+ // the rest read per-turn state (a query, the notes, the todo registry).Composer::ToolSchemas+ | Composer::MemoryChanges| Composer::MemoryRecall| Composer::PlanAddendum| Composer::TodoAddendum => None,@@ -477,6 +626,10 @@ fn render(composer: Composer, inputs: &CompositionInputs) -> Option<String> {/// fails the run instead of quietly costing a cache miss per turn. Blocks the/// policy sends to the tail are returned rather than dropped: they reach the/// model, just below the conversation instead of in front of it.+///+/// `memory` is false for a run that has no memory (a subagent): its prompt then+/// carries no memory index and no memory instructions.+#[allow(clippy::too_many_arguments)]pub(crate) fn compose_system_prompt(base: Option<&str>,project_root: &Path,@@ -484,6 +637,7 @@ pub(crate) fn compose_system_prompt(subagents_enabled: bool,policy: &PromptPolicy,session_start: Option<&SessionStart>,+ memory: bool,) -> Result<ComposedPrompt, String> {let inputs = CompositionInputs {base,@@ -491,6 +645,7 @@ pub(crate) fn compose_system_prompt(scratch,subagents_enabled,session_start,+ memory,};policy.validate()?;let mut prefix: Vec<String> = Vec::new();@@ -533,6 +688,7 @@ mod tests {subagents_enabled,&PromptPolicy::default(),None,+ true,).ok().map(|composed| composed.as_prompt())@@ -616,13 +772,88 @@ mod tests {assert!(block.contains("- `decisions` - We use Yarn not npm."));assert!(block.contains("- `prefs` - Keep it minimal."));// Progressive disclosure: only the first line is advertised; the rest- // of the body stays out until memory_read.+ // of the body stays out until it is viewed.assert!(!block.contains("SECRET_BODY_MARKER"));- assert!(block.contains("memory_read"));+ assert!(block.contains("`memory` op `view`"));assert!(!block.contains("ignored.txt"));let _ = std::fs::remove_dir_all(&root);}+ /// A CRLF checkout (Windows, `core.autocrlf`) strips the memory half of the+ /// guide exactly like an LF one: the split and heading swap match on `\n`.+ #[test]+ fn the_memoryless_skill_guide_ignores_line_endings() {+ // From an LF base: on a CRLF checkout the constant already has `\r\n`,+ // and replacing `\n` again would produce `\r\r\n`.+ let base = DEFAULT_SKILL_GUIDE.replace("\r\n", "\n");+ let lf = skill_guide_from(&base, false);+ let crlf = skill_guide_from(&base.replace('\n', "\r\n"), false);+ assert_eq!(lf, crlf);+ assert!(crlf.starts_with("# Skills\n"), "{crlf}");+ assert!(!crlf.contains("## Memory"), "{crlf}");+ assert!(!crlf.contains('\r'));+ }++ /// P0 of #497: a note written mid-session leaves the composed prompt+ /// byte-identical; the change is reported by the tail block instead.+ #[test]+ fn a_memory_write_mid_session_does_not_change_the_prompt() {+ let root = scratch_project("memsnapshot");+ write_memory(&root, "keep.md", "Kept.");+ write_memory(&root, "edit.md", "Before.");+ write_memory(&root, "gone.md", "Deleted later.");+ let start = SessionStart::capture(Some(&root));+ let compose = || {+ compose_system_prompt(None, &root, None, false, &PromptPolicy::default(), Some(&start), true)+ .unwrap()+ .prefix+ };+ let before = compose();+ assert!(before.contains("`gone`"), "{before}");+ let snapshot = start.memory().expect("a project session snapshots memory");+ assert_eq!(snapshot.changes_block(&root), None, "nothing changed yet");++ write_memory(&root, "new.md", "Added.");+ write_memory(&root, "edit.md", "After.");+ let dir = crate::core::agent::project::store_root(&root).join("memory");+ std::fs::remove_file(dir.join("gone.md")).unwrap();++ assert_eq!(compose(), before, "the prompt is the session-start snapshot");+ let changes = snapshot.changes_block(&root).expect("changes are reported");+ assert!(changes.starts_with("# Memory Changes"), "{changes}");+ assert!(+ changes.contains("Memory changes this session: ~ edit, + new, - gone"),+ "{changes}"+ );+ assert!(!changes.contains("keep"), "{changes}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn the_memory_changes_block_caps_the_names_it_lists() {+ let before = BTreeMap::new();+ let after: BTreeMap<String, u64> =+ (0..25).map(|i| (format!("n{i:02}"), 1)).collect();+ let block = memory_changes(&before, &after).unwrap();+ assert_eq!(block.matches("+ n").count(), MAX_CHANGED_NAMES);+ assert!(block.contains(", and 5 more"), "{block}");+ }++ /// After a compaction the session keeps its date and branch but takes a+ /// fresh memory index, so the tail stops repeating folded-in changes.+ #[test]+ #[cfg(feature = "cli")]+ fn a_fresh_memory_snapshot_keeps_the_date_and_branch() {+ let root = scratch_project("memrefresh");+ let start = SessionStart::capture(Some(&root));+ write_memory(&root, "later.md", "Written after the start.");+ let fresh = start.with_fresh_memory(&root);+ assert_eq!((fresh.date.as_str(), &fresh.branch), (start.date.as_str(), &start.branch));+ assert!(fresh.memory().unwrap().block().unwrap().contains("`later`"));+ assert_eq!(fresh.memory().unwrap().changes_block(&root), None);+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn memory_catalog_is_none_when_no_notes() {let root = scratch_project("memnone");@@ -693,7 +924,8 @@ mod tests {let out = default_prompt(None, &root, None, false).expect("guide always present");assert!(out.contains("Skills and Project Memory"));assert!(out.contains("skill_write"));- assert!(out.contains("memory_write"));+ assert!(out.contains("`memory` tool"));+ assert!(!out.contains("memory_write"), "the old tools are gone");// Base is preserved and precedes the guide.let with_base = default_prompt(Some("base"), &root, None, false).expect("prompt");@@ -1027,6 +1259,7 @@ mod tests {false,&PromptPolicy::default(),Some(&start),+ true,).expect("default policy");let block = "# Session Start\n\nSession start date: 2026-09-30\nStarting branch: `feat/x`";@@ -1052,6 +1285,7 @@ mod tests {false,&PromptPolicy::default(),Some(&start),+ true,).unwrap().prefix;@@ -1087,6 +1321,7 @@ mod tests {false,&PromptPolicy::default(),Some(&start),+ true,).unwrap().prefix@@ -1113,7 +1348,7 @@ mod tests {"guidelines".to_string(),]),);- let composed = compose_system_prompt(None, &root, None, false, &policy, None).expect("policy");+ let composed = compose_system_prompt(None, &root, None, false, &policy, None, true).expect("policy");assert!(composed.prefix.contains("# Guidelines"));assert!(@@ -1146,7 +1381,7 @@ mod tests {let root = scratch_project("varying");std::fs::create_dir_all(&root).unwrap();let policy = PromptPolicy::new(Placement::Tail, Some(vec!["memory_recall".to_string()]));- let error = compose_system_prompt(None, &root, None, false, &policy, None)+ let error = compose_system_prompt(None, &root, None, false, &policy, None, true).expect_err("a per-turn composer cannot be allowed into the prefix");assert!(error.contains("memory_recall"), "{error}");let _ = std::fs::remove_dir_all(&root);@@ -1159,7 +1394,7 @@ mod tests {let root = scratch_project("typo");std::fs::create_dir_all(&root).unwrap();let policy = PromptPolicy::new(Placement::Tail, Some(vec!["skils".to_string()]));- let error = compose_system_prompt(None, &root, None, false, &policy, None)+ let error = compose_system_prompt(None, &root, None, false, &policy, None, true).expect_err("an unknown id must not read as a policy");assert!(error.contains("skils"), "{error}");let _ = std::fs::remove_dir_all(&root);@@ -1173,7 +1408,7 @@ mod tests {let root = scratch_project("order");write_skill(&root, "s.md", "Do the thing.");std::fs::write(root.join("JAN.md"), "PROJECT_RULES").unwrap();- let composed = compose_system_prompt(None, &root, None, false, &PromptPolicy::default(), None)+ let composed = compose_system_prompt(None, &root, None, false, &PromptPolicy::default(), None, true).expect("default policy");// Every block the registry declares for the prefix is present, in thediff --git a/src-tauri/src/core/agent/default_skill.md b/src-tauri/src/core/agent/default_skill.mdindex 7d89494af..903ed0c80 100644--- a/src-tauri/src/core/agent/default_skill.md+++ b/src-tauri/src/core/agent/default_skill.md@@ -33,23 +33,36 @@ runs. Refine an existing skill instead of duplicating it.## Memory-Memory holds durable facts about this project that should outlive the current-session: decisions made, conventions agreed, user preferences, and context you-would otherwise forget.--- `memory_list` - see which memory notes exist.-- `memory_read` (name) - read a specific note.-- `memory_write` (name, content) - create or update a note (same name- overwrites). 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 facts-that become wrong by overwriting the note. Do not record transient details that-only matter to the current turn. The "Available Memories" section of your-system prompt is a catalog of these notes; call `memory_read` to load a note's-full contents when it is relevant to the current task.+Memory holds durable facts that should outlive the current session: decisions+made, conventions agreed, user preferences, and context you would otherwise+forget. It is yours to keep accurate; no memory operation asks the user.++Use the `memory` tool with an `op`:++- `view` - no name: the full index. `folder/`: that folder's notes. A note name:+ its content.+- `search` (query) - keyword search over titles and bodies, archived notes too.+- `write` (name, title, content) - create or overwrite a note; the title is its+ first line and what the index shows.+- `edit` (name, old, new) - replace one exact, unique piece of text.+- `delete` (name) - remove a note.+- `move` (name, to) - rename a note or move it into a folder, content and+ front matter kept.++Names are scoped. A plain `name` (or `folder/name`) is this project's note.+`user:name` is a user-wide note for personal preferences and conventions that+are not specific to this codebase. `project:<slug>` views another project's+index and `project:<slug>/name` one of its notes; those are read-only.++Keep memory small and current. Before writing, search for an existing note on+the topic and update it instead of adding another. Delete a note a new fact+supersedes. When work a note tracks is finished (a merged PR, a closed issue),+archive it with front matter `status: done`: it stays readable and searchable+but leaves the index. Group related notes in folders with `move`. Never write an+index or overview note: the index is built for you (`index` and `MEMORY` are+reserved names). Do not record transient+details that only matter to the current turn.++The "Available Memories" section of your system prompt is the index as it was+when this session started, titles only and capped in size; view a note by name+to load its content. Changes made since are listed in a "Memory Changes" block.diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 692605b3d..75a3f4b8b 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -435,10 +435,8 @@ fn classify_agent_path(path: &str) -> Option<(&'static str, String)> {pub fn describe_tool_call(name: &str, args: &serde_json::Value) -> String {// Dedicated skill/memory tools are self-describing via their name + `name` arg.let dedicated = match name {- "memory_list" => Some(("Reading", "memory", String::new())),+ "memory" => Some(memory_label(args)),"skill_list" => Some(("Reading", "skill", String::new())),- "memory_read" => Some(("Reading", "memory", arg_name(args))),- "memory_write" => Some(("Updating", "memory", arg_name(args))),"skill_read" => Some(("Reading", "skill", arg_name(args))),"skill_write" => Some(("Updating", "skill", arg_name(args))),_ => None,@@ -468,6 +466,22 @@ pub fn describe_tool_call(name: &str, args: &serde_json::Value) -> String {format!("{name} {args}")}+/// The verb and target of one `memory` op: reads list or open, the rest change.+fn memory_label(args: &serde_json::Value) -> (&'static str, &'static str, String) {+ let verb = match args.get("op").and_then(|v| v.as_str()) {+ Some("write") | Some("edit") => "Updating",+ Some("delete") => "Deleting",+ Some("move") => "Moving",+ Some("search") => "Searching",+ _ => "Reading",+ };+ let item = match args.get("op").and_then(|v| v.as_str()) {+ Some("search") => args.get("query").and_then(|v| v.as_str()).unwrap_or_default().to_string(),+ _ => arg_name(args),+ };+ (verb, "memory", item)+}+fn arg_name(args: &serde_json::Value) -> String {args.get("name").and_then(|v| v.as_str())@@ -909,11 +923,11 @@ pub(crate) mod tests {#[test]fn describe_labels_dedicated_skill_and_memory_tools() {assert_eq!(- describe_tool_call("memory_write", &json!({"name": "decisions"})),+ describe_tool_call("memory", &json!({"op": "write", "name": "decisions"})),"Updating memory: decisions");assert_eq!(- describe_tool_call("memory_read", &json!({"name": "drift.md"})),+ describe_tool_call("memory", &json!({"op": "view", "name": "drift.md"})),"Reading memory: drift");assert_eq!(@@ -921,10 +935,22 @@ pub(crate) mod tests {"Updating skill: deploy");assert_eq!(- describe_tool_call("memory_list", &json!({})),+ describe_tool_call("memory", &json!({"op": "view"})),"Reading memory notes");assert_eq!(describe_tool_call("skill_list", &json!({})), "Reading skills");+ assert_eq!(+ describe_tool_call("memory", &json!({"op": "delete", "name": "old"})),+ "Deleting memory: old"+ );+ assert_eq!(+ describe_tool_call("memory", &json!({"op": "search", "query": "yarn"})),+ "Searching memory: yarn"+ );+ assert_eq!(+ describe_tool_call("memory", &json!({"op": "move", "name": "old", "to": "tui/old"})),+ "Moving memory: old"+ );}#[test]diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex a5e66d9f0..bcdee7dd4 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -61,6 +61,10 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# memory_cross_project = false # hide other projects' memory from the# # agent (the root ~/.jan/MEMORY.md lists# # them by default)+# memory_auto_tidy = false # stop the TUI tidying memory in the+# # background when its index outgrows the+# # prompt budget (on by default; /memory+# # tidy still runs it on demand)# prune_threads = true # delete old saved threads at TUI start,# # under each project's agent.toml# # thread_retention_days / max_threads.@@ -173,6 +177,10 @@ struct GlobalConfigToml {/// memory to itself (user-wide `user:` notes still apply everywhere).#[serde(default, skip_serializing_if = "Option::is_none")]memory_cross_project: Option<bool>,+ /// Tidy memory in the background once its index outgrows the prompt+ /// budget. `None` = the default, on.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ memory_auto_tidy: Option<bool>,/// Prune old saved threads at TUI start. `None` = the default, off: a/// deleted thread is not recoverable, so removing the user's history is/// something they turn on, not something they find out about.@@ -718,6 +726,17 @@ pub(crate) fn memory_cross_project_enabled() -> bool {.unwrap_or(true)}+/// Whether the TUI tidies memory on its own when the index outgrows its budget+/// (`memory_auto_tidy` in `~/.jan/config.toml`), defaulting to on. Unreadable+/// config yields the default, like the other preferences.+#[cfg(feature = "cli")]+pub(crate) fn memory_auto_tidy_enabled() -> bool {+ load_raw()+ .ok()+ .and_then(|config| config.memory_auto_tidy)+ .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.@@ -769,6 +788,8 @@ const ROOT_KEYS: &[&str] = &["theme","ask_timeout_secs","terminal_hint",+ "memory_cross_project",+ "memory_auto_tidy","hooks",];@@ -1126,6 +1147,19 @@ mod tests {});}+ #[test]+ fn memory_auto_tidy_is_on_by_default_and_reads_its_key() {+ with_temp_home(|home| {+ assert!(memory_auto_tidy_enabled(), "missing file");+ let path = home.join(".jan").join("config.toml");+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, "memory_auto_tidy = false\n").unwrap();+ assert!(!memory_auto_tidy_enabled());+ std::fs::write(&path, "memory_auto_tidy = [").unwrap();+ assert!(memory_auto_tidy_enabled(), "fails open to the default");+ });+ }+#[test]fn hide_secrets_is_unset_by_default_and_reads_its_key() {with_temp_home(|home| {diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex c37f0f14c..eaa5df34a 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -143,7 +143,7 @@ pub(crate) struct OrchestrationArgs {/// subagents via the cloned parent args.pub auto_approve: bool,/// Read-only plan mode. When `Plan`, mutation-capable tools (write/edit/bash,- /// memory_write/skill_write, MCP, subagent dispatch) are neither advertised+ /// skill_write, MCP, subagent dispatch) are neither advertised/// nor executable: the dispatcher hard-denies them with `plan_mode_read_only`,/// stronger than auto-approval's prompt suppression (it cannot override this).pub run_mode: crate::core::agent::plan::RunMode,@@ -216,6 +216,10 @@ pub(crate) struct OrchestrationArgs {/// turn composes the same bytes. `None` for a one-off run with no session to/// freeze across, which snapshots at the start of that run instead.pub session_start: Option<crate::core::agent::context::SessionStart>,+ /// The cap on this run's memory mutations. Set only for Jan's memory tidy+ /// subagent (`subagent::spawn_memory_tidy`), which shares it with the TUI+ /// so a hit cap is reported; `None` everywhere else.+ pub memory_change_budget: Option<Arc<tauri_plugin_agent_tools::memory::ChangeBudget>>,}#[async_trait]@@ -377,6 +381,46 @@ pub(crate) trait ToolInvoker: Send + Sync {/// the default does nothing, which is right for every invoker that has no/// project and therefore no hook files to read.async fn pre_compact(&self, _message_count: usize) {}++ /// The `# Memory Changes` block, when it differs from the one this run+ /// last sent: called after a batch with a successful `memory` call, so a+ /// later request in the same run learns what changed. `None` when nothing+ /// new is to be said, and for every invoker without a memory snapshot.+ fn fresh_memory_changes(&self) -> Option<String> {+ None+ }+}++/// The session's memory snapshot and the `# Memory Changes` block this run+/// last sent. The block is part of the run's tail, built once per run; a note+/// written mid-run would otherwise reach the model only on the next run.+pub(crate) struct MemoryChangesTracker {+ snapshot: crate::core::agent::context::MemorySnapshot,+ sent: std::sync::Mutex<Option<String>>,+}++impl MemoryChangesTracker {+ /// `sent` is the block the run's tail already carries, if any.+ pub(crate) fn new(+ snapshot: crate::core::agent::context::MemorySnapshot,+ sent: Option<String>,+ ) -> Self {+ Self {+ snapshot,+ sent: std::sync::Mutex::new(sent),+ }+ }++ /// The current block when it is not the one last sent, marking it sent.+ fn fresh(&self, project_root: &std::path::Path) -> Option<String> {+ let now = self.snapshot.changes_block(project_root)?;+ let mut sent = self.sent.lock().unwrap();+ if sent.as_deref() == Some(now.as_str()) {+ return None;+ }+ *sent = Some(now.clone());+ Some(now)+ }}/// Emit [`StreamEvent::Monitors`] when the set differs from what was last@@ -823,6 +867,12 @@ struct CompositeToolInvoker {parent_link: Option<crate::core::agent::subagent::ParentLink>,/// See [`OrchestrationArgs::shell_detach`].shell_detach: Option<tokio::sync::watch::Receiver<bool>>,+ /// The session's memory snapshot, for a mid-run `# Memory Changes`+ /// block. `None` where the run's tail carries none (a child run, a+ /// host-owned prompt, no snapshot).+ memory_changes: Option<MemoryChangesTracker>,+ /// See [`OrchestrationArgs::memory_change_budget`].+ memory_change_budget: Option<Arc<tauri_plugin_agent_tools::memory::ChangeBudget>>,}/// Default for the sandboxed shell's network namespace, used when@@ -1208,7 +1258,8 @@ impl CompositeToolInvoker {&self.project_root,&self.enabled_skills,))- .with_skill_user_root(self.memory_home.as_deref());+ .with_skill_user_root(self.memory_home.as_deref())+ .with_memory_change_budget(self.memory_change_budget.as_deref());let ctx = ctx.with_network(self.allow_network).with_home_readonly(self.allow_home_read).with_sandbox(self.sandbox)@@ -2172,6 +2223,10 @@ impl ToolInvoker for CompositeToolInvoker {self.monitors.snapshot()}+ fn fresh_memory_changes(&self) -> Option<String> {+ self.memory_changes.as_ref()?.fresh(&self.project_root)+ }+async fn pre_compact(&self, message_count: usize) {crate::core::agent::compaction::fire_pre_compact(&self.hooks,@@ -2686,6 +2741,7 @@ impl ToolInvoker for CompositeToolInvoker {let hooks = self.hooks.clone();let planning = self.run_mode == crate::core::agent::plan::RunMode::Plan;let hook_sink = self.hook_sink();+ let change_budget = self.memory_change_budget.clone();read_futures.push(async move {let ctx = ToolContext::new(&root, &store, &enabled);let ctx = match memory_home.as_deref() {@@ -2697,6 +2753,7 @@ impl ToolInvoker for CompositeToolInvoker {&root, &enabled,)).with_skill_user_root(memory_home.as_deref())+ .with_memory_change_budget(change_budget.as_deref()).with_network(allow_network).with_home_readonly(allow_home_read).with_sandbox(sandbox)@@ -2933,6 +2990,7 @@ pub(crate) async fn run_server_side_openai_orchestration(compaction: None,// Each proxy request is a session of one run: it snapshots its own.session_start: None,+ memory_change_budget: None,};let body = match json_body.get("max_turns") {Some(_) => std::borrow::Cow::Borrowed(json_body),@@ -3342,6 +3400,8 @@ fn build_run_system_prompt(// real `/tmp`, and advertising a scratch nothing binds would send// the model to a directory only the filesystem tools can see.let scratch = sandbox.then(|| scratch_root_for(session_id, root));+ // A subagent (the run with an override prompt) has no memory, so+ // its prompt carries no memory index or memory instructions.crate::core::agent::context::compose_system_prompt(base,root,@@ -3349,6 +3409,7 @@ fn build_run_system_prompt(subagents_enabled,policy,session_start,+ override_prompt.is_none(),).map(Some)}@@ -3611,6 +3672,8 @@ async fn orchestrate_inner(allow_escalation,compaction,session_start,+ // Read through `args` where the invoker is built.+ memory_change_budget: _,} = args;// Per-turn override: the TUI toggles plan mode live via the request body@@ -3662,6 +3725,14 @@ async fn orchestrate_inner(.as_ref().map(|s| s.prompt.clone()).unwrap_or_default();+ // The one snapshot this run composes with and reports memory changes+ // against. A run with no session snapshot (the API server) takes its own+ // here, and both halves must read that same one: the tracker below would+ // otherwise have nothing to diff against, so the run's own writes never+ // reached its next request. A host prompt carries neither, so none is taken.+ let run_start = host_system_prompt+ .is_none()+ .then(|| run_session_start(session_start.as_ref(), project_root.as_deref()));// A host prompt replaces the composition outright: nothing Jan writes is// placed around it, above the cache line or below the history.let stable_system = match host_system_prompt.as_deref() {@@ -3678,7 +3749,7 @@ async fn orchestrate_inner(settings.as_ref().is_some_and(|s| s.sandbox),&prompt_policy,// With no project, it still reaches the prompt, after the base.- Some(&run_session_start(session_start.as_ref(), project_root.as_deref())),+ run_start.as_ref(),)?,};let jan_owns_prompt = host_system_prompt.is_none();@@ -3707,6 +3778,24 @@ async fn orchestrate_inner(}}}+ // The index above the cache line is the session's snapshot, so a note+ // written since (by this run, a tidy, another session) is reported here instead.+ // Not gated on `project_memory`: that is about recall and indexing, and an+ // ephemeral session still has the index and the tool.+ // The same block is recomputed after a successful `memory` call later in+ // this run (`MemoryChangesTracker`), so the run's own writes reach its+ // next request rather than only the next run.+ let mut memory_changes: Option<MemoryChangesTracker> = None;+ if jan_owns_prompt && system_prompt_override.is_none() {+ let snapshot = run_start.as_ref().and_then(|s| s.memory());+ if let (Some(root), Some(snapshot)) = (project_root.as_deref(), snapshot) {+ let block = snapshot.changes_block(root);+ if let Some(block) = &block {+ volatile_parts.push((Composer::MemoryChanges, block.clone()));+ }+ memory_changes = Some(MemoryChangesTracker::new(snapshot.clone(), block));+ }+ }// Child (subagent) runs are excluded via `system_prompt_override`, the// same gate the memory-recall block above uses to distinguish a// top-level run from a subagent's isolated context.@@ -4037,6 +4126,8 @@ async fn orchestrate_inner(// command's end except a park, which holds the message just the// same; so the signal only applies where the session owns shells.shell_detach: args.shell_detach.clone().filter(|_| session_bg_shells.is_some()),+ memory_changes,+ memory_change_budget: args.memory_change_budget.clone(),};// Entries dropped while loading the hook files are reported once here,// before anything fires: a user whose matcher is a bad glob otherwise@@ -5270,6 +5361,7 @@ async fn run_turn_cycle(// `todo` at all means the list was just reconciled, regardless of// what else ran alongside it.let mut todo_touched_this_batch = false;+ let mut memory_touched_this_batch = false;for outcome in tool_results {// Emitted here only when the invoker did not announce it already// (the default invoker never does; a failed call refused before@@ -5287,6 +5379,9 @@ async fn run_turn_cycle(..} = outcome;let name = tool_names.get(id.as_str()).copied().unwrap_or("");+ if name == tauri_plugin_agent_tools::tools::MEMORY_TOOL && !is_error {+ memory_touched_this_batch = true;+ }if name == "todo" {todo_touched_this_batch = true;} else if !is_error@@ -5328,6 +5423,14 @@ async fn run_turn_cycle(}));}}+ // A note this run wrote is reported to its next request, below the+ // history like the run's own tail: the index above the cache line is+ // the session-start snapshot and must not move.+ if memory_touched_this_batch {+ if let Some(block) = tools.fresh_memory_changes() {+ transcript.record_reminder(&block);+ }+ }if todo_touched_this_batch {mutations_since_todo_touch = 0;} else if mutations_since_todo_touch >= MID_RUN_NUDGE_MUTATION_THRESHOLD@@ -8842,6 +8945,8 @@ mod tests {),parent_link: None,shell_detach: None,+ memory_changes: None,+ memory_change_budget: None,}}@@ -9135,6 +9240,38 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// Plan mode is read-only for memory too: `view` and `search` run, every+ /// op that changes the store is refused before it touches a note.+ #[tokio::test]+ async fn plan_mode_reads_memory_but_refuses_to_change_it() {+ let root = hooks_root("planmemory");+ let invoker = invoker_with_hooks(+ root.clone(),+ Default::default(),+ Default::default(),+ crate::core::agent::plan::RunMode::Plan,+ );+ let note = invoker.store_root.join("memory").join("fact.md");+ std::fs::create_dir_all(note.parent().unwrap()).unwrap();+ std::fs::write(¬e, "A fact").unwrap();+ for args in [+ r#"{"op":"write","name":"new","content":"x"}"#,+ r#"{"op":"edit","name":"fact","old":"A","new":"B"}"#,+ r#"{"op":"delete","name":"fact"}"#,+ r#"{"op":"move","name":"fact","to":"moved"}"#,+ ] {+ let out = invoker.invoke(&[hooked_tool_call("memory", args)]).await.unwrap();+ assert!(out[0].content.contains(PLAN_MODE_UNAVAILABLE), "{args}: {}", out[0].content);+ }+ assert_eq!(std::fs::read_to_string(¬e).unwrap(), "A fact", "nothing changed");+ assert!(!invoker.store_root.join("memory").join("new.md").exists());+ let view = invoker.invoke(&[hooked_tool_call("memory", r#"{"op":"view","name":"fact"}"#)]).await.unwrap();+ assert_eq!(view[0].content, "A fact");+ let search = invoker.invoke(&[hooked_tool_call("memory", r#"{"op":"search","query":"fact"}"#)]).await.unwrap();+ assert!(search[0].content.contains("`fact`"), "{}", search[0].content);+ let _ = std::fs::remove_dir_all(&root);+ }+/// The hooks cover plugin tools too: a third party's command is exactly/// where a PreToolUse policy most needs to apply.#[tokio::test]@@ -11742,6 +11879,272 @@ mod tests {assert!(out.contains("only a subagent"), "{out}");}+ /// The names a dispatched child is advertised, given the allowlist it was+ /// dispatched with and whether it is Jan's tidy subagent.+ fn child_tools(allowed: Option<&[&str]>, memory_access: bool) -> Vec<String> {+ let root = std::env::temp_dir().join(format!(+ "jan-child-tools-{}-{}",+ std::process::id(),+ TEST_ROOT_SEQ.fetch_add(1, Ordering::SeqCst)+ ));+ std::fs::create_dir_all(&root).unwrap();+ let permissions = if memory_access {+ ToolPermissions::allow_all()+ } else {+ ToolPermissions::allow_all().with_denied(tauri_plugin_agent_tools::tools::MEMORY_TOOL)+ };+ let allowed: Option<std::collections::HashSet<String>> =+ allowed.map(|names| names.iter().map(|n| n.to_string()).collect());+ let mut tools = Vec::new();+ advertise_local_tools(+ &mut tools,+ allowed.as_ref(),+ &permissions,+ Some(root.as_path()),+ crate::core::agent::plan::RunMode::Normal,+ false,+ crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,+ false,+ false,+ #[cfg(feature = "cli")]+ &crate::core::agent::host_tools::HostToolSet::new(),+ true,+ );+ let _ = std::fs::remove_dir_all(&root);+ tools+ .iter()+ .map(|t| t["function"]["name"].as_str().unwrap_or_default().to_string())+ .collect()+ }++ /// Subagents have no memory: a dispatched child is never offered the tool,+ /// even when its `allowed_tools` names it. Jan's tidy subagent is the one+ /// child that keeps it.+ #[test]+ fn a_dispatched_child_is_never_offered_memory_but_the_tidy_child_is() {+ let full = child_tools(None, false);+ assert!(full.iter().any(|n| n == "read"), "{full:?}");+ assert!(!full.iter().any(|n| n.starts_with("memory")), "{full:?}");+ let asked = child_tools(Some(&["read", "memory"]), false);+ assert_eq!(asked, vec!["read".to_string()], "allowed_tools cannot add it back");+ let tidy = child_tools(None, true);+ assert!(tidy.iter().any(|n| n == "memory"), "{tidy:?}");+ }++ /// #497 bug 1: a headless run builds its tail once, so a note the model+ /// wrote mid-run never reached a later request of the same run. The next+ /// request now carries `# Memory Changes` naming the note, below the+ /// history, while the system prompt bytes stay the session's.+ #[tokio::test]+ async fn a_memory_write_mid_run_reaches_the_next_request_of_the_same_run() {+ let root = unique_project_root();+ let dir = crate::core::agent::project::store_root(&root).join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("kept.md"), "Kept\n\nAlready here.").unwrap();+ let snapshot = crate::core::agent::context::MemorySnapshot::capture(&root);+ let (tx, _rx) = mpsc::unbounded_channel();+ let mut invoker = build_prompting_invoker(root.clone(), tx, PermissionRegistry::default());+ invoker.sandbox = false;+ invoker.hidden_root = None;+ invoker.auto_approve = true;+ invoker.memory_changes = Some(MemoryChangesTracker::new(snapshot, None));+ let write = json!({"choices": [{"message": {"content": null, "tool_calls": [{+ "id": "w1", "type": "function", "function": {"name": "memory",+ "arguments": "{\"op\":\"write\",\"name\":\"build_cmd\",\"title\":\"Build\",\"content\":\"make foo\"}"}+ }]}, "finish_reason": "tool_calls"}]});+ let shell = json!({"choices": [{"message": {"content": null, "tool_calls": [{+ "id": "v1", "type": "function", "function": {"name": "memory",+ "arguments": "{\"op\":\"view\",\"name\":\"build_cmd\"}"}+ }]}, "finish_reason": "tool_calls"}]});+ let model = MockModel::new(vec![write, shell, final_answer("done")]);+ let (events, _events_rx) = mpsc::unbounded_channel();+ let mut budget = SessionBudget::new(None);+ run_turn_cycle(+ &events,+ &json!({}),+ "m",+ &[],+ Transcript::from_history(vec![+ json!({"role": "system", "content": "Stable instructions."}),+ json!({"role": "user", "content": "remember the build command"}),+ ]),+ None,+ true,+ 8,+ &mut budget,+ &model,+ &invoker,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ None,+ None,+ )+ .await+ .expect("run completes");+ let _ = std::fs::remove_dir_all(&root);+ let sent = model.requests.lock().unwrap().clone();+ assert_eq!(sent.len(), 3);+ let text = |i: usize| serde_json::to_string(&sent[i]["messages"]).unwrap();+ assert!(!text(0).contains("# Memory Changes"), "nothing changed yet: {}", text(0));+ assert!(text(1).contains("# Memory Changes"), "{}", text(1));+ assert!(text(1).contains("+ build_cmd"), "{}", text(1));+ // Said once: a read-only call later does not repeat an unchanged block.+ assert_eq!(text(2).matches("# Memory Changes").count(), 1, "{}", text(2));+ for request in &sent {+ let messages = request["messages"].as_array().unwrap();+ assert_eq!(messages[0], json!({"role": "system", "content": "Stable instructions."}));+ let systems = messages.iter().filter(|m| m["role"] == "system").count();+ assert_eq!(systems, 1, "no second system message: {messages:?}");+ }+ // The block follows the tool result, below the history.+ let second = sent[1]["messages"].as_array().unwrap();+ let last = second.last().unwrap();+ assert_eq!(last["role"], "user", "{second:?}");+ assert!(last["content"].as_str().unwrap().contains("+ build_cmd"));+ }++ /// A run with no session snapshot (the API server's orchestration, which+ /// goes through `run_orchestration_streamed` with `session_start: None`)+ /// takes one for its prompt; the same snapshot must back its+ /// `# Memory Changes` tracker, or a note written mid-run never reaches the+ /// run's next request. Driven end to end against a stub provider.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn a_run_without_a_session_snapshot_still_reports_its_memory_changes() {+ use std::io::{BufRead, BufReader, Read, Write};+ let root = unique_project_root();+ let dir = crate::core::agent::project::store_root(&root).join("memory");+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("kept.md"), "Kept\n\nAlready here.").unwrap();+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ let bodies = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));+ let seen = bodies.clone();+ std::thread::spawn(move || {+ let call = |id: &str, args: &str| {+ json!({"id": "s", "object": "chat.completion.chunk", "created": 1, "model": "m",+ "choices": [{"index": 0, "delta": {"role": "assistant", "tool_calls": [{+ "index": 0, "id": id, "type": "function",+ "function": {"name": "memory", "arguments": args}}]},+ "finish_reason": "tool_calls"}]})+ };+ let chunks = [+ call("w1", r#"{"op":"write","name":"build_cmd","title":"Build","content":"make foo"}"#),+ call("v1", r#"{"op":"view","name":"build_cmd"}"#),+ json!({"id": "s", "object": "chat.completion.chunk", "created": 1, "model": "m",+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": "done"},+ "finish_reason": "stop"}]}),+ ];+ for (i, connection) in listener.incoming().enumerate() {+ let Ok(mut stream) = connection else { break };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut size = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ size = n.trim().parse().unwrap_or(0);+ }+ }+ let mut body = vec![0; size];+ let _ = reader.read_exact(&mut body);+ seen.lock().unwrap().push(String::from_utf8_lossy(&body).into_owned());+ let chunk = &chunks[i.min(chunks.len() - 1)];+ let answer = format!("data: {chunk}\n\ndata: [DONE]\n\n");+ let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len());+ }+ });+ let mut args = crate::core::agent::subagent::tests::max_par_args(&root);+ args.session_start = None;+ args.sandbox = Some(false);+ args.subagents_enabled = false;+ args.provider_configs = Arc::new(Mutex::new(+ std::iter::once((+ "stub".to_string(),+ ProviderConfig {+ provider: "stub".into(),+ base_url: Some(format!("http://{addr}/v1")),+ api_key: Some("k".into()),+ models: vec!["m".into()],+ ..Default::default()+ },+ ))+ .collect(),+ ));+ let body = json!({"model": "m", "messages": [{"role": "user", "content": "remember the build command"}]});+ let (tx, _rx) = mpsc::unbounded_channel();+ let out = run_orchestration_streamed(&tx, &body, &args).await;+ let _ = std::fs::remove_dir_all(&dir);+ let _ = std::fs::remove_dir_all(&root);+ out.expect("run completes");+ let sent = bodies.lock().unwrap().clone();+ assert_eq!(sent.len(), 3, "{sent:?}");+ assert!(sent[0].contains("kept"), "the prompt carries the snapshot index: {}", sent[0]);+ assert!(!sent[0].contains("# Memory Changes"), "{}", sent[0]);+ let tail = |b: &str| b.chars().rev().take(600).collect::<Vec<_>>().into_iter().rev().collect::<String>();+ assert!(sent[1].contains("# Memory Changes"), "{}", tail(&sent[1]));+ assert!(sent[1].contains("+ build_cmd"), "{}", tail(&sent[1]));+ }++ /// A child that names `memory` anyway is refused at the gate.+ #[tokio::test]+ async fn a_child_calling_memory_is_refused() {+ let root = unique_project_root();+ let (tx, _rx) = mpsc::unbounded_channel();+ let mut invoker =+ build_prompting_invoker(root.clone(), tx, Arc::new(Mutex::new(HashMap::new())));+ invoker.permissions = ToolPermissions::allow_all()+ .with_denied(tauri_plugin_agent_tools::tools::MEMORY_TOOL);+ let call = json!({+ "id": "m1",+ "type": "function",+ "function": { "name": "memory", "arguments": "{\"op\":\"view\"}" }+ });+ let out = invoker.invoke(&[call]).await.unwrap();+ let _ = std::fs::remove_dir_all(&root);+ assert!(out[0].content.starts_with("ERROR:"), "{}", out[0].content);+ }++ /// A subagent's prompt carries no memory section: no index, no memory+ /// instructions. The main agent's has both, and tells it subagents have+ /// no memory.+ #[test]+ fn a_child_prompt_has_no_memory_section() {+ let root = unique_project_root();+ let dir = crate::core::agent::project::store_root(&root).join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("fact.md"), "A remembered fact.").unwrap();+ let build = |override_prompt: Option<&str>, subagents: bool| {+ build_run_system_prompt(+ None,+ override_prompt,+ Some(&root),+ Some("s1"),+ subagents,+ false,+ &PromptPolicy::default(),+ None,+ )+ .unwrap()+ .unwrap()+ .as_prompt()+ };+ let child = build(Some("You are a reviewer."), false);+ for absent in ["# Available Memories", "A remembered fact", "`memory` tool", "## Memory"] {+ assert!(!child.contains(absent), "{absent} leaked into a child prompt:\n{child}");+ }+ assert!(child.contains("# Skills"), "skills stay: {child}");+ assert!(child.contains("Memory belongs to the agent that\ndispatched you"), "{child}");+ let main = build(None, true);+ assert!(main.contains("# Available Memories") && main.contains("A remembered fact"));+ assert!(main.contains("Subagents have no memory"), "{main}");+ let _ = std::fs::remove_dir_all(&root);+ }+/// A dispatching run is offered the steering tool beside dispatch, and/// never the doorbell: it is the main agent, there is nobody above it.#[test]diff --git a/src-tauri/src/core/agent/plan.rs b/src-tauri/src/core/agent/plan.rsindex 08f02a8cc..d613c78f3 100644--- a/src-tauri/src/core/agent/plan.rs+++ b/src-tauri/src/core/agent/plan.rs@@ -1,7 +1,7 @@//! Read-only plan mode. A first-class run mode for safe repository exploration//! and plan review: the agent may read/search/list/read-file, do web research,//! and read memory/skills, but every mutation-capable tool (write/edit/bash,-//! memory_write/skill_write, MCP, subagent dispatch) is blocked at the core+//! skill_write, MCP, subagent dispatch) is blocked at the core//! dispatcher and never advertised to the model. Enforcement is authoritative;//! the prompt addendum below is only defense in depth.diff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rsindex 90f927150..c18b04f69 100644--- a/src-tauri/src/core/agent/prefix_stability.rs+++ b/src-tauri/src/core/agent/prefix_stability.rs@@ -271,6 +271,7 @@ fn turn(project: &Path, history: &[Value], recall: &str, tools: &[Value]) -> Reqfalse,&PromptPolicy::default(),Some(&start),+ true,).unwrap();let mut tail = composed.tail;diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex 538a2426b..1139dff49 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -548,10 +548,11 @@ pub(crate) struct RunSettings {/// like the `[agent]` section it comes from.#[cfg(feature = "cli")]pub worktree: Option<bool>,- /// One line per `[tools]` `allow`/`deny`/`allow_write` entry that names the- /// shell tool's old name `bash`, which now matches nothing. Reported at run- /// start with the hook-load notices, so a deny rule that stopped applying- /// does not do so silently.+ /// One line per `[tools]` `allow`/`deny`/`allow_write` entry that names a+ /// tool by an old name: the shell's `bash`, which now matches nothing, or+ /// an old memory tool, which now applies to all of `memory`. Reported at+ /// run start with the hook-load notices, so a rule whose reach changed does+ /// not do so silently.pub tool_notices: Vec<String>,}@@ -587,7 +588,7 @@ fn renamed_tool_notices(tools: &ToolsSection) -> Vec<String> {.into_iter().flat_map(|(where_, list)| {list.iter().filter_map(move |name| {- tauri_plugin_agent_tools::tools::renamed_shell_notice(name, where_)+ tauri_plugin_agent_tools::tools::renamed_tool_notice(name, where_)})}).collect()@@ -895,6 +896,20 @@ mod tests {assert!(notices[0].starts_with("[tools] deny names `bash`"), "{}", notices[0]);}+ /// A `[tools]` entry on an old memory tool name still applies, to the+ /// whole `memory` tool, and is reported so the user renames it.+ #[test]+ fn a_tools_list_naming_an_old_memory_tool_still_applies_and_is_reported() {+ let root = unique_root("renamed_memory");+ write_agent_toml(&root, "[tools]\ndeny = [\"memory_write\"]\n");+ let notices = run_settings(&root).tool_notices;+ assert_eq!(notices.len(), 1, "{notices:?}");+ assert!(notices[0].starts_with("[tools] deny names `memory_write`"), "{}", notices[0]);+ let cfg = load_agent_config(&root).unwrap();+ assert!(permissions_from(&cfg).is_denied("memory"));+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn run_settings_reads_allow_network_both_ways() {let root = unique_root("allow_net");diff --git a/src-tauri/src/core/agent/prompt.rs b/src-tauri/src/core/agent/prompt.rsindex f03352922..bf4a4dc23 100644--- a/src-tauri/src/core/agent/prompt.rs+++ b/src-tauri/src/core/agent/prompt.rs@@ -89,6 +89,7 @@ pub(crate) enum Composer {MemoryCatalog,ToolSchemas,// Below it today: per-turn content, so they can never be in the prefix.+ MemoryChanges,MemoryRecall,PlanAddendum,TodoAddendum,@@ -109,6 +110,7 @@ impl Composer {Composer::Skills,Composer::MemoryCatalog,Composer::ToolSchemas,+ Composer::MemoryChanges,Composer::MemoryRecall,Composer::PlanAddendum,Composer::TodoAddendum,@@ -130,6 +132,7 @@ impl Composer {Composer::Skills => "skills",Composer::MemoryCatalog => "memory_catalog",Composer::ToolSchemas => "tool_schemas",+ Composer::MemoryChanges => "memory_changes",Composer::MemoryRecall => "memory_recall",Composer::PlanAddendum => "plan_addendum",Composer::TodoAddendum => "todo_addendum",@@ -157,6 +160,7 @@ impl Composer {Composer::Skills => "the installed skill catalog",Composer::MemoryCatalog => "the curated memory note catalog",Composer::ToolSchemas => "the advertised tool array (a request field)",+ Composer::MemoryChanges => "memory notes changed since the session started",Composer::MemoryRecall => "memory recalled for this request",Composer::PlanAddendum => "the plan-mode instructions",Composer::TodoAddendum => "the active todo list",@@ -186,7 +190,8 @@ impl Composer {| Composer::Skills| Composer::MemoryCatalog| Composer::ToolSchemas => Some(Placement::Prefix),- Composer::MemoryRecall+ Composer::MemoryChanges+ | Composer::MemoryRecall| Composer::PlanAddendum| Composer::TodoAddendum => None,}@@ -217,7 +222,8 @@ impl Composer {| Composer::Skills| Composer::MemoryCatalog| Composer::ToolSchemas => true,- Composer::MemoryRecall+ Composer::MemoryChanges+ | Composer::MemoryRecall| Composer::PlanAddendum| Composer::TodoAddendum => false,}diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 1416d02de..b5c27b851 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -766,6 +766,12 @@ pub struct SubagentRequest {pub description: String,pub allowed_tools: Option<Vec<String>>,pub agent: String,+ /// Whether the child keeps the `memory` tool. Subagents have no memory:+ /// the main agent hands them the facts they need in the task, and a child+ /// writing notes the main agent never sees would fork the record. Only+ /// Jan's own tidy subagent sets this. It is never read from a tool call, so+ /// neither the model nor a definition can ask for it.+ pub memory_access: bool,}/// A group of subagents that run concurrently. The next phase starts only once@@ -1556,11 +1562,11 @@ impl PhaseGate {}impl BackgroundSubagents {- /// A dispatch scope for a caller that will outlive the dispatch it takes- /// now. Production callers hold one from run start ([`DispatchScope`] is- /// built from the run's own generation); the CLI's tests take one on the- /// spot, which is the only config whose tests dispatch at all.- #[cfg(all(test, feature = "cli"))]+ /// A dispatch scope taken now. A run holds one from its start+ /// ([`DispatchScope`] is built from the run's own generation); the TUI+ /// takes one on the spot for a memory tidy, which belongs to the session+ /// rather than a run, and so do the CLI's tests.+ #[cfg(feature = "cli")]pub(crate) fn scope(self: &Arc<Self>) -> DispatchScope {DispatchScope {bg: self.clone(),@@ -1914,12 +1920,13 @@ async fn run_subagent(inbox: Arc<ChildInbox>,parent_link: ParentLink,transcript_dir: Option<PathBuf>,+ memory_access: bool,) -> Result<String, SubagentError> {use crate::core::agent::events::StreamEvent;use crate::core::agent::r#loop::run_orchestration_steered;let name = resolved.definition.name.clone();- let mut child_args = parent_args;+ let mut child_args = without_memory(parent_args, memory_access);child_args.system_prompt_override = Some(resolved.definition.system_prompt.clone());// The host wrote its prompt for the conversation it drives, not for a// delegate with a task of its own; left in place it would also replace the@@ -2042,6 +2049,27 @@ async fn run_subagent(outcome}+/// The run args a child starts from: the parent's, minus memory unless+/// `memory_access` (Jan's own tidy subagent). Denying the tool both hides it+/// from the child's tool list and refuses a call to it, whatever the child's+/// `allowed_tools` or definition says; recall and indexing are already off for+/// a child (`system_prompt_override`), and so is the memory section of its+/// prompt (see `context::compose_system_prompt`).+pub(crate) fn without_memory(+ mut args: crate::core::agent::r#loop::OrchestrationArgs,+ memory_access: bool,+) -> crate::core::agent::r#loop::OrchestrationArgs {+ if !memory_access {+ args.permissions = args+ .permissions+ .with_denied(tauri_plugin_agent_tools::tools::MEMORY_TOOL);+ // A tidy's cap is the tidy's; nothing else inherits it.+ args.memory_change_budget = None;+ }+ args.project_memory = false;+ args+}+/// Resolve and start a subagent on a background task, returning its `run_id`/// immediately (non-blocking). The caller collects the result later with/// [`await_subagent`]. Registered in `bg` so the parent run can abort it on@@ -2074,10 +2102,6 @@ pub(crate) fn spawn_subagent(scratch: Option<&Path>,notify_on_finish: bool,) -> Result<Dispatched, SubagentError> {- use crate::core::agent::events::StreamEvent;- use std::sync::atomic::Ordering;-- let bg = &scope.bg;if !parent_args.subagents_enabled {return Err(SubagentError::PermissionDenied("subagents cannot dispatch nested subagents".to_string(),@@ -2108,7 +2132,27 @@ pub(crate) fn spawn_subagent()?,..resolved};+ launch(scope, parent_args, resolved, req, parent, events, scratch, notify_on_finish)+}++/// Start an already-resolved child on a background task: the half of+/// [`spawn_subagent`] after its definition and tools are settled, shared with+/// Jan's internal subagents, which are not in the registry.+#[allow(clippy::too_many_arguments)]+fn launch(+ scope: &DispatchScope,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ resolved: ResolvedDispatch,+ req: SubagentRequest,+ parent: &ParentRun,+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ scratch: Option<&Path>,+ notify_on_finish: bool,+) -> Result<Dispatched, SubagentError> {+ use crate::core::agent::events::StreamEvent;+ use std::sync::atomic::Ordering;+ let bg = &scope.bg;let name = resolved.definition.name.clone();let run_id = next_subagent_run_id(&name);let (tx, rx) = tokio::sync::oneshot::channel();@@ -2155,6 +2199,7 @@ pub(crate) fn spawn_subagent(let entry_events = bg.child_events(events);let inherited = parent.clone();let description = req.description.clone();+ let memory_access = req.memory_access;let run_id_task = run_id.clone();let name_task = name.clone();let registry = bg.clone();@@ -2218,6 +2263,7 @@ pub(crate) fn spawn_subagent(task_inbox,parent_link,transcript_dir,+ memory_access,).await;if let Some((_, path)) = &result_file {@@ -2264,6 +2310,112 @@ pub(crate) fn spawn_subagent(Ok(Dispatched { run_id })}+/// The name Jan's memory-tidy subagent runs under. Not a registry entry: the+/// model cannot dispatch it, and a saved definition of the same name does not+/// replace it.+#[cfg(feature = "cli")]+pub(crate) const MEMORY_TIDY_AGENT: &str = "memory-tidy";++/// The tidy subagent's instructions. It reads the notes in its own context, so+/// the main conversation never loads them.+#[cfg(feature = "cli")]+const MEMORY_TIDY_PROMPT: &str = "You are Jan's memory tidier. You curate the agent's long-term memory \+with the `memory` tool and nothing else; no change you make asks the user. Be conservative: a note \+left alone costs a line in the index, a note wrongly archived or deleted loses a fact. When unsure, \+leave the note alone.++1. `view` the index, then `view` each folder and every note you are considering changing. Never change \+a note you have not read in full. The main agent may change notes while you work: if the tool says a \+note changed since you viewed it, `view` it again before deciding.+2. Archive a note only when its own content explicitly says the work is finished: merged, released, \+shipped, closed, done, abandoned or obsolete. Never archive a note because it looks generic, old, \+neutral or unimportant. Archive with `edit`, adding front matter `status: done` at the top \+(`---\\nstatus: done\\n---\\n`); keep its content.+3. Merge only clear duplicates: two notes stating the same fact. `edit` or `write` the clearer one with \+the combined content, then `delete` the other.+4. Delete a note only when a newer note explicitly supersedes it.+5. Use `move` (`name`, `to`) to rename a note or put it in a folder; never `write` a copy and \+`delete` the original. Group notes only when many clearly share one topic.+6. Never create index, overview, summary or list-of-links notes (no `index`, `MEMORY`, `README`): the \+harness builds the index itself.++Only change this project's notes and `user:` notes; other projects are read-only. Keep every durable, \+still-true fact. You have a budget of 30 changes (write, edit, delete or move) per tidy, enforced by \+the tool: spend them on the clearest cases first, and stop when the tool says the cap is reached.++Finish with a short report, one line per change: `archived <name>`, `merged <a> into <b>`, \+`deleted <name>: <why>`, `moved <a> to <b>`; add `cap reached` if the tool refused a change; or \+`no changes` when nothing needed doing.";++/// Start the memory-tidy subagent on the session's registry, returning its run+/// id. It runs on the `smol` model with only the `memory` tool -- the one child+/// that keeps memory (see [`without_memory`]) -- and in the background: the+/// caller collects it with [`await_subagent`]. It never rings the parent's+/// doorbell, so a tidy never starts a model turn of its own.+#[cfg(feature = "cli")]+pub(crate) fn spawn_memory_tidy(+ scope: &DispatchScope,+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ parent: &ParentRun,+ events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ budget: Arc<tauri_plugin_agent_tools::memory::ChangeBudget>,+) -> Result<Dispatched, SubagentError> {+ if parent_args.project_root.is_none() {+ return Err(SubagentError::Upstream("memory tidy needs an active project".to_string()));+ }+ let (resolved, req) = memory_tidy_dispatch();+ let parent = &ParentRun {+ cost_remaining: child_cost_ceiling(&child_model(&resolved, parent), parent)?,+ ..parent.clone()+ };+ let args = memory_tidy_args(parent_args, budget);+ launch(scope, &args, resolved, req, parent, events, None, false)+}++/// The tidy child's run args: the parent's, with the change cap its `memory`+/// tool enforces (so a tidy that misjudges the store cannot rewrite all of+/// it), and never in plan mode. A tidy only starts on the user's word+/// (`/memory tidy`, or the auto trigger, which stands down in plan mode), so+/// a session started with `--plan` must not hand it a read-only memory tool;+/// entering plan mode stops a running tidy instead.+#[cfg(feature = "cli")]+fn memory_tidy_args(+ parent_args: &crate::core::agent::r#loop::OrchestrationArgs,+ budget: Arc<tauri_plugin_agent_tools::memory::ChangeBudget>,+) -> crate::core::agent::r#loop::OrchestrationArgs {+ let mut args = parent_args.clone();+ args.memory_change_budget = Some(budget);+ args.run_mode = crate::core::agent::plan::RunMode::Normal;+ args+}++/// The tidy subagent's resolved definition and request: the `smol` model, the+/// `memory` tool alone, and the internal memory-access flag.+#[cfg(feature = "cli")]+fn memory_tidy_dispatch() -> (ResolvedDispatch, SubagentRequest) {+ let tools = vec![tauri_plugin_agent_tools::tools::MEMORY_TOOL.to_string()];+ let definition = SubagentDefinition {+ name: MEMORY_TIDY_AGENT.to_string(),+ description: "Tidies the agent's memory".to_string(),+ system_prompt: MEMORY_TIDY_PROMPT.to_string(),+ allowed_tools: Some(tools.clone()),+ model: Some(SMOL_ROLE.to_string()),+ scope: SubagentScope::Builtin,+ };+ let resolved = ResolvedDispatch {+ definition,+ allowed_tools: Some(tools),+ };+ let req = SubagentRequest {+ name: MEMORY_TIDY_AGENT.to_string(),+ description: "Tidy the memory now.".to_string(),+ allowed_tools: None,+ agent: MEMORY_TIDY_AGENT.to_string(),+ memory_access: true,+ };+ (resolved, req)+}+/// What a phased dispatch reports back to the model.pub(crate) struct DispatchedPlan {pub(crate) phase_count: usize,@@ -2921,11 +3073,13 @@ pub fn agent_catalog(registry: &SubagentRegistry) -> Option<String> {}/// Tools a child never gets whatever its allowlist says: it cannot dispatch-/// (nesting is capped at one), and it has no `ask` client, todo list or-/// monitor set of its own (see [`run_subagent`]).+/// (nesting is capped at one), it has no `ask` client, todo list or monitor+/// set of its own, and it has no memory (see [`run_subagent`] and+/// [`without_memory`]).fn never_delegated(name: &str) -> bool {is_subagent_tool(name)|| matches!(name, "ask" | "todo")+ || name == tauri_plugin_agent_tools::tools::MEMORY_TOOL|| name == tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME}@@ -3010,7 +3164,7 @@ pub fn subagent_tool_schemas(let bg = format!(" Subagents run in the BACKGROUND, concurrently (up to {max_parallel} at once, from max_parallel_subagents in agent.toml; more are queued FIFO). You keep working and get a note the moment each finishes. Each subagent's final answer is written to blackboard/<name>.md in a shared scratch directory the whole plan can read from and write to. Steer a running child with message_subagent, or stop it with stop_subagent, by its name (reported when it starts).");let phases_desc = " List all the subagents in one call. To PIPELINE them, give a subagent a `phase`: subagents sharing a phase run together, lower phases run first, and each later phase is handed the previous phase's results automatically. Omit `phase` for a plain fan-out (one stage, everyone at once); use it to stage work (e.g. phase 0 researches in parallel, phase 1 synthesizes).";let dispatch_desc = format!(- "Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} Every subagent gets your full toolset unless its agent's definition or allowed_tools restricts it."+ "Dispatch one or more subagents -- nested, isolated agents -- to do work for you.{phases_desc}{bg} Every subagent gets your full toolset unless its agent's definition or allowed_tools restricts it, except memory: subagents have no memory tool and no memory index, so put any remembered fact a subagent needs into its task.");vec![json!({@@ -3028,7 +3182,7 @@ pub fn subagent_tool_schemas("type": "object","properties": {"agent": agent_field,- "task": { "type": "string", "description": "The subagent's sole instruction. Include everything it needs; it does not see this conversation. A subagent in a later phase also receives the previous phase's results automatically, so tell it what to DO with them." },+ "task": { "type": "string", "description": "The subagent's sole instruction. Include everything it needs, including any facts from your memory; it does not see this conversation or your memory. A subagent in a later phase also receives the previous phase's results automatically, so tell it what to DO with them." },"phase": { "type": "integer", "minimum": 0, "description": "Optional stage (default 0). Subagents with the same phase run concurrently; a phase starts only after every lower phase has finished. Omit it entirely for a plain fan-out." },"allowed_tools": {"type": "array",@@ -3181,6 +3335,7 @@ pub fn parse_dispatch_plan(description,allowed_tools: optional_tool_list(sub),agent,+ memory_access: false,});}let phases = by_phase@@ -3885,6 +4040,7 @@ pub(crate) mod tests {description: "do the thing".to_string(),allowed_tools: allowed,agent: name.to_string(),+ memory_access: false,}}@@ -4687,6 +4843,7 @@ pub(crate) mod tests {allow_escalation: None,compaction: None,session_start: None,+ memory_change_budget: None,}}@@ -6019,6 +6176,110 @@ pub(crate) mod tests {assert!(create["function"]["parameters"]["properties"].get("allowed_tools").is_none());}+ /// The tidy subagent is the one child with memory: the `memory` tool and+ /// nothing else, on the cheap model, and not a name the model can dispatch.+ #[cfg(feature = "cli")]+ #[test]+ fn the_tidy_subagent_keeps_memory_and_nothing_else() {+ let (resolved, req) = memory_tidy_dispatch();+ assert!(req.memory_access);+ assert_eq!(resolved.allowed_tools, Some(vec!["memory".to_string()]));+ assert_eq!(resolved.definition.model.as_deref(), Some(SMOL_ROLE));+ let child = without_memory(max_par_args(&unique_root("tidy-child")), req.memory_access);+ assert!(!child.permissions.is_denied("memory"));+ let reg = SubagentRegistry::load(&unique_root("tidy-not-dispatchable"));+ assert!(!reg.dispatchable_names().contains(&MEMORY_TIDY_AGENT));+ let prompt = &resolved.definition.system_prompt;+ for step in ["status: done", "Merge only clear duplicates", "explicitly supersedes", "report"] {+ assert!(prompt.contains(step), "{step}");+ }+ }++ /// The tidy child carries the change cap and is never in plan mode, even+ /// when the session was started with `--plan`.+ #[cfg(feature = "cli")]+ #[test]+ fn the_tidy_child_is_capped_and_never_planning() {+ let mut parent = max_par_args(&unique_root("tidy-plan"));+ parent.run_mode = crate::core::agent::plan::RunMode::Plan;+ let budget = Arc::new(tauri_plugin_agent_tools::memory::ChangeBudget::new(3));+ let args = memory_tidy_args(&parent, budget);+ assert_eq!(args.run_mode, crate::core::agent::plan::RunMode::Normal);+ assert!(args.memory_change_budget.is_some());+ }++ /// #497 bug 3: the tidy prompt is conservative (archive only what says it+ /// is finished, never index notes, `move` rather than write+delete) and+ /// names the harness's cap, which a child inherits only from a tidy.+ #[cfg(feature = "cli")]+ #[test]+ fn the_tidy_prompt_is_conservative_and_names_the_cap() {+ let prompt = MEMORY_TIDY_PROMPT;+ for rule in [+ "explicitly says the work is finished",+ "Never archive a note because it looks generic",+ "never `write` a copy and",+ "Never create index, overview",+ "When unsure",+ "`cap reached`",+ ] {+ assert!(prompt.contains(rule), "{rule}: {prompt}");+ }+ let cap = tauri_plugin_agent_tools::memory::TIDY_MAX_CHANGES;+ assert!(prompt.contains(&format!("budget of {cap} changes")), "{prompt}");+ let mut parent = max_par_args(&unique_root("tidy-cap"));+ parent.memory_change_budget =+ Some(Arc::new(tauri_plugin_agent_tools::memory::ChangeBudget::new(cap)));+ assert!(without_memory(parent.clone(), true).memory_change_budget.is_some());+ assert!(without_memory(parent, false).memory_change_budget.is_none());+ }++ /// Subagents have no memory, so `memory` is never a name a dispatch or a+ /// definition can hand a child, even when the parent offers it.+ #[test]+ fn memory_is_never_a_delegable_tool_name() {+ let reg = SubagentRegistry::load(&unique_root("tool_enum_memory"));+ let mut tools = subagent_tool_schemas(®, DEFAULT_MAX_PARALLEL_SUBAGENTS);+ tools.push(serde_json::json!({ "type": "function", "function": { "name": "memory" } }));+ tools.push(serde_json::json!({ "type": "function", "function": { "name": "shell" } }));+ constrain_tool_names(&mut tools, &ToolPermissions::allow_all(), false);+ let dispatch = &tools[0]["function"]["parameters"]["properties"]["subagents"]["items"]+ ["properties"]["allowed_tools"]["items"]["enum"];+ assert_eq!(dispatch, &serde_json::json!(["find", "grep", "ls", "shell"]));+ let create = tools+ .iter()+ .find(|s| s["function"]["name"] == "create_subagent")+ .unwrap();+ let names = &create["function"]["parameters"]["properties"]["allowed_tools"]["items"]["enum"];+ assert!(!names.as_array().unwrap().iter().any(|n| n == "memory"), "{names}");+ for gone in ["memory_list", "memory_read", "memory_write"] {+ assert!(!dispatch.as_array().unwrap().iter().any(|n| n == gone));+ }+ let description = tools[0]["function"]["description"].as_str().unwrap();+ assert!(description.contains("subagents have no memory tool"), "{description}");+ }++ /// A dispatched child's args deny `memory` (so it is neither advertised nor+ /// callable) and turn recall/indexing off; only the internal tidy request+ /// keeps the tool.+ #[cfg(feature = "cli")]+ #[test]+ fn a_child_loses_memory_unless_it_is_the_tidy_subagent() {+ let parent = max_par_args(&unique_root("child-memory"));+ let child = without_memory(parent.clone(), false);+ assert!(child.permissions.is_denied("memory"));+ assert!(!child.project_memory);+ let tidy = without_memory(parent, true);+ assert!(!tidy.permissions.is_denied("memory"));+ assert!(!tidy.project_memory, "a tidy run still indexes nothing");+ // Nothing a model writes can set it.+ let plan = parse_dispatch_plan_fresh(&serde_json::json!({+ "subagents": [{ "agent": "general", "task": "t", "memory_access": true }]+ }))+ .unwrap();+ assert!(!plan.phases[0].subagents[0].memory_access);+ }+/// A name is held from the moment a dispatch hands it out -- a later-phase/// worker that has not started included -- and by an answer still on the/// blackboard after the registry that ran it is gone.diff --git a/src-tauri/src/core/cli/acp.rs b/src-tauri/src/core/cli/acp.rsindex 6061d236e..6cbf71432 100644--- a/src-tauri/src/core/cli/acp.rs+++ b/src-tauri/src/core/cli/acp.rs@@ -414,7 +414,7 @@ fn replay(history: &[Value], cwd: &Path) -> Vec<SessionUpdate> {.unwrap_or(Value::Null);out.push(SessionUpdate::ToolCall(ToolCall::new(id.to_string(), tool_title(name, &args))- .kind(tool_kind(name))+ .kind(tool_kind(name, &args)).status(ToolCallStatus::Completed).locations(tool_locations(&args, cwd)).raw_input(args),@@ -763,13 +763,13 @@ impl TurnMap {let call = self.call(&id, &name);call.announced = true;update(SessionUpdate::ToolCall(- ToolCall::new(id, name.clone()).kind(tool_kind(&name)).status(ToolCallStatus::Pending),+ ToolCall::new(id, name.clone()).kind(tool_kind(&name, &Value::Null)).status(ToolCallStatus::Pending),))}StreamEvent::ToolCall { id, name, args } => {let locations = tool_locations(&args, &self.cwd);let title = tool_title(&name, &args);- let kind = tool_kind(&name);+ let kind = tool_kind(&name, &args);let call = self.call(&id, &name);call.args = Some(args.clone());if call.announced {@@ -930,7 +930,12 @@ impl TurnMap {(None, Some(path)) => format!("{tool_name} ({capability}) {path}"),(None, None) => format!("{tool_name} ({capability})"),};- let mut fields = ToolCallUpdateFields::new().title(title).kind(tool_kind(tool_name));+ let args = matched+ .as_ref()+ .and_then(|id| self.calls.get(id))+ .and_then(|c| c.args.clone())+ .unwrap_or(Value::Null);+ let mut fields = ToolCallUpdateFields::new().title(title).kind(tool_kind(tool_name, &args));if let Some(path) = &path {fields = fields.locations(vec![ToolCallLocation::new(absolute(&self.cwd, path))]);}@@ -979,11 +984,23 @@ fn plan(list: &TodoList) -> Plan {Plan::new(entries)}-/// What kind of work a tool does, for the client's icon and grouping.-fn tool_kind(name: &str) -> ToolKind {+/// What kind of work a tool does, for the client's icon and grouping. `args`+/// matters only for `memory`, whose `op` decides between reading and editing;+/// before its arguments are known it is `Other` rather than a guessed edit.+fn tool_kind(name: &str, args: &Value) -> ToolKind {match name {- "read" | "ls" | "memory_read" | "memory_list" | "skill_read" | "skill_list" => ToolKind::Read,- "edit" | "write" | "memory_write" | "skill_write" => ToolKind::Edit,+ tauri_plugin_agent_tools::tools::MEMORY_TOOL => match args.get("op").and_then(Value::as_str) {+ Some("view") => ToolKind::Read,+ Some("search") => ToolKind::Search,+ Some("write" | "edit" | "delete" | "move") => ToolKind::Edit,+ _ => ToolKind::Other,+ },+ // `memory_read`/`memory_list`/`memory_write` are the memory tool's+ // pre-rename names, still in replayed history.+ "read" | "ls" | "skill_read" | "skill_list" | "memory_read" | "memory_list" => {+ ToolKind::Read+ }+ "edit" | "write" | "skill_write" | "memory_write" => ToolKind::Edit,"grep" | "find" => ToolKind::Search,// `bash` is the shell's pre-rename name, still in replayed history."bash" | tauri_plugin_agent_tools::tools::SHELL_TOOL => ToolKind::Execute,@@ -1053,6 +1070,25 @@ mod tests {}}+ /// `memory` is one tool for reads and writes, so its kind comes from the+ /// call's `op`; before the arguments arrive it is not claimed to edit.+ #[test]+ fn a_memory_call_is_classified_by_its_op() {+ let kind = |args: Value| tool_kind("memory", &args);+ assert_eq!(kind(json!({"op": "view"})), ToolKind::Read);+ assert_eq!(kind(json!({"op": "search", "query": "q"})), ToolKind::Search);+ for op in ["write", "edit", "delete", "move"] {+ assert_eq!(kind(json!({"op": op})), ToolKind::Edit, "{op}");+ }+ assert_eq!(kind(Value::Null), ToolKind::Other);+ assert_eq!(tool_kind("write", &Value::Null), ToolKind::Edit);+ assert_eq!(tool_kind("read", &Value::Null), ToolKind::Read);+ // A thread recorded before the rename replays its old memory calls.+ assert_eq!(tool_kind("memory_read", &Value::Null), ToolKind::Read);+ assert_eq!(tool_kind("memory_list", &Value::Null), ToolKind::Read);+ assert_eq!(tool_kind("memory_write", &Value::Null), ToolKind::Edit);+ }+#[test]fn the_opt_in_is_off_by_default_and_the_env_wins() {assert!(!enabled_from(None, None));diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 503cbbe46..75a90776f 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1480,6 +1480,8 @@ fn build_cli_orchestration_args(session_start: Some(crate::core::agent::context::SessionStart::capture(Some(&project_root,))),+ // Only Jan's memory tidy subagent has one.+ memory_change_budget: None,}}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 80c077002..c28cabef4 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -4842,6 +4842,20 @@ struct App {plugin_collection_url: Option<String>,/// A plugin install is in flight: a second request is refused.plugin_installing: bool,+ /// A memory tidy was asked for (`/memory tidy`, or the auto trigger); the+ /// chat loop starts it on the session's subagent registry. Taken once.+ tidy_request: Option<TidyKind>,+ /// The tidy in flight, if any: one at a time.+ tidy_running: Option<TidyKind>,+ /// The in-flight tidy's subagent run id, so entering plan mode can stop it.+ tidy_run_id: Option<String>,+ /// Whether this session already queued an automatic tidy. Auto-tidy runs+ /// at most once per session, so a tidy that cannot get the index under+ /// budget never loops; `/new`, `/clear` and `/resume` reset it.+ auto_tidy_checked: bool,+ /// The memory stamp (`Scopes::stamp`) the last under-budget check saw, so+ /// a turn that changed no note skips rebuilding the index.+ auto_tidy_stamp: Option<u64>,/// Compaction handed off to the loop, which spawns the summarizing model/// call off the render loop. Taken once.compact_request: Option<CompactKind>,@@ -5632,6 +5646,11 @@ impl App {plugin_collection_url: None,plugin_installing: false,update_installing: false,+ tidy_request: None,+ tidy_running: None,+ tidy_run_id: None,+ auto_tidy_checked: false,+ auto_tidy_stamp: None,compact_request: None,compacting: None,compact_started: None,@@ -5737,6 +5756,22 @@ impl App {self.adopt_session_start(Some(start));}+ /// Re-take the session's memory index after a compaction. The compaction+ /// already rewrote the history, so the prompt it is about to send is new+ /// either way, and a fresh index stops the changes block from repeating+ /// what the summary folded in. The date and branch stay the session's.+ fn refresh_memory_snapshot(&mut self) {+ let Some(args) = self.args.as_ref() else {+ return;+ };+ let Some(start) = args.session_start.as_ref() else {+ return;+ };+ let root = args.project_root.clone().unwrap_or_else(|| self.project_root.clone());+ let fresh = start.with_fresh_memory(&root);+ self.adopt_session_start(Some(fresh));+ }+/// Run the session on `start` from the next turn on; a no-op when it is/// already the one in use.fn adopt_session_start(&mut self, start: Option<crate::core::agent::context::SessionStart>) {@@ -5770,6 +5805,9 @@ impl App {self.resume_notice_pending = false;self.set_host_system_prompt(None);self.refresh_session_start();+ // A new session gets its own chance at an automatic tidy.+ self.auto_tidy_checked = false;+ self.auto_tidy_stamp = None;self.workspace_record = self.workspace.clone();self.snap_queue.clear();self.base_requested = false;@@ -8770,6 +8808,7 @@ impl App {if child.is_none() {self.run_compacting = None;self.pending_compaction_refresh = true;+ self.refresh_memory_snapshot();}self.transcript.finalize_tool_group();self.transcript.flush_assistant();@@ -8987,9 +9026,89 @@ impl App {// Reminder policy runs last: only if nothing else already claimed the// next turn (goal eval, a dequeued message) and open work remains.self.maybe_inject_todo_reminder(normal, no_answer, &answer);+ self.maybe_auto_tidy();self.persist();}+ /// Switch to plan mode, the one way the TUI enters it once the session is+ /// up. A tidy child runs in normal mode, so one already running would keep+ /// changing memory under a mode that keeps memory read only: it is+ /// aborted (the registry releases its slot; a note it was mid-way through+ /// is written whole or not at all, and the index is rebuilt by the next+ /// change), and a queued one is dropped. A stopped automatic tidy gets its+ /// check back, so it runs again at the first turn end after plan mode.+ fn enter_plan_mode(&mut self) {+ self.run_mode = crate::core::agent::plan::RunMode::Plan;+ let queued = self.tidy_request.take();+ let running = self.tidy_running.take();+ if let Some(run_id) = self.tidy_run_id.take() {+ self.subagent_set.abort_child(&run_id);+ }+ if queued.or(running) == Some(TidyKind::Auto) {+ self.auto_tidy_checked = false;+ self.auto_tidy_stamp = None;+ }+ if queued.is_some() || running.is_some() {+ self.note("memory tidy stopped: plan mode is read only");+ }+ }++ /// Whether this project's rules deny the `memory` tool. A tidy child keeps+ /// the parent's permissions, so with `memory` denied it could change+ /// nothing: no tidy is started.+ fn memory_denied(&self) -> bool {+ self.args.as_ref().is_some_and(|a| {+ a.permissions+ .is_denied(tauri_plugin_agent_tools::tools::MEMORY_TOOL)+ })+ }++ /// Queue an automatic memory tidy when the index has outgrown its prompt+ /// budget, at most once per session.+ ///+ /// Checked at the end of every turn rather than per write: that is when the+ /// session's own writes have landed, and the first turn's end also covers+ /// a store that was already over budget at session start. Only a queued+ /// tidy spends the session's one automatic tidy, so a store that grows+ /// past its budget mid-session is still tidied. Cheap when nothing changed:+ /// the index is rebuilt only when the notes' metadata stamp moved. The tidy+ /// runs in the background on the session's subagent registry and never+ /// starts a model turn, so it cannot block or loop; its changes reach this+ /// session only through the `Memory Changes` tail block. Off with+ /// `memory_auto_tidy = false`.+ fn maybe_auto_tidy(&mut self) {+ // Plan mode is read-only, memory included; the check resumes at the+ // first turn end after it.+ if self.auto_tidy_checked+ || self.tidy_running.is_some()+ || self.tidy_request.is_some()+ || self.run_mode == crate::core::agent::plan::RunMode::Plan+ {+ return;+ }+ let Some(root) = self.args.as_ref().and_then(|a| a.project_root.clone()) else {+ return;+ };+ if !crate::core::agent::global_config::memory_auto_tidy_enabled() || self.memory_denied() {+ return;+ }+ let (store, home, cross_project) = crate::core::agent::project::memory_roots(&root);+ let scopes = tauri_plugin_agent_tools::memory::Scopes {+ store: &store,+ home: home.as_deref(),+ cross_project,+ };+ let stamp = scopes.stamp();+ if self.auto_tidy_stamp == Some(stamp) {+ return;+ }+ self.auto_tidy_stamp = Some(stamp);+ if scopes.over_budget() {+ self.auto_tidy_checked = true;+ self.tidy_request = Some(TidyKind::Auto);+ }+ }+/// Whether auto-compaction should trigger: a non-zero token use above the/// active resolved threshold (window minus reserve) with enough history to/// shrink. The window is authoritative for the selected model (configured@@ -11466,11 +11585,19 @@ fn explore_of(name: &str, args: &serde_json::Value) -> Option<Explore> {query: s("pattern"),scope: scope(),}),- "memory_read" => Some(named("memory")),+ "memory" => match args.get("op").and_then(|v| v.as_str()) {+ Some("view") if !s("name").is_empty() => Some(named("memory")),+ Some("view") => Some(Explore::List {+ target: "memory notes".to_string(),+ }),+ Some("search") => Some(Explore::Search {+ query: s("query"),+ scope: Some("memory".to_string()),+ }),+ // write/edit/delete change memory: not an exploration.+ _ => None,+ },"skill_read" => Some(named("skill")),- "memory_list" => Some(Explore::List {- target: "memory notes".to_string(),- }),"skill_list" => Some(Explore::List {target: "skills".to_string(),}),@@ -13516,7 +13643,7 @@ async fn chat_loop<B: Backend>(// whole session rather than for one run: a child outliving the run that// dispatched it must still reach its panel and emit its closing bracket.let (session_events_tx, mut session_events) = mpsc::unbounded_channel::<StreamEvent>();- subagent_set.install_session_events(session_events_tx);+ subagent_set.install_session_events(session_events_tx.clone());// Active MCP servers connect in the background; gate the first run on them// so the model's tools (collected once per run) are ready.let mut mcp_ready = mcp_task.is_none();@@ -13588,6 +13715,8 @@ async fn chat_loop<B: Backend>(let mut compact_task: Option<tokio::task::JoinHandle<Result<Vec<serde_json::Value>, String>>> =None;let mut compact_base = 0usize;+ // A memory tidy runs as a session-owned subagent; this collects its answer.+ let mut tidy_task: Option<tokio::task::JoinHandle<Result<String, String>>> = None;// The dock's branch indicator is captured once at startup; re-read it on a// slow timer so a checkout made outside the TUI (another terminal, an@@ -13821,6 +13950,23 @@ async fn chat_loop<B: Backend>(}}+ // Entering plan mode stops the tidy and drops `tidy_running`; its+ // collector would only report the cancellation as a failure.+ if app.tidy_running.is_none() {+ if let Some(task) = tidy_task.take() {+ task.abort();+ }+ }++ // A memory tidy was asked for: start it in the background. It writes+ // only memory and never starts a turn, so it runs beside whatever else+ // the session is doing.+ if tidy_task.is_none() {+ if let Some(kind) = app.tidy_request.take() {+ tidy_task = start_memory_tidy(app, kind, &session_events_tx);+ }+ }+// A turn finished under an active goal: run the (stateless) evaluator// before anything else. It either auto-submits the next turn (setting// want_start) or hands control back. Gated on an idle, run-free state so@@ -14111,6 +14257,9 @@ async fn chat_loop<B: Backend>(compacted = await_compaction(&mut compact_task) => {finish_compaction(app, compacted, compact_base);}+ tidied = await_memory_tidy(&mut tidy_task) => {+ finish_memory_tidy(app, tidied);+ }snap_res = await_snapshot(&mut snap_task) => {match (snap_inflight.take(), snap_res) {(Some(SnapshotJob::Base), Ok(sha)) => {@@ -16569,6 +16718,12 @@ const SLASH_COMMANDS: &[SlashCommand] = &[description: "Study the project, then write AGENTS.md, skills, and memory",alias_of: None,},+ SlashCommand {+ name: "/memory",+ hint: "[tidy]",+ description: "Show the memory index size, or tidy memory in the background",+ alias_of: None,+ },SlashCommand {name: "/compact",hint: "",@@ -16985,6 +17140,7 @@ async fn run_command("settings" => settings_command(app, arg),"vibe-setting" => vibe_setting::command(app, arg),"goal" => goal_command(app, arg),+ "memory" => memory_command(app, arg),"init" => init_command(app),"plan" => plan_command(app, arg),"effort" | "think" | "reasoning" => effort_command(app, arg),@@ -17208,7 +17364,7 @@ it wholesale.\n\n\3. Write skills with `skill_write` for the project's repeatable procedures -- releasing, running \migrations, adding a module, debugging a subsystem -- one skill per procedure, only where a real \multi-step recipe exists. Do not invent skills to fill space.\n\n\-4. Record durable project facts with `memory_write`: decisions, constraints, and gotchas that are \+4. Record durable project facts with the `memory` tool (search first, update rather than duplicate): decisions, constraints, and gotchas that are \true beyond this session and not already stated in the code.\n\n\Then report what you wrote and why, briefly.")@@ -17351,6 +17507,200 @@ fn compact_command(app: &mut App) {app.compact_request = Some(CompactKind::Manual);}+/// `/memory`: `tidy` starts a memory tidy in the background; bare shows the+/// index size against its budget.+fn memory_command(app: &mut App, arg: &str) {+ let Some(root) = app.args.as_ref().and_then(|a| a.project_root.clone()) else {+ app.note("memory is unavailable (no active project)");+ return;+ };+ match arg.trim() {+ "tidy" => {+ if app.memory_denied() {+ app.note("memory tidy is unavailable: this project's rules deny the memory tool");+ return;+ }+ // The tidy child runs in normal mode, so without this it would+ // change memory that plan mode keeps read-only.+ if app.run_mode == crate::core::agent::plan::RunMode::Plan {+ app.note("memory tidy is unavailable in plan mode (read only); /plan exit to leave");+ return;+ }+ if app.tidy_running.is_some() || app.tidy_request.is_some() {+ app.note("a memory tidy is already running");+ return;+ }+ // A manual tidy also settles this session's automatic one.+ app.auto_tidy_checked = true;+ app.tidy_request = Some(TidyKind::Manual);+ }+ "" => {+ let (store, home, cross_project) = crate::core::agent::project::memory_roots(&root);+ let scopes = tauri_plugin_agent_tools::memory::Scopes {+ store: &store,+ home: home.as_deref(),+ cross_project,+ };+ app.note(&format!(+ "memory index: ~{} of {} tokens; /memory tidy archives, merges and prunes notes",+ scopes.index_tokens(),+ tauri_plugin_agent_tools::memory::INDEX_BUDGET_TOKENS+ ));+ }+ other => app.note(&format!("unknown /memory option '{other}' (try /memory tidy)")),+ }+}++/// Which path asked for a memory tidy. A manual one reports even when it+/// changed nothing; an automatic one stays quiet unless it did something.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+enum TidyKind {+ Manual,+ Auto,+}++/// Start the requested tidy on the session's registry. Fire-and-forget from+/// the caller's view: the result is collected off the render loop.+fn start_memory_tidy(+ app: &mut App,+ kind: TidyKind,+ events: &mpsc::UnboundedSender<StreamEvent>,+) -> Option<tokio::task::JoinHandle<Result<String, String>>> {+ let args = app.args.clone()?;+ if app.model.is_empty() {+ if kind == TidyKind::Manual {+ app.note("memory tidy needs a model: run /login first");+ }+ return None;+ }+ let parent = crate::core::agent::subagent::ParentRun {+ model: app.model.clone(),+ smol_model: crate::core::agent::subagent::configured_smol_model(),+ budget_remaining: None,+ send_reasoning: app.send_reasoning,+ cost_remaining: None,+ tool_ceiling: None,+ known_tools: Vec::new(),+ };+ let set = app.subagent_set.clone();+ let budget = Arc::new(tauri_plugin_agent_tools::memory::ChangeBudget::new(+ tauri_plugin_agent_tools::memory::TIDY_MAX_CHANGES,+ ));+ let dispatched = crate::core::agent::subagent::spawn_memory_tidy(+ &set.scope(),+ &args,+ &parent,+ events,+ budget.clone(),+ );+ match dispatched {+ Ok(dispatched) => {+ app.tidy_running = Some(kind);+ app.tidy_run_id = Some(dispatched.run_id.clone());+ let label = match kind {+ TidyKind::Manual => "tidying memory in the background",+ TidyKind::Auto => "memory index is over its budget: tidying in the background",+ };+ app.note(label);+ Some(tokio::spawn(async move {+ let report = crate::core::agent::subagent::await_subagent(&set, &dispatched.run_id)+ .await+ .map(|collected| collected.text)+ .map_err(|e| e.to_string())?;+ Ok(with_cap_note(report, &budget))+ }))+ }+ Err(e) => {+ if kind == TidyKind::Manual {+ app.note(&format!("memory tidy failed to start: {e}"));+ }+ None+ }+ }+}++/// Report a finished tidy: its own summary of what it changed, as one note.+fn finish_memory_tidy(app: &mut App, result: Result<String, String>) {+ let kind = app.tidy_running.take().unwrap_or(TidyKind::Manual);+ app.tidy_run_id = None;+ match result {+ Ok(report) => {+ let report = report.trim();+ let quiet = report.is_empty() || report.eq_ignore_ascii_case("no changes");+ if quiet && kind == TidyKind::Auto {+ return;+ }+ app.note(&format!(+ "memory tidied: {}",+ if quiet { "no changes".to_string() } else { tidy_summary(report) }+ ));+ }+ Err(e) => app.note(&format!("memory tidy failed: {e}")),+ }+}++/// The tidy's report, with a closing line when the harness refused changes+/// past the cap: the model may not say so, and the user should know the store+/// was only partly tidied.+fn with_cap_note(report: String, budget: &tauri_plugin_agent_tools::memory::ChangeBudget) -> String {+ if budget.refused() == 0 {+ return report;+ }+ format!(+ "{}\ncap reached ({} changes); run /memory tidy again to continue",+ report.trim_end(),+ budget.used()+ )+}++/// Verbs a tidy report's lines start with (see `MEMORY_TIDY_PROMPT`).+const TIDY_VERBS: [&str; 4] = ["archived", "merged", "deleted", "moved"];++/// A tidy report as one line. The report has a line per change, and a note+/// that carried all of them grew taller than the screen, pushing its own+/// `memory tidied:` header out of view. A few changes are listed; more are+/// counted per verb, the full list staying in the memory-tidy row.+fn tidy_summary(report: &str) -> String {+ let changes: Vec<&str> = report+ .lines()+ .map(|l| l.trim().trim_start_matches(['-', '*', ' ']))+ .filter(|l| TIDY_VERBS.iter().any(|v| l.starts_with(v)))+ .collect();+ let summary = if changes.is_empty() {+ let first = report.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim();+ first.chars().take(160).collect()+ } else if changes.len() <= 3 {+ changes.join("; ")+ } else {+ TIDY_VERBS+ .iter()+ .filter_map(|verb| {+ let n = changes.iter().filter(|l| l.starts_with(verb)).count();+ (n > 0).then(|| format!("{verb} {n}"))+ })+ .collect::<Vec<_>>()+ .join(", ")+ };+ match report.lines().find(|l| l.starts_with("cap reached (")) {+ Some(cap) if !summary.contains("cap reached") => format!("{summary}; {cap}"),+ _ => summary,+ }+}++async fn await_memory_tidy(+ task: &mut Option<tokio::task::JoinHandle<Result<String, String>>>,+) -> Result<String, String> {+ let joined = match task.as_mut() {+ Some(h) => h.await,+ None => return pending().await,+ };+ *task = None;+ match joined {+ Ok(inner) => inner,+ Err(e) => Err(format!("memory tidy task failed: {e}")),+ }+}+/// Compact-and-retry attempts allowed per user turn. The loop already retries/// within a single request (`MAX_COMPACTION_ATTEMPTS`); this bounds the outer/// recovery so a model that overflows at any size still hands control back.@@ -17418,6 +17768,7 @@ fn finish_compaction(Ok(mut compacted) if compacted.len() < base_len => {compacted.extend(app.history.split_off(base_len.min(app.history.len())));app.history = compacted;+ app.refresh_memory_snapshot();app.persist();// Estimate tokens from compacted message content (~4 chars ≈ 1 token).// The provider's last `usage` measured the pre-compaction history, so@@ -17663,6 +18014,13 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[kind: AgentSettingKind::Bool { default: true },scope: SettingScope::Global,},+ AgentSettingDef {+ key: "memory_auto_tidy",+ label: "memory_auto_tidy",+ desc: "tidy memory in the background when its index outgrows the prompt budget",+ kind: AgentSettingKind::Bool { default: true },+ scope: SettingScope::Global,+ },AgentSettingDef {key: "hide_secrets",label: "hide_secrets",@@ -19134,7 +19492,7 @@ fn plan_command(app: &mut App, arg: &str) {}return;}- app.run_mode = RunMode::Plan;+ app.enter_plan_mode();app.persist();app.note("◈ PLAN · read only — investigate, then propose a plan for review");if app.goal.is_some() {@@ -21938,6 +22296,7 @@ fn restore_run_mode(app: &mut App, metadata: Option<&serde_json::Value>) {{app.run_mode = mode;if mode == RunMode::Plan {+ app.enter_plan_mode();app.note("resumed in plan mode (read only); /plan exit to leave");}}@@ -25715,6 +26074,7 @@ mod tests {await_shell_ping, brand,build_user_message, clipboard_path, compact_tokens, context_lines, diff_lines,drain_stream_events, estimate_token_count, finish_account_login, finish_compaction,+ finish_memory_tidy, memory_command, start_memory_tidy, TidyKind, with_cap_note,finish_context_report, finish_login, finish_plugin_install, finish_tokamak_login,agent_stats, finish_update_install, fork_at, format_tokens, group_detail_lines, group_summary,handle_ask_key, handle_ask_mouse, handle_key, handle_mouse, handle_plugin_setup_key,@@ -30064,7 +30424,7 @@ mod tests {"Reading main.rs");assert_eq!(- tool_activity("memory_write", &json!({ "name": "decisions" })),+ tool_activity("memory", &json!({ "op": "write", "name": "decisions" })),"Updating memory: decisions");}@@ -32716,7 +33076,7 @@ mod tests {assert!(sent.contains("Write `AGENTS.md`"), "{sent}");assert!(!sent.contains("JAN.md"), "a new project never hears of JAN.md: {sent}");assert!(sent.contains("skill_write"), "{sent}");- assert!(sent.contains("memory_write"), "{sent}");+ assert!(sent.contains("`memory` tool"), "{sent}");let _ = std::fs::remove_dir_all(&app.agent_dir);}@@ -33265,6 +33625,7 @@ mod tests {shell_detach: None,compaction: None,session_start: None,+ memory_change_budget: None,})}@@ -36987,10 +37348,10 @@ mod tests {fn consecutive_collapsible_tools_fold_into_one_summary_row() {let mut app = test_app();let calls = [- ("c1", "memory_list", json!({})),+ ("c1", "memory", json!({ "op": "view" })),("c2", "skill_list", json!({})),- ("c3", "memory_read", json!({ "name": "project-overview" })),- ("c4", "memory_read", json!({ "name": "top-p" })),+ ("c3", "memory", json!({ "op": "view", "name": "project-overview" })),+ ("c4", "memory", json!({ "op": "view", "name": "top-p" })),];for (id, name, args) in calls {app.apply(StreamEvent::ToolCall {@@ -37042,8 +37403,8 @@ mod tests {fn folded_group_expands_and_collapses_via_keybinding() {let mut app = test_app();let calls = [- ("c1", "memory_read", json!({ "name": "project-overview" })),- ("c2", "memory_read", json!({ "name": "top-p" })),+ ("c1", "memory", json!({ "op": "view", "name": "project-overview" })),+ ("c2", "memory", json!({ "op": "view", "name": "top-p" })),];for (id, name, args) in calls {app.apply(StreamEvent::ToolCall {@@ -37082,8 +37443,8 @@ mod tests {fn folded_group_expands_and_collapses_via_click() {let mut app = test_app();let calls = [- ("c1", "memory_read", json!({ "name": "project-overview" })),- ("c2", "memory_read", json!({ "name": "top-p" })),+ ("c1", "memory", json!({ "op": "view", "name": "project-overview" })),+ ("c2", "memory", json!({ "op": "view", "name": "top-p" })),];for (id, name, args) in calls {app.apply(StreamEvent::ToolCall {@@ -37664,8 +38025,8 @@ mod tests {let mut app = test_app();app.apply(StreamEvent::ToolCall {id: "c1".into(),- name: "memory_read".into(),- args: json!({ "name": "x" }),+ name: "memory".into(),+ args: json!({ "op": "view", "name": "x" }),});app.apply(StreamEvent::ToolResult {id: "c1".into(),@@ -44185,6 +44546,392 @@ mod tests {assert_eq!(start, Some(fresh), "the snapshot is the one taken at /new");}+ /// Point `app` at a fresh project of its own, so its memory store is not+ /// shared with any other test's.+ fn own_project(app: &mut App) {+ app.project_root = tempfile::tempdir().unwrap().keep();+ let _ = std::fs::remove_dir_all(crate::core::agent::project::store_root(&app.project_root));+ app.args = Some(test_args(app, std::collections::HashMap::new()));+ }++ /// An app on a project whose memory index is far over its budget, with a+ /// temp home so the config read is the default (auto-tidy on).+ fn over_budget_app(app: &mut App) {+ own_project(app);+ fill_store(app);+ }++ /// Write enough notes into `app`'s own store to put its index over budget.+ fn fill_store(app: &App) {+ let dir = crate::core::agent::project::store_root(&app.project_root).join("memory");+ std::fs::create_dir_all(&dir).unwrap();+ for i in 0..200 {+ std::fs::write(+ dir.join(format!("n{i:03}.md")),+ "A long finished note about a merged pull request and its review",+ )+ .unwrap();+ }+ }++ /// Auto-tidy is on by default and fires once per session when the index is+ /// over budget: a second turn does not queue another, and a new session+ /// gets one fresh check.+ #[test]+ fn auto_tidy_queues_once_per_session_when_over_budget() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut app = test_app();+ over_budget_app(&mut app);+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, Some(TidyKind::Auto));+ app.tidy_request = None;+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None, "debounced: once per session");+ app.reset_session();+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, Some(TidyKind::Auto), "a new session checks again");+ });+ }++ /// Under budget nothing is queued and the check is not spent: a store that+ /// outgrows its budget later in the session is tidied at that turn's end,+ /// still only once.+ #[test]+ fn auto_tidy_rechecks_each_turn_until_the_index_outgrows_its_budget() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut app = test_app();+ own_project(&mut app);+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None, "a small index is left alone");+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None);+ fill_store(&app);+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, Some(TidyKind::Auto), "a later over-budget turn tidies");+ app.tidy_request = None;+ let dir = crate::core::agent::project::store_root(&app.project_root).join("memory");+ std::fs::write(dir.join("later.md"), "Another note").unwrap();+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None, "still at most once per session");+ });+ }++ /// With `memory` denied a tidy child could change nothing, so neither the+ /// automatic nor the manual tidy starts one.+ #[test]+ fn no_tidy_starts_when_the_project_denies_memory() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut app = test_app();+ over_budget_app(&mut app);+ let mut args = (**app.args.as_ref().unwrap()).clone();+ args.permissions = tauri_plugin_agent_tools::permissions::ToolPermissions::new(+ tauri_plugin_agent_tools::permissions::PermissionDefault::Allow,+ &[],+ &["memory".to_string()],+ &[],+ );+ app.args = Some(Arc::new(args));+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None, "no automatic tidy");+ memory_command(&mut app, "tidy");+ assert_eq!(app.tidy_request, None, "no manual tidy");+ });+ }++ /// Plan mode is read-only, so auto-tidy waits it out rather than spending+ /// the session's one automatic tidy.+ #[test]+ fn auto_tidy_waits_out_plan_mode() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut app = test_app();+ over_budget_app(&mut app);+ app.run_mode = crate::core::agent::plan::RunMode::Plan;+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None, "nothing queued in plan mode");+ app.run_mode = crate::core::agent::plan::RunMode::Normal;+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, Some(TidyKind::Auto));+ });+ }++ /// A manual tidy changes memory, which plan mode refuses: it is turned+ /// away with a pointer out of plan mode, and works once plan mode is left.+ #[test]+ fn manual_tidy_is_refused_in_plan_mode() {+ crate::core::agent::global_config::with_temp_home(|_| {+ let mut app = test_app();+ over_budget_app(&mut app);+ app.run_mode = crate::core::agent::plan::RunMode::Plan;+ memory_command(&mut app, "tidy");+ assert_eq!(app.tidy_request, None, "nothing queued in plan mode");+ let text: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("plan mode") && text.contains("/plan exit"), "{text}");+ app.run_mode = crate::core::agent::plan::RunMode::Normal;+ memory_command(&mut app, "tidy");+ assert_eq!(app.tidy_request, Some(TidyKind::Manual));+ });+ }++ /// A tidy already running when plan mode is entered is stopped, not left+ /// to change memory under a read-only mode: its child is aborted, its+ /// bookkeeping released, and the user is told. Driven with a real spawned+ /// tidy against an upstream that never answers, so it is mid-run.+ #[tokio::test]+ async fn entering_plan_mode_stops_a_running_tidy() {+ use crate::core::agent::plan::RunMode;+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ std::thread::spawn(move || {+ let held: Vec<_> = listener.incoming().collect();+ drop(held);+ });+ let providers = std::iter::once((+ "stub".to_string(),+ crate::core::state::ProviderConfig {+ provider: "stub".into(),+ base_url: Some(format!("http://{addr}/v1")),+ api_key: Some("k".into()),+ models: vec!["m".into()],+ ..Default::default()+ },+ ))+ .collect();+ let mut app = test_app();+ own_project(&mut app);+ app.args = Some(test_args(&app, providers));+ let (tx, _rx) = mpsc::unbounded_channel();+ let task = start_memory_tidy(&mut app, TidyKind::Manual, &tx).expect("tidy started");+ assert_eq!(app.tidy_running, Some(TidyKind::Manual));+ assert_eq!(app.subagent_set.live_run_ids().len(), 1, "the tidy child is live");+ run_command(&mut app, "plan", &no_mcp()).await;+ assert_eq!(app.run_mode, RunMode::Plan);+ assert!(app.subagent_set.live_run_ids().is_empty(), "the tidy child was aborted");+ assert_eq!(app.tidy_running, None, "a later tidy may start once plan mode is left");+ let collected = tokio::time::timeout(Duration::from_secs(5), task).await;+ assert!(matches!(collected, Ok(Ok(Err(_)))), "the tidy produced no report");+ let text: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("memory tidy stopped: plan mode is read only"), "{text}");+ }++ /// A queued tidy is dropped by entering plan mode, from `/plan` or by+ /// resuming a thread saved in plan mode; with nothing to stop, nothing is+ /// said.+ #[tokio::test]+ async fn entering_plan_mode_drops_a_queued_tidy() {+ use crate::core::agent::plan::RunMode;+ let mut app = test_app();+ app.tidy_request = Some(TidyKind::Manual);+ run_command(&mut app, "plan", &no_mcp()).await;+ assert_eq!(app.tidy_request, None);+ let text: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("memory tidy stopped: plan mode is read only"), "{text}");++ let meta = json!({ "run_mode": "plan" });+ let mut resumed = test_app();+ resumed.tidy_request = Some(TidyKind::Auto);+ resumed.tidy_running = Some(TidyKind::Auto);+ restore_run_mode(&mut resumed, Some(&meta));+ assert_eq!(resumed.run_mode, RunMode::Plan);+ assert_eq!(resumed.tidy_request, None);+ assert_eq!(resumed.tidy_running, None);+ let text: String = resumed.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("memory tidy stopped"), "{text}");++ let mut idle = test_app();+ run_command(&mut idle, "plan", &no_mcp()).await;+ let text: String = idle.transcript.rows.iter().map(row_text).collect();+ assert!(!text.contains("memory tidy"), "{text}");+ }++ /// `memory_auto_tidy = false` turns the automatic trigger off; `/memory+ /// tidy` still works.+ #[test]+ fn auto_tidy_can_be_turned_off_but_the_manual_tidy_still_runs() {+ crate::core::agent::global_config::with_temp_home(|home| {+ let path = home.join(".jan").join("config.toml");+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, "memory_auto_tidy = false\n").unwrap();+ let mut app = test_app();+ over_budget_app(&mut app);+ app.maybe_auto_tidy();+ assert_eq!(app.tidy_request, None);+ memory_command(&mut app, "tidy");+ assert_eq!(app.tidy_request, Some(TidyKind::Manual));+ memory_command(&mut app, "tidy");+ let text: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("already running"), "{text}");+ });+ }++ /// A tidy's report is surfaced as one note; an automatic tidy that changed+ /// nothing says nothing, a manual one says so.+ #[test]+ fn a_finished_tidy_reports_what_it_changed() {+ let mut app = test_app();+ app.tidy_running = Some(TidyKind::Auto);+ finish_memory_tidy(&mut app, Ok("no changes".into()));+ assert!(app.transcript.rows.is_empty(), "a quiet auto tidy adds no row");+ assert!(app.tidy_running.is_none());+ app.tidy_running = Some(TidyKind::Auto);+ finish_memory_tidy(&mut app, Ok("archived pr-1\ndeleted old: superseded".into()));+ app.tidy_running = Some(TidyKind::Manual);+ finish_memory_tidy(&mut app, Ok("no changes".into()));+ let text: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("memory tidied: archived pr-1"), "{text}");+ assert!(text.contains("memory tidied: no changes"), "{text}");+ }++ /// A stub OpenAI-compatible upstream answering every request with `text`+ /// as a plain final answer. Returns the provider configs pointing at it.+ fn stub_upstream(+ text: &'static str,+ ) -> std::collections::HashMap<String, crate::core::state::ProviderConfig> {+ use std::io::{BufRead, BufReader, Read, Write};+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ std::thread::spawn(move || {+ for connection in listener.incoming() {+ let Ok(mut stream) = connection else { break };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut size = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ size = n.trim().parse().unwrap_or(0);+ }+ }+ let mut body = vec![0; size];+ let _ = reader.read_exact(&mut body);+ let chunk = json!({"id": "s", "object": "chat.completion.chunk", "created": 1,+ "model": "m", "choices": [{"index": 0, "delta": {"role": "assistant",+ "content": text}, "finish_reason": "stop"}]});+ let answer = format!("data: {chunk}\n\ndata: [DONE]\n\n");+ let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len());+ }+ });+ std::iter::once((+ "stub".to_string(),+ crate::core::state::ProviderConfig {+ provider: "stub".into(),+ base_url: Some(format!("http://{addr}/v1")),+ api_key: Some("k".into()),+ models: vec!["m".into()],+ ..Default::default()+ },+ ))+ .collect()+ }++ /// #497 bug 2: the `memory tidied:` note never showed in the live TUI.+ /// The tidy's report is one line per change, and the whole report became+ /// one note, so with dozens of changes its header scrolled off before a+ /// frame painted it. Driven through the real select loop with a spawned+ /// tidy against a stub provider, and checked on the rendered frame.+ #[tokio::test]+ async fn a_spawned_tidy_shows_its_note_in_the_live_frame() {+ let report: &'static str = Box::leak(+ (0..70)+ .map(|i| format!("archived note-{i:03}"))+ .collect::<Vec<_>>()+ .join("\n")+ .into_boxed_str(),+ );+ let mut app = test_app();+ own_project(&mut app);+ let args = test_args(&app, stub_upstream(report));+ app.args = Some(args.clone());+ app.tidy_request = Some(TidyKind::Manual);+ let mut terminal =+ ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();+ let registry: PermissionRegistry = Default::default();+ let asks = crate::core::agent::interaction::new_registry();+ let servers: crate::core::state::SharedMcpServers = Default::default();+ // The loop has no exit of its own here; the tidy lands well inside this.+ let _ = tokio::time::timeout(+ Duration::from_secs(8),+ super::chat_loop(&mut terminal, &args, ®istry, &asks, &mut app, None, None, &servers, false),+ )+ .await;+ assert!(app.tidy_running.is_none(), "the tidy was collected");+ terminal.draw(|f| super::draw(f, &mut app)).unwrap();+ let buf = terminal.backend().buffer().clone();+ let frame: String = (0..buf.area.height)+ .map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect::<String>() + "\n")+ .collect();+ assert!(frame.contains("memory tidied: archived 70"), "{frame}");+ assert!(!frame.contains("archived note-030"), "one line, not the full list: {frame}");+ }++ /// A tidy the harness stopped at its cap says so in its note, even when+ /// the model's report does not.+ #[test]+ fn a_capped_tidy_reports_the_cap() {+ let budget = tauri_plugin_agent_tools::memory::ChangeBudget::new(2);+ assert_eq!(with_cap_note("archived a".into(), &budget), "archived a");+ let dir = tempfile::tempdir().unwrap();+ let rt = tokio::runtime::Runtime::new().unwrap();+ let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(dir.path(), dir.path(), &[])+ .with_memory_change_budget(Some(&budget));+ let memory = tauri_plugin_agent_tools::tools::lookup("memory").unwrap();+ for i in 0..3 {+ rt.block_on(tauri_plugin_agent_tools::tools::handlers::execute_builtin(+ memory,+ &json!({"op": "write", "name": format!("n{i}"), "content": "x"}),+ &ctx,+ ));+ }+ let report = with_cap_note("archived a\narchived b".into(), &budget);+ let mut app = test_app();+ app.tidy_running = Some(TidyKind::Auto);+ finish_memory_tidy(&mut app, Ok(report));+ let text: String = app.transcript.rows.iter().map(row_text).collect();+ assert!(text.contains("memory tidied: archived a; archived b; cap reached (2 changes)"), "{text}");+ }++ /// A tidy never touches the conversation: no turn is started and the+ /// history is unchanged, so the session's prompt is not rewritten.+ #[test]+ fn a_tidy_never_starts_a_turn_or_edits_history() {+ let mut app = test_app();+ app.history.push(json!({ "role": "user", "content": "hi" }));+ let before = app.history.clone();+ app.tidy_running = Some(TidyKind::Manual);+ finish_memory_tidy(&mut app, Ok("archived pr-1".into()));+ assert!(!app.want_start);+ assert_eq!(app.history, before);+ }++ #[test]+ fn memory_is_a_slash_command() {+ let row = SLASH_COMMANDS.iter().find(|c| c.name == "/memory").unwrap();+ assert_eq!(row.hint, "[tidy]");+ assert!(AGENT_SETTINGS.iter().any(|d| d.key == "memory_auto_tidy"+ && matches!(d.kind, super::AgentSettingKind::Bool { default: true })));+ }++ /// A compaction rewrites the history anyway, so the session takes a fresh+ /// memory index there; the date and branch stay the session's.+ #[test]+ fn a_compaction_refreshes_only_the_memory_snapshot() {+ let mut app = test_app();+ let mut args = (*test_args(&app, std::collections::HashMap::new())).clone();+ let stale = crate::core::agent::context::SessionStart::fixed("1999-01-01", Some("stale"));+ args.session_start = Some(stale.clone());+ app.args = Some(std::sync::Arc::new(args));+ app.compacting = Some(CompactKind::Manual);+ app.history = (0..5)+ .map(|i| json!({ "role": "user", "content": format!("m{i}") }))+ .collect();+ finish_compaction(&mut app, Ok(vec![json!({ "role": "user", "content": "s" })]), 5);+ let start = app.args.as_ref().and_then(|a| a.session_start.clone()).unwrap();+ let root = app.args.as_ref().and_then(|a| a.project_root.clone()).unwrap_or(app.project_root.clone());+ assert_eq!(start, stale.with_fresh_memory(&root));+ assert!(start.memory().is_some(), "the memory index was re-taken");+ }+/// A fork continues the source's prefix, so it keeps the source's snapshot/// (same date, same branch, same system prompt bytes) and sends no resume/// notice, where a resume of the same thread takes a fresh snapshot.diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rsindex 6a079094e..6e969e818 100644--- a/src-tauri/src/core/mcp/server/mod.rs+++ b/src-tauri/src/core/mcp/server/mod.rs@@ -72,7 +72,7 @@ impl ServedTools {match tool.capability {Capability::Exec => self.allow_exec,// A `Write` tool with no path argument is a workspace tool- // (`memory_write`, `skill_write`): it writes into the agent's own+ // (`skill_write`): it writes into the agent's own// store by sanitized name and can never reach a project file, so it// belongs to the memory/skill set rather than the mutating one.Capability::Write => self.allow_write || tool.path_args.is_empty(),diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rsindex 25ca25cd0..079fdd710 100644--- a/src-tauri/src/core/mcp/server/tests.rs+++ b/src-tauri/src/core/mcp/server/tests.rs@@ -32,10 +32,9 @@ fn default_served_set_is_read_only() {assert!(names.contains(&"find".to_string()));assert!(names.contains(&"grep".to_string()));assert!(names.contains(&"web_search".to_string()));- assert!(names.contains(&"memory_read".to_string()));- // Workspace writes stay in: they reach the agent's own store by name, never- // a project file.- assert!(names.contains(&"memory_write".to_string()));+ // Memory and workspace writes stay in: they reach the agent's own store+ // by name, never a project file.+ assert!(names.contains(&"memory".to_string()));assert!(names.contains(&"skill_write".to_string()));assert!(!names.contains(&"write".to_string()));assert!(!names.contains(&"edit".to_string()));diff --git a/web-app/src/containers/message/AgentToolWidget.tsx b/web-app/src/containers/message/AgentToolWidget.tsxindex eb9ff3634..81365334d 100644--- a/web-app/src/containers/message/AgentToolWidget.tsx+++ b/web-app/src/containers/message/AgentToolWidget.tsx@@ -239,44 +239,65 @@ const TOOL_ICONS: Record<string, typeof IconFile> = {grep: IconSearch,write: IconFilePencil,edit: IconFilePencil,- memory_list: IconNotebook,- memory_read: IconNotebook,- memory_write: IconNotebook,+ memory: IconNotebook,skill_list: IconBook,skill_read: IconBook,skill_write: IconBook,}/** Tools whose whole call is the verb: there is no argument worth a bar. */-const LISTING_TOOLS = new Set(['memory_list', 'skill_list', 'ls'])+const LISTING_TOOLS = new Set(['skill_list', 'ls'])// A workspace call is not always a read: `Reading...` under a `write` is simply// wrong, and the verb is the only progress signal the widget has.const RUNNING_KEYS: Record<string, string> = {write: 'tools:toolCall.writing',- memory_write: 'tools:toolCall.writing',skill_write: 'tools:toolCall.writing',edit: 'tools:toolCall.editing',find: 'tools:toolCall.searching',grep: 'tools:toolCall.searching',ls: 'tools:toolCall.listing',- memory_list: 'tools:toolCall.listing',skill_list: 'tools:toolCall.listing',}+type WorkspaceBar = Extract<ToolCallBar, { variant: 'workspace' }>++/** A bare `view` lists the whole store, like `ls` with no path. */+const isMemoryListing = (bar: WorkspaceBar) =>+ bar.tool === 'memory' && bar.op === 'view' && !bar.target++// `memory` is one tool for reads and changes alike, so its op picks the verb.+const runningKey = (bar: WorkspaceBar): string => {+ if (bar.tool !== 'memory') {+ return RUNNING_KEYS[bar.tool] ?? 'tools:toolCall.reading'+ }+ switch (bar.op) {+ case 'write':+ case 'edit':+ case 'delete':+ case 'move':+ return 'tools:toolCall.writing'+ case 'search':+ return 'tools:toolCall.searching'+ default:+ return isMemoryListing(bar)+ ? 'tools:toolCall.listing'+ : 'tools:toolCall.reading'+ }+}+// find/grep bars carry a pattern and memory/skill an entry name, so `path` is// the wrong prompt for both.const PLACEHOLDER_KEYS: Record<string, string> = {find: 'tools:toolCall.patternPlaceholder',grep: 'tools:toolCall.patternPlaceholder',- memory_read: 'tools:toolCall.namePlaceholder',- memory_write: 'tools:toolCall.namePlaceholder',+ memory: 'tools:toolCall.namePlaceholder',skill_read: 'tools:toolCall.namePlaceholder',skill_write: 'tools:toolCall.namePlaceholder',}export type AgentToolWidgetProps = {- bar: Extract<ToolCallBar, { variant: 'workspace' }>+ bar: WorkspaceBarstate: ToolUIPart['state']output?: ToolUIPart['output']errorText?: string@@ -298,11 +319,16 @@ export const AgentToolWidget = memo()const Icon = TOOL_ICONS[bar.tool] ?? IconFileconst body = asText(output)- // `ls` with no path lists the workspace root; show that rather than a bar- // that reads as though an argument failed to stream.+ // `ls` with no path lists the workspace root, and a bare memory view the+ // whole store; show that rather than a bar that reads as though an+ // argument failed to stream.const value =bar.target ||- (LISTING_TOOLS.has(bar.tool) ? t('tools:toolCall.workspaceRoot') : '')+ (LISTING_TOOLS.has(bar.tool)+ ? t('tools:toolCall.workspaceRoot')+ : isMemoryListing(bar)+ ? t('settings:cowork.memories')+ : '')return (<div className="space-y-1.5">@@ -340,7 +366,7 @@ export const AgentToolWidget = memo(!errorText && (<div className="px-2 text-sm"><Shimmer duration={1}>- {t(RUNNING_KEYS[bar.tool] ?? 'tools:toolCall.reading')}+ {t(runningKey(bar))}</Shimmer></div>)diff --git a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsxindex 53cc51de9..070f71004 100644--- a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx+++ b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx@@ -110,6 +110,40 @@ describe('AgentToolWidget', () => {expect(screen.queryByText(/\[hook config/)).not.toBeInTheDocument()})+ // One `memory` tool covers reads and changes alike, so its op, not the tool+ // name, decides the verb.+ it.each([+ ['write', 'prefs', 'tools:toolCall.writing'],+ ['edit', 'prefs', 'tools:toolCall.writing'],+ ['delete', 'prefs', 'tools:toolCall.writing'],+ ['move', 'prefs', 'tools:toolCall.writing'],+ ['search', 'cuda', 'tools:toolCall.searching'],+ ['view', '', 'tools:toolCall.listing'],+ ['view', 'prefs', 'tools:toolCall.reading'],+ ])('names what memory %s (%s) is doing while it runs', (op, target, key) => {+ render(+ <AgentToolWidget+ bar={{ variant: 'workspace', tool: 'memory', target, op }}+ state="input-available"+ toolCallId="tc1"+ />+ )+ expect(screen.getByText(key)).toBeInTheDocument()+ })++ // A bare view lists the whole store; say so rather than leave an empty bar+ // that reads as though the name failed to stream.+ it('names the store on a memory view with no name', () => {+ render(+ <AgentToolWidget+ bar={{ variant: 'workspace', tool: 'memory', target: '', op: 'view' }}+ state="input-available"+ toolCallId="tc1"+ />+ )+ expect(screen.getByText('settings:cowork.memories')).toBeInTheDocument()+ })+it('prompts for a pattern rather than a path on grep', () => {renderRunning('grep')expect(diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex 84d10f70c..c1890272c 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -91,12 +91,12 @@ describe('agentTools', () => {toolSchemas.mockResolvedValue([schemaFor('read'),schemaFor('write'),- schemaFor('memory_write'),+ schemaFor('memory'),schemaFor('web_search'),])const { getAgentToolSchemas } = await import('../agentTools')const names = (await getAgentToolSchemas()).map((s) => s.function.name)- expect(names).toEqual(['read', 'write', 'memory_write'])+ expect(names).toEqual(['read', 'write', 'memory'])})/// The diff must reach the caller so the UI can render it, but stay out of@@ -363,11 +363,11 @@ describe('agentTools', () => {it('coerces a non-object input to empty args', async () => {executeTool.mockResolvedValue({ content: '', diff: null, isError: false })const { executeAgentTool } = await import('../agentTools')- await executeAgentTool('memory_list', undefined, 'thread-1')+ await executeAgentTool('skill_list', undefined, 'thread-1')expect(executeTool).toHaveBeenCalledWith('/data','thread-1',- 'memory_list',+ 'skill_list',{},undefined,undefined,@@ -442,18 +442,28 @@ describe('agentTools', () => {expect(memoryCatalog).toHaveBeenCalledTimes(2)})- // Cowork's memory_write goes through executeAgentTool, so a note the model+ // Cowork's memory writes go through executeAgentTool, so a note the model// records mid-session must reach the next run/send without a restart.- it('invalidates the snapshot when the memory_write tool succeeds', async () => {+ it('invalidates the snapshot when a memory write succeeds', async () => {executeTool.mockResolvedValue({ content: 'ok', diff: null, isError: false })const { executeAgentTool, getMemoryCatalog } = await import('../agentTools')memoryCatalog.mockResolvedValue([])await getMemoryCatalog()- await executeAgentTool('memory_write', { name: 'a', content: 'b' }, 't1')+ await executeAgentTool('memory', { op: 'write', name: 'a', content: 'b' }, 't1')await getMemoryCatalog()expect(memoryCatalog).toHaveBeenCalledTimes(2)})+ it('keeps the snapshot across a memory view', async () => {+ executeTool.mockResolvedValue({ content: 'ok', diff: null, isError: false })+ const { executeAgentTool, getMemoryCatalog } = await import('../agentTools')+ memoryCatalog.mockResolvedValue([])+ await getMemoryCatalog()+ await executeAgentTool('memory', { op: 'view', name: 'a' }, 't1')+ await getMemoryCatalog()+ expect(memoryCatalog).toHaveBeenCalledTimes(1)+ })+it('degrades to empty recall when the store is unreachable', async () => {memoryCatalog.mockRejectedValue(new Error('no backend'))const { getMemoryCatalog, refreshMemoryDigest } = await import(diff --git a/web-app/src/lib/__tests__/agentWorkspace.test.ts b/web-app/src/lib/__tests__/agentWorkspace.test.tsindex db68aac63..8b021ef10 100644--- a/web-app/src/lib/__tests__/agentWorkspace.test.ts+++ b/web-app/src/lib/__tests__/agentWorkspace.test.ts@@ -86,8 +86,22 @@ describe('agentWorkspace', () => {expect(slugifyMemoryName('How to set up CUDA 12?')).toBe('how-to-set-up-cuda-12')- expect(slugifyMemoryName(' --- ')).toBe('memory')- expect(slugifyMemoryName('')).toBe('memory')+ // Never a name the store reserves for its index, which would make the+ // Remember action fail for an empty, non-Latin or literal title.+ expect(slugifyMemoryName(' --- ')).toBe('note')+ expect(slugifyMemoryName('')).toBe('note')+ expect(slugifyMemoryName('\u8bb0\u5fc6')).toBe('note')+ expect(slugifyMemoryName('Memory')).toBe('memory-note')+ expect(slugifyMemoryName('INDEX')).toBe('index-note')+ // Nor a Windows device name, which the store refuses on every OS.+ expect(slugifyMemoryName('Con')).toBe('con-note')+ expect(slugifyMemoryName('AUX')).toBe('aux-note')+ expect(slugifyMemoryName('nul')).toBe('nul-note')+ expect(slugifyMemoryName('PRN?')).toBe('prn-note')+ expect(slugifyMemoryName('COM1')).toBe('com1-note')+ expect(slugifyMemoryName('lpt0')).toBe('lpt0-note')+ expect(slugifyMemoryName('com10')).toBe('com10')+ expect(slugifyMemoryName('console')).toBe('console')expect(slugifyMemoryName('a'.repeat(100))).toHaveLength(60)})@@ -99,7 +113,7 @@ describe('agentWorkspace', () => {name: 'chat-notes-3',duplicate: false,})- // Suffixing, never overwriting: memory_write replaces by name, and the+ // Suffixing, never overwriting: a memory write replaces by name, and the// existing notes are not this action's to replace.expect(api.memoryWrite).toHaveBeenCalledWith('/data',diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsindex 1ecc66754..98de0add4 100644--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -114,6 +114,36 @@ describe('dispatchCoworkTool', () => {expect(executeAgentTool).toHaveBeenCalled()})+ // Plan mode is read-only for memory too: the tool stays advertised for its+ // reads, so the refusal is per op.+ it('refuses memory ops that change the store in plan mode', async () => {+ for (const op of ['write', 'edit', 'delete', 'move']) {+ const out = await dispatchCoworkTool(+ call('memory', { op, name: 'n' }),+ ctx({ planMode: true })+ )+ expect(out.isError).toBe(true)+ expect(out.output).toMatch(/plan mode/)+ expect(out.output).toMatch(/view/)+ }+ expect(executeAgentTool).not.toHaveBeenCalled()+ })++ it('still runs memory view and search in plan mode', async () => {+ for (const op of ['view', 'search']) {+ await dispatchCoworkTool(+ call('memory', { op, query: 'q' }),+ ctx({ planMode: true })+ )+ }+ expect(executeAgentTool).toHaveBeenCalledTimes(2)+ })++ it('runs memory writes outside plan mode', async () => {+ await dispatchCoworkTool(call('memory', { op: 'write' }), ctx())+ expect(executeAgentTool).toHaveBeenCalled()+ })+// The attached folder is passed twice: as the read-only filesystem root and// as the skill-overlay project (last arg), so the folder's skills reach the// agent on top of the permanent store (#8879).diff --git a/web-app/src/lib/__tests__/coworkPrompt.test.ts b/web-app/src/lib/__tests__/coworkPrompt.test.tsindex 8f11e71a0..798016e51 100644--- a/web-app/src/lib/__tests__/coworkPrompt.test.ts+++ b/web-app/src/lib/__tests__/coworkPrompt.test.ts@@ -64,7 +64,7 @@ describe('buildCoworkSystemPrompt', () => {expect(p).toContain('Exit plan mode')})- // Progressive disclosure: one line per note, `memory_read` for the rest. An+ // Progressive disclosure: one line per note, the memory tool for the rest. An// empty store adds nothing, so the prompt prefix is unchanged for users who// never recorded a memory.it('lists memory notes with summaries only when the store has any', () => {@@ -79,7 +79,7 @@ describe('buildCoworkSystemPrompt', () => {expect(p).toContain('# Available Memories')expect(p).toContain('- `decisions` - We use Yarn not npm.')expect(p).toContain('- `empty-note` - no summary')- expect(p).toContain('memory_read')+ expect(p).toContain('`memory` tool')expect(buildCoworkSystemPrompt(opts())).not.toContain('# Available Memories')diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.tsindex 09e8d8648..2d546f25d 100644--- a/web-app/src/lib/__tests__/coworkSubagent.test.ts+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts@@ -436,6 +436,14 @@ describe('subagentTools', () => {expect(Object.keys(out)).toEqual(['read'])})+ it('never gives a child memory, even when its allowlist names it', () => {+ const out = subagentTools(tools('read', 'memory'), ['read', 'memory'])+ expect(Object.keys(out)).toEqual(['read'])+ expect(Object.keys(subagentTools(tools('read', 'memory'), null))).toEqual([+ 'read',+ ])+ })+it('narrows to the allowlist', () => {const out = subagentTools(tools('read', 'grep', 'write'), ['read'])expect(Object.keys(out)).toEqual(['read'])diff --git a/web-app/src/lib/__tests__/coworkTools.test.ts b/web-app/src/lib/__tests__/coworkTools.test.tsindex 32da873ff..9059ce0b8 100644--- a/web-app/src/lib/__tests__/coworkTools.test.ts+++ b/web-app/src/lib/__tests__/coworkTools.test.ts@@ -10,6 +10,7 @@ import {coworkToolSignature,allowedToolNames,PLAN_DENIED_TOOLS,+ PLAN_DENIED_MEMORY_OPS,TODO_TOOL_NAME,ASK_TOOL_NAME,TASK_TOOL_NAME,@@ -20,7 +21,7 @@ const schema = (name: string) => ({function: { name, description: name, parameters: { type: 'object' } },})-const ALL = ['read', 'ls', 'grep', 'write', 'edit', 'shell', 'memory_write']+const ALL = ['read', 'ls', 'grep', 'write', 'edit', 'shell', 'memory']const opts = (over: Partial<Parameters<typeof buildCoworkTools>[0]> = {}) => ({planMode: false,@@ -143,7 +144,18 @@ describe('web tools', () => {describe('allowedToolNames', () => {it('refuses the same set plan mode withholds', () => {const out = allowedToolNames([...ALL, TASK_TOOL_NAME], opts({ planMode: true }))- expect(out).toEqual(['read', 'ls', 'grep'])+ // Memory stays for its reads (view, search); the dispatcher refuses the+ // ops that change the store.+ expect(out).toEqual(['read', 'ls', 'grep', 'memory'])+ })++ it('names the memory ops plan mode refuses', () => {+ expect([...PLAN_DENIED_MEMORY_OPS].sort()).toEqual([+ 'delete',+ 'edit',+ 'move',+ 'write',+ ])})it('refuses task past the subagent depth cap', () => {diff --git a/web-app/src/lib/__tests__/toolOrigin.test.ts b/web-app/src/lib/__tests__/toolOrigin.test.tsindex 944699097..3042efa06 100644--- a/web-app/src/lib/__tests__/toolOrigin.test.ts+++ b/web-app/src/lib/__tests__/toolOrigin.test.ts@@ -84,7 +84,7 @@ describe('resolveToolOrigin', () => {it('recognises a built-in agent tool', () => {expect(- resolveToolOrigin('memory_read', { ...context, isAgentTool: true })+ resolveToolOrigin('memory', { ...context, isAgentTool: true })).toEqual({ kind: 'agent' })})diff --git a/web-app/src/lib/__tests__/toolPresentation.test.ts b/web-app/src/lib/__tests__/toolPresentation.test.tsindex 72d4552cd..6d2b66821 100644--- a/web-app/src/lib/__tests__/toolPresentation.test.ts+++ b/web-app/src/lib/__tests__/toolPresentation.test.ts@@ -182,12 +182,30 @@ describe('describeNativeToolCall for agent tools', () => {})it('leads with the name for memory and skill tools', () => {- expect(describeNativeToolCall(agent, 'memory_read', { name: 'prefs' })).toEqual({+ expect(describeNativeToolCall(agent, 'memory', { op: 'view', name: 'prefs' })).toEqual({variant: 'workspace',- tool: 'memory_read',+ tool: 'memory',target: 'prefs',+ op: 'view',})})++ // `memory` is one tool with many ops: the op decides the verb, and a search+ // is about its query, not a name it does not have.+ it('carries the memory op and leads a search with its query', () => {+ expect(+ describeNativeToolCall(agent, 'memory', { op: 'search', query: 'cuda' })+ ).toEqual({ variant: 'workspace', tool: 'memory', target: 'cuda', op: 'search' })+ expect(describeNativeToolCall(agent, 'memory', { op: 'view' })).toEqual({+ variant: 'workspace',+ tool: 'memory',+ target: '',+ op: 'view',+ })+ expect(+ describeNativeToolCall(agent, 'memory', { op: 'move', name: 'a', to: 'b' })+ ).toEqual({ variant: 'workspace', tool: 'memory', target: 'a', op: 'move' })+ })})describe('parseBashOutput', () => {diff --git a/web-app/src/lib/agentActivity.test.ts b/web-app/src/lib/agentActivity.test.tsindex 647a708d3..651780ca0 100644--- a/web-app/src/lib/agentActivity.test.ts+++ b/web-app/src/lib/agentActivity.test.ts@@ -53,9 +53,12 @@ describe('toolActivityText', () => {})it('formats memory tools without a path', () => {- expect(toolActivityText('memory_write', {})).toBe('Saving memory')- expect(toolActivityText('memory_read', {})).toBe('Reading memory')- expect(toolActivityText('memory_list', {})).toBe('Reading memory')+ expect(toolActivityText('memory', { op: 'write' })).toBe('Saving memory')+ expect(toolActivityText('memory', { op: 'delete' })).toBe('Saving memory')+ expect(toolActivityText('memory', { op: 'move' })).toBe('Saving memory')+ expect(toolActivityText('memory', { op: 'search' })).toBe('Searching memory')+ expect(toolActivityText('memory', { op: 'view' })).toBe('Reading memory')+ expect(toolActivityText('memory', {})).toBe('Reading memory')})it('names the skill being read', () => {diff --git a/web-app/src/lib/agentActivity.ts b/web-app/src/lib/agentActivity.tsindex 73c41b1f4..9ae9d67e7 100644--- a/web-app/src/lib/agentActivity.ts+++ b/web-app/src/lib/agentActivity.ts@@ -35,16 +35,20 @@ const VERB_BY_TOOL: Record<string, string> = {grep: 'Searching',}-const NO_DETAIL_TOOLS: Record<string, string> = {- memory_write: 'Saving memory',- memory_read: 'Reading memory',- memory_list: 'Reading memory',+/** One phrase per `memory` op; a read-style op is the fallback. */+const MEMORY_ACTIVITY: Record<string, string> = {+ write: 'Saving memory',+ edit: 'Saving memory',+ delete: 'Saving memory',+ move: 'Saving memory',+ search: 'Searching memory',}/** Text for one tool call, given its name and args. Pure formatting, no timestamp. */export function toolActivityText(toolName: string, input: unknown): string {- const fixed = NO_DETAIL_TOOLS[toolName]- if (fixed) return fixed+ if (toolName === 'memory') {+ return MEMORY_ACTIVITY[stringArg(input, 'op') ?? ''] ?? 'Reading memory'+ }if (toolName === 'skill_read') {const name = stringArg(input, 'name')diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex 69bdc1d7e..115cc8681 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -44,9 +44,8 @@ export const AGENT_TOOL_NAMES = new Set(['write','edit','shell',- 'memory_list',- 'memory_read',- 'memory_write',+ // One tool for every memory op (view/search/write/edit/delete/move).+ 'memory','skill_list','skill_read','skill_write',@@ -155,7 +154,7 @@ let digestNow = ''/*** Drop the cached snapshot so the next run/send re-reads the store. Called from- * every in-app write path (the `memory_write` tool, the settings editors, the+ * every in-app write path (a `memory` tool change, the settings editors, the* chat Remember action); an edit made outside the app is picked up on restart.*/export function invalidateMemory(): void {@@ -172,7 +171,7 @@ async function loadMemorySnapshot(): Promise<MemorySnapshot> {// The digest is self-contained: whole notes only, newest first, under a// strict budget. A note that does not fit is simply absent -- chat has no- // memory_read to dereference a truncated one with.+ // memory tool to dereference a truncated one with.let remaining = MEMORY_DIGEST_BUDGETconst parts: string[] = []for (const entry of newestFirst) {@@ -304,7 +303,7 @@ export async function executeAgentTool(if (result.isError) return { error: result.content }// The store changed, so the recall injections must not keep serving the// snapshot taken before this note existed.- if (toolName === 'memory_write') invalidateMemory()+ if (toolName === 'memory' && isMemoryChange(args)) invalidateMemory()return {content: result.content,diff: result.diff ?? undefined,@@ -315,6 +314,11 @@ export async function executeAgentTool(}}+/** Whether a `memory` call changes the store (anything but view/search). */+function isMemoryChange(args: Record<string, unknown>): boolean {+ return args.op !== 'view' && args.op !== 'search'+}+export type { MonitorUpdate }/**diff --git a/web-app/src/lib/agentWorkspace.ts b/web-app/src/lib/agentWorkspace.tsindex 84e3e9bfe..a3bffe480 100644--- a/web-app/src/lib/agentWorkspace.ts+++ b/web-app/src/lib/agentWorkspace.ts@@ -60,6 +60,15 @@ export async function deleteMemory(name: string): Promise<void> {invalidateMemory()}+// The store refuses these stems: the harness builds the memory index itself+// (`MEMORY.md`), and on a case-insensitive filesystem `memory.md` is that file.+const RESERVED_MEMORY_NAMES = new Set(['index', 'memory'])++// Mirrors `is_windows_device_name` in the agent-tools plugin's workspace.rs,+// which the store applies on every OS: the part before the first dot, in any+// case, is CON/PRN/AUX/NUL or COM/LPT plus one digit.+const WINDOWS_DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i+/*** A filesystem-safe note name from a thread title. The store's names are file* stems, so everything but `[a-z0-9-]` collapses to hyphens; an unusable title@@ -72,7 +81,10 @@ export function slugifyMemoryName(title: string): string {.replace(/^-+|-+$/g, '').slice(0, 60).replace(/-+$/, '')- return slug || 'memory'+ if (!slug) return 'note'+ return RESERVED_MEMORY_NAMES.has(slug) || WINDOWS_DEVICE_NAME.test(slug)+ ? `${slug}-note`+ : slug}export type RememberResult = {@@ -83,7 +95,7 @@ export type RememberResult = {/*** The chat surface's "Remember" action: save `content` as a note named after- * the thread title. `memory_write` replaces a note by name, and this is a new+ * the thread title. A memory write replaces a note by name, and this is a new* fact rather than a curated topic, so an existing name gets a `-2`, `-3`, ...* suffix instead of silently overwriting it. A sibling that already holds this* exact content is returned instead of being copied again, so a second clickdiff --git a/web-app/src/lib/coworkCommands.ts b/web-app/src/lib/coworkCommands.tsindex 50273d0e1..7f3b3ef63 100644--- a/web-app/src/lib/coworkCommands.ts+++ b/web-app/src/lib/coworkCommands.ts@@ -14,7 +14,7 @@ export const INIT_PROMPT = `Onboard yourself to this project so future sessions2. Write skills with skill_write for the project's repeatable procedures - releasing, running migrations, adding a module, debugging a subsystem - one skill per procedure, only where a real multi-step recipe exists. Do not invent skills to fill space.-3. Record durable project facts with memory_write: decisions, constraints, and gotchas that are true beyond this session and not already stated in the code.+3. Record durable project facts with the memory tool (search first; update rather than duplicate): decisions, constraints, and gotchas that are true beyond this session and not already stated in the code.Then report what you wrote and why, briefly.`diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex 15ea9e1c5..6552de06d 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -7,6 +7,7 @@ import {import { useCoworkConfig } from '@/hooks/useCoworkConfig'import {ASK_TOOL_NAME,+ PLAN_DENIED_MEMORY_OPS,PLAN_DENIED_TOOLS,TASK_TOOL_NAME,TODO_TOOL_NAME,@@ -63,6 +64,16 @@ function planRefusal(toolName: string): ToolOutcome {}}+/** Refusal text for a `memory` op that changes the store in plan mode. */+function planMemoryRefusal(op: string): ToolOutcome {+ return {+ output:+ `The \`memory\` op \`${op}\` is disabled in plan mode, which is read-only. ` ++ 'Only `view` and `search` work; stage the memory change in the plan.',+ isError: true,+ }+}+// A model may try to create a missing file through `read` when write is// withheld. Keep the filesystem error, but explain the approval path at the// failure itself so the next step can recover instead of repeating the read.@@ -111,6 +122,12 @@ async function toolFailure(return { output, isError: true }}+function memoryOp(input: unknown): string {+ if (!input || typeof input !== 'object') return ''+ const op = (input as { op?: unknown }).op+ return typeof op === 'string' ? op : ''+}+function readPath(input: unknown): string | undefined {if (!input || typeof input !== 'object') return undefinedconst path = (input as { path?: unknown }).path@@ -174,6 +191,10 @@ export async function dispatchCoworkTool(if (ctx.planMode && PLAN_DENIED_TOOLS.has(toolName)) {return planRefusal(toolName)}+ if (ctx.planMode && toolName === 'memory') {+ const op = memoryOp(call.input)+ if (PLAN_DENIED_MEMORY_OPS.has(op)) return planMemoryRefusal(op)+ }try {if (toolName === TODO_TOOL_NAME) return await ctx.onTodo(call.input)diff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.tsindex f373d8c73..4ea253aea 100644--- a/web-app/src/lib/coworkPrompt.ts+++ b/web-app/src/lib/coworkPrompt.ts@@ -70,7 +70,7 @@ export type CoworkPromptOptions = {environment?: CoworkEnvironment | null/*** Progressive-disclosure recall: one line per note, dereferenced on demand- * with `memory_read`. Snapshotted at the run boundary alongside the frozen+ * with the `memory` tool. Snapshotted at the run boundary alongside the frozen* tool set, so the prompt prefix is stable for the run.*/memoryCatalog: { name: string; summary: string }[]@@ -86,9 +86,10 @@ function memoryBlock(catalog: { name: string; summary: string }[]): string {return ['# Available Memories','',- 'Durable facts recorded in earlier sessions. Read a note in full with',- '`memory_read` when it is relevant to the current task, and record new',- 'durable facts (not session state) with `memory_write`.',+ 'Durable facts recorded in earlier sessions. Read a note in full with the',+ '`memory` tool (op `view`) when it is relevant to the current task. Record',+ 'new durable facts (not session state) with op `write`, after a `search`',+ 'shows no note on the topic to update instead.','',list,].join('\n')diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsindex 6ad32498f..6fee636f4 100644--- a/web-app/src/lib/coworkSubagent.ts+++ b/web-app/src/lib/coworkSubagent.ts@@ -254,6 +254,9 @@ const WITHHELD_FROM_SUBAGENTS = new Set([// conversation; a child has no inbox, so its watcher would report to no one.// (The Rust CLI differs: there a child run owns a registry of its own.)MONITOR_TOOL_NAME,+ // Subagents have no memory: the dispatching agent states what matters in the+ // task. Matches the Rust child args, which deny `memory`.+ 'memory',])/**diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex 73beb0964..431d1167f 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -21,13 +21,16 @@ export const PLAN_DENIED_TOOLS = new Set(['write','edit','shell',- 'memory_write','skill_write','task',// Starting one schedules shell scripts, which is exec-class work.MONITOR_TOOL_NAME,])+/** `memory` ops that change the store. Plan mode keeps the tool for its+ * reads (`view`, `search`) and refuses these, as the Rust tool does. */+export const PLAN_DENIED_MEMORY_OPS = new Set(['write', 'edit', 'delete', 'move'])+/** Named `todo` to match the Rust tool: the plan-mode addendum instructs the* model to call `todo` by name, so renaming it here breaks that prompt. */export const TODO_TOOL_NAME = 'todo'diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.tsindex d93c1eba8..cc7d015ee 100644--- a/web-app/src/lib/toolPresentation.ts+++ b/web-app/src/lib/toolPresentation.ts@@ -25,11 +25,15 @@ export type ToolCallBar =* pairs) are the arguments worth showing while they stream: for those two* tools the arguments are the work itself, and a large one takes long enough* that a spinner says nothing about it.+ *+ * `op` is `memory`'s operation: one tool both reads and changes the store,+ * so the op, not the tool name, says what the call is doing.*/| {variant: 'workspace'tool: stringtarget: string+ op?: stringdetail?: stringbody?: stringedits?: { old_string: string; new_string?: string }[]@@ -145,6 +149,17 @@ export function describeNativeToolCall(detail: asString(args.path) || undefined,}}+ // A memory search is about its query; every other op names a note, or+ // none for a view of the whole store.+ if (toolName === 'memory') {+ const op = asString(args.op)+ return {+ variant: 'workspace',+ tool: toolName,+ target: op === 'search' ? asString(args.query) : asString(args.name),+ op,+ }+ }return {variant: 'workspace',tool: toolName,diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 64cff68ac..441c080c5 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -217,12 +217,12 @@"networkDesc": "Let Cowork commands reach the network, for things like installing packages or fetching a repository. On by default. The main chat's shell never has network access.","openFolder": "Open Folder","memories": "Memories",- "noMemories": "No memories yet. Models add them with the memory_write tool as they learn things worth keeping.",+ "noMemories": "No memories yet. Models add them with the memory tool as they learn things worth keeping.","skills": "Skills","noSkills": "No skills yet. A skill is a reusable set of instructions a model can load on demand.","add": "Add","editMemory": "Edit Memory",- "editMemoryDesc": "One topic per note. Models read these back with the memory_read tool.",+ "editMemoryDesc": "One topic per note. Models read these back with the memory tool.","editSkill": "Edit Skill","editSkillDesc": "Markdown instructions, optionally with a description in YAML frontmatter. The description is what models see before loading the skill.","namePlaceholder": "Name",