Skip to content

Commit 4d58dea

Browse files
tlongwell-blocknpub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d
authored
Archive managed agents when deleted (#2135)
Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@sprout-oss.stage.blox.sqprod.co>
1 parent a4d82ec commit 4d58dea

9 files changed

Lines changed: 274 additions & 7 deletions

File tree

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

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,95 @@ pub(super) fn tombstone_managed_agent_pending(
155155
}
156156
}
157157

158+
/// Build and sign the NIP-IA `kind:9035` archive request enqueued when an
159+
/// agent is deleted. Pure given the keys — unit-testable without an
160+
/// `AppHandle`. Reuses the same wire builder as the GUI's Archive action
161+
/// (`events::build_archive_identity_request`); the machine-readable reason is
162+
/// `retired` (NIP-IA suggested code for a deliberately decommissioned key).
163+
///
164+
/// The owner auth tag is minted locally from the same keys used to sign the
165+
/// request, avoiding a network fetch while the managed-agent store lock is
166+
/// held. The relay still independently verifies it against the agent's live
167+
/// kind:0.
168+
pub(super) fn build_agent_archive_request(
169+
keys: &nostr::Keys,
170+
agent_pubkey: &str,
171+
) -> Result<nostr::Event, String> {
172+
let auth_tag = if keys
173+
.public_key()
174+
.to_hex()
175+
.eq_ignore_ascii_case(agent_pubkey)
176+
{
177+
None
178+
} else {
179+
let agent = nostr::PublicKey::from_hex(agent_pubkey)
180+
.map_err(|e| format!("invalid agent pubkey: {e}"))?;
181+
let tag_json = buzz_sdk_pkg::nip_oa::compute_auth_tag(keys, &agent, "")
182+
.map_err(|e| format!("failed to build owner auth tag: {e}"))?;
183+
let parts: Vec<String> = serde_json::from_str(&tag_json)
184+
.map_err(|e| format!("failed to parse owner auth tag: {e}"))?;
185+
Some(
186+
<[String; 4]>::try_from(parts)
187+
.map_err(|_| "owner auth tag must have four elements".to_string())?,
188+
)
189+
};
190+
crate::events::build_archive_identity_request(
191+
agent_pubkey,
192+
"",
193+
Some("retired"),
194+
None,
195+
auth_tag.as_ref(),
196+
)?
197+
.sign_with_keys(keys)
198+
.map_err(|e| format!("failed to sign archive request: {e}"))
199+
}
200+
201+
/// Enqueue a NIP-IA `kind:9035` archive request for a deleted agent, retained
202+
/// next to its kind:5 tombstone with `pending_sync = 1`.
203+
///
204+
/// The tombstone removes the agent's 30177 record cross-device, but the
205+
/// agent's `kind:0` and channel membership keep populating member pickers and
206+
/// autocomplete on the relay until the identity is archived. Retaining the
207+
/// request here gives archival the same offline durability as the tombstone;
208+
/// the flush loop is the sole publisher and re-signs the request with a fresh
209+
/// `created_at` at publish time, because the relay enforces a ±120s freshness
210+
/// window on 9035s.
211+
///
212+
/// Same contract as `tombstone_managed_agent_pending`: called inside the
213+
/// `managed_agents_store_lock`-held delete body, never across an `.await`,
214+
/// best-effort — a failure is logged and swallowed so it never blocks the
215+
/// disk-authoritative delete.
216+
pub(super) fn archive_managed_agent_pending(app: &AppHandle, state: &AppState, agent_pubkey: &str) {
217+
use crate::managed_agents::retention::{open_retention_db, retain_event, RetainedEvent};
218+
use buzz_core_pkg::kind::KIND_IA_ARCHIVE_REQUEST;
219+
use nostr::JsonUtil;
220+
221+
let result = (|| -> Result<(), String> {
222+
let (owner_pubkey, event) = {
223+
let keys = state.signing_keys()?;
224+
let owner_pubkey = keys.public_key().to_hex();
225+
let event = build_agent_archive_request(&keys, agent_pubkey)?;
226+
(owner_pubkey, event)
227+
};
228+
let conn = open_retention_db(&managed_agents_base_dir(app)?.join("retention.db"))?;
229+
retain_event(
230+
&conn,
231+
&RetainedEvent {
232+
kind: KIND_IA_ARCHIVE_REQUEST,
233+
pubkey: owner_pubkey,
234+
d_tag: agent_pubkey.to_string(),
235+
content: event.content.to_string(),
236+
created_at: event.created_at.as_secs() as i64,
237+
raw_event: event.as_json(),
238+
pending_sync: true,
239+
},
240+
)
241+
})();
242+
if let Err(e) = result {
243+
eprintln!("buzz-desktop: agent-archive: {e}");
244+
}
245+
}
246+
158247
fn normalize_relay_mesh(
159248
config: Option<&RelayMeshConfig>,
160249
backend: &BackendKind,
@@ -1134,6 +1223,10 @@ pub async fn delete_managed_agent(
11341223
// deployment's relay record. Inside the lock, before the block closes
11351224
// (no .await here). Every agent published, so every delete tombstones.
11361225
tombstone_managed_agent_pending(&app, &state, &pubkey);
1226+
// NIP-IA: archive the deleted agent's identity on the relay so it
1227+
// stops appearing in member pickers and autocomplete. Same
1228+
// best-effort, inside-the-lock contract as the tombstone above.
1229+
archive_managed_agent_pending(&app, &state, &pubkey);
11371230
}
11381231
try_regenerate_nest(&app);
11391232
Ok(())

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,46 @@ fn persona_record(id: &str, model: Option<&str>, provider: Option<&str>) -> Agen
8686
}
8787
}
8888

89+
/// Auto-archive uses the same NIP-IA wire builder as the explicit GUI action,
90+
/// attaches owner consent, and marks a deliberate delete as `retired`.
91+
#[test]
92+
fn build_agent_archive_request_attaches_owner_auth_and_retired_reason() {
93+
use nostr::JsonUtil;
94+
95+
let owner = nostr::Keys::generate();
96+
let agent = nostr::Keys::generate();
97+
let event = build_agent_archive_request(&owner, &agent.public_key().to_hex())
98+
.expect("build archive request");
99+
let json: serde_json::Value = serde_json::from_str(&event.as_json()).unwrap();
100+
let tags = json["tags"].as_array().unwrap();
101+
102+
assert_eq!(event.kind.as_u16(), 9035);
103+
assert_eq!(event.pubkey, owner.public_key());
104+
assert!(event.verify_id());
105+
assert!(event.verify_signature());
106+
assert!(tags.iter().any(|tag| {
107+
tag.as_array().is_some_and(|parts| {
108+
parts.first().and_then(serde_json::Value::as_str) == Some("p")
109+
&& parts.get(1).and_then(serde_json::Value::as_str)
110+
== Some(agent.public_key().to_hex().as_str())
111+
})
112+
}));
113+
assert!(tags.iter().any(|tag| {
114+
tag.as_array().is_some_and(|parts| {
115+
parts.first().and_then(serde_json::Value::as_str) == Some("reason")
116+
&& parts.get(1).and_then(serde_json::Value::as_str) == Some("retired")
117+
})
118+
}));
119+
assert!(tags.iter().any(|tag| {
120+
tag.as_array().is_some_and(|parts| {
121+
parts.first().and_then(serde_json::Value::as_str) == Some("auth")
122+
&& parts.get(1).and_then(serde_json::Value::as_str)
123+
== Some(owner.public_key().to_hex().as_str())
124+
&& parts.len() == 4
125+
})
126+
}));
127+
}
128+
89129
/// Deploy-path regression for Fix 1 of Thufir pass-2: a persona-linked
90130
/// provider agent with a stale record snapshot must use the live persona
91131
/// model/provider in the deploy payload, not the stale record values.

‎desktop/src-tauri/src/commands/personas/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,7 @@ pub async fn delete_persona(id: String, app: AppHandle) -> Result<(), String> {
495495
// Remove nsec from keyring after the record is gone.
496496
delete_agent_key(pk);
497497
super::agents::tombstone_managed_agent_pending(&app, &state, pk);
498+
super::agents::archive_managed_agent_pending(&app, &state, pk);
498499
}
499500
tombstone_persona_pending(&app, &state, &d_tag);
500501

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,20 @@ pub async fn flush_pending_events(
256256
let event = nostr::Event::from_json(&current.raw_event)
257257
.map_err(|e| format!("failed to parse retained event '{}': {e}", current.d_tag))?;
258258

259+
// NIP-IA requests are freshness-checked by the relay (±120s on
260+
// `created_at`), so a request retained while the relay was
261+
// unreachable would be permanently stale. Re-sign with a fresh
262+
// timestamp at publish time; kind, tags, and content are preserved,
263+
// and `mark_synced` below still compares against the retained row's
264+
// original `created_at`/`content`, which are untouched.
265+
let is_archive_request =
266+
buzz_core_pkg::kind::is_identity_archive_request_kind(current.kind);
267+
let event = if is_archive_request {
268+
resign_with_fresh_timestamp(&event, state)?
269+
} else {
270+
event
271+
};
272+
259273
if crate::relay::submit_signed_event(&event, state)
260274
.await
261275
.is_err()
@@ -281,6 +295,29 @@ pub async fn flush_pending_events(
281295
Ok(flushed)
282296
}
283297

298+
/// Re-sign a retained event with the current owner keys and a fresh
299+
/// `created_at`, preserving kind, tags, and content.
300+
///
301+
/// Used for relay-freshness-checked kinds (NIP-IA 9035/9036) that would
302+
/// otherwise go permanently stale sitting in the retention store while the
303+
/// relay is unreachable. `.allow_self_tagging()` mirrors
304+
/// `events::build_archive_identity_request` — nostr strips `p` tags matching
305+
/// the signer by default, which would corrupt a self-targeted request.
306+
///
307+
/// Synchronous; the `state.keys` guard is dropped on return, so callers may
308+
/// `.await` afterwards.
309+
fn resign_with_fresh_timestamp(
310+
event: &nostr::Event,
311+
state: &AppState,
312+
) -> Result<nostr::Event, String> {
313+
let keys = state.signing_keys()?;
314+
nostr::EventBuilder::new(event.kind, event.content.clone())
315+
.tags(event.tags.iter().cloned())
316+
.allow_self_tagging()
317+
.sign_with_keys(&keys)
318+
.map_err(|e| format!("failed to re-sign retained event: {e}"))
319+
}
320+
284321
/// SHA-256 (lowercase hex) of a persona's canonical content JSON.
285322
///
286323
/// The drift indicator compares this digest, not event timestamps, to decide

‎desktop/src-tauri/src/managed_agents/persona_events/tests.rs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,37 @@ mod flush_barrier {
729729
.expect("retain test event");
730730
}
731731

732+
#[test]
733+
fn archive_request_resign_refreshes_timestamp_and_preserves_payload() {
734+
use nostr::JsonUtil;
735+
736+
let keys = nostr::Keys::generate();
737+
let target = nostr::Keys::generate().public_key().to_hex();
738+
let stale = crate::events::build_archive_identity_request(
739+
&target,
740+
"agent deleted",
741+
Some("retired"),
742+
None,
743+
None,
744+
)
745+
.unwrap()
746+
.custom_created_at(nostr::Timestamp::from(1))
747+
.sign_with_keys(&keys)
748+
.unwrap();
749+
let state = build_app_state();
750+
*state.keys.lock().unwrap() = keys;
751+
752+
let fresh = resign_with_fresh_timestamp(&stale, &state).unwrap();
753+
754+
assert!(fresh.created_at.as_secs() > stale.created_at.as_secs());
755+
assert_eq!(fresh.kind, stale.kind);
756+
assert_eq!(fresh.content, stale.content);
757+
assert_eq!(fresh.tags, stale.tags);
758+
assert!(fresh.verify_id());
759+
assert!(fresh.verify_signature());
760+
assert_ne!(fresh.as_json(), stale.as_json());
761+
}
762+
732763
/// The mid-sweep barrier: a tombstone the relay rejects must defer its
733764
/// own replacement to the next sweep (still pending, not counted as
734765
/// flushed) while unrelated rows in the same sweep publish normally.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import { personaDeleteDescription } from "./PersonaDeleteDialog.tsx";
5+
6+
// Regression guard for the persona-cascade consent copy: deleting a persona
7+
// with instances also archives each instance's identity on the relay
8+
// (NIP-IA 9035), a durable externally visible side effect. The confirmation
9+
// dialog must disclose it before the destructive confirm, exactly like the
10+
// direct agent-delete dialog does.
11+
12+
const persona = { displayName: "Scout" };
13+
14+
test("cascade delete discloses relay archival (plural)", () => {
15+
const copy = personaDeleteDescription(persona, 3);
16+
assert.match(copy, /deletes 3 agent instances/);
17+
assert.match(copy, /archives their identities on the relay/);
18+
});
19+
20+
test("cascade delete discloses relay archival (singular)", () => {
21+
const copy = personaDeleteDescription(persona, 1);
22+
assert.match(copy, /deletes 1 agent instance /);
23+
assert.match(copy, /archives its identity on the relay/);
24+
});
25+
26+
test("no instances → no archival claim (nothing is archived)", () => {
27+
const copy = personaDeleteDescription(persona, 0);
28+
assert.equal(copy, "Delete Scout.");
29+
assert.doesNotMatch(copy, /archiv/i);
30+
});
31+
32+
test("null persona keeps the generic fallback", () => {
33+
assert.equal(personaDeleteDescription(null, 2), "Delete this agent.");
34+
});

‎desktop/src/features/agents/ui/PersonaDeleteDialog.tsx‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,30 @@ type PersonaDeleteDialogProps = {
2020
onOpenChange: (open: boolean) => void;
2121
};
2222

23+
/**
24+
* Confirmation copy for deleting a persona. Pure so the cascade archival
25+
* disclosure stays unit-testable without a renderer: whenever instances are
26+
* cascade-deleted, each one's identity is also archived on the relay
27+
* (NIP-IA), and that durable side effect must be disclosed before the
28+
* destructive confirm — matching the direct agent-delete dialog.
29+
*/
30+
export function personaDeleteDescription(
31+
persona: AgentPersona | null,
32+
instanceCount: number,
33+
): string {
34+
if (!persona) {
35+
return "Delete this agent.";
36+
}
37+
if (instanceCount === 0) {
38+
return `Delete ${persona.displayName}.`;
39+
}
40+
const cascade =
41+
instanceCount === 1
42+
? "Also deletes 1 agent instance and archives its identity on the relay, so it no longer appears in member lists or mention suggestions."
43+
: `Also deletes ${instanceCount} agent instances and archives their identities on the relay, so they no longer appear in member lists or mention suggestions.`;
44+
return `Delete ${persona.displayName}. ${cascade}`;
45+
}
46+
2347
export function PersonaDeleteDialog({
2448
open,
2549
persona,
@@ -33,9 +57,7 @@ export function PersonaDeleteDialog({
3357
<AlertDialogHeader>
3458
<AlertDialogTitle>Delete agent?</AlertDialogTitle>
3559
<AlertDialogDescription>
36-
{persona
37-
? `Delete ${persona.displayName}.${instanceCount > 0 ? ` Also deletes ${instanceCount} agent instance${instanceCount === 1 ? "" : "s"}.` : ""}`
38-
: "Delete this agent."}
60+
{personaDeleteDescription(persona, instanceCount)}
3961
</AlertDialogDescription>
4062
</AlertDialogHeader>
4163
<AlertDialogFooter>

‎desktop/src/features/profile/ui/UserProfileAgentActions.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,10 @@ function AgentDeleteConfirmDialog({
318318
<ul className="list-disc space-y-1.5 pl-5 text-sm text-muted-foreground">
319319
<li>Removes the local management record and saved agent key</li>
320320
<li>Removes the agent from every channel it belongs to</li>
321+
<li>
322+
Archives the agent&apos;s identity on the relay so it no longer
323+
appears in member lists or mention suggestions
324+
</li>
321325
<li>
322326
{isProviderAgent
323327
? "Requests remote deletion; if it is online, Buzz first sends a shutdown command when possible. If the deployment cannot be reached through a channel, the remote process may keep running without local management."

‎desktop/tests/e2e/agent-lifecycle-feedback.spec.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,11 @@ test.describe("agent lifecycle feedback screenshots", () => {
118118
const dialog = page.getByRole("alertdialog");
119119
await expect(dialog).toBeVisible({ timeout: 5_000 });
120120

121-
// Core assertion: the cascade copy shows the correct instance count (plural).
122-
await expect(dialog).toContainText("Also deletes 2 agent instances.");
121+
// Core assertion: the cascade copy shows the correct instance count
122+
// (plural) and discloses the relay-side archival (PR #2135).
123+
await expect(dialog).toContainText(
124+
"Also deletes 2 agent instances and archives their identities on the relay",
125+
);
123126

124127
await waitForAnimations(page);
125128

@@ -243,8 +246,10 @@ test.describe("agent lifecycle feedback screenshots", () => {
243246
const dialog = page.getByRole("alertdialog");
244247
await expect(dialog).toBeVisible({ timeout: 5_000 });
245248

246-
// Singular copy: "Also deletes 1 agent instance." (not "instances").
247-
await expect(dialog).toContainText("Also deletes 1 agent instance.");
249+
// Singular copy ("instance", "its identity") plus the archival disclosure.
250+
await expect(dialog).toContainText(
251+
"Also deletes 1 agent instance and archives its identity on the relay",
252+
);
248253

249254
await waitForAnimations(page);
250255
await dialog.screenshot({

0 commit comments

Comments
 (0)