Skip to content

armgit / jan

Public Imported from GitHub
0

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

feat(agent): give the memory tidy read-only project context (#9577)

Akarshan Biswas2fe0016cfd2b
diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rs
index 0e2500003..f0dedd075 100644
--- a/src-tauri/src/core/agent/git.rs
+++ b/src-tauri/src/core/agent/git.rs
@@ -570,6 +570,237 @@ pub(crate) fn fetch_commit(
fetched
}
+/// How long each git in [`tidy_facts`] may take. All of it is local, so a
+/// git still running past this is stuck (a lock, a huge repo on a slow
+/// disk), and the tidy is better off without its facts than waiting.
+#[cfg(feature = "cli")]
+const TIDY_FACTS_GIT_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
+/// The most branches each of [`tidy_facts`]'s two branch lists shows.
+#[cfg(feature = "cli")]
+const TIDY_FACTS_BRANCHES: usize = 60;
+/// The most worktrees [`tidy_facts`] lists.
+#[cfg(feature = "cli")]
+const TIDY_FACTS_WORKTREES: usize = 20;
+/// How far back [`tidy_facts`] reads the default branch for PR numbers.
+#[cfg(feature = "cli")]
+const TIDY_FACTS_LOG_DEPTH: &str = "500";
+/// PR numbers per line of [`tidy_facts`]'s compact list.
+#[cfg(feature = "cli")]
+const TIDY_FACTS_PRS_PER_LINE: usize = 20;
+/// The hard ceiling on [`tidy_facts`]'s block, whatever the lists add up to:
+/// it rides in a small model's task, next to the notes it has to read.
+#[cfg(feature = "cli")]
+const TIDY_FACTS_MAX_LINES: usize = 200;
+
+/// What the memory tidy is told about `repo` so it can judge whether a note
+/// tracks finished work: the default branch and its head, which branches
+/// it contains, the registered worktrees (one gone from disk flagged), and
+/// the PR numbers squash merges and reverts left in its recent log.
+///
+/// Jan runs these itself, from a fixed list, so the tidy never needs a
+/// shell. Everything is local: no fetch, no `gh`, so a remote-tracking
+/// branch is only as fresh as the user's last fetch. `None` when `repo` is
+/// not in a git work tree, has no default branch, or git fails, so the tidy
+/// simply runs without it.
+#[cfg(feature = "cli")]
+pub(crate) fn tidy_facts(repo: &Path, today: &str) -> Option<String> {
+ let git = |args: &[&str]| run_limited(repo, args, TIDY_FACTS_GIT_LIMIT).ok();
+ git(&["rev-parse", "--show-toplevel"])?;
+ let default = default_branch(&git)?;
+ // `--` so a work-tree path named like the branch cannot be read instead.
+ let head = git(&["log", "-1", "--date=short", "--format=%h %ad %s", &default, "--"])?;
+ let merged_arg = format!("--merged={default}");
+ let at_head_arg = format!("--points-at={default}");
+ let refs = |extra: &[&str]| -> Option<Vec<String>> {
+ let mut args = vec!["for-each-ref", "--sort=-committerdate"];
+ args.extend_from_slice(extra);
+ args.extend(["--format=%(refname)%09%(symref)", "refs/heads", "refs/remotes"]);
+ Some(branch_names(&git(&args)?, &default))
+ };
+ let all = refs(&[])?;
+ let merged = refs(&[merged_arg.as_str()])?;
+ let open: Vec<String> = all.into_iter().filter(|b| !merged.contains(b)).collect();
+ // A branch at the default's very head has no commits of its own (just
+ // cut, or an agent worktree's), so it says nothing about landed work.
+ let at_head = refs(&[at_head_arg.as_str()])?;
+ let merged: Vec<String> = merged.into_iter().filter(|b| !at_head.contains(b)).collect();
+ let worktrees = worktree_lines(&git(&["worktree", "list", "--porcelain"])?);
+ let subjects =
+ git(&["log", "-n", TIDY_FACTS_LOG_DEPTH, "--format=%s", &default, "--"])?;
+ let prs = pr_numbers(&subjects);
+
+ let mut out = vec![
+ "Facts Jan gathered from the project's local git (no fetch, so remote branches are as of \
+ the last fetch):"
+ .to_string(),
+ format!("Today: {today}"),
+ format!("Default branch: {default}, head {head}"),
+ // Containment is all git can say: a branch cut from an older commit
+ // and never worked on is contained too, so this is not "landed".
+ format!(
+ "Branches whose tip is contained in {default} (fully merged, or created there with \
+ no commits of their own yet), most recent first:"
+ ),
+ ];
+ push_capped(&mut out, &merged, TIDY_FACTS_BRANCHES);
+ // Squash and rebase merges land a branch's work without its commits, so
+ // this list is "not merged by commit", never "still open".
+ out.push(format!(
+ "Branches not merged into {default} by commit (a squash-merged branch still lands here: \
+ check the PR numbers below), most recent first:"
+ ));
+ push_capped(&mut out, &open, TIDY_FACTS_BRANCHES);
+ out.push("Worktrees registered with git:".to_string());
+ push_capped(&mut out, &worktrees, TIDY_FACTS_WORKTREES);
+ out.push(format!(
+ "PR numbers in the subjects of {default}'s last {TIDY_FACTS_LOG_DEPTH} commits, newest \
+ first (a squash merge reads `subject (#123)`; the surest sign a PR landed):"
+ ));
+ if prs.landed.is_empty() {
+ out.push(" (none)".to_string());
+ }
+ push_pr_lines(&mut out, &prs.landed);
+ if !prs.reverted.is_empty() {
+ out.push(
+ "PRs reverted in that log (their work did NOT land, or was undone):".to_string(),
+ );
+ push_pr_lines(&mut out, &prs.reverted);
+ }
+ if out.len() > TIDY_FACTS_MAX_LINES {
+ out.truncate(TIDY_FACTS_MAX_LINES - 1);
+ out.push("... (truncated)".to_string());
+ }
+ // A branch or path is the user's bytes; the block goes into a prompt.
+ Some(out.join("\n").replace(|c: char| c.is_control() && c != '\n', "?"))
+}
+
+/// The branch [`tidy_facts`] treats as the default: the remote's own
+/// (`origin/HEAD`), else a local `main` or `master`, else their
+/// remote-tracking twins. Never just what is checked out: "merged into
+/// a feature branch" would read as landed when it is not.
+#[cfg(feature = "cli")]
+fn default_branch(git: &impl Fn(&[&str]) -> Option<String>) -> Option<String> {
+ // `symbolic-ref` answers even when the target is gone (the remote renamed
+ // its default and a prune deleted the old one), so the target must also
+ // resolve, or every later `git log` on it fails and the facts are lost.
+ let resolves = |full: &str| git(&["rev-parse", "--verify", "--quiet", full]).is_some();
+ let remote = git(&["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
+ if let Some(remote) = remote.filter(|r| !r.is_empty()) {
+ if resolves("refs/remotes/origin/HEAD") {
+ return Some(remote);
+ }
+ }
+ let known = ["main", "master", "origin/main", "origin/master"].into_iter().find(|b| {
+ let full = match b.strip_prefix("origin/") {
+ Some(name) => format!("refs/remotes/origin/{name}"),
+ None => format!("refs/heads/{b}"),
+ };
+ resolves(&full)
+ });
+ known.map(str::to_string)
+}
+
+/// Branch names from `for-each-ref`'s `<refname>\t<symref>` lines, as
+/// `git branch -a` names them (`feat/x`, `origin/feat/x`), without symbolic
+/// refs (`origin/HEAD`) or the default branch itself.
+#[cfg(feature = "cli")]
+fn branch_names(listing: &str, default: &str) -> Vec<String> {
+ listing
+ .lines()
+ // The output is trimmed, so the last line's empty symref takes its
+ // tab with it.
+ .map(|l| l.split_once('\t').unwrap_or((l, "")))
+ .filter(|(_, symref)| symref.is_empty())
+ .filter_map(|(r, _)| r.strip_prefix("refs/heads/").or(r.strip_prefix("refs/remotes/")))
+ .filter(|b| *b != default)
+ .map(str::to_string)
+ .collect()
+}
+
+/// `<path> [<branch>]` per worktree in a `worktree list --porcelain`
+/// listing, flagged when the directory is gone: a note naming a worktree
+/// can then be judged against what is still on disk.
+#[cfg(feature = "cli")]
+fn worktree_lines(porcelain: &str) -> Vec<String> {
+ porcelain
+ .split("\n\n")
+ .filter_map(|block| {
+ let path = block.lines().find_map(|l| l.strip_prefix("worktree "))?;
+ let branch = block
+ .lines()
+ .find_map(|l| l.strip_prefix("branch "))
+ .map(|b| b.strip_prefix("refs/heads/").unwrap_or(b))
+ .unwrap_or("detached");
+ let gone = if Path::new(path).exists() { "" } else { " (missing on disk)" };
+ Some(format!("{path} [{branch}]{gone}"))
+ })
+ .collect()
+}
+
+/// The PR numbers in a log's subjects, each once, in the order first seen.
+#[cfg(feature = "cli")]
+#[derive(Debug, Default)]
+struct PrNumbers {
+ /// Squash merges' PRs (`subject (#9497)`), less any reverted.
+ landed: Vec<String>,
+ /// PRs a GitHub revert undid (`Revert "subject (#9497)" (#9500)`).
+ reverted: Vec<String>,
+}
+
+/// Sort `subjects`' PR numbers into landed and reverted. Only a subject's
+/// trailing `(#N)` is its own PR: one earlier in the text is a mention, and
+/// the one inside a revert's quotes is the PR it undid. A reverted PR is
+/// never landed, even with its own merge in the log too.
+#[cfg(feature = "cli")]
+fn pr_numbers(subjects: &str) -> PrNumbers {
+ let mut prs = PrNumbers::default();
+ let add = |list: &mut Vec<String>, n: &str| {
+ if !list.iter().any(|seen| seen == n) {
+ list.push(n.to_string());
+ }
+ };
+ for subject in subjects.lines() {
+ if let Some(n) = trailing_pr(subject) {
+ add(&mut prs.landed, n);
+ }
+ let quoted = subject.strip_prefix("Revert \"").and_then(|r| r.rsplit_once('"'));
+ if let Some(n) = quoted.and_then(|(inner, _)| trailing_pr(inner)) {
+ add(&mut prs.reverted, n);
+ }
+ }
+ prs.landed.retain(|n| !prs.reverted.contains(n));
+ prs
+}
+
+/// The `N` of a subject ending in `(#N)`.
+#[cfg(feature = "cli")]
+fn trailing_pr(subject: &str) -> Option<&str> {
+ let (_, number) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
+ (!number.is_empty() && number.bytes().all(|b| b.is_ascii_digit())).then_some(number)
+}
+
+/// Append PR numbers to `out` as compact `#N` lines.
+#[cfg(feature = "cli")]
+fn push_pr_lines(out: &mut Vec<String>, numbers: &[String]) {
+ for chunk in numbers.chunks(TIDY_FACTS_PRS_PER_LINE) {
+ let line: Vec<String> = chunk.iter().map(|n| format!("#{n}")).collect();
+ out.push(format!(" {}", line.join(" ")));
+ }
+}
+
+/// Append `items` to `out` as a bulleted list of at most `cap`, saying how
+/// many were left out, or `(none)`.
+#[cfg(feature = "cli")]
+fn push_capped(out: &mut Vec<String>, items: &[String], cap: usize) {
+ if items.is_empty() {
+ out.push(" (none)".to_string());
+ }
+ out.extend(items.iter().take(cap).map(|i| format!(" - {i}")));
+ if items.len() > cap {
+ out.push(format!(" ... {} more not listed (truncated)", items.len() - cap));
+ }
+}
+
/// Forget worktree registrations whose directory the user has deleted. Without
/// this, `worktree add` refuses a path that a stale registration still claims.
#[cfg(feature = "cli")]
@@ -1714,4 +1945,223 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+
+ /// Commit an empty change with `subject` on whatever is checked out.
+ fn commit(root: &Path, subject: &str) {
+ run(root, None, &["commit", "-q", "--allow-empty", "--no-gpg-sign", "-m", subject])
+ .expect("commit");
+ }
+
+ /// The memory tidy's facts name the default branch and its head, sort the
+ /// branches by whether the default branch contains them, list the
+ /// worktrees (a gone one flagged) and the PR numbers squash merges left in
+ /// the log. A branch cut at the default's head has no commits of its own,
+ /// so it is in no list; one cut at an older commit is contained, and its
+ /// label says that may mean nothing landed.
+ #[test]
+ fn the_tidy_facts_say_what_landed_on_the_default_branch() {
+ let Some(root) = init_repo() else { return };
+ let r = root.to_string_lossy().to_string();
+ git(&["-C", &r, "branch", "-M", "main"]).expect("rename");
+ git(&["-C", &r, "checkout", "-q", "-b", "feat/landed"]).expect("checkout");
+ commit(&root, "landed work");
+ git(&["-C", &r, "checkout", "-q", "main"]).expect("checkout");
+ git(&["-C", &r, "merge", "-q", "--ff-only", "feat/landed"]).expect("merge");
+ git(&["-C", &r, "branch", "feat/older-start"]).expect("branch");
+ commit(&root, "feat: squashed (#9497)");
+ commit(&root, "feat: undone (#30)");
+ commit(&root, "Revert \"feat: undone (#30)\" (#31)");
+ commit(&root, "fix: another (#12)");
+ git(&["-C", &r, "branch", "feat/fresh"]).expect("branch");
+ git(&["-C", &r, "checkout", "-q", "-b", "feat/open"]).expect("checkout");
+ commit(&root, "open work (#77)");
+ git(&["-C", &r, "checkout", "-q", "main"]).expect("checkout");
+ let wt = root.parent().unwrap().join(format!(
+ "{}-factswt",
+ root.file_name().unwrap().to_string_lossy()
+ ));
+ let _ = std::fs::remove_dir_all(&wt);
+ let head = head_sha(&root).unwrap();
+ worktree_add(&root, &wt, "jan/agent/facts", &head).expect("worktree add");
+ std::fs::remove_dir_all(&wt).unwrap();
+
+ let facts = tidy_facts(&root, "2026-11-03").expect("a repo has facts");
+ assert!(facts.contains("Today: 2026-11-03"), "{facts}");
+ assert!(facts.contains("Default branch: main, head "), "{facts}");
+ assert!(facts.contains("fix: another (#12)"), "the head's subject: {facts}");
+ // Squash merges leave a landed branch unmerged by commit, so that
+ // list must not read as "still open".
+ assert!(
+ facts.contains("Branches not merged into main by commit (a squash-merged branch \
+ still lands here: check the PR numbers below)"),
+ "{facts}"
+ );
+ assert!(facts.contains("the surest sign a PR landed"), "{facts}");
+ assert!(
+ facts.contains("Branches whose tip is contained in main (fully merged, or created \
+ there with no commits of their own yet), most recent first:"),
+ "{facts}"
+ );
+ assert!(!facts.contains("their work landed"), "{facts}");
+ let (merged, rest) = facts.split_once("not merged into").expect("both lists");
+ assert!(merged.contains(" - feat/landed\n"), "{facts}");
+ assert!(merged.contains(" - feat/older-start\n"), "{facts}");
+ assert!(rest.contains(" - feat/open\n"), "{facts}");
+ assert!(!merged.contains("feat/open"), "{facts}");
+ assert!(!facts.contains("feat/fresh"), "no commits of its own: {facts}");
+ assert!(!facts.contains(" - jan/agent/facts"), "a worktree branch at head: {facts}");
+ assert!(!facts.contains(" - main\n"), "the default branch is not listed: {facts}");
+ let gone = format!("{} [jan/agent/facts] (missing on disk)", wt.display());
+ assert!(facts.contains(&gone), "{facts}");
+ assert!(facts.contains(&format!("{} [main]\n", root.display())), "{facts}");
+ assert!(
+ facts.contains(" #12 #31 #9497\n"),
+ "newest first, reverted #30 and branch-only #77 left out: {facts}"
+ );
+ assert!(
+ facts.ends_with("PRs reverted in that log (their work did NOT land, or was undone):\n \
+ #30"),
+ "{facts}"
+ );
+ assert!(!facts.contains("#77"), "{facts}");
+ assert!(facts.is_ascii() && !facts.contains("truncated"), "{facts}");
+ worktree_prune(&root);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The remote's default branch wins over a local `main`, which may be stale.
+ #[test]
+ fn the_tidy_facts_prefer_the_remotes_default_branch() {
+ let Some(root) = init_repo() else { return };
+ let r = root.to_string_lossy().to_string();
+ git(&["-C", &r, "branch", "-M", "main"]).expect("rename");
+ let head = head_sha(&root).unwrap();
+ run(&root, None, &["update-ref", "refs/remotes/origin/trunk", &head]).expect("ref");
+ run(
+ &root,
+ None,
+ &["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/trunk"],
+ )
+ .expect("origin/HEAD");
+ // Moved off the remote's head, which a listed branch must not share.
+ commit(&root, "local only");
+ let facts = tidy_facts(&root, "2026-11-03").expect("facts");
+ assert!(facts.contains("Default branch: origin/trunk, head "), "{facts}");
+ assert!(facts.contains(" - main\n"), "a local branch is listed: {facts}");
+ assert!(!facts.contains("origin/HEAD"), "{facts}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// An `origin/HEAD` left pointing at a pruned branch (the remote renamed
+ /// its default) falls through to a local `main` instead of dropping the
+ /// facts.
+ #[test]
+ fn the_tidy_facts_skip_a_dangling_origin_head() {
+ let Some(root) = init_repo() else { return };
+ let r = root.to_string_lossy().to_string();
+ git(&["-C", &r, "branch", "-M", "main"]).expect("rename");
+ run(
+ &root,
+ None,
+ &["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/master"],
+ )
+ .expect("dangling origin/HEAD");
+ let facts = tidy_facts(&root, "2026-11-03").expect("facts from the local main");
+ assert!(facts.contains("Default branch: main, head "), "{facts}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A long branch list is cut and says so, and the whole block stays
+ /// within its line budget.
+ #[test]
+ fn the_tidy_facts_truncate_and_say_so() {
+ let Some(root) = init_repo() else { return };
+ let r = root.to_string_lossy().to_string();
+ git(&["-C", &r, "branch", "-M", "main"]).expect("rename");
+ let head = head_sha(&root).unwrap();
+ let total = TIDY_FACTS_BRANCHES + 5;
+ // Loose ref files: one `git branch` per branch would spawn git a
+ // hundred times for no extra coverage.
+ let heads = root.join(".git/refs/heads");
+ for i in 0..total {
+ std::fs::write(heads.join(format!("b{i:03}")), format!("{head}\n")).unwrap();
+ }
+ // Branches at the default's head are left out, so move it on.
+ commit(&root, "later");
+ let facts = tidy_facts(&root, "2026-11-03").expect("facts");
+ let listed = facts.lines().filter(|l| l.starts_with(" - b")).count();
+ assert_eq!(listed, TIDY_FACTS_BRANCHES, "{facts}");
+ assert!(facts.contains("... 5 more not listed (truncated)"), "{facts}");
+ assert!(facts.lines().count() <= TIDY_FACTS_MAX_LINES, "{facts}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// With no `origin/HEAD`, `main` or `master` there is no branch whose
+ /// merges mean "landed", so no block rather than one keyed to whatever
+ /// happens to be checked out.
+ #[test]
+ fn the_tidy_facts_are_omitted_without_a_default_branch() {
+ let Some(root) = init_repo() else { return };
+ let r = root.to_string_lossy().to_string();
+ git(&["-C", &r, "branch", "-M", "feat/only"]).expect("rename");
+ assert_eq!(tidy_facts(&root, "2026-11-03"), None);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// Outside a repository there is nothing to say, so no block at all.
+ #[test]
+ fn the_tidy_facts_are_omitted_outside_a_repository() {
+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let dir = std::env::temp_dir().join(format!("jan_facts_norepo_{}_{n}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ assert_eq!(tidy_facts(&dir, "2026-11-03"), None);
+ assert_eq!(tidy_facts(&dir.join("missing"), "2026-11-03"), None);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// The last branch counts too, though trimming took its tab.
+ #[test]
+ fn branch_names_keep_the_last_line_and_skip_symrefs() {
+ let listing = "refs/heads/main\t\nrefs/remotes/origin/HEAD\trefs/remotes/origin/main\n\
+ refs/remotes/origin/feat/x\t\nrefs/heads/last";
+ assert_eq!(branch_names(listing, "main"), ["origin/feat/x", "last"]);
+ }
+
+ /// Only a subject's trailing `(#N)` is its squash merge's PR; one named
+ /// earlier in the subject is just mentioned.
+ #[test]
+ fn pr_numbers_are_read_from_squash_merge_subjects() {
+ let prs = pr_numbers("a (#1)\nb (#22) (#3)\nc #4\nd (#)\ne (#5x)\nf (#1)\ng (#6) ");
+ assert_eq!(prs.landed, ["1", "3", "6"]);
+ assert!(prs.reverted.is_empty());
+ }
+
+ /// A GitHub revert names the reverted PR inside its quotes: that one is
+ /// reverted, not landed, even when its own merge is in the log too. The
+ /// revert's own PR did land.
+ #[test]
+ fn pr_numbers_set_reverted_prs_apart() {
+ let log = "Revert \"feat: x (#123)\" (#124)\nfeat: x (#123)\nRevert \"fix: y (#9)\"\n\
+ Revert \"no number\" (#50)\nfeat: z (#7)";
+ let prs = pr_numbers(log);
+ assert_eq!(prs.landed, ["124", "50", "7"]);
+ assert_eq!(prs.reverted, ["123", "9"]);
+ }
+
+ /// A work-tree file named like the default branch must not make git read
+ /// the branch as a path.
+ #[test]
+ fn the_tidy_facts_survive_a_file_named_like_the_default_branch() {
+ let Some(root) = init_repo() else { return };
+ let r = root.to_string_lossy().to_string();
+ git(&["-C", &r, "branch", "-M", "main"]).expect("rename");
+ commit(&root, "feat: kept (#5)");
+ std::fs::write(root.join("main"), "x").unwrap();
+ let facts = tidy_facts(&root, "2026-11-03");
+ let _ = std::fs::remove_dir_all(&root);
+ let facts = facts.expect("facts despite the file");
+ assert!(facts.contains("Default branch: main, head "), "{facts}");
+ assert!(facts.contains(" #5"), "{facts}");
+ assert!(!facts.contains("PRs reverted"), "no reverts, no line: {facts}");
+ }
}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 9cb05f82c..7725e2511 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -2689,16 +2689,31 @@ pub(crate) const MEMORY_TIDY_AGENT: &str = "memory-tidy";
/// 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.
+with the `memory` tool; 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.
+
+Your task may carry a facts block Jan gathered from the project's local git: today's date, the \
+default branch, which branches it contains, the worktrees, and the PR numbers in its recent log, \
+including reverted PRs. The repository may squash-merge, so a branch absent from the contained list \
+may still have landed: the PR numbers are the stronger evidence, and a branch not merged by commit is \
+never on its own a sign the work is still open. Equally, branch containment alone never shows that \
+work landed: a branch the default branch contains may have been created there and have no commits of \
+its own yet. You can also look at the project with `read`, `ls`, `find` and `grep` \
+(read-only) to check whether the files, functions or branches a note names still exist. Do not spend \
+many calls on the project: check only what a candidate note references, nothing broader.
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 \
+2. Archive a note only when its own text explicitly says the work is finished (merged, released, \
+shipped, closed, done, abandoned or obsolete), or when the facts or the code show the work it tracks \
+is finished: its PR number appears in the default branch's log (and is not among the reverted PRs), \
+or the code it describes has landed. Its branch being contained in the default branch is at most \
+supporting evidence, never enough on its own. Never archive a note on a reverted PR's number: that \
+work did not land, or was undone. Archive this way only notes that track \
+in-progress work or state; a note recording a durable fact, decision, convention or gotcha is NOT \
+archived just because its PR merged. 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.
@@ -2717,10 +2732,12 @@ Finish with a short report, one line per change: `archived <name>`, `merged <a>
`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
+/// id. It runs on the `smol` model with the `memory` tool -- the one child
+/// that keeps memory (see [`without_memory`]) -- plus read-only project tools
+/// and the git `facts` from [`gather_tidy_facts`], 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.
+/// doorbell, so a tidy never starts a model turn of its own. The facts are
+/// the caller's to gather first, off its own loop: they take several gits.
#[cfg(feature = "cli")]
pub(crate) async fn spawn_memory_tidy(
scope: &DispatchScope,
@@ -2728,11 +2745,12 @@ pub(crate) async fn spawn_memory_tidy(
parent: &ParentRun,
events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
budget: Arc<tauri_plugin_agent_tools::memory::ChangeBudget>,
+ facts: Option<String>,
) -> 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 (resolved, req) = memory_tidy_dispatch(facts);
let parent = &ParentRun {
cost_remaining: child_cost_ceiling(&child_model(&resolved, parent), parent)?,
..parent.clone()
@@ -2759,11 +2777,34 @@ fn memory_tidy_args(
args
}
+/// The git facts a tidy of `project_root` is handed (see
+/// [`crate::core::agent::git::tidy_facts`]), or `None` when there are none.
+/// On the blocking pool, since it runs several gits; each is time-limited
+/// there, so a stuck one delays the tidy by seconds, never stalls it.
+#[cfg(feature = "cli")]
+pub(crate) async fn gather_tidy_facts(root: PathBuf) -> Option<String> {
+ let today = chrono::Local::now().format("%Y-%m-%d").to_string();
+ tokio::task::spawn_blocking(move || crate::core::agent::git::tidy_facts(&root, &today))
+ .await
+ .ok()
+ .flatten()
+}
+
/// The tidy subagent's resolved definition and request: the `smol` model, the
-/// `memory` tool alone, and the internal memory-access flag.
+/// `memory` tool plus the read-only project tools `explore` has, and the
+/// internal memory-access flag. `facts` (from [`gather_tidy_facts`]) ride in
+/// its task.
#[cfg(feature = "cli")]
-fn memory_tidy_dispatch() -> (ResolvedDispatch, SubagentRequest) {
- let tools = vec![tauri_plugin_agent_tools::tools::MEMORY_TOOL.to_string()];
+fn memory_tidy_dispatch(facts: Option<String>) -> (ResolvedDispatch, SubagentRequest) {
+ // Read tools only: a note is checked against the project, never the
+ // project changed, and no shell, web or skills to wander off with.
+ let memory = tauri_plugin_agent_tools::tools::MEMORY_TOOL;
+ let tools: Vec<String> = [memory, "read", "ls", "find", "grep"].map(String::from).to_vec();
+ let mut task = "Tidy the memory now.".to_string();
+ if let Some(facts) = facts {
+ task.push_str("\n\n");
+ task.push_str(&facts);
+ }
let definition = SubagentDefinition {
name: MEMORY_TIDY_AGENT.to_string(),
description: "Tidies the agent's memory".to_string(),
@@ -2778,7 +2819,7 @@ fn memory_tidy_dispatch() -> (ResolvedDispatch, SubagentRequest) {
};
let req = SubagentRequest {
name: MEMORY_TIDY_AGENT.to_string(),
- description: "Tidy the memory now.".to_string(),
+ description: task,
allowed_tools: None,
agent: MEMORY_TIDY_AGENT.to_string(),
memory_access: true,
@@ -7036,18 +7077,27 @@ 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.
+ /// The tidy subagent is the one child with memory: the `memory` tool plus
+ /// the project read tools 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();
+ fn the_tidy_subagent_keeps_memory_and_only_reads_the_project() {
+ let (resolved, req) = memory_tidy_dispatch(None);
assert!(req.memory_access);
assert!(req.internal, "a tidy is Jan's own agent, listed as internal");
- assert_eq!(resolved.allowed_tools, Some(vec!["memory".to_string()]));
+ let five = ["memory", "read", "ls", "find", "grep"].map(String::from).to_vec();
+ assert_eq!(resolved.allowed_tools, Some(five.clone()));
+ assert_eq!(resolved.definition.allowed_tools, Some(five));
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"));
+ // A reader on the parent's checkout: no worktree, and read-only there.
+ assert!(!crate::core::agent::child_workspace::is_writer(
+ resolved.allowed_tools.as_deref(),
+ &ToolPermissions::allow_all(),
+ ));
+ assert!(req.workspace.is_none(), "never a worktree");
let reg = SubagentRegistry::load(&unique_root("tidy-not-dispatchable"));
assert!(!reg.dispatchable_names().contains(&MEMORY_TIDY_AGENT));
let prompt = &resolved.definition.system_prompt;
@@ -7077,7 +7127,21 @@ pub(crate) mod tests {
fn the_tidy_prompt_is_conservative_and_names_the_cap() {
let prompt = MEMORY_TIDY_PROMPT;
for rule in [
- "explicitly says the work is finished",
+ "its own text explicitly says the work is finished",
+ "facts block Jan gathered from the project's local git",
+ "the PR numbers are the stronger evidence",
+ "never on its own a sign the work is still open",
+ "`read`, `ls`, `find` and `grep`",
+ "read-only",
+ "branch containment alone never shows that work landed",
+ "created there and have no commits of its own",
+ "at most supporting evidence, never enough on its own",
+ "its PR number appears in the default branch's log",
+ "not among the reverted PRs",
+ "Never archive a note on a reverted PR's number",
+ "is NOT archived just because its PR merged",
+ "only notes that track in-progress work or state",
+ "check only what a candidate note references",
"Never archive a note because it looks generic",
"never `write` a copy and",
"Never create index, overview",
@@ -7086,6 +7150,8 @@ pub(crate) mod tests {
] {
assert!(prompt.contains(rule), "{rule}: {prompt}");
}
+ // A branch the default contains may be one cut there with no commits.
+ assert!(!prompt.contains("its branch is merged into the default branch"), "{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"));
@@ -7095,6 +7161,35 @@ pub(crate) mod tests {
assert!(without_memory(parent, false).memory_change_budget.is_none());
}
+ /// The facts Jan gathered ride in the tidy's task, after the instruction;
+ /// without any the task is the bare instruction.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn the_tidy_task_carries_the_gathered_facts() {
+ let (_, bare) = memory_tidy_dispatch(None);
+ assert_eq!(bare.description, "Tidy the memory now.");
+ let facts = "Today: 2026-11-03\nDefault branch: main, head abc";
+ let (_, req) = memory_tidy_dispatch(Some(facts.to_string()));
+ assert!(req.description.starts_with("Tidy the memory now.\n\n"), "{}", req.description);
+ assert!(req.description.ends_with(facts), "{}", req.description);
+ }
+
+ /// The facts come from the project's repository, and a project outside
+ /// one gets none rather than an error.
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn the_tidy_facts_are_gathered_off_thread_or_omitted() {
+ let plain = unique_root("tidy-facts-plain");
+ std::fs::create_dir_all(&plain).unwrap();
+ assert_eq!(gather_tidy_facts(plain).await, None);
+ let here = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ if let Some(facts) = gather_tidy_facts(here).await {
+ assert!(facts.contains("Today: "), "{facts}");
+ // Shown with `--nocapture`: the block a tidy of this repo gets.
+ println!("{facts}");
+ }
+ }
+
/// 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]
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 18c0c1add..2177ab0d8 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -5147,9 +5147,11 @@ struct App {
/// 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.
+ /// The tidy in flight, if any: one at a time. Set from when its git facts
+ /// start being gathered, before its child exists.
tidy_running: Option<TidyKind>,
- /// The in-flight tidy's subagent run id, so entering plan mode can stop it.
+ /// The in-flight tidy's subagent run id, so entering plan mode can stop it;
+ /// `None` while its facts are gathered.
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
@@ -14415,6 +14417,8 @@ async fn chat_loop<B: Backend>(
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;
+ // A begun tidy's git facts, gathered before its child starts.
+ let mut tidy_facts_task: Option<tokio::task::JoinHandle<Option<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
@@ -14654,19 +14658,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.
+ // collector would only report the cancellation as a failure, and its
+ // facts must not start a child once they land.
if app.tidy_running.is_none() {
if let Some(task) = tidy_task.take() {
task.abort();
}
+ if let Some(task) = tidy_facts_task.take() {
+ task.abort();
+ }
}
- // A memory tidy was asked for: start it in the background. It writes
+ // A memory tidy was asked for: begin 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() {
+ // the session is doing; its facts arrive in the select below.
+ if tidy_task.is_none() && tidy_facts_task.is_none() {
if let Some(kind) = app.tidy_request.take() {
- tidy_task = start_memory_tidy(app, kind, &session_events_tx).await;
+ tidy_facts_task = begin_memory_tidy(app, kind);
}
}
@@ -14966,6 +14974,9 @@ async fn chat_loop<B: Backend>(
compacted = await_compaction(&mut compact_task) => {
finish_compaction(app, compacted, compact_base);
}
+ facts = await_tidy_facts(&mut tidy_facts_task) => {
+ tidy_task = start_memory_tidy(app, facts, &session_events_tx).await;
+ }
tidied = await_memory_tidy(&mut tidy_task) => {
finish_memory_tidy(app, tidied);
}
@@ -18269,20 +18280,49 @@ enum TidyKind {
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.
-async fn start_memory_tidy(
+/// Begin the requested tidy: mark it running and gather its git facts on a
+/// task of their own, which the loop hands to [`start_memory_tidy`] when they
+/// land. Never waits: the facts take several gits, each allowed seconds, and
+/// the loop must keep drawing meanwhile. Running already, so `/memory tidy`
+/// and the auto trigger stand off, and entering plan mode stops it here too.
+fn begin_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() {
+) -> Option<tokio::task::JoinHandle<Option<String>>> {
+ let root = app.args.as_ref()?.project_root.clone();
+ let problem = if app.model.is_empty() {
+ "memory tidy needs a model: run /login first"
+ } else {
+ "memory tidy failed to start: no active project"
+ };
+ let Some(root) = root.filter(|_| !app.model.is_empty()) else {
if kind == TidyKind::Manual {
- app.note("memory tidy needs a model: run /login first");
+ app.note(problem);
}
return None;
- }
+ };
+ app.tidy_running = Some(kind);
+ app.note(match kind {
+ TidyKind::Manual => "tidying memory in the background",
+ TidyKind::Auto => "memory index is over its budget: tidying in the background",
+ });
+ Some(tokio::spawn(crate::core::agent::subagent::gather_tidy_facts(root)))
+}
+
+/// Start the tidy [`begin_memory_tidy`] began, with its gathered `facts`, on
+/// the session's registry. Fire-and-forget from the caller's view: the result
+/// is collected off the render loop. Nothing starts when the tidy was stopped
+/// while its facts were gathered (plan mode drops `tidy_running`).
+async fn start_memory_tidy(
+ app: &mut App,
+ facts: Option<String>,
+ events: &mpsc::UnboundedSender<StreamEvent>,
+) -> Option<tokio::task::JoinHandle<Result<String, String>>> {
+ app.tidy_running?;
+ let Some(args) = app.args.clone() else {
+ app.tidy_running = None;
+ return None;
+ };
let parent = crate::core::agent::subagent::ParentRun {
model: app.model.clone(),
smol_model: crate::core::agent::subagent::configured_smol_model(),
@@ -18302,17 +18342,12 @@ async fn start_memory_tidy(
&parent,
events,
budget.clone(),
+ facts,
)
.await;
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
@@ -18322,14 +18357,29 @@ async fn start_memory_tidy(
}))
}
Err(e) => {
- if kind == TidyKind::Manual {
- app.note(&format!("memory tidy failed to start: {e}"));
- }
+ // Either kind has announced itself by now (see
+ // `begin_memory_tidy`), so a silent failure would leave that note
+ // promising a tidy that never reports back.
+ app.tidy_running = None;
+ app.note(&format!("memory tidy failed to start: {e}"));
None
}
}
}
+/// The git facts a begun tidy is waiting on; pending while there is none.
+async fn await_tidy_facts(
+ task: &mut Option<tokio::task::JoinHandle<Option<String>>>,
+) -> Option<String> {
+ let joined = match task.as_mut() {
+ Some(h) => h.await,
+ None => return pending().await,
+ };
+ *task = None;
+ // A facts task that died leaves the tidy without facts, as a failed git does.
+ joined.ok().flatten()
+}
+
/// 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);
@@ -26940,7 +26990,8 @@ 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,
+ begin_memory_tidy, 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,
tool_kind, ToolOp,
@@ -47099,7 +47150,9 @@ fn a() {}
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).await.expect("tidy started");
+ let facts = begin_memory_tidy(&mut app, TidyKind::Manual).expect("facts gathering");
+ let facts = facts.await.expect("facts task");
+ let task = start_memory_tidy(&mut app, facts, &tx).await.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;
@@ -47112,6 +47165,75 @@ fn a() {}
assert!(text.contains("memory tidy stopped: plan mode is read only"), "{text}");
}
+ /// Starting a tidy never waits on its git facts: the loop gets the facts
+ /// task back at once, and until it lands the tidy already counts as
+ /// running, so neither `/memory tidy` nor the auto trigger starts another.
+ #[tokio::test]
+ async fn a_tidy_gathers_its_facts_without_blocking_the_loop() {
+ let mut app = test_app();
+ own_project(&mut app);
+ app.args = Some(test_args(&app, std::collections::HashMap::new()));
+ let facts = begin_memory_tidy(&mut app, TidyKind::Manual).expect("facts gathering");
+ assert_eq!(app.tidy_running, Some(TidyKind::Manual), "running while facts are pending");
+ assert_eq!(app.tidy_run_id, None, "no child before the facts land");
+ assert!(app.subagent_set.live_run_ids().is_empty());
+ memory_command(&mut app, "tidy");
+ assert_eq!(app.tidy_request, None);
+ app.auto_tidy_checked = false;
+ app.maybe_auto_tidy();
+ assert_eq!(app.tidy_request, None, "no auto tidy beside a pending one");
+ let text: String = app.transcript.rows.iter().map(row_text).collect();
+ assert!(text.contains("tidying memory in the background"), "{text}");
+ assert!(text.contains("already running"), "{text}");
+ facts.abort();
+ }
+
+ /// An automatic tidy has already announced itself when its facts are sent
+ /// off, so a dispatch that fails afterwards must say so, or the transcript
+ /// promises a tidy that never reports back.
+ #[tokio::test]
+ async fn an_auto_tidy_that_fails_to_start_says_so() {
+ let mut app = test_app();
+ own_project(&mut app);
+ app.args = Some(test_args(&app, std::collections::HashMap::new()));
+ let facts = begin_memory_tidy(&mut app, TidyKind::Auto).expect("facts gathering");
+ facts.abort();
+ // The project goes away before dispatch, so the spawn itself fails.
+ let mut args = (**app.args.as_ref().unwrap()).clone();
+ args.project_root = None;
+ app.args = Some(Arc::new(args));
+ let (tx, _rx) = mpsc::unbounded_channel();
+ assert!(start_memory_tidy(&mut app, None, &tx).await.is_none());
+ assert_eq!(app.tidy_running, None);
+ let text: String = app.transcript.rows.iter().map(row_text).collect();
+ assert!(text.contains("over its budget: tidying in the background"), "{text}");
+ assert!(text.contains("memory tidy failed to start"), "{text}");
+ }
+
+ /// Plan mode entered while a tidy's facts are being gathered stops it
+ /// there: the facts that land afterwards start no child, and an automatic
+ /// tidy gets its check back.
+ #[tokio::test]
+ async fn plan_mode_during_the_facts_phase_starts_no_tidy() {
+ use crate::core::agent::plan::RunMode;
+ let mut app = test_app();
+ own_project(&mut app);
+ app.args = Some(test_args(&app, stub_upstream("no changes")));
+ app.auto_tidy_checked = true;
+ let facts = begin_memory_tidy(&mut app, TidyKind::Auto).expect("facts gathering");
+ run_command(&mut app, "plan", &no_mcp()).await;
+ assert_eq!(app.run_mode, RunMode::Plan);
+ assert_eq!(app.tidy_running, None);
+ assert!(!app.auto_tidy_checked, "the auto tidy runs again after plan mode");
+ let facts = facts.await.expect("facts task");
+ let (tx, _rx) = mpsc::unbounded_channel();
+ assert!(start_memory_tidy(&mut app, facts, &tx).await.is_none(), "no tidy started");
+ assert!(app.subagent_set.live_run_ids().is_empty(), "no child");
+ assert_eq!(app.tidy_run_id, None);
+ 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.