Skip to content

Commit 1011cea

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
fix(desktop): ground agent workspace, migrate legacy nest, configurable repos_dir (#1194)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent fa1262a commit 1011cea

20 files changed

Lines changed: 1034 additions & 29 deletions

File tree

‎crates/buzz-acp/src/base_prompt.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,13 @@ Your persistent workspace is in your working directory:
6767
| `GUIDES/` | How-to documentation |
6868
| `WORK_LOGS/` | Timestamped activity logs |
6969
| `OUTBOX/` | Drafts pending review or send |
70-
| `REPOS/` | Checked-out source repositories |
70+
| `REPOS/` | Source checkouts. Work in an existing local checkout when one exists; clone here only when none does |
7171
| `.scratch/` | Ephemeral working files |
7272

7373
Knowledge files use `ALL_CAPS_WITH_UNDERSCORES.md` naming. `AGENTS.md` lists active agents and roles. See `AGENTS.md` in your working directory for full workspace conventions.
7474

75+
These paths are relative to your working directory — keep exploration there. Never run `find` or recursive searches over `$HOME` or `/` hunting for workspace files: they live under your working directory, not elsewhere on disk.
76+
7577
## Agent Memory
7678

7779
Your `core` memory is auto-injected into your context every turn — it holds identity, durable rules, and goals across sessions.

‎crates/buzz-acp/src/pool.rs‎

Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ async fn create_session_and_apply_model(
440440
// header from `engram_fetch::build_core_section`, so we just append it.
441441
let combined_system_prompt: Option<String> = if agent.protocol_version >= 2 {
442442
with_core(
443-
framed_system_prompt(ctx.base_prompt, ctx.system_prompt.as_deref()),
443+
framed_system_prompt(&ctx.cwd, ctx.base_prompt, ctx.system_prompt.as_deref()),
444444
agent_core,
445445
)
446446
} else {
@@ -670,15 +670,53 @@ pub(crate) fn prepend_base_for_legacy(
670670
/// split the combined value into labeled sub-sections. Each prompt is wrapped
671671
/// only when present, so a persona-only agent yields `[System]\n{persona}`
672672
/// rather than an unlabeled blob that would be mislabeled as `[Base]`.
673-
fn framed_system_prompt(base_prompt: Option<&str>, system_prompt: Option<&str>) -> Option<String> {
674-
match (base_prompt, system_prompt) {
673+
///
674+
/// Prepends a `[Workspace]` section naming the agent's absolute working
675+
/// directory. The base prompt describes the workspace layout but never its
676+
/// absolute root, so without this anchor a model fills the gap by searching
677+
/// `$HOME` (triggering macOS TCC prompts) or by inventing its own workspace
678+
/// directory. The line is emitted only when a real base prompt is present and
679+
/// `cwd` is an absolute path other than the `/` fallback — naming `/` as the
680+
/// workspace would itself invite a `$HOME`-wide scan.
681+
fn framed_system_prompt(
682+
cwd: &str,
683+
base_prompt: Option<&str>,
684+
system_prompt: Option<&str>,
685+
) -> Option<String> {
686+
let body = match (base_prompt, system_prompt) {
675687
(Some(bp), Some(sp)) => Some(format!(
676688
"{}\n\n[System]\n{sp}",
677689
crate::queue::base_section(bp)
678690
)),
679691
(Some(bp), None) => Some(crate::queue::base_section(bp)),
680692
(None, Some(sp)) => Some(format!("[System]\n{sp}")),
681693
(None, None) => None,
694+
}?;
695+
// Anchor the workspace only when a base prompt is present — the workspace
696+
// section grounds the base prompt's layout description, so it is meaningless
697+
// for a persona-only (`[System]`-only) agent that never received that layout.
698+
match (base_prompt, workspace_section(cwd)) {
699+
(Some(_), Some(workspace)) => Some(format!("{workspace}\n\n{body}")),
700+
_ => Some(body),
701+
}
702+
}
703+
704+
/// Render the `[Workspace]` grounding section, or `None` when `cwd` is unusable.
705+
///
706+
/// Skips relative paths and the `/` fallback (`std::env::current_dir()` resolves
707+
/// to `/` on failure): a `/`-rooted workspace line would actively encourage the
708+
/// `$HOME`-wide scan this section exists to prevent.
709+
fn workspace_section(cwd: &str) -> Option<String> {
710+
if cwd != "/" && cwd.starts_with('/') {
711+
Some(format!(
712+
"[Workspace]\nYour absolute working directory is `{cwd}`. All workspace \
713+
files — `AGENTS.md`, `RESEARCH/`, `PLANS/`, `GUIDES/`, `WORK_LOGS/`, \
714+
`OUTBOX/` — and any repositories you clone (under `{cwd}/REPOS/`) live \
715+
here. This is where you already are; do not search `$HOME` or other \
716+
directories for them."
717+
))
718+
} else {
719+
None
682720
}
683721
}
684722

@@ -2393,28 +2431,66 @@ mod tests {
23932431

23942432
#[test]
23952433
fn test_framed_system_prompt_both_present_carries_both_headers() {
2396-
let framed = framed_system_prompt(Some("base text"), Some("persona text"))
2434+
let framed = framed_system_prompt("/", Some("base text"), Some("persona text"))
23972435
.expect("both present yields Some");
23982436
assert_eq!(framed, "[Base]\nbase text\n\n[System]\npersona text");
23992437
}
24002438

24012439
#[test]
24022440
fn test_framed_system_prompt_base_only_labels_base() {
2403-
let framed = framed_system_prompt(Some("base text"), None).expect("base yields Some");
2441+
let framed = framed_system_prompt("/", Some("base text"), None).expect("base yields Some");
24042442
assert_eq!(framed, "[Base]\nbase text");
24052443
}
24062444

24072445
#[test]
24082446
fn test_framed_system_prompt_persona_only_labels_system() {
24092447
// A bare persona would be mislabeled "Base" downstream — it must carry
24102448
// its own [System] header even when no base prompt exists.
2411-
let framed = framed_system_prompt(None, Some("persona text")).expect("persona yields Some");
2449+
let framed =
2450+
framed_system_prompt("/", None, Some("persona text")).expect("persona yields Some");
24122451
assert_eq!(framed, "[System]\npersona text");
24132452
}
24142453

24152454
#[test]
24162455
fn test_framed_system_prompt_neither_is_none() {
2417-
assert!(framed_system_prompt(None, None).is_none());
2456+
assert!(framed_system_prompt("/", None, None).is_none());
2457+
}
2458+
2459+
#[test]
2460+
fn test_framed_system_prompt_absolute_cwd_prepends_workspace_before_base() {
2461+
let framed = framed_system_prompt("/Users/me/.buzz", Some("base text"), None)
2462+
.expect("base yields Some");
2463+
assert!(
2464+
framed.starts_with("[Workspace]\n"),
2465+
"workspace section must lead: {framed}"
2466+
);
2467+
assert!(framed.contains("`/Users/me/.buzz`"));
2468+
assert!(
2469+
framed.contains("\n\n[Base]\nbase text"),
2470+
"base must follow the workspace section: {framed}"
2471+
);
2472+
}
2473+
2474+
#[test]
2475+
fn test_framed_system_prompt_persona_only_omits_workspace() {
2476+
// The workspace section grounds the base prompt's layout; a persona-only
2477+
// agent never received that layout, so no [Workspace] anchor is emitted.
2478+
let framed = framed_system_prompt("/Users/me/.buzz", None, Some("persona text"))
2479+
.expect("persona yields Some");
2480+
assert_eq!(framed, "[System]\npersona text");
2481+
}
2482+
2483+
#[test]
2484+
fn test_framed_system_prompt_root_cwd_omits_workspace() {
2485+
// The "/" fallback must never be named — it would invite a $HOME scan.
2486+
let framed = framed_system_prompt("/", Some("base text"), None).expect("base yields Some");
2487+
assert_eq!(framed, "[Base]\nbase text");
2488+
}
2489+
2490+
#[test]
2491+
fn test_workspace_section_relative_cwd_is_none() {
2492+
assert!(workspace_section("relative/path").is_none());
2493+
assert!(workspace_section("").is_none());
24182494
}
24192495

24202496
// ── with_core tests ──────────────────────────────────────────────────────

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,20 @@ const rules = [
3131
// file is broken up. Tracked as a follow-up.
3232
const overrides = new Map([
3333
["src-tauri/src/commands/agents.rs", 1294],
34-
["src-tauri/src/managed_agents/nest.rs", 1420],
34+
// Residual repos_dir integration in ensure_nest_at: REPOS is provisioned
35+
// outside NEST_DIRS (it may be a symlink), so it needs its own create +
36+
// chmod-only-when-real-dir handling plus integration test coverage. The
37+
// self-contained repos_dir functions and their unit tests live in repos.rs;
38+
// this is the seam that must stay in nest.rs. Approved override; still queued
39+
// to split with the rest of this list.
40+
["src-tauri/src/managed_agents/nest.rs", 1447],
3541
["src-tauri/src/managed_agents/runtime.rs", 1953],
3642
["src-tauri/src/managed_agents/personas.rs", 1080],
3743
["src-tauri/src/managed_agents/persona_card.rs", 1050],
38-
["src/shared/api/tauri.ts", 1196],
44+
// applyWorkspace reposDir parameter threaded through the Tauri invoke for
45+
// configurable repos_dir — a 3-line overage from load-bearing parameter
46+
// plumbing, not generic debt growth. Approved override; still queued to split.
47+
["src/shared/api/tauri.ts", 1198],
3948
["src-tauri/src/nostr_convert.rs", 1126],
4049
["src/shared/api/relayClientSession.ts", 1022],
4150
["src-tauri/src/migration.rs", 1295],

‎desktop/src-tauri/src/commands/workspace.rs‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use nostr::Keys;
22
use serde::Serialize;
3-
use tauri::{AppHandle, State};
3+
use tauri::{AppHandle, Emitter, State};
44

55
use crate::app_state::AppState;
6-
use crate::managed_agents::try_regenerate_nest;
6+
use crate::managed_agents::{ensure_repos_symlink, nest_dir, try_regenerate_nest};
77
use crate::relay;
88

99
#[derive(Serialize)]
@@ -26,11 +26,20 @@ pub fn get_active_workspace(state: State<'_, AppState>) -> Result<ActiveWorkspac
2626
/// Apply a workspace's configuration to the backend session.
2727
///
2828
/// Called by the frontend on app init (after reload) to configure the
29-
/// Tauri backend with the selected workspace's relay URL and keys.
29+
/// Tauri backend with the selected workspace's relay URL, keys, and repos
30+
/// directory.
31+
///
32+
/// Validation runs before any state mutation: an invalid `repos_dir` (bad
33+
/// path) rejects cleanly with nothing applied. The `REPOS` symlink itself is
34+
/// a filesystem *side-effect* — its failure (e.g. a non-empty real `REPOS`
35+
/// refusing a downgrade, or a renamed external target on a later launch) is
36+
/// non-fatal: relay/keys still apply, the command returns `Ok`, and a
37+
/// `repos-dir-error` event surfaces the failure to the frontend.
3038
#[tauri::command]
3139
pub fn apply_workspace(
3240
relay_url: String,
3341
nsec: Option<String>,
42+
repos_dir: Option<String>,
3443
app: AppHandle,
3544
state: State<'_, AppState>,
3645
) -> Result<(), String> {
@@ -42,6 +51,24 @@ pub fn apply_workspace(
4251
None => None,
4352
};
4453

54+
// Normalize repos_dir to a trimmed non-empty value. `None`/empty clears
55+
// the override (REPOS falls back to a real dir). A bad path is rejected
56+
// here — before any mutation — so the dialog sees a clean Err.
57+
let repos_dir = repos_dir
58+
.map(|s| s.trim().to_string())
59+
.filter(|s| !s.is_empty());
60+
if let Some(dir) = repos_dir.as_deref() {
61+
let nest = nest_dir().ok_or("cannot resolve home directory for nest")?;
62+
// Validate without mutating the filesystem. Keeps the command's
63+
// "validate-first, nothing below can fail" contract honest. Also emit
64+
// the error so it surfaces even at the init call site (which swallows
65+
// the returned Err to console for the relay/keys path).
66+
if let Err(error) = crate::managed_agents::validate_repos_dir(&nest, dir) {
67+
let _ = app.emit("repos-dir-error", error.clone());
68+
return Err(error);
69+
}
70+
}
71+
4572
// ── Apply all state changes (nothing below can fail) ──────────────────
4673
{
4774
let mut override_guard = state.relay_url_override.lock().map_err(|e| e.to_string())?;
@@ -53,6 +80,17 @@ pub fn apply_workspace(
5380
*keys_guard = keys;
5481
}
5582

83+
// ── Filesystem side-effect (non-fatal) ────────────────────────────────
84+
// Re-point REPOS to match repos_dir. Failure here (downgrade refused,
85+
// external target gone) must NOT fail the command — relay/keys are already
86+
// applied. Surface it via a `repos-dir-error` event the frontend toasts.
87+
if let Some(nest) = nest_dir() {
88+
if let Err(error) = ensure_repos_symlink(&nest, repos_dir.as_deref()) {
89+
eprintln!("buzz-desktop: repos dir setup failed: {error}");
90+
let _ = app.emit("repos-dir-error", error);
91+
}
92+
}
93+
5694
try_regenerate_nest(&app);
5795

5896
Ok(())

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,15 @@ pub fn run() {
586586
eprintln!("buzz-desktop: failed to create nest: {error}");
587587
}
588588

589+
// Carry the agent's knowledge from the legacy nest (~/.sprout) into
590+
// the live nest (~/.buzz) after it exists. Must run after
591+
// ensure_nest() so the destination is present. Non-fatal.
592+
// On a real migration, emit a one-time hint so the user can delete
593+
// the now-inert ~/.sprout; the frontend dedupes the toast.
594+
if migration::migrate_legacy_nest() {
595+
let _ = app_handle.emit("legacy-nest-migrated", ());
596+
}
597+
589598
// Create/update the local CLI symlink pointing to the
590599
// bundled CLI binary. Non-fatal: agents find CLI via PATH.
591600
if let Ok(exe) = std::env::current_exe() {

‎desktop/src-tauri/src/managed_agents/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ mod personas;
99
mod process_lifecycle;
1010
#[cfg(feature = "mesh-llm")]
1111
mod relay_mesh;
12+
mod repos;
1213
mod restore;
1314
mod runtime;
1415
mod storage;
@@ -26,6 +27,7 @@ pub use personas::*;
2627
pub use process_lifecycle::*;
2728
#[cfg(feature = "mesh-llm")]
2829
pub use relay_mesh::*;
30+
pub use repos::{ensure_repos_symlink, validate_repos_dir};
2931
pub use restore::*;
3032
pub use runtime::*;
3133
pub use storage::*;

‎desktop/src-tauri/src/managed_agents/nest.rs‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,22 @@ use tauri::{AppHandle, Manager};
2020
use crate::managed_agents::discovery::known_skill_dirs;
2121

2222
/// Subdirectories created inside the nest.
23+
/// `REPOS` is intentionally absent: it is provisioned by
24+
/// [`super::repos::ensure_repos_symlink`], which makes it either a real directory (default)
25+
/// or a symlink to a user-configured `repos_dir`. Creating it here
26+
/// unconditionally would race a future symlink re-point.
2327
const NEST_DIRS: &[&str] = &[
2428
"GUIDES",
2529
"RESEARCH",
2630
"PLANS",
2731
"WORK_LOGS",
28-
"REPOS",
2932
"OUTBOX",
3033
".scratch",
3134
];
3235

3336
/// Default AGENTS.md content written on first init.
3437
/// Fully static — no runtime interpolation, no secrets, no user paths.
35-
const AGENTS_MD: &str = include_str!("nest_agents.md");
38+
pub(crate) const AGENTS_MD: &str = include_str!("nest_agents.md");
3639

3740
/// Default SKILL.md content for the buzz-cli skill.
3841
/// Written to ~/.buzz/.agents/skills/buzz-cli/SKILL.md on first init.
@@ -109,6 +112,11 @@ pub fn ensure_nest_at(root: &Path) -> Result<(), String> {
109112
fs::create_dir_all(&path).map_err(|e| format!("create {}: {e}", path.display()))?;
110113
}
111114

115+
// REPOS is provisioned separately from NEST_DIRS: it may be a symlink to a
116+
// user-configured repos_dir (applied later via apply_workspace), so setup
117+
// must not clobber an existing configured symlink. See repos.rs.
118+
super::repos::ensure_repos_setup_default(root)?;
119+
112120
// Write AGENTS.md only if it doesn't already exist.
113121
// Uses create_new (O_CREAT|O_EXCL) to atomically check-and-create,
114122
// closing the TOCTOU gap that exists() + write() would leave open.
@@ -184,6 +192,18 @@ pub fn ensure_nest_at(root: &Path) -> Result<(), String> {
184192
.map_err(|e| format!("set permissions on {}: {e}", path.display()))?;
185193
}
186194
}
195+
// REPOS is provisioned outside NEST_DIRS (it may be a symlink). Only
196+
// chmod it when it is a real directory — chmod on a symlink would
197+
// affect the user's external repos_dir target.
198+
let repos_path = root.join("REPOS");
199+
let repos_is_symlink = repos_path
200+
.symlink_metadata()
201+
.map(|m| m.file_type().is_symlink())
202+
.unwrap_or(false);
203+
if !repos_is_symlink {
204+
fs::set_permissions(&repos_path, perms.clone())
205+
.map_err(|e| format!("set permissions on {}: {e}", repos_path.display()))?;
206+
}
187207
// Skill directory trees inside root get 700.
188208
// Build the list from canonical path + all known provider skill dirs.
189209
let mut skill_perm_dirs = Vec::new();
@@ -618,6 +638,9 @@ mod tests {
618638
for dir in NEST_DIRS {
619639
assert!(root.join(dir).is_dir(), "{dir}/ should exist");
620640
}
641+
// REPOS is provisioned separately (may be a symlink); with no
642+
// repos_dir configured it lands as a real directory.
643+
assert!(root.join("REPOS").is_dir(), "REPOS/ should exist");
621644

622645
// AGENTS.md was written with default content.
623646
let content = fs::read_to_string(root.join("AGENTS.md")).unwrap();
@@ -633,6 +656,12 @@ mod tests {
633656
let mode = fs::metadata(root.join(dir)).unwrap().permissions().mode() & 0o777;
634657
assert_eq!(mode, 0o700, "{dir}/ should be 700");
635658
}
659+
let repos_mode = fs::metadata(root.join("REPOS"))
660+
.unwrap()
661+
.permissions()
662+
.mode()
663+
& 0o777;
664+
assert_eq!(repos_mode, 0o700, "REPOS/ should be 700");
636665
}
637666
}
638667

‎desktop/src-tauri/src/managed_agents/nest_agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Your persistent workspace. Created once by the Buzz desktop app. The static cont
1111
| `RESEARCH/` | Findings, notes, and reference material |
1212
| `WORK_LOGS/` | Session logs — what was tried, learned, decided |
1313
| `OUTBOX/` | Shareable docs for external readers (no frontmatter) |
14-
| `REPOS/` | Cloned repositories (clone freely here for exploration) |
14+
| `REPOS/` | Source checkouts. Work in an existing local checkout when one exists; clone here only when none does |
1515
| `.scratch/` | Temporary working files — treat as disposable between sessions |
1616

1717
Filenames: `ALL_CAPS_WITH_UNDERSCORES.md` (e.g., `OAUTH_FLOW_NOTES.md`).

0 commit comments

Comments
 (0)