Skip to content

Commit 0dbd036

Browse files
wpfleger96DuncanHayt
authored
feat(agents): harness-agnostic effort write path and spawn bridge (#4625)
## Summary Genericizes the agent effort write-side so Goose participates in the same canonical effort contract as buzz-agent. A spawn bridge translates the canonical key to whatever the target harness expects at launch time. Read/write/spawn paths all derive their vocabulary from runtime metadata rather than a hardcoded buzz-agent list. ## What changed ### Rust — config bridge + spawn path - `apply_spawn_effort_env` in `effort.rs`: production command-boundary seam — writes baked env, runs the effort projection, strips per-runtime suppress set, and emits exactly one projected key. - `apply_effort_to_spawn_command` in `runtime.rs`: thin wrapper returning a `#[must_use] EffortApplied(())` token (private field — unforgeable outside the function). `spawn_agent_child` calls it as `let effort = apply_effort_to_spawn_command(...)` and passes `effort` to `spawn_with_effort_proof`. Deleting the call is a compile error: `effort` is undefined at the `spawn_with_effort_proof` site. Deleting `apply_spawn_effort_env` inside the wrapper turns the production-sequence tests RED. - `apply_record_field_updates` in `agent_models_update.rs`: returns `Result<RecordFieldsApplied, String>` (`#[must_use]` token). `update_managed_agent` calls it as `let applied = apply_record_field_updates(...)?` then passes `applied` to `stamp_record_updated_at`. Deleting the call is a compile error: `applied` is undefined at the `stamp_record_updated_at` site. - Unknown/custom-runtime passthrough: `apply_effort_launch_to_command` skips the suppress loop when `preserve_passthrough && value.is_none()`, preserving ambient ACP sentinels. - `EnvVarGuard`: prior value stored as `OsString` (`var_os`) so non-Unicode values are restored exactly on Drop. A single `PROCESS_ENV_MUTEX` in `managed_agents/mod.rs` is shared by `lock_path_mutex()` and `lock_env_mutex()` — any two tests calling either helper are mutually exclusive with each other. Tests in other modules (`app_state_tests`, `agent_config_tests`, `reader_tests`) maintain their own independent locks and are not in this domain. - Dead-code: `strip_effort_keys_from_command` marked `#[cfg(test)]`; import path in `effort_cmd_tests.rs` fixed. - Windows CI fix: platform-gated variants for inherited-env tests. ### TypeScript — renderer + model cleanup - `AgentConfigFields` orphan-model cleanup effect: the `isHarnessNativeEffort` early-return was skipping the model clear on provider→Custom transitions. Refined to: return early only when model is already null; clear model once while preserving the harness-native effort key (Carl P2). - Provider-empty convergence: when model is null and effort is native, the cleanup effect returns early (nothing to clear) — prevents spurious `onConfigChange` loop. - `EffortSelectField` / `humanizeEffortLabel`: runtime-native option labels title-cased (`off` → `Off`) with raw canonical values preserved for round-trip fidelity. - `AgentConfigFields`: drives effort renderer from `selectedRuntime.effortCanonicalValues` (harness-native path) or the model/provider catalog (buzz-agent/provider path), selected by `isHarnessNativeEffort`. ### Docs - `desktop/src/features/agents/AGENTS.md` item 14: updated from deleted `persistAgentEffortLevel` direct-write contract to the shipped Save-gated `update_managed_agent.effortLevel` path. Consistent with `EffortPickerField`'s own doc comment. ### Tests - `agent_models_update_tests.rs`: seam tests via `apply_record_field_updates` — non-local rejects, local set/clear, ordering invariant, ACP-sentinel sweep. `record_field_updates_persist_effort_to_disk` (renamed from the prior false-claim name) drives load→apply→stamp→save→load via a mock AppHandle + tempdir, asserting `effort_level` persists to disk. Manual HOME/XDG restore replaced with RAII `EnvVarGuard` (panic-safe, `OsString`-exact). - `effort_cmd_tests.rs` / `effort_tests.rs`: production-sequence seam tests via `apply_effort_to_spawn_command`. Spawns `/usr/bin/env` to verify child's real env. `EnvVarGuard` for panic-safe restore. Windows twin using `cmd /c set`. - `effortAutoClear.test.mjs`: five mounted stateful journeys via `AgentConfigFields` with `useCustomSelect=true`. Covers: custom trigger shows "Off" at mount; provider-empty mount is a stable fixed point; provider→Custom switch converges; stale Anthropic model cleared on Custom switch with Goose effort preserved (Carl P2 regression); Settings-style Save/reread preserves effort. - `agentDefaultsEditor.test.mjs`: two full Save/Next journey tests through the real production parent trees. Both start with `GOOSE_THINKING_EFFORT: "low"` and operate the real Popover-based effort control (click trigger → click "off" option) before Save/Next, asserting zero writes after selection. The `set_global_agent_config` stub captures the submitted payload; each test asserts raw `GOOSE_THINKING_EFFORT: "off"` in the captured config. The stub stores its canonical response from the actual payload; the fresh remount's `get_global_agent_config` returns that stored object (not a hand-written fixture), then asserts "Off" shown. The `DefaultConfigStep` test starts with `isDirty: false` — the real-control effort selection calls `onConfigChange → updateDraft → isDirtyRef=true`, making the `commit()` on Next load-bearing. ## Mutation evidence - Delete `let effort = apply_effort_to_spawn_command(...)` call from `spawn_agent_child` → compile error: `error[E0425]: cannot find value `effort`` at `spawn_with_effort_proof` site. - Delete `let applied = apply_record_field_updates(...)?` from `update_managed_agent` → compile error: `error[E0425]: cannot find value `applied`` at `stamp_record_updated_at` site. - Delete `apply_spawn_effort_env` from inside `apply_effort_to_spawn_command` wrapper → `production_sequence_goose_inherited_collision_resolved_in_child` RED. - Revert `isHarnessNativeEffort &&` guard in cleanup `useEffect` to bare `if (isHarnessNativeEffort) return` → stale model not cleared → Carl P2 regression test RED. - Remove `isHarnessNativeEffort ||` from the nothing-to-clear condition → provider-empty mount emits `onConfigChange` → loop test RED. - Remove `isHarnessNativeEffort` branch in `AgentConfigFields.tsx:634-636` → both `agentDefaultsEditor.test.mjs` mount assertions fail: trigger shows "Select" instead of initial effort label. - Remove `preserve_passthrough` guard in `apply_effort_launch_to_command` → `production_sequence_custom_inherited_acp_sentinel_survives` RED. - Drop `GOOSE_THINKING_EFFORT` from the `set_global_agent_config` stub payload → payload assertion in `agentDefaultsEditor.test.mjs` fails (`undefined !== "off"`) → RED (verified). - Remove the effort-select dirtying steps from the `DefaultConfigStep` test (so `isDirty` stays false) → `commit()` is a no-op → write-count assertion after Next fails (0 instead of 1) → RED. --------- Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Hayt <9e1c23a3fd83f61da34420e4e88ff1b16e45cafcc0cd9019eb07d4ecfa8ca9b0@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Hayt <9e1c23a3fd83f61da34420e4e88ff1b16e45cafcc0cd9019eb07d4ecfa8ca9b0@buzz.block.builderlab.xyz>
1 parent 04babf0 commit 0dbd036

55 files changed

Lines changed: 7121 additions & 919 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 9 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@ use crate::{
1414
},
1515
current_instance_id, is_reserved_env_key, is_safe_to_reveal, is_well_formed_env_key,
1616
known_acp_runtime, load_managed_agents, load_personas, resolve_effective_agent_env,
17-
save_managed_agents, sync_managed_agent_processes, AgentDefinition, BackendKind,
18-
GlobalAgentConfig, KnownAcpRuntime, ManagedAgentRecord, ManagedAgentRuntimeKey,
19-
MAX_ENV_VALUE_BYTES,
17+
save_managed_agents, sync_managed_agent_processes, AgentDefinition, GlobalAgentConfig,
18+
KnownAcpRuntime, ManagedAgentRecord, ManagedAgentRuntimeKey, MAX_ENV_VALUE_BYTES,
2019
},
2120
};
2221

@@ -535,42 +534,15 @@ fn parse_models(raw: Option<&serde_json::Value>) -> (Vec<AcpModelEntry>, Option<
535534
(models, current_model)
536535
}
537536

538-
/// Persist the canonical startup effort level for a local managed agent.
539-
///
540-
/// B5 (v4 direct-write): the panel's EffortPicker calls this directly to set the
541-
/// effort a spawn will apply at next session start. The value is stored on the
542-
/// record; at spawn `runtime.rs` injects it as `BUZZ_ACP_EFFORT_LEVEL` and the
543-
/// harness applies it via `session/set_config_option` against the adapter's
544-
/// advertised `thought_level` configId. Pass `None` to clear (adapter default).
545-
///
546-
/// Rejects non-local backends: remote agents receive effort through `policy_env`
547-
/// at deploy time (see `agents_deploy.rs`), never this local persistence path —
548-
/// so an effort edit against a deployed agent is a caller error, not a silent
549-
/// no-op that leaves the panel and the running agent disagreeing.
550-
#[tauri::command]
551-
pub fn persist_agent_effort_level(
552-
pubkey: String,
537+
/// Atomically set the record's canonical effort column and strip every stale
538+
/// record-scope effort env alias. Split from the Tauri command so the invariant
539+
/// — no leftover alias can outrank the just-set column — is directly testable.
540+
pub(crate) fn apply_picker_effort_level(
541+
record: &mut ManagedAgentRecord,
553542
effort_level: Option<String>,
554-
app: AppHandle,
555-
state: State<'_, AppState>,
556-
) -> Result<(), String> {
557-
let _store_guard = state
558-
.managed_agents_store_lock
559-
.lock()
560-
.map_err(|e| e.to_string())?;
561-
let mut records = load_managed_agents(&app)?;
562-
let record = records
563-
.iter_mut()
564-
.find(|r| r.pubkey == pubkey)
565-
.ok_or_else(|| format!("agent {pubkey} not found"))?;
566-
if record.backend != BackendKind::Local {
567-
return Err(format!(
568-
"agent {pubkey} is not a local agent; remote effort is set at deploy time"
569-
));
570-
}
543+
) {
571544
record.effort_level = effort_level;
572-
record.updated_at = crate::util::now_iso();
573-
save_managed_agents(&app, &records)
545+
crate::managed_agents::remove_record_effort_aliases(&mut record.env_vars);
574546
}
575547

576548
#[cfg(test)]

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

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ fn with_no_goose_config<T>(body: impl FnOnce() -> T) -> T {
2929
}
3030

3131
fn goose_runtime() -> &'static KnownAcpRuntime {
32-
&KnownAcpRuntime {
32+
static RUNTIME: KnownAcpRuntime = KnownAcpRuntime {
3333
id: "goose",
3434
label: "Goose",
3535
commands: &["goose"],
@@ -55,13 +55,16 @@ fn goose_runtime() -> &'static KnownAcpRuntime {
5555
config_file_format: Some("yaml"),
5656
supports_acp_native_config: true,
5757
thinking_env_var: Some("GOOSE_THINKING_EFFORT"),
58+
effort_normalization: Some(&crate::managed_agents::GOOSE_EFFORT_NORMALIZATION),
59+
effort_accepted_values: None,
5860
max_tokens_env_var: Some("GOOSE_MAX_TOKENS"),
5961
context_limit_env_var: Some("GOOSE_CONTEXT_LIMIT"),
6062
max_rounds_env_var: None,
6163
required_normalized_fields: &["model", "provider"],
6264
login_hint: None,
6365
auth_probe_args: None,
64-
}
66+
};
67+
&RUNTIME
6568
}
6669

6770
fn agent_record() -> ManagedAgentRecord {
@@ -630,6 +633,58 @@ fn baked_env_mixed_keys_correct_masking() {
630633
assert!(token.masked);
631634
}
632635

636+
/// F1 picker direct-write invariant: a stale record-native `GOOSE_THINKING_EFFORT`
637+
/// (launch-projection tier 1, ABOVE the canonical column) must not survive a
638+
/// picker write. Setting effort `high` through the picker path both writes the
639+
/// column and sweeps the stale alias, so the reader and the launch projection
640+
/// both resolve `high` — not the stale `low`. Deleting the sweep in
641+
/// `apply_picker_effort_level` re-breaks this: the projection would emit `low`.
642+
#[test]
643+
fn picker_write_sweeps_stale_record_native_effort_alias() {
644+
let mut record = agent_record();
645+
record
646+
.env_vars
647+
.insert("GOOSE_THINKING_EFFORT".to_string(), "low".to_string());
648+
649+
super::apply_picker_effort_level(&mut record, Some("high".to_string()));
650+
651+
// The stale record-native alias is gone; only the column carries the value.
652+
assert!(
653+
!record.env_vars.contains_key("GOOSE_THINKING_EFFORT"),
654+
"stale record-native effort alias must be swept by the picker write"
655+
);
656+
assert_eq!(record.effort_level.as_deref(), Some("high"));
657+
658+
// Reader: the panel resolves the just-set value, not the stale alias.
659+
let surface = with_no_goose_config(|| {
660+
resolve_config_surface(
661+
record.clone(),
662+
&[],
663+
Some(goose_runtime()),
664+
None,
665+
&Default::default(),
666+
None,
667+
)
668+
});
669+
let effort = surface
670+
.normalized
671+
.thinking_effort
672+
.expect("picker-set effort must resolve");
673+
assert_eq!(effort.value.as_deref(), Some("high"));
674+
675+
// Launch projection: the spawned child receives the picker value.
676+
let launch = crate::managed_agents::config_bridge::effort::effort_launch_projection(
677+
&record,
678+
Some(goose_runtime()),
679+
&[],
680+
None,
681+
&std::collections::BTreeMap::new(),
682+
None,
683+
&std::collections::BTreeMap::new(),
684+
);
685+
assert_eq!(launch.value.as_deref(), Some("high"));
686+
}
687+
633688
#[test]
634689
fn baked_env_thinking_effort_is_unmasked() {
635690
// BUZZ_AGENT_THINKING_EFFORT is a non-secret enum — must not be masked.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ fn active_installs() -> &'static std::sync::Mutex<std::collections::HashSet<Stri
1717
/// Returns the adapter install commands that `install_acp_runtime_blocking` would
1818
/// run for `runtime_id` given a resolved adapter binary at `adapter_path` (or `None` if not found).
1919
/// Returns `None` when no install is needed; `Some(cmds)` when adapter is missing or outdated.
20-
///
2120
/// For the codex **outdated** case, returns a two-step reinstall: uninstall `@zed-industries/codex-acp`
2221
/// then install `@agentclientprotocol/codex-acp` (npm ≥7 refuses to overwrite a bin from another pkg).
2322
/// For the **missing** case, catalog's `adapter_install_commands` are used as-is.
@@ -150,6 +149,7 @@ pub async fn save_custom_harness(
150149
model_env_var: None,
151150
provider_env_var: None,
152151
thinking_env_var: None,
152+
effort_canonical_values: None,
153153
max_tokens_env_var: None,
154154
context_limit_env_var: None,
155155
max_rounds_env_var: None,

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ use crate::{
2626
UpdateManagedAgentResponse, DEFAULT_ACP_COMMAND,
2727
},
2828
relay::{relay_ws_url_with_override, sync_managed_agent_profile},
29-
util::now_iso,
3029
};
3130

3231
/// Query available models from an agent via `buzz-acp models --json`.

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

Lines changed: 115 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,88 @@ fn ensure_access_policy_change_supported(
3535
Ok(())
3636
}
3737

38+
/// Reject an effort mutation for a non-local record. Remote effort is
39+
/// deployment-owned (set via `policy_env` at deploy time); persisting locally
40+
/// would make the canonical column diverge from the deployed runtime's actual
41+
/// effort.
42+
fn ensure_effort_change_supported(
43+
record: &ManagedAgentRecord,
44+
effort_level: &Option<Option<String>>,
45+
) -> Result<(), String> {
46+
if effort_level.is_some() && record.backend != crate::managed_agents::BackendKind::Local {
47+
return Err(format!(
48+
"agent {} is not a local agent; remote effort is set at deploy time",
49+
record.pubkey
50+
));
51+
}
52+
Ok(())
53+
}
54+
55+
/// Guard/apply seam for the effort step inside `apply_record_field_updates`.
56+
fn apply_effort_update(
57+
record: &mut ManagedAgentRecord,
58+
effort_level: Option<Option<String>>,
59+
) -> Result<(), String> {
60+
ensure_effort_change_supported(record, &effort_level)?;
61+
if let Some(effort_override) = effort_level {
62+
crate::commands::agent_config::apply_picker_effort_level(record, effort_override);
63+
}
64+
Ok(())
65+
}
66+
67+
/// Proof token returned by `apply_record_field_updates`. Zero-size and
68+
/// `#[must_use]`; consumed by `stamp_record_updated_at`, so removing the
69+
/// `apply_record_field_updates` call from `update_managed_agent` leaves
70+
/// `applied` undefined at the timestamp site — a compile error.
71+
#[derive(Debug)]
72+
#[must_use]
73+
pub(crate) struct RecordFieldsApplied(());
74+
75+
/// Apply the env-vars and effort steps of `update_managed_agent` to a record
76+
/// in the correct order: env_vars FIRST (so the same-request map cannot
77+
/// reintroduce a stale alias), then the canonical effort column write.
78+
///
79+
/// Returns a `RecordFieldsApplied` token that must be passed to
80+
/// `stamp_record_updated_at`. Removing this call from `update_managed_agent`
81+
/// leaves `applied` undefined at the timestamp site — a compile error.
82+
///
83+
/// Called by `update_managed_agent` inside its locked transaction and by tests.
84+
/// Any step deleted from inside this function is directly caught by the
85+
/// corresponding test assertion.
86+
///
87+
/// Mutation proofs (see `agent_models_update_tests.rs`):
88+
/// - Deleting the `apply_effort_update` call leaves `effort_level` unchanged.
89+
/// - Deleting `ensure_effort_change_supported` inside `apply_effort_update`
90+
/// lets non-local writes pass `Ok(())` without mutating the column.
91+
/// - Deleting `apply_picker_effort_level` inside `apply_effort_update`
92+
/// leaves `effort_level == None` on a local-set request.
93+
pub(crate) fn apply_record_field_updates(
94+
record: &mut ManagedAgentRecord,
95+
env_vars: Option<&std::collections::BTreeMap<String, String>>,
96+
inherit_transition: bool,
97+
effort_level: Option<Option<String>>,
98+
) -> Result<RecordFieldsApplied, String> {
99+
// Order is load-bearing: env_vars before effort so a same-request
100+
// env_vars map cannot reintroduce a stale alias after the column write.
101+
crate::managed_agents::apply_env_vars_then_effort_transition(
102+
record,
103+
env_vars.cloned(),
104+
inherit_transition,
105+
);
106+
apply_effort_update(record, effort_level)?;
107+
Ok(RecordFieldsApplied(()))
108+
}
109+
110+
/// Stamp `record.updated_at` with the current ISO timestamp, consuming the
111+
/// `RecordFieldsApplied` proof token. Removing `apply_record_field_updates`
112+
/// from `update_managed_agent` leaves `applied` undefined here — a compile error.
113+
pub(crate) fn stamp_record_updated_at(
114+
record: &mut ManagedAgentRecord,
115+
_applied: RecordFieldsApplied,
116+
) {
117+
record.updated_at = crate::util::now_iso();
118+
}
119+
38120
/// Flush a retained managed-agent policy, preserving any earlier profile error.
39121
pub(crate) async fn flush_managed_agent_policy(
40122
app: &AppHandle,
@@ -115,15 +197,17 @@ pub async fn update_managed_agent(
115197
// Harness edit: the persona's runtime is authoritative, so an explicit
116198
// `agent_command_override` is persisted ONLY when the user picks a
117199
// command that diverges from the persona, and the empty/whitespace
118-
// "Inherit from persona" sentinel clears both the pin and the
119-
// materialized record runtime. A name-only edit
200+
// "Inherit from persona" sentinel clears the pin, the materialized
201+
// record runtime, AND the per-instance effort override (column here,
202+
// env aliases after `env_vars` is applied below). A name-only edit
120203
// (`agent_command == None`) leaves the pin intact. `harness_override`
121204
// threads the user's explicit intent — see `apply_agent_command_update`
122205
// and `update_time_agent_command_override` for the full resolution
123206
// rules.
207+
let mut inherit_transition = false;
124208
if let Some(agent_command) = input.agent_command {
125209
let personas = load_personas(&app).unwrap_or_default();
126-
crate::managed_agents::apply_agent_command_update(
210+
inherit_transition = crate::managed_agents::apply_agent_command_update(
127211
record,
128212
&personas,
129213
&agent_command,
@@ -136,9 +220,16 @@ pub async fn update_managed_agent(
136220
// mcp_command is intentionally not applied here — the effective MCP
137221
// command is always catalog-derived (known_acp_runtime at spawn time)
138222
// and the per-record field is never read by the runtime.
139-
if let Some(env_vars) = input.env_vars {
140-
crate::managed_agents::validate_user_env_keys(&env_vars)?;
141-
record.env_vars = env_vars;
223+
//
224+
// Apply the caller-supplied `env_vars` (validated first), then — only on
225+
// the pin→inherit transition — strip the record effort env aliases. The
226+
// order is load-bearing: stripping AFTER the env replacement is what
227+
// stops a same-request `env_vars` map from reintroducing a stale effort
228+
// alias while the instance inherits its harness. The column was already
229+
// cleared inside `apply_agent_command_update`. See
230+
// `apply_env_vars_then_effort_transition` for the pinned invariant.
231+
if let Some(ref env_vars) = input.env_vars {
232+
crate::managed_agents::validate_user_env_keys(env_vars)?;
142233
}
143234

144235
// Native provider/model fields are authoritative. Keep the typed marker
@@ -211,7 +302,23 @@ pub async fn update_managed_agent(
211302
record.respond_to_allowlist = prospective_allowlist;
212303
}
213304

214-
record.updated_at = now_iso();
305+
// Effort + env_vars: applied together inside `apply_record_field_updates` to
306+
// enforce the ordering invariant (env_vars before effort column write) and
307+
// provide a directly-testable production seam. Effort persists inside the
308+
// locked transaction so an access-policy restart above snapshots and
309+
// launches the new effort value. Present+Some(v)=set; Present+None=clear;
310+
// Absent=don't touch (the dialog sends it only when effortTouched).
311+
// The returned token is consumed by `stamp_record_updated_at`; removing
312+
// this call from `update_managed_agent` leaves `applied` undefined there
313+
// — a compile error (the sole outer-seam proof for this call site).
314+
let applied = apply_record_field_updates(
315+
record,
316+
input.env_vars.as_ref(),
317+
inherit_transition,
318+
input.effort_level,
319+
)?;
320+
321+
stamp_record_updated_at(record, applied);
215322

216323
save_managed_agents(&app, &records)?;
217324

@@ -365,5 +472,6 @@ pub async fn update_managed_agent(
365472
}
366473

367474
#[cfg(test)]
475+
#[allow(unused_must_use)]
368476
#[path = "agent_models_update_tests.rs"]
369477
mod tests;

0 commit comments

Comments
 (0)