Skip to content

Commit 0b3ff0c

Browse files
SeanGearinSean Gearinwpfleger96
authored
fix(desktop): republish agent identity records when a persona rename propagates (#2607)
## Problem Part of #2423 (renaming personal agents desynchronises identity). Renaming an agent definition (persona) propagates the new display name to its linked agent instances (`propagate_persona_name_rename` in `desktop/src-tauri/src/commands/personas/mod.rs`) and saves `managed-agents.json` — but, unlike the instance-rename path (`update_managed_agent`), it never re-retains the renamed instances' kind:30177 managed-agent identity records. `record.name` is part of the published identity projection (`agent_event_content`), so after a persona rename: - `managed-agents.json` says the NEW name, - the retained kind:30177 row (retention.db → relay flush loop) still carries the OLD name, with the OLD `created_at`. The stale identity record stays live on the relay until the next app launch, when the boot-time reconcile (`reconcile_agents_in_dir`) finally notices the content diff and republishes. Until that restart, any surface that resolves agents from kind:30177 records (second desktop of the same owner, CLI, other NIP-AP clients) sees the OLD name bound to the agent pubkey while the kind:0 profile already shows the NEW one — the name→identity binding desync described in #2423, and consistent with the report's observation that repairing state required "a separate restart". ## Fix - Extract the per-record retain body of the boot reconcile into `managed_agents::reconcile::retain_agent_record(conn, keys, record) -> Result<bool, String>` — one shared content-diff + monotonic-`created_at`-bump engine (returns whether a row was rewritten). `reconcile_agents_in_dir` now calls it per record (behavior unchanged; existing reconcile tests still pass). - `commands::agents::retain_managed_agent_pending` delegates to the shared engine instead of carrying a duplicate implementation (same semantics: projection-equality no-op guard, monotonic bump, `pending_sync = 1`). - `update_persona` (Phase 1, still under the store lock, after `save_managed_agents`): call `retain_managed_agent_pending` for every record the rename propagated to — mirroring `update_managed_agent`. Avatar-only edits are deliberately excluded (the avatar is not part of the kind:30177 projection; retaining would be a guaranteed no-op). No new events, kinds, or APIs — this uses the existing signed-event retention and flush pipeline, per CONTRIBUTING's guidance to prefer a signed Nostr event and the existing ingest path over endpoint-specific JSON APIs. ## Out of scope (deliberately) - Rename → runtime restart is #1823, fixed by open PR #2507 (spawn_hash). - Surfacing kind:0 relay profile-sync failures on rename is PR #2302/#2279 territory (and largely superseded by the merged rollback in #2258). - Mention-picker UX (owner/status disambiguation) and channel-membership repair for stale identities: TS-side, noted in #2423, not touched here. ## Test evidence Two new unit tests in `desktop/src-tauri/src/managed_agents/reconcile/tests.rs` (same harness as the existing reconcile tests — tempdir + retention.db + fresh keys, no AppHandle): - `rename_re_retains_identity_record_with_new_name` — retain "Fizz", confirm flush, rename to "Spark", re-retain: row keeps the pubkey coordinate, carries the new name only, is `pending_sync`, and its `created_at` is strictly past the retained head (replaceable-event acceptance). - `retain_agent_record_is_noop_when_unchanged` — an unchanged projection does not rewrite the row and produces zero `pending_sync` churn. Ran scoped per CONTRIBUTING build discipline (from `desktop/src-tauri`): ``` cargo fmt -p buzz-desktop # applied, clean cargo clippy -p buzz-desktop --lib --tests -- -D warnings # exit 0, no warnings cargo test -p buzz-desktop --lib # full lib suite ``` Full `buzz-desktop` lib suite: **1562 passed, 0 failed, 13 ignored** — including all 12 `managed_agents::reconcile` tests (10 pre-existing, all unmodified in behavior, plus the 2 new regression tests above). ## Links - Issue: #2423 - Adjacent (no overlap): PR #2507 (rename-restart, #1823), PRs #2302/#2279 (kind:0 sync-failure surfacing), merged #2258 (instance-rename rollback). --------- Signed-off-by: Sean Gearin <[email protected]> Co-authored-by: Sean Gearin <[email protected]> Co-authored-by: Will Pfleger <[email protected]>
1 parent 995afd7 commit 0b3ff0c

4 files changed

Lines changed: 170 additions & 80 deletions

File tree

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

Lines changed: 6 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -45,52 +45,15 @@ pub(super) fn retain_managed_agent_pending(
4545
state: &AppState,
4646
record: &ManagedAgentRecord,
4747
) {
48-
use crate::managed_agents::{
49-
agent_events::{agent_event_content, build_agent_event},
50-
persona_events::monotonic_created_at,
51-
retention::{get_retained_event, open_retention_db, retain_event, RetainedEvent},
52-
};
53-
use buzz_core_pkg::kind::KIND_MANAGED_AGENT;
54-
use nostr::JsonUtil;
48+
use crate::managed_agents::{reconcile::retain_agent_record, retention::open_retention_db};
5549

5650
let result = (|| -> Result<(), String> {
5751
let conn = open_retention_db(&managed_agents_base_dir(app)?.join("retention.db"))?;
58-
// The published content is the opt-IN projection JSON, independent of
59-
// signing and created_at. Compute it once to drive the no-republish
60-
// guard without signing twice.
61-
let content = serde_json::to_string(&agent_event_content(record))
62-
.map_err(|e| format!("failed to serialize managed-agent content: {e}"))?;
63-
let (owner_pubkey, event) = {
64-
let keys = state.signing_keys()?;
65-
let owner_pubkey = keys.public_key().to_hex();
66-
let existing =
67-
get_retained_event(&conn, KIND_MANAGED_AGENT, &owner_pubkey, &record.pubkey)?;
68-
// Skip re-publishing when the projection is unchanged: a start/stop
69-
// or any edit that touched only excluded runtime/local fields
70-
// produces an identical projection, so it is a no-op — operational
71-
// churn never re-enqueues a publish.
72-
if existing.as_ref().is_some_and(|row| row.content == content) {
73-
return Ok(());
74-
}
75-
// Monotonic created_at: bump past the retained head (NIP-AP step 3).
76-
let event = build_agent_event(record)?
77-
.custom_created_at(monotonic_created_at(existing.map(|row| row.created_at)))
78-
.sign_with_keys(&keys)
79-
.map_err(|e| format!("failed to sign managed-agent event: {e}"))?;
80-
(owner_pubkey, event)
81-
};
82-
retain_event(
83-
&conn,
84-
&RetainedEvent {
85-
kind: KIND_MANAGED_AGENT,
86-
pubkey: owner_pubkey,
87-
d_tag: record.pubkey.clone(),
88-
content: event.content.to_string(),
89-
created_at: event.created_at.as_secs() as i64,
90-
raw_event: event.as_json(),
91-
pending_sync: true,
92-
},
93-
)
52+
let keys = state.signing_keys()?;
53+
// Shared engine with the boot-time reconcile: projection content diff
54+
// (no republish for runtime-only churn) + monotonic created_at bump
55+
// past the retained head (NIP-AP step 3).
56+
retain_agent_record(&conn, &keys, record).map(|_| ())
9457
})();
9558
if let Err(e) = result {
9659
eprintln!("buzz-desktop: agent-retain: {e}");

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,15 @@ pub async fn update_persona(
272272

273273
if agents_modified {
274274
save_managed_agents(&app, &records)?;
275+
// Keep retained kind:30177 identity records in lockstep with
276+
// the rename (#2423): `record.name` is part of the published
277+
// identity projection, so skipping this strands the relay on
278+
// the stale name→pubkey binding until the next boot reconcile.
279+
// Avatar-only edits are excluded — the avatar is not in the
280+
// projection, so retaining would be a guaranteed no-op.
281+
for record in records.iter().filter(|r| renamed.contains(&r.pubkey)) {
282+
super::agents::retain_managed_agent_pending(&app, &state, record);
283+
}
275284
}
276285

277286
params

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

Lines changed: 55 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,6 @@ pub(crate) fn reconcile_agents_in_dir(base_dir: &Path, keys: &nostr::Keys) -> Re
7979
return Ok(0);
8080
}
8181

82-
let owner_pubkey = keys.public_key().to_hex();
83-
8482
let db_path = base_dir.join("retention.db");
8583
let conn =
8684
open_retention_db(&db_path).map_err(|e| format!("failed to open retention db: {e}"))?;
@@ -94,46 +92,66 @@ pub(crate) fn reconcile_agents_in_dir(base_dir: &Path, keys: &nostr::Keys) -> Re
9492
continue;
9593
}
9694

97-
let existing =
98-
get_retained_event(&conn, KIND_MANAGED_AGENT, &owner_pubkey, &record.pubkey)?;
99-
100-
// Build the event first and compare ITS content, so the comparison and
101-
// the retained row share one serialization of the projection (mirrors
102-
// `migrate_personas_in_dir`). Serializing the projection independently
103-
// here would silently diverge if `build_agent_event` ever changed how
104-
// it serializes — republishing every agent every boot. Content is
105-
// timestamp-independent, so the monotonic bump below never forces a
106-
// spurious republish; an unchanged agent is still a true no-op.
107-
let event = build_agent_event(record)?
108-
.custom_created_at(monotonic_created_at(
109-
existing.as_ref().map(|row| row.created_at),
110-
))
111-
.sign_with_keys(keys)
112-
.map_err(|e| format!("failed to sign event for '{}': {e}", record.name))?;
113-
114-
let content = event.content.clone();
115-
if existing.as_ref().is_some_and(|row| row.content == content) {
116-
continue;
95+
if retain_agent_record(&conn, keys, record)? {
96+
reconciled += 1;
11797
}
118-
119-
retain_event(
120-
&conn,
121-
&RetainedEvent {
122-
kind: KIND_MANAGED_AGENT,
123-
pubkey: owner_pubkey.clone(),
124-
d_tag: record.pubkey.clone(),
125-
content,
126-
created_at: event.created_at.as_secs() as i64,
127-
raw_event: event.as_json(),
128-
pending_sync: true,
129-
},
130-
)
131-
.map_err(|e| format!("failed to retain '{}': {e}", record.name))?;
132-
reconciled += 1;
13398
}
13499

135100
Ok(reconciled)
136101
}
137102

103+
/// Retain `record`'s kind:30177 identity record, marking it `pending_sync`
104+
/// for the flush loop, when its projection differs from the retained head.
105+
/// Returns `Ok(true)` when a row was (re)written and `Ok(false)` when the
106+
/// retained content already matches (a true no-op — no `pending_sync` churn).
107+
///
108+
/// This is the single content-diff + monotonic-bump engine shared by the
109+
/// boot-time reconcile above and the interactive edit paths
110+
/// (`retain_managed_agent_pending`, persona-rename propagation). Every
111+
/// mutation of an agent's published identity must go through it so the
112+
/// retained record can never silently drift from `managed-agents.json`.
113+
pub(crate) fn retain_agent_record(
114+
conn: &rusqlite::Connection,
115+
keys: &nostr::Keys,
116+
record: &ManagedAgentRecord,
117+
) -> Result<bool, String> {
118+
let owner_pubkey = keys.public_key().to_hex();
119+
let existing = get_retained_event(conn, KIND_MANAGED_AGENT, &owner_pubkey, &record.pubkey)?;
120+
121+
// Build the event first and compare ITS content, so the comparison and
122+
// the retained row share one serialization of the projection (mirrors
123+
// `migrate_personas_in_dir`). Serializing the projection independently
124+
// here would silently diverge if `build_agent_event` ever changed how
125+
// it serializes — republishing every agent every boot. Content is
126+
// timestamp-independent, so the monotonic bump below never forces a
127+
// spurious republish; an unchanged agent is still a true no-op.
128+
let event = build_agent_event(record)?
129+
.custom_created_at(monotonic_created_at(
130+
existing.as_ref().map(|row| row.created_at),
131+
))
132+
.sign_with_keys(keys)
133+
.map_err(|e| format!("failed to sign event for '{}': {e}", record.name))?;
134+
135+
let content = event.content.clone();
136+
if existing.as_ref().is_some_and(|row| row.content == content) {
137+
return Ok(false);
138+
}
139+
140+
retain_event(
141+
conn,
142+
&RetainedEvent {
143+
kind: KIND_MANAGED_AGENT,
144+
pubkey: owner_pubkey,
145+
d_tag: record.pubkey.clone(),
146+
content,
147+
created_at: event.created_at.as_secs() as i64,
148+
raw_event: event.as_json(),
149+
pending_sync: true,
150+
},
151+
)
152+
.map_err(|e| format!("failed to retain '{}': {e}", record.name))?;
153+
Ok(true)
154+
}
155+
138156
#[cfg(test)]
139157
mod tests;

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

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,3 +300,103 @@ fn slimming_republish_wave_is_one_time() {
300300
"second boot must be a no-op (idempotence)"
301301
);
302302
}
303+
304+
// ── retain_agent_record (interactive-edit engine) ────────────────────────────
305+
//
306+
// #2423: renaming an agent must re-retain its kind:30177 identity record
307+
// IMMEDIATELY, not at the next boot-time reconcile. These tests pin the shared
308+
// engine both the boot reconcile and the interactive edit paths
309+
// (`retain_managed_agent_pending`, persona-rename propagation) run on.
310+
311+
/// A rename re-retains the identity record under the SAME coordinate (the
312+
/// agent pubkey) with the new name, queued for publish, with a created_at
313+
/// strictly past the retained head so the relay's replaceable-event rule
314+
/// accepts it. Without this, the relay keeps the old name→pubkey binding
315+
/// until the next restart — the identity desync in #2423.
316+
#[test]
317+
fn rename_re_retains_identity_record_with_new_name() {
318+
let dir = TempDir::new().unwrap();
319+
let keys = nostr::Keys::generate();
320+
let conn = open_retention_db(&dir.path().join("retention.db")).unwrap();
321+
let owner = keys.public_key().to_hex();
322+
let pubkey = "9".repeat(64);
323+
let mut record = sample_record(&pubkey, "Fizz");
324+
325+
assert!(retain_agent_record(&conn, &keys, &record).unwrap());
326+
let first = get_retained_event(&conn, KIND_MANAGED_AGENT, &owner, &pubkey)
327+
.unwrap()
328+
.unwrap();
329+
// Simulate the flush loop confirming the initial publish.
330+
mark_synced(
331+
&conn,
332+
first.kind,
333+
&first.pubkey,
334+
&first.d_tag,
335+
first.created_at,
336+
&first.content,
337+
)
338+
.unwrap();
339+
340+
record.name = "Spark".to_string();
341+
assert!(
342+
retain_agent_record(&conn, &keys, &record).unwrap(),
343+
"a renamed record must re-retain its identity record"
344+
);
345+
346+
let row = get_retained_event(&conn, KIND_MANAGED_AGENT, &owner, &pubkey)
347+
.unwrap()
348+
.unwrap();
349+
assert_eq!(row.d_tag, pubkey, "coordinate stays keyed by agent pubkey");
350+
assert!(
351+
row.content.contains("Spark"),
352+
"retained identity record must carry the new name"
353+
);
354+
assert!(
355+
!row.content.contains("Fizz"),
356+
"the stale name must not survive the rename"
357+
);
358+
assert!(row.pending_sync, "a rename must queue a republish");
359+
assert!(
360+
row.created_at > first.created_at,
361+
"created_at must bump past the retained head (replaceable-event rule)"
362+
);
363+
}
364+
365+
/// An unchanged record is a true no-op: no rewrite, no `pending_sync` churn.
366+
/// This is what lets every edit path call the engine unconditionally.
367+
#[test]
368+
fn retain_agent_record_is_noop_when_unchanged() {
369+
let dir = TempDir::new().unwrap();
370+
let keys = nostr::Keys::generate();
371+
let conn = open_retention_db(&dir.path().join("retention.db")).unwrap();
372+
let pubkey = "8".repeat(64);
373+
let record = sample_record(&pubkey, "steady-agent");
374+
375+
assert!(retain_agent_record(&conn, &keys, &record).unwrap());
376+
let row = get_retained_event(
377+
&conn,
378+
KIND_MANAGED_AGENT,
379+
&keys.public_key().to_hex(),
380+
&pubkey,
381+
)
382+
.unwrap()
383+
.unwrap();
384+
mark_synced(
385+
&conn,
386+
row.kind,
387+
&row.pubkey,
388+
&row.d_tag,
389+
row.created_at,
390+
&row.content,
391+
)
392+
.unwrap();
393+
394+
assert!(
395+
!retain_agent_record(&conn, &keys, &record).unwrap(),
396+
"an unchanged projection must not re-retain"
397+
);
398+
assert!(
399+
get_pending_sync(&conn).unwrap().is_empty(),
400+
"no pending_sync churn for an unchanged record"
401+
);
402+
}

0 commit comments

Comments
 (0)