|
| 1 | +//! Strip the legacy baked team-instructions suffix from stored prompts. |
| 2 | +//! |
| 3 | +//! Records written before the runtime team framing landed have their team |
| 4 | +//! instructions BAKED into `system_prompt` by the now-removed |
| 5 | +//! `compose_prompt()` in buzz-persona: |
| 6 | +//! |
| 7 | +//! ```text |
| 8 | +//! {persona_prompt}\n\n---\n# Team Instructions\n{instructions} |
| 9 | +//! ``` |
| 10 | +//! |
| 11 | +//! `with_team()` in `buzz-acp/src/pool.rs` now appends the LIVE |
| 12 | +//! `[Team Instructions]` section on top of that stored value, so an affected |
| 13 | +//! agent receives two team-instruction blocks per turn — the frozen copy first, |
| 14 | +//! the live one second — and the observer feed renders two Team Instructions |
| 15 | +//! cards. The frozen copy is not merely redundant: it carries whatever the team |
| 16 | +//! roster said the day it was written, so the agent is fed a stale roster ahead |
| 17 | +//! of the current one. |
| 18 | +//! |
| 19 | +//! The fix has to happen at rest. Suppressing the duplicate in the observer |
| 20 | +//! parser would hide the symptom while the agent kept receiving the stale bytes. |
| 21 | +//! |
| 22 | +//! Stripping a definition's prompt also changes its `persona_content_hash`, the |
| 23 | +//! drift basis behind the Agents-menu "out of date" badge, so the migration |
| 24 | +//! advances the pin of instances that were current before the strip (see |
| 25 | +//! [`repin_current_instances`]). |
| 26 | +
|
| 27 | +use std::collections::HashMap; |
| 28 | +use std::path::Path; |
| 29 | + |
| 30 | +use crate::managed_agents::{ |
| 31 | + persona_events::{persona_content_hash, persona_event_content}, |
| 32 | + ManagedAgentRecord, |
| 33 | +}; |
| 34 | + |
| 35 | +/// The exact producer boundary emitted by the removed `compose_prompt()`. |
| 36 | +/// Matched byte-for-byte: a bare `---`, a `# Team Instructions` heading at a |
| 37 | +/// different position, or a single preceding newline are author content, not a |
| 38 | +/// producer boundary, and are left alone. |
| 39 | +const TEAM_DELIMITER: &str = "\n\n---\n# Team Instructions\n"; |
| 40 | + |
| 41 | +/// Strip the baked team-instructions suffix from every stored `system_prompt`. |
| 42 | +/// |
| 43 | +/// Ordering (see `run_boot_migrations`): runs AFTER |
| 44 | +/// `fold_personas_into_agent_store` so definitions folded out of the legacy |
| 45 | +/// `personas.json` are cleaned in the same boot, and BEFORE |
| 46 | +/// `backfill_standalone_agents` so a manufactured definition never snapshots |
| 47 | +/// a suffix this migration is about to remove. |
| 48 | +pub fn strip_baked_team_instructions(app: &tauri::AppHandle) { |
| 49 | + let Ok(base_dir) = crate::managed_agents::managed_agents_base_dir(app) else { |
| 50 | + return; |
| 51 | + }; |
| 52 | + match strip_baked_team_instructions_in_dir(&base_dir) { |
| 53 | + Ok(0) => {} |
| 54 | + Ok(stripped) => eprintln!( |
| 55 | + "buzz-desktop: team-suffix-strip: removed the baked team-instructions suffix from \ |
| 56 | + {stripped} record(s)" |
| 57 | + ), |
| 58 | + Err(e) => eprintln!("buzz-desktop: team-suffix-strip: {e}"), |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/// Core logic, decoupled from the Tauri `AppHandle` for testing. |
| 63 | +/// |
| 64 | +/// `base_dir` is the managed-agents base directory (`<AppDataDir>/agents/`). |
| 65 | +/// Returns the number of records changed; `Ok(0)` means nothing to do and |
| 66 | +/// nothing was written, so a second boot is a clean no-op. |
| 67 | +pub(super) fn strip_baked_team_instructions_in_dir(base_dir: &Path) -> Result<usize, String> { |
| 68 | + let agents_path = base_dir.join("managed-agents.json"); |
| 69 | + if !agents_path.exists() { |
| 70 | + return Ok(0); |
| 71 | + } |
| 72 | + let content = std::fs::read_to_string(&agents_path) |
| 73 | + .map_err(|e| format!("failed to read managed-agents.json: {e}"))?; |
| 74 | + let mut all: Vec<ManagedAgentRecord> = serde_json::from_str(&content) |
| 75 | + .map_err(|e| format!("failed to parse managed-agents.json: {e}"))?; |
| 76 | + |
| 77 | + // Definition hashes BEFORE the strip: stripping a definition's |
| 78 | + // `system_prompt` changes its `persona_content_hash`, which is the drift |
| 79 | + // basis the Agents menu compares each linked instance's pinned |
| 80 | + // `persona_source_version` against. Captured here so instances that were |
| 81 | + // current before the strip can be re-pinned after it. |
| 82 | + let pre_strip_hashes = definition_hashes(&all); |
| 83 | + |
| 84 | + // Applies to every record: the definition records carry the suffix as |
| 85 | + // surely as the instances minted from them, and neither `team_id` nor |
| 86 | + // `persona_id` nor a key is evidence either way. |
| 87 | + let mut stripped = 0usize; |
| 88 | + for record in all.iter_mut() { |
| 89 | + let Some(prompt) = record.system_prompt.as_deref() else { |
| 90 | + continue; |
| 91 | + }; |
| 92 | + // Last occurrence only, mirroring the observer parser's own |
| 93 | + // `lastIndexOf` guard (`agentSessionTranscriptHelpers.ts`): a persona |
| 94 | + // body may legitimately quote a delimiter-shaped passage, and only the |
| 95 | + // final one is the boundary `compose_prompt()` appended. |
| 96 | + let Some(at) = prompt.rfind(TEAM_DELIMITER) else { |
| 97 | + continue; |
| 98 | + }; |
| 99 | + let head = &prompt[..at]; |
| 100 | + // An empty head means the record held nothing but the baked suffix. |
| 101 | + // Store `None` rather than `Some("")`, matching the empty-prompt |
| 102 | + // convention in `AgentDefinition::into_agent_record`, so no phantom |
| 103 | + // empty prompt is left behind. |
| 104 | + record.system_prompt = (!head.is_empty()).then(|| head.to_string()); |
| 105 | + stripped += 1; |
| 106 | + } |
| 107 | + |
| 108 | + if stripped == 0 { |
| 109 | + return Ok(0); |
| 110 | + } |
| 111 | + |
| 112 | + repin_current_instances(&mut all, &pre_strip_hashes); |
| 113 | + |
| 114 | + // Pre-migration backup, taken ONCE (same contract as the B5 backfill): a |
| 115 | + // re-run after a partial failure must not replace the pristine backup with |
| 116 | + // a half-migrated snapshot. Owner-only from the initial open, and sited next |
| 117 | + // to the resolved store — see `create_restricted_backup_once` and |
| 118 | + // `resolved_backup_path`. |
| 119 | + let bak_path = crate::util::resolved_backup_path( |
| 120 | + &agents_path, |
| 121 | + "managed-agents.json.pre-team-suffix-strip.bak", |
| 122 | + ); |
| 123 | + crate::util::create_restricted_backup_once(&bak_path, content.as_bytes()) |
| 124 | + .map_err(|e| format!("failed to write pre-strip backup: {e}"))?; |
| 125 | + |
| 126 | + let payload = serde_json::to_vec_pretty(&all) |
| 127 | + .map_err(|e| format!("failed to serialize managed-agents.json: {e}"))?; |
| 128 | + crate::managed_agents::atomic_write_json_restricted(&agents_path, &payload)?; |
| 129 | + Ok(stripped) |
| 130 | +} |
| 131 | + |
| 132 | +/// `slug → persona_content_hash` for every definition record, computed through |
| 133 | +/// the same projection the drift indicator uses (`persona_drift_state` in |
| 134 | +/// `managed_agents/runtime.rs`). |
| 135 | +fn definition_hashes(records: &[ManagedAgentRecord]) -> HashMap<String, String> { |
| 136 | + records |
| 137 | + .iter() |
| 138 | + .filter(|record| record.pubkey.is_empty()) |
| 139 | + .filter_map(|record| { |
| 140 | + let definition = record.to_definition_view()?; |
| 141 | + let hash = persona_content_hash(&persona_event_content(&definition)); |
| 142 | + Some((definition.id, hash)) |
| 143 | + }) |
| 144 | + .collect() |
| 145 | +} |
| 146 | + |
| 147 | +/// Advance the drift pin of instances that were current before the strip. |
| 148 | +/// |
| 149 | +/// Stripping a definition's prompt changes its `persona_content_hash`, so every |
| 150 | +/// linked instance would otherwise light up "out of date" in the Agents menu |
| 151 | +/// for a change the user never made — a badge that only clears on the next |
| 152 | +/// start, when `apply_persona_snapshot` re-pins. Same conditional as |
| 153 | +/// `refresh_builtin_agent_avatars`: move the pin only when it still equals the |
| 154 | +/// definition's PRE-strip hash. An instance that had genuinely drifted keeps |
| 155 | +/// its stale pin, and its badge. |
| 156 | +fn repin_current_instances( |
| 157 | + records: &mut [ManagedAgentRecord], |
| 158 | + pre_strip_hashes: &HashMap<String, String>, |
| 159 | +) { |
| 160 | + let post_strip_hashes = definition_hashes(records); |
| 161 | + for record in records.iter_mut() { |
| 162 | + if record.pubkey.is_empty() { |
| 163 | + continue; |
| 164 | + } |
| 165 | + let Some(persona_id) = record.persona_id.as_deref() else { |
| 166 | + continue; |
| 167 | + }; |
| 168 | + let (Some(old), Some(new)) = ( |
| 169 | + pre_strip_hashes.get(persona_id), |
| 170 | + post_strip_hashes.get(persona_id), |
| 171 | + ) else { |
| 172 | + continue; |
| 173 | + }; |
| 174 | + if old != new && record.persona_source_version.as_deref() == Some(old.as_str()) { |
| 175 | + record.persona_source_version = Some(new.clone()); |
| 176 | + } |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +#[cfg(test)] |
| 181 | +#[path = "team_suffix_tests.rs"] |
| 182 | +mod tests; |
0 commit comments