agentmux_srv_core/backend/storage/agents/instance.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `instance_*`: per-launch instance rows, named-agent continuation, and
5//! identity-bound active-for-block resolution, on `db_agents`.
6
7use super::*;
8
9impl Store {
10
11 // ---- Agent instance CRUD ----
12 //
13 // Agent-concept consolidation Phase 3b, PR 2 of 4
14 // (SPEC_AGENT_ARCHITECTURE_2026_05_27.md): every method in this block
15 // reads and writes `db_agents` only. `db_agent_instances` is no longer
16 // touched by the live instance API; it stays on disk until PR 4 drops it.
17 //
18 // What an "instance" is now: the launch-side view of a non-template
19 // `db_agents` row. One row per agent, so:
20 // - `id` / `definition_id` are both the row's `id` — the agent's
21 // identity (the rule `instance_list` adopted in PR #1111).
22 // - `block_id`/`session_id`/`status`/`started_at`/`ended_at` are the
23 // row's LATEST launch state (schema v29); a continuation moves them
24 // to the new launch instead of adding a row, so `parent_instance_id`
25 // is always empty and chains are pre-collapsed.
26 // - Launching a TEMPLATE creates a new user-agent row keyed by the
27 // launch's instance id (`parent_template_id` = the template);
28 // launching a USER agent folds into its own row.
29 // - `display_hidden` is `user_hidden` (one flag, one row).
30
31 /// List agents as instances. Both filters are optional — pass `None`
32 /// to scan all. Ordered by `updated_at` descending, `created_at` as a
33 /// tiebreaker (most recent activity first — every launch, continuation
34 /// and lifecycle write bumps `updated_at`).
35 ///
36 /// The `definition_id` filter matches the agent's own `id` only:
37 /// templates are not agents and user agents derived from one template
38 /// are separate agents (see `instance_list_named` for the one caller
39 /// that wants "everything derived from this template"). The `status`
40 /// filter reads the row's latest launch status (v29).
41 pub fn instance_list(
42 &self,
43 definition_id: Option<&str>,
44 status: Option<&str>,
45 ) -> Result<Vec<AgentInstance>, StoreError> {
46 let conn = self.conn.lock().unwrap();
47 let mut sql = format!(
48 "SELECT {INSTANCE_COLUMNS} FROM db_agents WHERE is_template = 0 AND user_hidden = 0"
49 );
50 let mut param_vals: Vec<String> = Vec::new();
51 if let Some(d) = definition_id {
52 sql.push_str(&format!(" AND id = ?{}", param_vals.len() + 1));
53 param_vals.push(d.to_string());
54 }
55 if let Some(s) = status {
56 sql.push_str(&format!(" AND status = ?{}", param_vals.len() + 1));
57 param_vals.push(s.to_string());
58 }
59 sql.push_str(" ORDER BY updated_at DESC, created_at DESC");
60 let mut stmt = conn.prepare(&sql)?;
61 let iter = stmt.query_map(rusqlite::params_from_iter(param_vals.iter()), map_instance_row)?;
62 let mut out = Vec::new();
63 for r in iter {
64 out.push(r?);
65 }
66 Ok(out)
67 }
68
69 /// One agent by id, as an instance. `None` for a template or an
70 /// unknown id.
71 pub fn instance_get(&self, id: &str) -> Result<Option<AgentInstance>, StoreError> {
72 let conn = self.conn.lock().unwrap();
73 let mut stmt = conn.prepare(&format!(
74 "SELECT {INSTANCE_COLUMNS} FROM db_agents WHERE id = ?1 AND is_template = 0"
75 ))?;
76 match stmt.query_row(params![id], map_instance_row) {
77 Ok(a) => Ok(Some(a)),
78 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
79 Err(e) => Err(e.into()),
80 }
81 }
82
83 /// The Runtime menu choices the user last made for agent `id` (JSON, see
84 /// [`normalize_last_runtime`]), or '' when there are none or the agent is
85 /// unknown or a template.
86 pub fn agent_last_runtime_get(&self, id: &str) -> Result<String, StoreError> {
87 let conn = self.conn.lock().unwrap();
88 match conn.query_row(
89 "SELECT last_runtime FROM db_agents WHERE id = ?1 AND is_template = 0",
90 params![id],
91 |row| row.get::<_, String>(0),
92 ) {
93 Ok(v) => Ok(v),
94 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(String::new()),
95 Err(e) => Err(e.into()),
96 }
97 }
98
99 /// Replace agent `id`'s remembered runtime. Returns false for an unknown
100 /// agent or a template (templates are not agents anyone continues, so
101 /// they remember nothing). Deliberately leaves `updated_at` alone: this is
102 /// a note about how the agent was last run, not an edit of its definition.
103 pub fn agent_last_runtime_set(&self, id: &str, runtime: &str) -> Result<bool, StoreError> {
104 let conn = self.conn.lock().unwrap();
105 let rows = conn.execute(
106 "UPDATE db_agents SET last_runtime = ?2 WHERE id = ?1 AND is_template = 0",
107 params![id, runtime],
108 )?;
109 Ok(rows > 0)
110 }
111
112 /// A single `db_agents` row in the `AgentDefinition` shape, no registry
113 /// overlay — the definition a launch resolves against. Templates and
114 /// user agents alike.
115 pub(in crate::backend::storage) fn agent_row_get(&self, id: &str) -> Result<Option<AgentDefinition>, StoreError> {
116 let conn = self.conn.lock().unwrap();
117 let mut stmt = conn.prepare(&format!("{AGENT_DEFINITION_SELECT} WHERE id = ?1"))?;
118 match stmt.query_row(params![id], map_agent_definition_row) {
119 Ok(d) => Ok(Some(d)),
120 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
121 Err(e) => Err(e.into()),
122 }
123 }
124
125 /// Record a launch. Returns the agent row the launch now lives on, as an
126 /// instance — **its `id` may differ from `inst.id`**: a launch of a user
127 /// agent folds into that agent's row, and a continuation (non-empty
128 /// `parent_instance_id` naming an existing row) folds into the row it
129 /// continues. Only a fresh launch of a TEMPLATE creates a new row, keyed
130 /// by `inst.id`. Callers must persist the returned id, not the one they
131 /// passed (the frontend stores it as the block's `agentInstanceId`).
132 ///
133 /// `inst.definition_id` must name a `db_agents` row; when it only exists
134 /// in the global cross-channel definition registry (an agent created in
135 /// another channel), the local definition is backfilled first, exactly
136 /// as before (`REPORT_AGENT_DEFINITION_DB_GAP_2026_07_27.md`). A
137 /// definition that exists nowhere is `StoreError::NotFound` — the error
138 /// the legacy FK used to raise, minus the FK.
139 pub fn instance_create(&self, inst: &AgentInstance) -> Result<AgentInstance, StoreError> {
140 let def = match self.agent_row_get(&inst.definition_id)? {
141 Some(d) => d,
142 None => {
143 if let Some(reg) = self.shared_def_registry() {
144 match reg.get(&inst.definition_id) {
145 Ok(Some(record)) => {
146 if let Err(e) = self.agent_def_backfill_local_from_registry(&record) {
147 tracing::warn!(
148 definition_id = %inst.definition_id,
149 error = %e,
150 "instance_create: registry backfill failed"
151 );
152 }
153 }
154 Ok(None) => {}
155 Err(e) => {
156 tracing::warn!(
157 definition_id = %inst.definition_id,
158 error = %e,
159 "instance_create: registry lookup failed"
160 );
161 }
162 }
163 }
164 match self.agent_row_get(&inst.definition_id)? {
165 Some(d) => d,
166 None => {
167 tracing::warn!(
168 definition_id = %inst.definition_id,
169 instance_id = %inst.id,
170 "instance_create: definition exists nowhere; refusing the launch"
171 );
172 return Err(StoreError::NotFound);
173 }
174 }
175 }
176 };
177
178 let display_name = if inst.instance_name.is_empty() { def.name.clone() } else { inst.instance_name.clone() };
179 let hidden = if inst.display_hidden { 1_i64 } else { 0_i64 };
180 // The agent's working directory is the launch's RESOLVED path when
181 // the launch supplies one (`agent.open` resolves it, including slug
182 // collision suffixing), falling back to the definition's configured
183 // cwd. Phase 3a's dual-write always wrote the definition's, on the
184 // reasoning that "db_agents holds durable agent config; the
185 // per-launch resolved cwd lives on the block" — that split ends with
186 // the instance table: one row per agent means the row holds the
187 // agent's real workspace, which is also what the cross-version JSON
188 // registry mirror records (and it silently skips any row whose
189 // working_directory is not under the agents root).
190 let working_directory = if inst.working_directory.is_empty() {
191 def.working_directory.clone()
192 } else {
193 inst.working_directory.clone()
194 };
195 // The row this launch lands on. A user agent IS its row; a template
196 // launch is its own row unless it continues one that already exists.
197 let key = if def.is_seeded == 0 {
198 def.id.clone()
199 } else if !inst.parent_instance_id.is_empty() && self.instance_get(&inst.parent_instance_id)?.is_some() {
200 inst.parent_instance_id.clone()
201 } else {
202 inst.id.clone()
203 };
204 // A fresh template launch picks a new slug, as `agent_def_insert`
205 // does: under the host-wide allocation lock and against every other
206 // holder on this host, since its row is never published and only the
207 // scan of every `objects.db` lets another channel see it.
208 let fresh_launch = key == inst.id;
209 let allocating = match self.shared_def_registry().filter(|_| fresh_launch) {
210 Some(reg) => Some(reg.lock_slug_allocation().map_err(|e| {
211 StoreError::Other(format!("could not pick a slug for the launch of {}: {e}", def.name))
212 })?),
213 None => None,
214 };
215 let shared = self.shared_slugs();
216 let host = if fresh_launch { self.host_slugs_for_allocation()? } else { None };
217 {
218 let conn = self.conn.lock().unwrap();
219 let now_ms = Self::monotonic_updated_at(&conn, inst.created_at);
220 if fresh_launch {
221 // Fresh template launch — its own user-agent row, config
222 // copied from the template, bindings + launch state from the
223 // launch. ON CONFLICT covers an id the caller reuses on a
224 // retry (the App-API stub path).
225 //
226 // The slug is collision-resolved rather than copied verbatim
227 // from the template (#3497 §4). `agent_def_insert` has always
228 // done this; this path did not, making it the one writer that
229 // could mint a duplicate slug into a column with no UNIQUE
230 // constraint. In practice the launch flow names its agent and
231 // goes through `agent_def_insert`, so this branch is reached
232 // only by handing `instance_create` a seeded template id
233 // directly — this closes the function's contract rather than an
234 // observed fault (§2.5.2).
235 let launch_slug = resolve_slug_collision(&conn, &def.slug, &inst.id, &shared, host.as_ref())?;
236 conn.execute(
237 "INSERT INTO db_agents (
238 id, name, icon, description,
239 is_template, parent_template_id,
240 provider, provider_flags, shell, environment,
241 agent_type, agent_bus_id, accounts,
242 auto_start, restart_on_crash, idle_timeout_minutes,
243 slug, branch_label,
244 identity_id, memory_id, working_directory, github_context,
245 instance_name,
246 created_at, updated_at, is_seeded, user_hidden,
247 last_block_id,
248 container_image, container_volumes, container_name,
249 use_ambient_login, model_vendor_base_url,
250 conversation_visibility,
251 session_id, status, started_at, ended_at
252 ) VALUES (
253 ?1, ?2, ?3, ?4,
254 0, ?5,
255 ?6, ?7, ?8, ?9,
256 ?10, ?11, ?12,
257 ?13, ?14, ?15,
258 ?16, ?17,
259 ?18, ?19, ?20, ?21,
260 ?22,
261 ?23, ?24, 0, ?25,
262 ?26,
263 ?27, ?28, ?29,
264 ?30, ?31,
265 ?32,
266 ?33, ?34, ?35, ?36
267 )
268 ON CONFLICT(id) DO UPDATE SET
269 name = excluded.name,
270 identity_id = excluded.identity_id,
271 memory_id = excluded.memory_id,
272 working_directory = excluded.working_directory,
273 github_context = excluded.github_context,
274 instance_name = excluded.instance_name,
275 updated_at = excluded.updated_at,
276 user_hidden = excluded.user_hidden,
277 last_block_id = CASE WHEN excluded.last_block_id = '' THEN db_agents.last_block_id ELSE excluded.last_block_id END,
278 session_id = CASE WHEN excluded.session_id = '' THEN db_agents.session_id ELSE excluded.session_id END,
279 status = excluded.status,
280 started_at = excluded.started_at,
281 ended_at = excluded.ended_at",
282 params![
283 inst.id,
284 display_name,
285 def.icon,
286 def.description,
287 def.id,
288 def.provider,
289 def.provider_flags,
290 def.shell,
291 def.environment,
292 def.agent_type,
293 def.agent_bus_id,
294 def.accounts,
295 def.auto_start,
296 def.restart_on_crash,
297 def.idle_timeout_minutes,
298 launch_slug,
299 def.branch_label,
300 inst.identity_id,
301 inst.memory_id,
302 working_directory,
303 inst.github_context,
304 inst.instance_name,
305 inst.created_at,
306 now_ms,
307 hidden,
308 inst.block_id,
309 def.container_image,
310 def.container_volumes,
311 def.container_name,
312 def.use_ambient_login,
313 def.model_vendor_base_url,
314 def.conversation_visibility,
315 inst.session_id,
316 inst.status,
317 inst.started_at,
318 inst.ended_at,
319 ],
320 )?;
321 } else {
322 // Fold: the launch (or continuation) moves the row's bindings
323 // and launch state to this launch. Config stays the row's own.
324 //
325 // An EMPTY `session_id` never clears the row's: a fresh
326 // continuation is created session-less and the CLI only
327 // reports the real session id later, so overwriting here
328 // would drop the pointer `--resume` needs (the same reason
329 // `last_block_id` is guarded). A deliberate clear goes
330 // through `instance_update_partial(Some(""))`, which does
331 // write it — see `poison_resume`.
332 conn.execute(
333 "UPDATE db_agents SET
334 name = ?2,
335 identity_id = ?3,
336 memory_id = ?4,
337 working_directory = ?14,
338 github_context = ?5,
339 instance_name = ?6,
340 updated_at = ?7,
341 user_hidden = ?8,
342 last_block_id = CASE WHEN ?9 = '' THEN last_block_id ELSE ?9 END,
343 session_id = CASE WHEN ?10 = '' THEN session_id ELSE ?10 END,
344 status = ?11,
345 started_at = ?12,
346 ended_at = ?13
347 WHERE id = ?1 AND is_template = 0",
348 params![
349 key,
350 display_name,
351 inst.identity_id,
352 inst.memory_id,
353 inst.github_context,
354 inst.instance_name,
355 now_ms,
356 hidden,
357 inst.block_id,
358 inst.session_id,
359 inst.status,
360 inst.started_at,
361 inst.ended_at,
362 working_directory,
363 ],
364 )?;
365 }
366 }
367 drop(allocating);
368 let canonical = self.instance_get(&key)?.ok_or(StoreError::NotFound)?;
369 self.registry_upsert_if_named(&canonical, !inst.session_id.is_empty());
370 // A freshly created launch's session_id is never a genuine capture
371 // in production (continuations start with ""), so only a non-empty
372 // one is worth propagating to the registry.
373 if !inst.session_id.is_empty() {
374 self.registry_propagate_continuation_session_id(&canonical);
375 }
376 Ok(canonical)
377 }
378
379 /// An `updated_at` strictly greater than any already on `db_agents`, so
380 /// recency ordering survives fast successive writes within one
381 /// millisecond (reagent P2 round 3 on #1013 — the rule the dual-write
382 /// used; inherited here).
383 fn monotonic_updated_at(conn: &rusqlite::Connection, floor: i64) -> i64 {
384 let wall_now: i64 = std::time::SystemTime::now()
385 .duration_since(std::time::UNIX_EPOCH)
386 .map(|d| d.as_millis() as i64)
387 .unwrap_or(floor);
388 let global_prior: i64 = conn
389 .query_row("SELECT COALESCE(MAX(updated_at), 0) FROM db_agents", [], |row| row.get::<_, i64>(0))
390 .unwrap_or(0);
391 std::cmp::max(wall_now, global_prior.saturating_add(1))
392 }
393
394 /// Set the hidden flag on an agent row. Used by the "Forget agent"
395 /// affordance — soft-delete only; the row + working directory remain on
396 /// disk for audit + recovery.
397 ///
398 /// Cross-version case: an agent migrated into the registry from another
399 /// version's SQLite won't have a row in the current version's SQLite.
400 /// The UPDATE returns 0 rows, but the registry still needs to flip —
401 /// otherwise "Forget agent" silently no-ops for those. Returns `true`
402 /// when either side acted.
403 pub fn instance_set_hidden(&self, id: &str, hidden: bool) -> Result<bool, StoreError> {
404 // Read in the same critical section as the UPDATE, so the row can't
405 // change kind underneath the registry call below. See
406 // `scope_for_row`: retiring a TEMPLATE with the wide scope
407 // would hide every real agent launched from it (ReAgent P1 round 4
408 // on PR #3262).
409 let (rows, scope) = {
410 let conn = self.conn.lock().unwrap();
411 let scope = Self::scope_for_row(&conn, id);
412 let rows = conn.execute(
413 "UPDATE db_agents SET user_hidden = ?1 WHERE id = ?2 AND is_template = 0",
414 params![if hidden { 1_i64 } else { 0_i64 }, id],
415 )?;
416 (rows, scope)
417 };
418 let mut registry_acted = false;
419 if let Some(reg) = self.registry() {
420 // Matches by file key OR the record's own `definition_id`.
421 // Retiring by file key alone left any launch-keyed record for
422 // this agent active — literally the "'Forget agent' retires the
423 // NEW key while the stale file stays active, so the forgotten
424 // agent reappears" failure `m0026_registry_agent_id_rekey`'s own
425 // doc comment describes, still reachable on an install where
426 // that migration no-ops (see
427 // `Registry::hard_delete_for_agent`). A count of 0 is a genuine
428 // no-op for an unrelated id, which is what the old
429 // `exists_anywhere` pre-check was guarding against.
430 let res = if hidden {
431 reg.retire_for_agent(id, scope)
432 } else {
433 reg.unretire_for_agent(id, scope)
434 };
435 match res {
436 Ok(moved) => registry_acted = moved > 0,
437 Err(e) => tracing::warn!(
438 instance_id = %id,
439 hidden,
440 error = %e,
441 "registry: failed to mirror instance_set_hidden"
442 ),
443 }
444 }
445 Ok(rows > 0 || registry_acted)
446 }
447
448 /// Rename the agent's PICKER-VISIBLE display name (`instance_name`),
449 /// in SQLite and across every registry record for it.
450 ///
451 /// `renameagentdefinitiontitle` on its own writes `name` (or
452 /// `branch_label` for a fork) — the fields the pane tab strip's
453 /// `titleOf()` reads. "My Agents" rows render
454 /// `instance_name || definition_name` instead, and `instance_name` is
455 /// non-empty for every launched or registry-backed row, so a rename
456 /// closed the editor, refetched, and redisplayed the OLD name; for a
457 /// fork it changed `branch_label`, which no picker row shows at all
458 /// (codex P1 on PR #3262). Renaming an agent has to move the name the
459 /// user is actually looking at, so the handler calls this too.
460 ///
461 /// Scoped to rows that ALREADY have an `instance_name`: writing one
462 /// onto an agent that has never had a named launch would make it appear
463 /// in `instance_list_named` (which filters `instance_name <> ''`) —
464 /// conjuring a picker row rather than renaming one. Those rows fall
465 /// back to `definition_name`, which the title update already moved.
466 ///
467 /// Returns whether anything changed, counting the registry: a
468 /// cross-channel agent has no local row to update but does have records.
469 pub fn instance_rename(&self, id: &str, instance_name: &str) -> Result<bool, StoreError> {
470 // Same critical-section read as `instance_set_hidden`, for the same
471 // reason: renaming a TEMPLATE with the wide scope would rewrite
472 // `instance_name` on every real agent launched from it (ReAgent P1
473 // round 4 on PR #3262).
474 let (rows, scope) = {
475 let conn = self.conn.lock().unwrap();
476 let scope = Self::scope_for_row(&conn, id);
477 let now_ms = Self::monotonic_updated_at(&conn, 0);
478 let rows = conn.execute(
479 "UPDATE db_agents SET instance_name = ?1, updated_at = ?2
480 WHERE id = ?3 AND is_template = 0 AND instance_name <> ''",
481 params![instance_name, now_ms, id],
482 )?;
483 (rows, scope)
484 };
485 self.former_names_changed();
486 let mut registry_renamed = 0usize;
487 if let Some(reg) = self.registry() {
488 match reg.set_instance_name_for_agent(id, scope, instance_name) {
489 Ok(n) => registry_renamed = n,
490 Err(e) => tracing::warn!(
491 agent_id = %id, error = %e,
492 "registry: failed to mirror instance_rename — picker may keep showing the old name"
493 ),
494 }
495 }
496 Ok(rows > 0 || registry_renamed > 0)
497 }
498
499 /// Named agents for the picker's "My Agents" surface: non-hidden rows with an `instance_name`,
500 /// newest launch first, capped by `limit`.
501 ///
502 /// `definition_id` restricts the result to that agent itself OR every
503 /// agent derived from it (`parent_template_id`), so a per-template list
504 /// includes any agent launched from it. `identity_id` filters on the row's identity
505 /// binding.
506 ///
507 /// `include_continuations` is accepted for API compatibility but no
508 /// longer changes the query: chains are pre-collapsed (one row per
509 /// agent carrying its latest launch), so the legacy "heads only" and
510 /// "latest per chain" modes both yield exactly this list.
511 pub fn instance_list_named(
512 &self,
513 limit: usize,
514 definition_id: Option<&str>,
515 identity_id: Option<&str>,
516 _include_continuations: bool,
517 ) -> Result<Vec<AgentInstance>, StoreError> {
518 let conn = self.conn.lock().unwrap();
519 let mut sql = format!(
520 "SELECT {INSTANCE_COLUMNS} FROM db_agents
521 WHERE is_template = 0 AND user_hidden = 0 AND instance_name <> ''"
522 );
523 let mut param_vals: Vec<String> = Vec::new();
524 if let Some(id) = identity_id {
525 sql.push_str(&format!(" AND identity_id = ?{}", param_vals.len() + 1));
526 param_vals.push(id.to_string());
527 }
528 if let Some(def) = definition_id {
529 let n = param_vals.len() + 1;
530 sql.push_str(&format!(" AND (id = ?{n} OR parent_template_id = ?{n})"));
531 param_vals.push(def.to_string());
532 }
533 sql.push_str(&format!(
534 " ORDER BY started_at DESC, updated_at DESC, id DESC LIMIT ?{}",
535 param_vals.len() + 1
536 ));
537 param_vals.push(limit.to_string());
538 let mut stmt = conn.prepare(&sql)?;
539 let iter = stmt.query_map(rusqlite::params_from_iter(param_vals.iter()), map_instance_row)?;
540 let mut out = Vec::new();
541 for r in iter {
542 out.push(r?);
543 }
544 Ok(out)
545 }
546
547 /// Force a row's `slug` to an exact value, bypassing collision resolution.
548 ///
549 /// **Tests only, and deliberately awkward to reach for.** Both write paths
550 /// now suffix-resolve (#3497 §4), so a test cannot build two rows sharing a
551 /// slug through the normal API any more — and the read-path guards
552 /// (`instance_get_by_slug`, `agent_resolve::resolve_agent_id`, `check_s1`)
553 /// exist precisely for that state. Without this, those tests still *pass*,
554 /// but vacuously: the lookup returns nothing because nothing matches the
555 /// slug, not because the guard refused an ambiguous one. That is the
556 /// failure mode the guards were written to prevent, reproduced in their own
557 /// tests.
558 ///
559 /// The state is still reachable in production — no `UNIQUE` constraint
560 /// backs the column, so a future writer, a migration, or hand-edited data
561 /// can produce it. Defence in depth: prevent it on write, refuse it on
562 /// read, and test both.
563 /// Make every `db_agents` read fail, to test how a caller treats a store
564 /// fault (as opposed to an empty answer).
565 #[cfg(test)]
566 pub(crate) fn test_break_agents_table(&self) -> Result<(), StoreError> {
567 let conn = self.conn.lock().unwrap();
568 conn.execute_batch("DROP TABLE db_agents")?;
569 Ok(())
570 }
571
572 /// Make every name-keyed signing key ensure fail (host and LAN).
573 #[cfg(test)]
574 pub(crate) fn test_break_name_key_tables(&self) -> Result<(), StoreError> {
575 let conn = self.conn.lock().unwrap();
576 conn.execute_batch("DROP TABLE db_agent_jekt_keys; DROP TABLE db_agent_lan_keys")?;
577 Ok(())
578 }
579
580 #[cfg(any(test, feature = "test-support"))]
581 pub fn test_force_slug(&self, id: &str, slug: &str) -> Result<(), StoreError> {
582 let conn = self.conn.lock().unwrap();
583 conn.execute("UPDATE db_agents SET slug = ?2 WHERE id = ?1", params![id, slug])?;
584 Ok(())
585 }
586
587 /// Resolve an agent by its persisted `slug` — the App-API self-lookup
588 /// (`AGENTMUX_AGENT_ID` is the slug) — **only if exactly one agent has
589 /// it**. Matches ONLY `slug`; deliberately single-purpose after reagentx
590 /// P1 on PR #2428 (round 2): a lookup that also matched another column
591 /// let a coincidental cross-namespace collision return an unrelated
592 /// agent's memory, accounts or bundle. Hidden rows are excluded.
593 ///
594 /// `None` means "no agent" *or* "more than one agent" — callers already
595 /// treat both as "fall back to another source", so they are not
596 /// distinguished. The fallbacks are themselves fail-closed
597 /// (`agent_registry_lookup::find_active_record_by_slug`), so refusing
598 /// here routes to another refusal rather than to a guess.
599 ///
600 /// **Why ambiguity returns `None` rather than the most recently updated
601 /// row:** `db_agents.slug` has no `UNIQUE` constraint — `migrations.rs`
602 /// declines the index deliberately. Both write paths now suffix-resolve
603 /// (#3497 §4), so neither mints a duplicate, but nothing at the schema
604 /// level prevents one: a future writer, a migration, or hand-edited data
605 /// still can. (An earlier revision of this comment claimed
606 /// `instance_create` copied its template's slug onto every launch, so two
607 /// launches collided. That was never true of the real launch flow — see
608 /// the spec's §2.5.2 — and is no longer true of the function either.) This
609 /// function used to `ORDER BY updated_at DESC LIMIT 1` and hand the
610 /// winner's `definition_id` and `working_directory` to the caller.
611 /// `HistoryService::sessions_for_agent` consults it to resolve an
612 /// agent's *conversation history*, so guessing wrong does not degrade
613 /// gracefully — it discloses one agent's transcripts to another, and
614 /// deterministically: the same wrong agent won every time. A slug simply
615 /// does not identify an agent when it collides, so the honest answer is
616 /// "unknown". Same rule and same reasoning as
617 /// [`crate::backend::agent_registry_lookup::find_active_record_by_slug`]
618 /// (PR #3480), which this mirrors for `db_agents`.
619 ///
620 /// The slug compared is the canonical one ([`canonical_slug`]).
621 pub fn instance_get_by_slug(&self, slug: &str) -> Result<Option<AgentInstance>, StoreError> {
622 if slug.is_empty() {
623 return Ok(None);
624 }
625 let shared = self.shared_slugs();
626 let conn = self.conn.lock().unwrap();
627 let ids: Vec<String> =
628 rows_with_canonical_slugs(&conn, "WHERE is_template = 0 AND user_hidden = 0", &shared)?
629 .into_iter()
630 .filter(|r| r.slug == slug)
631 .map(|r| r.id)
632 .collect();
633 if ids.len() > 1 {
634 tracing::warn!(
635 slug = %slug,
636 matches = ids.len(),
637 "db_agents slug collision: refusing to resolve an agent by slug alone"
638 );
639 return Ok(None);
640 }
641 let Some(id) = ids.first() else {
642 return Ok(None);
643 };
644 let mut stmt = conn.prepare(&format!("SELECT {INSTANCE_COLUMNS} FROM db_agents WHERE id = ?1"))?;
645 match stmt.query_row(params![id], map_instance_row) {
646 Ok(a) => Ok(Some(a)),
647 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
648 Err(e) => Err(e.into()),
649 }
650 }
651
652 /// Every non-template, non-hidden agent a typed name could mean (identity
653 /// M3, spec §5): exact (canonical) slug, or `name`/`instance_name`
654 /// ASCII-case-insensitively, as SQLite's `NOCASE` compared them. Lists
655 /// rather than picks — the caller decides what to do with several. A name
656 /// none of them answers to may be a slug or display name an agent was
657 /// renamed from: that agent's row (`former_names`).
658 pub fn agents_matching_name(&self, typed: &str) -> Result<Vec<AgentNameMatch>, StoreError> {
659 let typed = typed.trim();
660 if typed.is_empty() {
661 return Ok(Vec::new());
662 }
663 // Asked before the lock: it may re-read the store.
664 let maybe_former = self.former_name_candidate(typed);
665 let shared = self.shared_slugs();
666 let conn = self.conn.lock().unwrap();
667 let rows = rows_with_canonical_slugs(&conn, "WHERE is_template = 0 AND user_hidden = 0", &shared)?;
668 let matched: Vec<AgentNameMatch> = rows.iter().filter(|r| answers_to(r, typed)).cloned().collect();
669 let Some(key) = maybe_former.filter(|_| matched.is_empty()) else {
670 return Ok(matched);
671 };
672 let Some(owner) = FormerNameIndex::read(&conn, &shared)?.owner(&key).map(str::to_string) else {
673 return Ok(Vec::new());
674 };
675 if let Some(row) = rows.into_iter().find(|r| r.id == owner) {
676 return Ok(vec![row]);
677 }
678 drop(conn);
679 // An agent only the shared definitions hold (made in another
680 // channel): matched from its record, as `agent_def_list` overlays it.
681 let def = self.agent_def_get(&owner)?.filter(|d| d.is_seeded == 0 && d.user_hidden == 0);
682 Ok(def.map(|d| AgentNameMatch { id: d.id, name: d.name, slug: d.slug, instance_name: String::new() }).into_iter().collect())
683 }
684
685 /// Every row a name selects, **templates and hidden rows included** — the
686 /// identity M4a-2 ambiguity check (spec §6.5.3). Unlike
687 /// [`Self::agents_matching_name`], which lists only the agents a typed
688 /// name could mean, this asks whether the name is *anyone else's*: slug
689 /// collision suffixing (`resolve_slug_collision`) counts template rows,
690 /// so a "Claude" made from the "Claude" template is `claude-2`, and a name
691 /// its MCP sends as `claude` belongs to the template (#3573).
692 pub fn rows_answering_to(&self, name: &str) -> Result<Vec<AgentNameMatch>, StoreError> {
693 let name = name.trim();
694 if name.is_empty() {
695 return Ok(Vec::new());
696 }
697 let shared = self.shared_slugs();
698 let conn = self.conn.lock().unwrap();
699 let rows = rows_with_canonical_slugs(&conn, "", &shared)?;
700 Ok(rows.into_iter().filter(|r| answers_to(r, name)).collect())
701 }
702
703 /// The names row `id` answers to — the by-id counterpart of
704 /// [`Self::agents_matching_name`], for checking a body's actor name
705 /// against the calling agent's own row (identity M4a-2, spec §6.5.3).
706 /// Any row, template or hidden: the caller's token already names it.
707 /// The slug is the canonical one, so ownership checks agree with spawn.
708 pub fn agent_names_by_id(&self, id: &str) -> Result<Option<AgentNameMatch>, StoreError> {
709 let shared = self.shared_slug_of(id);
710 let conn = self.conn.lock().unwrap();
711 match conn.query_row(
712 "SELECT id, name, slug, instance_name FROM db_agents WHERE id = ?1",
713 params![id],
714 |row| {
715 let local: String = row.get(2)?;
716 Ok(AgentNameMatch {
717 id: row.get(0)?,
718 name: row.get(1)?,
719 slug: canonical_slug(id, &local, shared.as_deref()),
720 instance_name: row.get(3)?,
721 })
722 },
723 ) {
724 Ok(m) => Ok(Some(m)),
725 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
726 Err(e) => Err(e.into()),
727 }
728 }
729
730 /// Whether `id` names an agent that was **deleted**: no local row (template
731 /// or not), and the shared definition registry holds a record for it that
732 /// is retired rather than active — deleting a user agent retires its
733 /// global record (`registry_def_retire`). A template, a removed template
734 /// and a live cross-channel agent all read false: templates are never
735 /// mirrored, and a cross-channel agent's record is active. With no shared
736 /// registry this cannot be told and reads false. For the identity spawn
737 /// gate (#3577).
738 pub fn agent_was_deleted(&self, id: &str) -> bool {
739 let id = id.trim();
740 if id.is_empty() {
741 return false;
742 }
743 match self.agent_row_get(id) {
744 Ok(None) => {}
745 Ok(Some(_)) | Err(_) => return false,
746 }
747 match self.shared_def_registry() {
748 Some(reg) => reg.exists_anywhere(id) && !reg.exists(id),
749 None => false,
750 }
751 }
752
753 /// Ensure a user agent `id` has a local `db_agents` row, backfilling it
754 /// from the shared definition registry when it exists only there (a
755 /// cross-channel agent) — the same backfill `instance_create` runs, without
756 /// its fold. Identity M4b-4 (spec §6.5.8): so a block naming a
757 /// cross-channel agent resolves to a local row at its spawn. Returns
758 /// whether the row exists afterwards.
759 pub fn agent_row_ensure_local(&self, id: &str) -> Result<bool, StoreError> {
760 if self.agent_row_get(id)?.is_some() {
761 return Ok(true);
762 }
763 if let Some(reg) = self.shared_def_registry() {
764 match reg.get(id) {
765 Ok(Some(record)) => {
766 if let Err(e) = self.agent_def_backfill_local_from_registry(&record) {
767 tracing::warn!(definition_id = %id, error = %e, "agent_row_ensure_local: registry backfill failed");
768 }
769 }
770 Ok(None) => {}
771 Err(e) => {
772 tracing::warn!(definition_id = %id, error = %e, "agent_row_ensure_local: registry lookup failed");
773 }
774 }
775 }
776 Ok(self.agent_row_get(id)?.is_some())
777 }
778
779 /// Record a launch of user agent `id` on `block_id`: a **lifecycle-only**
780 /// update — `last_block_id`, `status = running`, `started_at`,
781 /// `ended_at = 0`, a monotonic `updated_at` and the registry mirror — the
782 /// columns `instance_create`'s fold moves, and none of the ones it would
783 /// overwrite from a caller's record (`name`, `identity_id`, `memory_id`,
784 /// `instance_name`, `github_context`, `user_hidden`). Identity M4b-4 (spec
785 /// §6.5.8), for `agent.open`, which has no such record. Returns false for
786 /// a template or a missing row.
787 pub fn instance_record_launch(
788 &self,
789 id: &str,
790 block_id: &str,
791 started_at: i64,
792 ) -> Result<bool, StoreError> {
793 let rows = {
794 let conn = self.conn.lock().unwrap();
795 let now_ms = Self::monotonic_updated_at(&conn, 0);
796 conn.execute(
797 "UPDATE db_agents
798 SET last_block_id = ?2, status = 'running', started_at = ?3, ended_at = 0, updated_at = ?4
799 WHERE id = ?1 AND is_template = 0",
800 params![id, block_id, started_at, now_ms],
801 )?
802 };
803 if rows == 0 {
804 return Ok(false);
805 }
806 if let Some(fresh) = self.instance_get(id)? {
807 self.registry_upsert_if_named(&fresh, false);
808 }
809 Ok(true)
810 }
811
812 /// Partial update of an agent's launch state. Only `Some` fields are
813 /// written; `None` leaves that column untouched. `Some("")` explicitly
814 /// clears (the `updateagentinstance` command contract, and
815 /// `poison_resume`'s deliberate stale-session clear).
816 ///
817 /// Returns the post-update row. `None` is reserved for **not-found**;
818 /// an all-`None` update on an existing id is a no-op that returns the
819 /// unchanged row, so callers can tell "nothing to change" from "no such
820 /// agent". See SPEC_UPDATEAGENTINSTANCE_PARTIAL_UPDATE_2026_05_29.md.
821 pub fn instance_update_partial(
822 &self,
823 id: &str,
824 upd: &InstanceUpdate,
825 ) -> Result<Option<AgentInstance>, StoreError> {
826 use rusqlite::types::ToSql;
827
828 let mut sets: Vec<&str> = Vec::new();
829 let mut vals: Vec<Box<dyn ToSql>> = Vec::new();
830 if let Some(v) = &upd.block_id {
831 sets.push("last_block_id = ?");
832 vals.push(Box::new(v.clone()));
833 }
834 if let Some(v) = &upd.session_id {
835 sets.push("session_id = ?");
836 vals.push(Box::new(v.clone()));
837 }
838 if let Some(v) = &upd.status {
839 sets.push("status = ?");
840 vals.push(Box::new(v.clone()));
841 }
842 if let Some(v) = &upd.github_context {
843 sets.push("github_context = ?");
844 vals.push(Box::new(v.clone()));
845 }
846 if let Some(v) = upd.ended_at {
847 sets.push("ended_at = ?");
848 vals.push(Box::new(v));
849 }
850 if sets.is_empty() {
851 return self.instance_get(id);
852 }
853
854 let rows = {
855 let conn = self.conn.lock().unwrap();
856 let now_ms = Self::monotonic_updated_at(&conn, 0);
857 sets.push("updated_at = ?");
858 vals.push(Box::new(now_ms));
859 let sql = format!("UPDATE db_agents SET {} WHERE id = ? AND is_template = 0", sets.join(", "));
860 vals.push(Box::new(id.to_string()));
861 let params: Vec<&dyn ToSql> = vals.iter().map(|b| b.as_ref()).collect();
862 conn.execute(&sql, params.as_slice())?
863 };
864 if rows == 0 {
865 return Ok(None);
866 }
867 let fresh = self.instance_get(id)?;
868 if let Some(f) = &fresh {
869 self.registry_upsert_if_named(f, upd.session_id.is_some());
870 // Only propagate when THIS call actually targeted session_id —
871 // `Some("")` (a deliberate clear) and `Some(real_sid)` both mean
872 // this call wrote it; `None` means the row's existing value is
873 // not this call's to broadcast. See
874 // registry_propagate_continuation_session_id's doc comment.
875 if upd.session_id.is_some() {
876 self.registry_propagate_continuation_session_id(f);
877 }
878 }
879 Ok(fresh)
880 }
881
882 /// Full-struct update of the mutable launch-state fields (`block_id`,
883 /// `session_id`, `status`, `github_context`, `ended_at`). Retained as a
884 /// convenience for tests + internal callers; the `updateagentinstance`
885 /// handler uses [`Self::instance_update_partial`].
886 #[cfg(test)]
887 pub fn instance_update(&self, inst: &AgentInstance) -> Result<bool, StoreError> {
888 let upd = InstanceUpdate {
889 block_id: Some(inst.block_id.clone()),
890 session_id: Some(inst.session_id.clone()),
891 status: Some(inst.status.clone()),
892 github_context: Some(inst.github_context.clone()),
893 ended_at: Some(inst.ended_at),
894 };
895 Ok(self.instance_update_partial(&inst.id, &upd)?.is_some())
896 }
897
898 /// Repoint every agent derived from `old_def_id` at `new_def_id`. Used by
899 /// the Phase 1 two-tier-picker migration
900 /// (SPEC_AGENT_PICKER_TWO_TIER_2026_05_24.md): when a seeded template has
901 /// been used directly, the migration clones it into a user agent and
902 /// repoints its launches so the existing reattach flow keeps working.
903 /// Returns the number of rows updated.
904 pub fn instance_repoint_definition(&self, old_def_id: &str, new_def_id: &str) -> Result<usize, StoreError> {
905 let conn = self.conn.lock().unwrap();
906 Ok(conn.execute(
907 // `id != ?1` keeps the promote target out of its own result set:
908 // the clone is itself derived from the template, so an unguarded
909 // update would re-parent it to itself and count as a repoint.
910 "UPDATE db_agents SET parent_template_id = ?1
911 WHERE parent_template_id = ?2 AND is_template = 0 AND id != ?1",
912 params![new_def_id, old_def_id],
913 )?)
914 }
915
916 /// Delete an agent row (never a template). The row IS the agent in the
917 /// consolidated model, so this removes the agent — previously a launch
918 /// row of a user-clone definition could be deleted while the definition
919 /// stayed; there is no such split any more. As of the definition flip,
920 /// this and `agent_def_delete` are the same operation reached from two
921 /// names: neither writes `db_agent_definitions`, and nothing reads it
922 /// per-boot any more to resurrect what either one deletes (the startup
923 /// gap-repair that once could is gone — codex P2 on #3080 closed the
924 /// resurrection path this way rather than by re-adding a legacy-table
925 /// delete here).
926 pub fn instance_delete(&self, id: &str) -> Result<bool, StoreError> {
927 let shared = self.shared_slugs_for_delete(id)?;
928 let rows = {
929 let conn = self.conn.lock().unwrap();
930 // Refuse a template explicitly, rather than leaning on the
931 // DELETE's own `is_template = 0` guard. The registry sweep below
932 // runs even when the DELETE matches nothing, and a template's id
933 // can appear as the `definition_id` of a legacy, never-re-keyed
934 // launch record — sweeping on it would take records belonging to
935 // agents launched from that template, which
936 // `agent_def_delete_removes_only_its_own_registry_file` exists
937 // to forbid. A missing row reads as "not a template" so the
938 // retry path below still works.
939 if Self::scope_for_row(&conn, id) == RecordScope::FileKeyOnly {
940 return Ok(false);
941 }
942 // Identity M4a: read the names before the row goes.
943 tombstone_key_names(&conn, id, &shared)?;
944 purge_name_keyed_keys(&conn, id, self.wan_identity().as_deref(), self.host_lan_keys().as_deref(), &shared)?;
945 let rows =
946 conn.execute("DELETE FROM db_agents WHERE id = ?1 AND is_template = 0", params![id])?;
947 // Same dependent purge `agent_def_delete` runs, and
948 // unconditional for the same reason — this is that deletion
949 // arriving from the launch side, and an agent deleted through
950 // this name used to keep its credentials and signing keys on
951 // disk purely because the cleanup lived in the other function.
952 purge_agent_dependents(&conn, id, self.token_index().as_deref())?;
953 rows
954 };
955 // Unconditional, for the reason `agent_def_delete`'s own sweep is
956 // (ReAgent P1 round 2 on PR #3262): a retry after a previous attempt
957 // removed the `db_agents` row but failed to remove the registry file
958 // sees `rows == 0`, so gating here left the iconless ghost row
959 // behind indefinitely — the exact bug this PR exists to fix, just
960 // unfixed on this entry point. "The same deletion under a second
961 // name" has to mean the same convergence too, not just the same
962 // table list.
963 // Always `Agent`: the template case returned early above, because
964 // this method's contract is "never a template" — it reports no
965 // deletion for one rather than sweeping narrowly the way
966 // `agent_def_delete` does.
967 self.purge_agent_side_effects(id, "instance_delete", RecordScope::Agent);
968 // Tombstone the GLOBAL definition record too. Clearing the local
969 // tables alone leaves an active record in the cross-channel
970 // definition registry, and `agent_def_list` overlays every active
971 // record back onto the local list on every read — so the deleted
972 // agent reappears on the very next My Agents fetch, no restart
973 // needed (reagent P1 round 2 on #3080). Same tombstone
974 // `agent_def_delete` writes; this is that deletion arriving from the
975 // launch side.
976 //
977 // Unconditional, like everything else in this function (ReAgent P2
978 // on PR #3262). This was the last step still gated on `rows > 0`,
979 // on the reasoning that an agent existing only in the global
980 // registry is `agent_def_delete`'s business — but once the purge
981 // above went unconditional, that gate left a genuinely incoherent
982 // outcome reachable here: a cross-channel agent's dependent rows
983 // and registry records swept while its definition stays ACTIVE, so
984 // the overlay keeps serving a definition nothing backs. Retiring an
985 // id with no global record is a no-op, and a template can't reach
986 // this line (early return above), so there is nothing to gate on.
987 let global_retired = self.registry_def_retire(id);
988 Ok(rows > 0 || global_retired)
989 }
990
991 /// Resolve the agent bindings tied to a block.
992 ///
993 /// Resolves through `block.meta.agentId` (or legacy `agent:id`) first —
994 /// the block says which agent it shows — returning that agent's row
995 /// with `block_id` set to the asked-for block. Falls back to the agent
996 /// whose latest launch is on this block and still active, which is what
997 /// a block from before the block meta carried `agentId` needs.
998 ///
999 /// `block.meta.agentInstanceId` never overrides `agentId`: codex P1 on
1000 /// PR #1114 round 3 surfaced that pane reuse can leave a stale one
1001 /// behind. It is consulted only for a block whose `agentId` names no
1002 /// agent row, and only within what that block names, while it is still
1003 /// the block's latest launch (see the fallback below).
1004 pub fn instance_get_active_for_block(&self, block_id: &str) -> Result<Option<AgentInstance>, StoreError> {
1005 let block: crate::backend::obj::Block = match self.get(block_id)? {
1006 Some(b) => b,
1007 None => return Ok(None),
1008 };
1009 let agent_id = crate::backend::obj::block_meta_agent_id(&block.meta)
1010 .unwrap_or("")
1011 .to_string();
1012 if !agent_id.is_empty() {
1013 // Any non-template row, hidden or not: an existing pane of a
1014 // "forgotten" agent must still resolve its bindings.
1015 let conn = self.conn.lock().unwrap();
1016 let mut stmt = conn.prepare(&format!(
1017 "SELECT {INSTANCE_COLUMNS} FROM db_agents WHERE id = ?1 AND is_template = 0"
1018 ))?;
1019 match stmt.query_row(params![agent_id], map_instance_row) {
1020 Ok(mut a) => {
1021 a.block_id = block_id.to_string();
1022 return Ok(Some(a));
1023 }
1024 Err(rusqlite::Error::QueryReturnedNoRows) => {}
1025 Err(e) => return Err(e.into()),
1026 }
1027 // The block names something that is not an agent row: a
1028 // template (a template launch or continuation finds the row it
1029 // created or folded into this way), a template since removed
1030 // from the manifest (its launched agents are kept, and their
1031 // blocks still name it), a deleted agent whose pane survived, or
1032 // a provider key. Fall back only to a row *launched from* what
1033 // the block names (`parent_template_id`), and — when the frontend
1034 // has stamped the launched row (`agentInstanceId`) — only to that
1035 // row. Row status is never corrected when a pane is switched or
1036 // a process exits, so the latest launch on the block can be
1037 // another agent's stale `running` row, including a sibling
1038 // launched from the same template; resolving to it handed the
1039 // pane that agent's UID, token, slug and provider credentials.
1040 // A stamped row that no longer exists resolves to nothing.
1041 // "Launched from" reaches one hop: the template-promotion
1042 // migration repointed launch rows' `parent_template_id` from the
1043 // seeded template to its promoted clone (itself launched from
1044 // the template), while pre-migration blocks still name the
1045 // template (Codex P1 on #3576). Neither the row nor the hop may
1046 // be a fork: `forkagentdefinition` also stores its source in
1047 // `parent_template_id`, and `branch_label` (always set on a
1048 // fork, never on a template launch) is what tells them apart
1049 // (`template.rs`; Codex P1 on #3576).
1050 let stamped = block
1051 .meta
1052 .get("agentInstanceId")
1053 .and_then(|v| v.as_str())
1054 .map(str::trim)
1055 .unwrap_or("")
1056 .to_string();
1057 if !stamped.is_empty() {
1058 // The stamp is the frontend's own record of the row it
1059 // launched on this block — stronger evidence than lineage,
1060 // which migrations and deletions rewrite (a removed
1061 // template, a promoted clone deleted after the repoint).
1062 // Accepted only while it is still the block's latest launch
1063 // (by `started_at`, which only a launch or fold moves; a tie
1064 // with another active launch is undecided and rejected —
1065 // Codex P2 on #3576): a
1066 // stale stamp left by pane reuse, with a newer launch since
1067 // folded onto the block, resolves to nothing rather than to
1068 // the older row. Never a fork: a fork is launched under its
1069 // own row id, so a fork reached here is a stale stamp. And
1070 // the row must still relate to what the block names —
1071 // launched from it, or one hop from it — so a stale stamp
1072 // naming an unrelated agent cannot select it (ReAgent P0/P1
1073 // on #3576). Recorded, fail-safe: a launch the promotion
1074 // migration repointed to a clone that was later deleted has
1075 // no lineage left and resolves to nothing until relaunched;
1076 // and `started_at` is wall-clock, so a backward clock step
1077 // between two launches on one block makes the stamped row
1078 // look older — it then resolves to nothing, never to another
1079 // row. (Only an unstamped legacy block, reused, across such a
1080 // step could pick the older launch.)
1081 // Recorded: a legacy continuation stamp naming an id that
1082 // never had a row (m0025 keyed chains to their root) resolves
1083 // to nothing, not to the root — nothing distinguishes it from
1084 // a deleted launch, and no identity is safer than a wrong one.
1085 let mut stmt = conn.prepare(&format!(
1086 "SELECT {INSTANCE_COLUMNS} FROM db_agents a
1087 WHERE a.id = ?2 AND a.last_block_id = ?1 AND a.is_template = 0
1088 AND a.status IN ('running', 'paused') AND a.branch_label = ''
1089 AND (a.parent_template_id = ?3
1090 OR a.parent_template_id IN (
1091 SELECT id FROM db_agents
1092 WHERE parent_template_id = ?3 AND is_template = 0 AND branch_label = '')
1093 )
1094 AND NOT EXISTS (
1095 SELECT 1 FROM db_agents b
1096 WHERE b.last_block_id = ?1 AND b.is_template = 0 AND b.id != a.id
1097 AND b.status IN ('running', 'paused') AND b.started_at >= a.started_at)"
1098 ))?;
1099 return match stmt.query_row(params![block_id, stamped, agent_id], map_instance_row)
1100 {
1101 Ok(a) => Ok(Some(a)),
1102 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
1103 Err(e) => Err(e.into()),
1104 };
1105 }
1106 // Unstamped (a block from before `agentInstanceId`): lineage.
1107 let mut stmt = conn.prepare(&format!(
1108 "SELECT {INSTANCE_COLUMNS} FROM db_agents
1109 WHERE last_block_id = ?1 AND is_template = 0 AND status IN ('running', 'paused')
1110 AND branch_label = ''
1111 AND (parent_template_id = ?2
1112 OR parent_template_id IN (
1113 SELECT id FROM db_agents
1114 WHERE parent_template_id = ?2 AND is_template = 0 AND branch_label = ''))
1115 ORDER BY started_at DESC, updated_at DESC, id DESC
1116 LIMIT 1"
1117 ))?;
1118 return match stmt.query_row(params![block_id, agent_id], map_instance_row) {
1119 Ok(a) => Ok(Some(a)),
1120 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
1121 Err(e) => Err(e.into()),
1122 };
1123 }
1124 // A block whose meta names no agent (from before `agentId`): the
1125 // agent whose latest launch is on it — by launch time, which a
1126 // rename or lifecycle write does not move (Codex P1 on #3576).
1127 let conn = self.conn.lock().unwrap();
1128 let mut stmt = conn.prepare(&format!(
1129 "SELECT {INSTANCE_COLUMNS} FROM db_agents
1130 WHERE last_block_id = ?1 AND is_template = 0 AND status IN ('running', 'paused')
1131 ORDER BY started_at DESC, updated_at DESC, id DESC
1132 LIMIT 1"
1133 ))?;
1134 match stmt.query_row(params![block_id], map_instance_row) {
1135 Ok(a) => Ok(Some(a)),
1136 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
1137 Err(e) => Err(e.into()),
1138 }
1139 }
1140
1141 /// The agent whose latest launch is on `block_id`, regardless of status
1142 /// — with its real `session_id`, so callers that write back to that
1143 /// exact row (keeping `session_id` live as the CLI emits it — see
1144 /// `persist_session_id` /
1145 /// SPEC_PANE_CLOSE_REOPEN_CONTINUITY_GUARANTEE_2026_07_27.md §4.1) have
1146 /// the right id to pass to `instance_update_partial`.
1147 ///
1148 /// When a pane is reused, several rows can name the block. The one the
1149 /// pane runs is the block's own `agentId` (or legacy `agent:id`), while
1150 /// its latest launch is still this block; otherwise the most recent
1151 /// *launch* (`started_at`). Never the most recently *updated* row: a
1152 /// rename or definition edit bumps `updated_at`, and a session id then
1153 /// landed on the renamed agent instead of the one running (#3580).
1154 pub fn instance_get_by_block_id(&self, block_id: &str) -> Result<Option<AgentInstance>, StoreError> {
1155 let shown = self
1156 .get::<crate::backend::obj::Block>(block_id)?
1157 .and_then(|b| crate::backend::obj::block_meta_agent_id(&b.meta).map(str::to_string))
1158 .filter(|id| !id.is_empty());
1159 let conn = self.conn.lock().unwrap();
1160 if let Some(agent_id) = shown {
1161 let mut stmt = conn.prepare(&format!(
1162 "SELECT {INSTANCE_COLUMNS} FROM db_agents
1163 WHERE id = ?1 AND last_block_id = ?2 AND is_template = 0"
1164 ))?;
1165 match stmt.query_row(params![agent_id, block_id], map_instance_row) {
1166 Ok(a) => return Ok(Some(a)),
1167 Err(rusqlite::Error::QueryReturnedNoRows) => {}
1168 Err(e) => return Err(e.into()),
1169 }
1170 }
1171 let mut stmt = conn.prepare(&format!(
1172 "SELECT {INSTANCE_COLUMNS} FROM db_agents
1173 WHERE last_block_id = ?1 AND is_template = 0
1174 ORDER BY started_at DESC, updated_at DESC, id DESC
1175 LIMIT 1"
1176 ))?;
1177 match stmt.query_row(params![block_id], map_instance_row) {
1178 Ok(a) => Ok(Some(a)),
1179 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
1180 Err(e) => Err(e.into()),
1181 }
1182 }
1183}