Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

make forked sessions fully isolated (#3188)

kt603376a19497
diff --git a/crates/pa-daemon/src/agent_roster.rs b/crates/pa-daemon/src/agent_roster.rs
index e2ad9631a6..b47026710b 100644
--- a/crates/pa-daemon/src/agent_roster.rs
+++ b/crates/pa-daemon/src/agent_roster.rs
@@ -328,6 +328,40 @@ impl AgentRoster {
.collect()
}
+ /// The rows a worker's root-slot swap retires (TS `flushRoster`'s
+ /// "swapped in place: also a removal" class): a whole-session
+ /// replacement (`new_session`/`switch_session`/`import_jsonl`/`fork`)
+ /// serves a NEW durable session under the SAME active session id, so
+ /// the row the worker previously owned for that active id describes a
+ /// session it no longer serves. The roster must not keep presenting
+ /// the superseded session as this worker's live root: the agents view
+ /// would show a session nobody serves, and a roster wake by address
+ /// would resolve the id against the wrong file. Only the worker's own
+ /// rows for the fresh entry's active id match — its subagent children
+ /// key under their own active ids and never ride a root swap.
+ pub(crate) fn swapped_out_root_rows(
+ &self,
+ worker_id: &str,
+ fresh: &AgentRosterEntry,
+ ) -> Vec<String> {
+ let Some(active) = fresh
+ .summary
+ .get("activeSessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ else {
+ return Vec::new();
+ };
+ self.entries_for_worker(worker_id)
+ .into_iter()
+ .filter(|entry| entry.agent_id != fresh.agent_id)
+ .filter(|entry| {
+ entry.summary.get("activeSessionId").and_then(Value::as_str) == Some(active)
+ })
+ .map(|entry| entry.agent_id.clone())
+ .collect()
+ }
+
/// All entries in stable (insertion) order for pushes and snapshots.
pub(crate) fn entries(&self) -> Vec<AgentRosterEntry> {
self.entries.values().cloned().collect()
diff --git a/crates/pa-daemon/src/descriptor.rs b/crates/pa-daemon/src/descriptor.rs
index ef81b62531..210d66c668 100644
--- a/crates/pa-daemon/src/descriptor.rs
+++ b/crates/pa-daemon/src/descriptor.rs
@@ -252,6 +252,75 @@ pub fn persist_worker(path: &Path, descriptor: &WorkerDescriptor) -> Result<()>
write_file_atomic(path, &content)
}
+/// The identity-pending side record (the descriptor store's own
+/// durability marker for the root-identity follow): written beside the
+/// descriptor when a moved identity's persist failed on both attempts,
+/// carrying the moved-to identity AND the moment of the move so a
+/// restart never serves the superseded session from the stale record —
+/// and never rolls a NEWER persisted identity back onto an older move
+/// (the boot applies the pending only while it is fresher than the
+/// record's `updated_at`). Removed by the repair — the first persist
+/// that lands the repaired record.
+pub(crate) fn identity_pending_path(descriptor_path: &Path) -> PathBuf {
+ descriptor_path.with_extension("identity-pending")
+}
+
+/// Record the moved-to identity durably (the follow's fallback when the
+/// descriptor write failed: the boot reads this and applies the moved
+/// identity to the resident before any routing or relaunch).
+///
+/// # Errors
+///
+/// Returns an error when the atomic write of the side record fails.
+pub(crate) fn write_identity_pending(
+ descriptor_path: &Path,
+ session_id: &str,
+ session_file: &str,
+ moved_at: &str,
+) -> Result<()> {
+ let record = serde_json::json!({
+ "sessionId": session_id,
+ "sessionFile": session_file,
+ "movedAt": moved_at,
+ });
+ write_file_atomic(
+ &identity_pending_path(descriptor_path),
+ &serde_json::to_string(&record)?,
+ )
+}
+
+/// The moved-to identity a failed follow left beside the descriptor,
+/// with the move's timestamp (`None` when no follow is pending).
+#[must_use]
+pub(crate) fn read_identity_pending(descriptor_path: &Path) -> Option<(String, String, String)> {
+ let content = std::fs::read_to_string(identity_pending_path(descriptor_path)).ok()?;
+ let record: serde_json::Value = serde_json::from_str(&content).ok()?;
+ let session_id = record.get("sessionId").and_then(Value::as_str)?;
+ let session_file = record.get("sessionFile").and_then(Value::as_str)?;
+ let moved_at = record.get("movedAt").and_then(Value::as_str)?;
+ Some((
+ session_id.to_string(),
+ session_file.to_string(),
+ moved_at.to_string(),
+ ))
+}
+
+/// Remove the side record (the repair landed: the descriptor itself now
+/// carries the moved-to identity).
+///
+/// # Errors
+///
+/// Returns an error when the removal fails — a stale side record left
+/// behind could roll a later boot back onto this move, so the callers
+/// surface the failure and the next repair retries the removal.
+pub(crate) fn clear_identity_pending(descriptor_path: &Path) -> Result<()> {
+ match std::fs::remove_file(identity_pending_path(descriptor_path)) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(anyhow!("remove the identity-pending record: {error}")),
+ }
+}
+
#[must_use]
pub fn load_descriptors(
dir: &Path,
diff --git a/crates/pa-daemon/src/ownership.rs b/crates/pa-daemon/src/ownership.rs
index 3292806300..6fb0504053 100644
--- a/crates/pa-daemon/src/ownership.rs
+++ b/crates/pa-daemon/src/ownership.rs
@@ -28,9 +28,21 @@ use crate::supervisor::{Supervisor, ROUTE_TIMEOUT_MS};
impl Supervisor {
/// Resolve the resident a `retry_worker` targets: the direct match on
/// the root active session id or the root persisted session id (TS
- /// `direct`), then the generic selector resolution.
+ /// `direct`), then the generic selector resolution. This is the ONE
+ /// descriptor-scan primitive behind the owned-session arms
+ /// (`complete_owned_session`, `promote_owned_session`,
+ /// `retry_worker`), so the boot-reconciliation quarantine fences
+ /// HERE, by construction: a quarantined resident's descriptor never
+ /// matches — a `retry_worker` with a superseded durable id must not
+ /// reach the live-but-unreconciled worker (its summary would name the
+ /// wrong session, and a disconnected one would RELAUNCH the stale
+ /// persisted create path). The refusal reads as the unknown session —
+ /// the conservative miss, never a route on the unreconciled identity.
async fn resolve_retry_target(&self, selector: &str) -> Result<Arc<ResidentWorker>, String> {
for resident in self.registry.list().await {
+ if resident.identity_quarantined() {
+ continue;
+ }
let matches = {
let descriptor = resident.descriptor.lock().await;
descriptor.root_active_session_id == selector
@@ -286,3 +298,133 @@ impl Supervisor {
)
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use pa_types::daemon::DaemonWorkerDescriptor;
+ use serde_json::json;
+
+ use crate::registry::ResidentWorker;
+ use crate::supervisor::Supervisor;
+ use crate::supervisor_roster::WorkerRosterDelta;
+
+ /// One supervisor with one registered resident whose persisted identity
+ /// (`s0` / `s0.jsonl`) the quarantine fence must never serve.
+ async fn supervisor_with_stale_identity(dir: &std::path::Path) -> Arc<Supervisor> {
+ let supervisor = Arc::new(
+ Supervisor::new(crate::supervisor::SupervisorOptions {
+ socket_path: dir.join("daemon.sock"),
+ agent_dir: dir.join("agent"),
+ })
+ .expect("supervisor"),
+ );
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(json!({
+ "version": 2,
+ "workerId": "w-a",
+ "pid": 0,
+ "socketPath": "/tmp/none.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "token-a",
+ "rootActiveSessionId": "w-a",
+ "rootSessionId": "s0",
+ "sessionFile": dir.join("s0.jsonl").to_string_lossy(),
+ "createdAt": "2026-09-30T00:00:00Z",
+ "updatedAt": "2026-09-30T00:00:00Z",
+ "lifecycle": "ready",
+ "createCommand": { "sessionPath": dir.join("s0.jsonl").to_string_lossy() },
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ supervisor
+ .registry
+ .insert(ResidentWorker::new(
+ "w-a".to_string(),
+ descriptor,
+ dir.join("w-a.json"),
+ ))
+ .await;
+ supervisor
+ }
+
+ /// The boot-reconciliation quarantine fences the owned-session scan:
+ /// a `retry_worker`/`complete`/`promote` selector — the address OR the
+ /// OLD durable id — never reaches a live-but-unreconciled worker
+ /// (whose summary would name the wrong session, or whose relaunch
+ /// would replay the stale persisted create path). The live word
+ /// (the worker's own roster push) reconciles the identity and the
+ /// scan serves again — on the reconciled identity only.
+ #[tokio::test]
+ async fn the_owned_session_scan_refuses_a_quarantined_identity() {
+ let dir = std::env::temp_dir().join(format!("pa-own-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = supervisor_with_stale_identity(&dir).await;
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+
+ // The quarantined boot outcome: every owned-session selector
+ // refuses — the address AND the stale persisted durable id.
+ resident.mark_identity_quarantined();
+ assert!(
+ supervisor.resolve_retry_target("w-a").await.is_err(),
+ "the quarantined address never serves the owned-session arms"
+ );
+ assert!(
+ supervisor.resolve_retry_target("s0").await.is_err(),
+ "the stale persisted durable id never reaches the worker"
+ );
+
+ // The live word: the worker's own roster push (no command
+ // channel involved) reconciles the identity onto sA.
+ let summary = json!({
+ "id": "w-a",
+ "lifecycle": "live",
+ "activity": "idle",
+ "isSessionActive": false,
+ "activeSessionId": "w-a",
+ "sessionId": "sA",
+ "sessionFile": dir.join("a.jsonl").to_string_lossy(),
+ "sessionName": "owned",
+ "cwd": dir.to_string_lossy(),
+ "rlmDepth": 0,
+ "runtimeKind": "top-level",
+ "messageCount": 1,
+ "attachedClients": 0,
+ "thinkingLevel": "default",
+ "workerState": "ready",
+ });
+ let response = supervisor
+ .handle_worker_roster_delta(
+ "d",
+ "worker_roster_delta",
+ WorkerRosterDelta {
+ worker_token: "token-a".to_string(),
+ summary,
+ removed: Vec::new(),
+ sequence: Some(1),
+ worker_instance_id: Some("i1".to_string()),
+ },
+ )
+ .await;
+ assert!(response.success, "the delta applied: {response:?}");
+
+ // The scan serves again — the address resolves, and the OLD
+ // durable id stays unresolvable (the identity moved; the stale
+ // persisted id must never reach the worker again).
+ let resolved = supervisor
+ .resolve_retry_target("w-a")
+ .await
+ .expect("the address serves once reconciled");
+ assert_eq!(
+ resolved.descriptor.lock().await.root_session_id.as_deref(),
+ Some("sA"),
+ "the served identity is the reconciled one"
+ );
+ assert!(
+ supervisor.resolve_retry_target("s0").await.is_err(),
+ "the superseded durable id never resolves again"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/pa-daemon/src/registry.rs b/crates/pa-daemon/src/registry.rs
index 4d0e03f5db..48e6e4ea14 100644
--- a/crates/pa-daemon/src/registry.rs
+++ b/crates/pa-daemon/src/registry.rs
@@ -168,6 +168,21 @@ pub(crate) struct ResidentWorker {
/// replacement-aware route clones a receiver and sleeps until the
/// worker is route-ready or retired).
route_state_tx: tokio::sync::watch::Sender<WorkerRouteState>,
+ /// The root-identity transition's persist is unresolved (the
+ /// descriptor moved but the durable record write failed): the next
+ /// roster write re-runs the transition's persist from the live state
+ /// before a restart can replay the superseded session.
+ identity_persist_pending: AtomicBool,
+ /// The boot-reconciliation quarantine: a resident adopted from a
+ /// persisted record whose live reconciliation pull FAILED is fenced
+ /// from every identity-based route (the selector resolution, the
+ /// by-file reuse, the stale-id rebind) until the live word lands (an
+ /// accepted roster write) or the worker's death removes the resident.
+ /// A failed pull is not proof the worker is dead: routing on the
+ /// unreconciled persisted identity can deliver across sessions (the
+ /// fork leak's boot form), so the fence refuses — the conservative
+ /// miss, never a mis-delivery.
+ identity_quarantined: AtomicBool,
/// Monotonic connection epoch: only the pumps of the current
/// connection may flip `connected` false, so a superseded socket's
/// late EOF cannot retire a live replacement.
@@ -226,6 +241,8 @@ impl ResidentWorker {
cron_snapshot: Mutex::new(None),
heartbeat_snapshot_generation: AtomicU64::new(0),
route_state_tx,
+ identity_persist_pending: AtomicBool::new(false),
+ identity_quarantined: AtomicBool::new(false),
connection_epoch: AtomicU64::new(0),
compaction: crate::compaction_supervision::CompactionSupervision::default(),
})
@@ -335,6 +352,49 @@ impl ResidentWorker {
self.publish_route_state(|state| state.retired = true);
}
+ /// Whether the root-identity transition's durable record write is
+ /// still unresolved (the live descriptor moved; the persist failed).
+ pub(crate) fn identity_persist_pending(&self) -> bool {
+ self.identity_persist_pending
+ .load(std::sync::atomic::Ordering::SeqCst)
+ }
+
+ /// Mark the root-identity persist unresolved: the next roster write
+ /// repairs it from the live state.
+ pub(crate) fn mark_identity_persist_pending(&self) {
+ self.identity_persist_pending
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+
+ /// Clear the unresolved marker (the durable record matches the live
+ /// identity again).
+ pub(crate) fn clear_identity_persist_pending(&self) {
+ self.identity_persist_pending
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ }
+
+ /// Fence this resident from every identity-based route (the
+ /// boot-reconciliation quarantine: the persisted identity was not
+ /// reconciled from the live worker).
+ pub(crate) fn mark_identity_quarantined(&self) {
+ self.identity_quarantined
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+
+ /// Open the routing again: an accepted roster write carried the
+ /// identity follow, so the live identity is reconciled.
+ pub(crate) fn clear_identity_quarantine(&self) {
+ self.identity_quarantined
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ }
+
+ /// Whether this resident is fenced from identity-based routing (the
+ /// unreconciled quarantine).
+ pub(crate) fn identity_quarantined(&self) -> bool {
+ self.identity_quarantined
+ .load(std::sync::atomic::Ordering::SeqCst)
+ }
+
/// Selector labels: root active session id, session-file stem, name.
pub(crate) async fn labels(&self) -> (String, String, String) {
let descriptor = self.descriptor.lock().await;
@@ -499,6 +559,14 @@ impl SessionRegistry {
);
let mut matches = Vec::new();
for resident in self.list().await {
+ // The boot-reconciliation quarantine: an unreconciled
+ // persisted identity never serves a by-file reuse (a create
+ // over the superseded file must launch fresh, and a create
+ // over the worker's own file answers the lease refusal —
+ // never this worker on the wrong session).
+ if resident.identity_quarantined() {
+ continue;
+ }
let owned = resident
.descriptor
.lock()
@@ -553,13 +621,22 @@ impl SessionRegistry {
/// Resolve one session worker by any accepted selector: the full root
/// active session id, a suffix of it, the session-file stem, or the
- /// session name. Errors for unknown and ambiguous selectors.
+ /// session name. Errors for unknown and ambiguous selectors. A
+ /// quarantined resident never resolves (the unreconciled boot
+ /// identity): the failure reads as the unknown session, and the
+ /// client's own retry drives the reconciliation retry — the
+ /// conservative miss, never a route on the persisted identity.
pub(crate) async fn resolve(&self, selector: &str) -> Result<Arc<ResidentWorker>> {
if let Some(resident) = self.get(selector).await {
- return Ok(resident);
+ if !resident.identity_quarantined() {
+ return Ok(resident);
+ }
}
let mut matches: Vec<(Arc<ResidentWorker>, String, String)> = Vec::new();
for resident in self.list().await {
+ if resident.identity_quarantined() {
+ continue;
+ }
let (root_id, file_stem, name) = resident.labels().await;
if selector_matches(&root_id, selector)
|| selector_matches(&file_stem, selector)
diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rs
index 5b2735b3f2..a2d99d1dc4 100644
--- a/crates/pa-daemon/src/supervisor.rs
+++ b/crates/pa-daemon/src/supervisor.rs
@@ -13,6 +13,7 @@ mod clients;
mod launch_budget;
mod notes;
mod options;
+mod root_identity;
mod routing;
mod sessions;
mod signals_shutdown;
diff --git a/crates/pa-daemon/src/supervisor/adoption.rs b/crates/pa-daemon/src/supervisor/adoption.rs
index cc25dadd7c..e31401ffcc 100644
--- a/crates/pa-daemon/src/supervisor/adoption.rs
+++ b/crates/pa-daemon/src/supervisor/adoption.rs
@@ -174,6 +174,14 @@ impl Supervisor {
let pid = descriptor.pid;
let journal_path = PathBuf::from(&descriptor.recovery_journal_path);
let resident = ResidentWorker::new(worker_id.clone(), descriptor, path);
+ // The durable pending FIRST: a failed identity persist left a side
+ // record beside this descriptor carrying the moved-to identity —
+ // apply it before any routing, relaunch, or revival can act on the
+ // stale record (a revived worker replays the moved-to session's
+ // create path), and retry the record's persist: the repair removes
+ // the side record, a failure arms the resident's pending marker
+ // for the first roster write.
+ self.apply_identity_pending(&resident).await;
// The stop tombstone outranks liveness (TS's stop ownership: the
// stop was durable intent BEFORE the worker was told): a
// supervisor that died between the tombstone and the worker's
@@ -196,6 +204,34 @@ impl Supervisor {
.connect_worker(&resident, worker_connect_deadline())
.await;
if adopted.is_ok() {
+ // The boot reconciliation (the root-identity seam): the
+ // adopted worker already serves a session this supervisor
+ // has only ever seen through its PERSISTED record — and
+ // the record can name a superseded session (a whole-session
+ // replacement whose identity persist failed before the
+ // restart, or any descriptor the restart re-adopted
+ // mid-flight). Pull the live state BEFORE the routing
+ // opens: the roster write carries the identity follow, so
+ // the descriptor, the persisted record, and the binding
+ // re-bind onto the session the worker actually serves
+ // before a single client route can resolve them. A failed
+ // pull serves the persisted identity (logged) until the
+ // next roster write runs the follow from the live state.
+ if !self.refresh_roster_entry(&resident).await {
+ // A failed pull is not proof the worker is dead: the
+ // persisted identity is unreconciled, so the resident
+ // is quarantined from every identity route until the
+ // live word lands (a slow pull retries on the
+ // backoff below; the worker's own roster push or a
+ // later pull clears the fence). The routing refuses
+ // (the conservative miss) instead of serving the
+ // superseded identity.
+ resident.mark_identity_quarantined();
+ self.spawn_identity_reconciliation_retry(&resident);
+ self.log_line(&format!(
+ "session worker {worker_id}: the boot reconciliation pull failed; the resident is quarantined from routing until the live state lands"
+ ));
+ }
// The adopted worker's session already exists (its create
// ran before the supervisor restart): routed client
// commands may reach it immediately.
@@ -555,6 +591,13 @@ impl Supervisor {
descriptor,
descriptor_path,
);
+ // The durable pending (the same repair the descriptor adoption
+ // runs): the registration rebuilt the resident from the PERSISTED
+ // record — apply the failed follow's side record before the
+ // routing opens, so the in-memory identity serves the moved-to
+ // session even when the reconciliation pull below fails (the
+ // quarantine fences the routes until the live word lands).
+ self.apply_identity_pending(&resident).await;
// A tombstoned identity is mid-stop (TS `adoptOrRecoverWorker`'s
// stopRequestedAt branch): adoption finishes the stop — the
// original command forwarded, the variant's finalize belt, the
@@ -595,12 +638,33 @@ impl Supervisor {
}
self.connect_worker(&resident, worker_connect_deadline())
.await?;
+ // The boot reconciliation (the root-identity seam): registration
+ // rebuilt the resident from the PERSISTED record — and the worker
+ // already serves a whole-session replacement (a fork/switch the
+ // record never learned, or whose identity persist failed before
+ // this restart). Pull the live state BEFORE the resident joins the
+ // registry: the roster write carries the identity follow, so the
+ // descriptor, the persisted record, and the binding re-bind onto
+ // the session the worker actually serves before any client route
+ // can resolve them (the registration block above recorded the
+ // persisted identity — this heals it from the live truth).
+ if !self.refresh_roster_entry(&resident).await {
+ // A failed pull is not proof the worker is dead: the persisted
+ // identity is unreconciled, so the resident is quarantined
+ // from every identity route until the live word lands (a slow
+ // pull retries; the worker's own roster push or a later pull
+ // clears the fence).
+ resident.mark_identity_quarantined();
+ self.spawn_identity_reconciliation_retry(&resident);
+ self.log_line(&format!(
+ "session worker {worker_id}: the registration reconciliation pull failed; the resident is quarantined from routing until the live state lands"
+ ));
+ }
// The self-registered worker's session already exists: routed
// client commands may reach it immediately.
resident.note_session_ready();
self.registry.insert(Arc::clone(&resident)).await;
self.spawn_monitor(Arc::clone(&resident), None, registration.pid);
- self.refresh_roster_entry(&resident).await;
self.log_line(&format!(
"adopted session worker {worker_id} via self-registration"
));
diff --git a/crates/pa-daemon/src/supervisor/root_identity.rs b/crates/pa-daemon/src/supervisor/root_identity.rs
new file mode 100644
index 0000000000..2618b817e5
--- /dev/null
+++ b/crates/pa-daemon/src/supervisor/root_identity.rs
@@ -0,0 +1,957 @@
+//! The root-identity follow (the fork-isolation seam, operator bug #5): a
+//! whole-session replacement (`new_session`/`switch_session`/`import_jsonl`/
+//! `fork`) moves the worker onto a NEW durable session under its UNCHANGED
+//! active session id, and the supervisor-side identity follows the roster
+//! when it does (the port of TS `syncRootDescriptorFromRosterEntry` onto
+//! the Rust roster writes).
+//!
+//! The follow is what detaches a forked session. Without it every
+//! supervisor-side selector keeps addressing the superseded session file
+//! even though the worker serves the moved-to one: the create-reuse seam
+//! answers a re-open of the ORIGINAL file with the fork's worker (so a
+//! message sent in the original lands in the fork), a prompt by the
+//! original's durable id resolves the fork worker, and a crash of the
+//! fork worker rebinds its stale address onto whatever worker later takes
+//! the original file. The follow re-binds the resident descriptor (the
+//! durable id, the session file, and the durable create command the
+//! respawn paths replay), the persisted worker record, and the
+//! stale-active-id binding table onto the session the worker actually
+//! serves — exactly when the roster first sees it.
+//!
+//! The transition is ONE per-worker critical section: the roster write,
+//! the descriptor move, the durable persist, and the binding record all
+//! run under the resident's descriptor lock — the same lock every
+//! identity reader takes (the registry's labels and file matches, the
+//! create-reuse classification, the wake, the stale-id rebind). Two
+//! properties follow: a routing reader can never observe a half-applied
+//! swap (the move, its persist, and its binding land together or the
+//! reader waits), and an older follow can never overwrite a newer one
+//! (each accepted roster row carries its own follow inside the same
+//! guard, so the persists apply in accept order — the last accepted
+//! row's identity is always the one that stays).
+
+use std::sync::Arc;
+
+use pa_types::daemon::DaemonWorkerDescriptor;
+use serde_json::Value;
+use tokio::sync::MutexGuard;
+
+use crate::registry::ResidentWorker;
+
+use super::Supervisor;
+
+/// The reconciliation retry's backoff cadence: 250ms base doubling to a
+/// 5s cap, the registration loop's own shape (a slow-but-alive worker's
+/// boot pull times out; the retry converges on its answer).
+const RECONCILIATION_BACKOFF_MS: u64 = 250;
+const RECONCILIATION_BACKOFF_MAX_MS: u64 = 5_000;
+
+impl Supervisor {
+ /// The boot's durable-pending repair (the descriptor store's own
+ /// fallback for a failed identity persist): a side record beside the
+ /// descriptor carries the moved-to identity — apply it to the
+ /// resident BEFORE any routing or relaunch can use the stale record
+ /// (a revived worker replays the moved-to session's create path, not
+ /// the superseded one), then retry the record's persist; the first
+ /// roster write that persists the repaired record removes the side
+ /// record. The in-memory marker arms while the record still lags.
+ pub(crate) async fn apply_identity_pending(&self, resident: &Arc<ResidentWorker>) {
+ let Some((session_id, session_file, moved_at)) =
+ crate::descriptor::read_identity_pending(&resident.descriptor_path)
+ else {
+ return;
+ };
+ let mut descriptor = resident.descriptor.lock().await;
+ // The freshness gate: the side record only wins while the record is
+ // STRICTLY OLDER than the move — a later swap whose persist
+ // succeeded (and whose side-record removal failed) must never be
+ // rolled back onto this older pending, including the same-
+ // millisecond case (a repair persist that lands at the exact
+ // moment of the move's stamp carries the moved identity, so the
+ // pending is obsolete at equality). An obsolete record is
+ // cleared, not applied.
+ if descriptor.updated_at.as_str() >= moved_at.as_str() {
+ drop(descriptor);
+ if let Err(error) = crate::descriptor::clear_identity_pending(&resident.descriptor_path)
+ {
+ self.log_line(&format!(
+ "the obsolete identity-pending record for worker {} did not clear: {error:#}",
+ resident.worker_id
+ ));
+ }
+ return;
+ }
+ if descriptor.root_session_id.as_deref() != Some(session_id.as_str())
+ || descriptor.session_file.as_deref() != Some(session_file.as_str())
+ {
+ descriptor.root_session_id = Some(session_id.clone());
+ descriptor.session_file = Some(session_file.clone());
+ descriptor.create_command.session_path = Some(session_file.clone());
+ descriptor.create_command.no_session = None;
+ }
+ match crate::descriptor::persist_worker(&resident.descriptor_path, &descriptor) {
+ Ok(()) => {
+ resident.clear_identity_persist_pending();
+ if let Err(error) =
+ crate::descriptor::clear_identity_pending(&resident.descriptor_path)
+ {
+ self.log_line(&format!(
+ "the identity-pending record for worker {} did not clear after the boot repair: {error:#}",
+ resident.worker_id
+ ));
+ }
+ }
+ Err(error) => {
+ resident.mark_identity_persist_pending();
+ self.log_line(&format!(
+ "the boot applied worker {}'s pending identity but the record persist failed (repairing on the first roster write): {error:#}",
+ resident.worker_id
+ ));
+ }
+ }
+ }
+
+ /// The quarantine's retry path: a slow-but-alive worker's boot
+ /// reconciliation pull can time out, and no roster push is guaranteed
+ /// while it idles — re-run the reconciliation on a backoff until the
+ /// live word lands (an accepted roster write clears the quarantine
+ /// wherever it arrives: the pull below, the worker's own delta, or a
+ /// refresh) or the worker leaves the registry (the supervisor's own
+ /// death verdict — only then may the persisted identity serve, via
+ /// the lazy re-open).
+ pub(crate) fn spawn_identity_reconciliation_retry(
+ self: &Arc<Self>,
+ resident: &Arc<ResidentWorker>,
+ ) {
+ let supervisor = Arc::clone(self);
+ let resident = Arc::clone(resident);
+ tokio::spawn(async move {
+ let mut backoff_ms = RECONCILIATION_BACKOFF_MS;
+ loop {
+ tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
+ backoff_ms = (backoff_ms * 2).min(RECONCILIATION_BACKOFF_MAX_MS);
+ if supervisor
+ .shutting_down
+ .load(std::sync::atomic::Ordering::SeqCst)
+ {
+ // The shutdown exit (the background loops' join
+ // discipline): a stopping daemon never leaves the
+ // retry spinning behind.
+ return;
+ }
+ if !resident.identity_quarantined() {
+ // The live word already landed elsewhere (the
+ // worker's own roster push or a concurrent pull).
+ return;
+ }
+ if supervisor.registry.get(&resident.worker_id).await.is_none() {
+ // The death verdict: the persisted identity serves the
+ // lazy re-open, never this quarantined resident.
+ return;
+ }
+ if supervisor.refresh_roster_entry(&resident).await {
+ // The pull landed: the roster write carried the
+ // identity follow and cleared the quarantine.
+ return;
+ }
+ }
+ });
+ }
+
+ /// Follow the roster's root row for one worker's address, under the
+ /// resident's descriptor guard the caller holds across the whole
+ /// transition: when the row names a different durable session than
+ /// the descriptor, the descriptor, the persisted record, the durable
+ /// create command, and the binding table all move onto it — the same
+ /// identity trio the create path writes, re-derived from the worker's
+ /// live summary. Idempotent: a row matching the persisted descriptor
+ /// moves nothing, so the registration/adoption/create refresh pulls
+ /// stay no-ops.
+ /// Returns whether the worker's root row carries the live identity (a
+ /// root-identity-bearing write): `false` means the write that ran was
+ /// NOT the root's own (a subagent/child summary keying under its own
+ /// address, before the root's first push landed), so the boot
+ /// reconciliation quarantine must stay — a child delta never lifts
+ /// the root's fence.
+ pub(crate) fn sync_root_identity_from_roster(
+ &self,
+ resident: &Arc<ResidentWorker>,
+ descriptor: &mut MutexGuard<'_, DaemonWorkerDescriptor>,
+ ) -> bool {
+ let summary = {
+ let roster = self.roster.lock().unwrap();
+ roster
+ .by_active_session_id(&resident.worker_id)
+ .map(|entry| entry.summary.clone())
+ };
+ let Some(summary) = summary else {
+ // The roster holds no root row for this worker's address: the
+ // registration/adoption seeding has not landed it yet, and
+ // the next write triggers the follow.
+ return false;
+ };
+ let (session_id, session_file) = match (
+ summary.get("sessionId").and_then(Value::as_str),
+ summary.get("sessionFile").and_then(Value::as_str),
+ ) {
+ (Some(session_id), Some(session_file))
+ if !session_id.is_empty() && !session_file.is_empty() =>
+ {
+ (session_id.to_string(), session_file.to_string())
+ }
+ // A row without a durable identity (an in-memory `no_session`
+ // session) names no file to follow: its worker never had one —
+ // but the row IS the root's own live word, so the quarantine
+ // lifts with it (the follow has nothing durable to move).
+ _ => return true,
+ };
+ if descriptor.root_session_id.as_deref() == Some(session_id.as_str())
+ && descriptor.session_file.as_deref() == Some(session_file.as_str())
+ && !resident.identity_persist_pending()
+ {
+ return true;
+ }
+ descriptor.root_session_id = Some(session_id.clone());
+ descriptor.session_file = Some(session_file.clone());
+ // The durable create command must reopen the moved-to session on
+ // relaunch, or a respawned worker would replay the superseded
+ // session instead of the one it serves. A path-backed follow is a
+ // persisted replay by construction: the worker's create refuses
+ // the `noSession`+`sessionPath` combination, so a worker that
+ // started `noSession` and then switched onto a real file must
+ // drop the in-memory flag with the path (TS leaves it, but its
+ // relaunch never replays that contradiction).
+ descriptor.create_command.session_path = Some(session_file.clone());
+ descriptor.create_command.no_session = None;
+ // The durable record is the restart edge: a failed persist leaves
+ // the LIVE routing correct (the descriptor above already moved)
+ // while the persisted identity lags — retry once here, then keep
+ // the transition marked pending so the next roster write (any
+ // delta or refresh pull) repairs it from the live state. A
+ // restart in that window re-runs the reconciliation itself: the
+ // boot paths pull the live state BEFORE the routing opens, so the
+ // adoption/registration re-binds and re-persists the moved-to
+ // identity before a single client route can resolve it.
+ // One in-transition retry: a transient write failure (a scan, an
+ // fs flush) heals without waiting for the next roster write.
+ let persisted = crate::descriptor::persist_worker(&resident.descriptor_path, descriptor)
+ .or_else(|error| {
+ let retry =
+ crate::descriptor::persist_worker(&resident.descriptor_path, descriptor);
+ match retry {
+ Ok(()) => Ok(()),
+ Err(_retry_failed) => Err(error),
+ }
+ });
+ match persisted {
+ Ok(()) => {
+ resident.clear_identity_persist_pending();
+ // The repair landed: the descriptor itself carries the
+ // moved-to identity, and the side record's job is done. A
+ // failed removal leaves a stale record a later boot could
+ // roll back onto — surface it (the next repair retries).
+ if let Err(clear_error) =
+ crate::descriptor::clear_identity_pending(&resident.descriptor_path)
+ {
+ self.log_line(&format!(
+ "the identity-pending record for worker {} did not clear after the repair (retrying on the next roster write): {clear_error:#}",
+ resident.worker_id
+ ));
+ }
+ }
+ Err(error) => {
+ resident.mark_identity_persist_pending();
+ // The durable pending (the descriptor store's own
+ // fallback): record the moved-to identity beside the
+ // descriptor so a restart applies it before any routing
+ // or relaunch — the in-memory marker alone dies with the
+ // process, and the stale record would serve the
+ // superseded session.
+ if let Err(pending_error) = crate::descriptor::write_identity_pending(
+ &resident.descriptor_path,
+ &session_id,
+ &session_file,
+ &crate::util::now_iso(),
+ ) {
+ // The last resort: the side record could not land
+ // either. The boot's live reconciliation (a worker
+ // still alive) or the death verdict (a lazy re-open)
+ // remain the safety nets — surface both failures.
+ self.log_line(&format!(
+ "session identity move for {} persisted neither record nor pending side record: {pending_error:#}",
+ resident.worker_id
+ ));
+ }
+ self.log_line(&format!(
+ "session identity move for {} did not persist (the pending side record carries it; repairing on the next roster write): {error:#}",
+ resident.worker_id
+ ));
+ self.note_daemon_event("root_identity_persist_failed", None);
+ }
+ }
+ // The binding table learns the moved-to identity here: the
+ // worker's address now carries the fork's durable session, and
+ // the address's crash-window rebind resolves the fork's file —
+ // never the original another worker may have re-opened. Recorded
+ // under the same guard as the move: a stale-id rebind never
+ // resolves a binding that outlived its descriptor.
+ self.record_session_binding(
+ &resident.worker_id,
+ Some(session_id.as_str()),
+ Some(session_file.as_str()),
+ );
+ // The durable ids never ride the log (the logging discipline);
+ // the worker's address — the established log id — identifies the
+ // move, and the roster surfaces the identity.
+ self.log_line(&format!(
+ "session identity moved: worker {} now serves its current session (the root-identity follow ran)",
+ resident.worker_id
+ ));
+ true
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use pa_types::daemon::DaemonWorkerDescriptor;
+ use serde_json::json;
+
+ use crate::registry::ResidentWorker;
+ use crate::supervisor::Supervisor;
+ use crate::supervisor_roster::WorkerRosterDelta;
+
+ /// A supervisor with one registered resident whose address matches its
+ /// roster row (`w-a`), carrying a persisted root identity the deltas can
+ /// move.
+ async fn supervisor_with_movable_worker(dir: &std::path::Path) -> Arc<Supervisor> {
+ let supervisor = Arc::new(
+ Supervisor::new(crate::supervisor::SupervisorOptions {
+ socket_path: dir.join("daemon.sock"),
+ agent_dir: dir.join("agent"),
+ })
+ .expect("supervisor"),
+ );
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(json!({
+ "version": 2,
+ "workerId": "w-a",
+ "pid": 0,
+ "socketPath": "/tmp/none.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "token-a",
+ "rootActiveSessionId": "w-a",
+ "rootSessionId": "s0",
+ "sessionFile": dir.join("s0.jsonl").to_string_lossy(),
+ "createdAt": "2026-09-30T00:00:00Z",
+ "updatedAt": "2026-09-30T00:00:00Z",
+ "lifecycle": "ready",
+ "createCommand": { "sessionPath": dir.join("s0.jsonl").to_string_lossy() },
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ let resident = ResidentWorker::new("w-a".to_string(), descriptor, dir.join("w-a.json"));
+ supervisor.registry.insert(resident).await;
+ supervisor
+ }
+
+ /// One root-slot swap summary: the worker `w-a` now serves `session`
+ /// out of `file`.
+ fn swap_summary(dir: &std::path::Path, session: &str, file: &str) -> serde_json::Value {
+ json!({
+ "id": "w-a",
+ "lifecycle": "live",
+ "activity": "idle",
+ "isSessionActive": false,
+ "activeSessionId": "w-a",
+ "sessionId": session,
+ "sessionFile": dir.join(file).to_string_lossy(),
+ "sessionName": "movable",
+ "cwd": dir.to_string_lossy(),
+ "rlmDepth": 0,
+ "runtimeKind": "top-level",
+ "messageCount": 1,
+ "attachedClients": 0,
+ "thinkingLevel": "default",
+ "workerState": "ready",
+ })
+ }
+
+ /// Drive one accepted roster delta for the worker (a sequenced
+ /// generation, the real handler path).
+ async fn drive_delta(supervisor: &Arc<Supervisor>, summary: serde_json::Value, sequence: u64) {
+ let response = supervisor
+ .handle_worker_roster_delta(
+ "d",
+ "worker_roster_delta",
+ WorkerRosterDelta {
+ worker_token: "token-a".to_string(),
+ summary,
+ removed: Vec::new(),
+ sequence: Some(sequence),
+ worker_instance_id: Some("i1".to_string()),
+ },
+ )
+ .await;
+ assert!(response.success, "the delta applied: {response:?}");
+ }
+
+ /// The full identity state for the worker's address, as a triple of
+ /// (the live descriptor's root session id, its session file, the
+ /// persisted record's root session id) plus the binding table's
+ /// session id — every identity reader funnels through the same values.
+ async fn identity_state(
+ supervisor: &Arc<Supervisor>,
+ ) -> (
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ ) {
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+ let (root_session_id, session_file) = {
+ let descriptor = resident.descriptor.lock().await;
+ (
+ descriptor.root_session_id.clone(),
+ descriptor.session_file.clone(),
+ )
+ };
+ let persisted: Option<String> = std::fs::read_to_string(&resident.descriptor_path)
+ .ok()
+ .and_then(|content| serde_json::from_str::<DaemonWorkerDescriptor>(&content).ok())
+ .and_then(|record| record.root_session_id);
+ let binding = supervisor
+ .session_bindings
+ .binding_for("w-a")
+ .and_then(|binding| binding.session_id.clone());
+ (root_session_id, session_file, persisted, binding)
+ }
+
+ /// The expected (descriptor id, file, record id, binding id) for one
+ /// moved-to session.
+ fn expect_state(
+ dir: &std::path::Path,
+ session: &str,
+ file: &str,
+ ) -> (
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ ) {
+ let file = dir.join(file).to_string_lossy().to_string();
+ (
+ Some(session.to_string()),
+ Some(file),
+ Some(session.to_string()),
+ Some(session.to_string()),
+ )
+ }
+
+ /// FINDING 1's pin: successive root-slot swaps (the A → B → A chain a
+ /// fork/switch sequence produces) land the identity on the FINAL row —
+ /// an older follow never persists over a newer one — and a CONCURRENT
+ /// burst of swaps converges on whatever row the roster accepted last,
+ /// with the descriptor, the persisted record, and the binding all
+ /// naming the same session.
+ #[tokio::test]
+ async fn successive_swaps_land_the_identity_on_the_final_row() {
+ let dir = std::env::temp_dir().join(format!("pa-root-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = supervisor_with_movable_worker(&dir).await;
+
+ // A → B: each accepted row moves the whole triple.
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 1).await;
+ assert_eq!(
+ identity_state(&supervisor).await,
+ expect_state(&dir, "sA", "a.jsonl"),
+ "the first swap moved the descriptor, the record, and the binding"
+ );
+ drive_delta(&supervisor, swap_summary(&dir, "sB", "b.jsonl"), 2).await;
+ assert_eq!(
+ identity_state(&supervisor).await,
+ expect_state(&dir, "sB", "b.jsonl"),
+ "the second swap moved the whole triple"
+ );
+
+ // The A → B → A chain: the final row wins, and no older follow can
+ // overwrite it afterwards.
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 3).await;
+ assert_eq!(
+ identity_state(&supervisor).await,
+ expect_state(&dir, "sA", "a.jsonl"),
+ "the return swap landed on the final row"
+ );
+
+ // A CONCURRENT burst of three swaps (F1, F2, F1 again): whatever
+ // arrival order the accept gate admits, the live descriptor, the
+ // persisted record, and the binding must name the identity of the
+ // roster's final accepted row — the permanent-overwrite class
+ // leaves a triple that disagrees with the roster.
+ let burst = tokio::join!(
+ drive_delta(&supervisor, swap_summary(&dir, "sF1", "f1.jsonl"), 4),
+ drive_delta(&supervisor, swap_summary(&dir, "sF2", "f2.jsonl"), 5),
+ drive_delta(&supervisor, swap_summary(&dir, "sF1", "f1.jsonl"), 6),
+ );
+ let _ = burst;
+ let (roster_session, roster_file) = {
+ let roster = supervisor.roster.lock().unwrap();
+ let entry = roster
+ .by_active_session_id("w-a")
+ .expect("the worker's root row");
+ (
+ entry.summary["sessionId"].as_str().unwrap().to_string(),
+ entry.summary["sessionFile"].as_str().unwrap().to_string(),
+ )
+ };
+ let (root_session_id, session_file, persisted, binding) = identity_state(&supervisor).await;
+ assert_eq!(
+ root_session_id.as_deref(),
+ Some(roster_session.as_str()),
+ "the descriptor names the roster's final row (the values print above)"
+ );
+ assert_eq!(session_file.as_deref(), Some(roster_file.as_str()));
+ assert_eq!(persisted.as_deref(), Some(roster_session.as_str()));
+ assert_eq!(binding.as_deref(), Some(roster_session.as_str()));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// FINDING 3's pin: a failed durable-record write leaves the LIVE
+ /// routing on the moved identity and marks the transition unresolved;
+ /// the next roster write repairs the record from the live state. The
+ /// restart edge is covered by the boot reconciliation (the e2e restart
+ /// pin): the boot paths pull the live state before the routing opens,
+ /// so the stale persisted record never serves.
+ #[tokio::test]
+ async fn a_failed_identity_persist_is_repaired_by_the_next_roster_write() {
+ let dir = std::env::temp_dir().join(format!("pa-root-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = supervisor_with_movable_worker(&dir).await;
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+
+ // The record path cannot take a file: the atomic write's rename
+ // onto a directory fails deterministically.
+ std::fs::remove_file(&resident.descriptor_path).ok();
+ std::fs::create_dir_all(&resident.descriptor_path).unwrap();
+
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 1).await;
+ assert_eq!(
+ resident.descriptor.lock().await.root_session_id.as_deref(),
+ Some("sA"),
+ "the live descriptor moved even though the record write failed"
+ );
+ assert!(
+ resident.identity_persist_pending(),
+ "the unresolved persist is marked for repair"
+ );
+ assert!(
+ supervisor
+ .session_bindings
+ .binding_for("w-a")
+ .is_some_and(|binding| binding.session_id.as_deref() == Some("sA")),
+ "the binding follows the live identity (the routing is correct while the record lags)"
+ );
+ let pending = crate::descriptor::read_identity_pending(&resident.descriptor_path)
+ .expect("the durable pending landed");
+ assert_eq!(pending.0, "sA");
+ assert_eq!(
+ pending.1,
+ dir.join("a.jsonl").to_string_lossy().to_string(),
+ "the double-failed persist durably recorded the moved-to identity beside the record"
+ );
+
+ // The repair: the next write re-runs the transition's persist from
+ // the live state — even a NO-CHANGE row (the identity already
+ // moved in memory; the pending marker is what forces the retry).
+ std::fs::remove_dir_all(&resident.descriptor_path).unwrap();
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 2).await;
+ assert!(
+ !resident.identity_persist_pending(),
+ "the repair cleared the marker"
+ );
+ let record: DaemonWorkerDescriptor = serde_json::from_str(
+ &std::fs::read_to_string(&resident.descriptor_path).expect("the repaired record"),
+ )
+ .expect("the record parses");
+ assert_eq!(record.root_session_id.as_deref(), Some("sA"));
+ assert_eq!(
+ record.session_file.as_deref(),
+ Some(dir.join("a.jsonl").to_string_lossy().to_string().as_str())
+ );
+ assert!(
+ crate::descriptor::read_identity_pending(&resident.descriptor_path).is_none(),
+ "the repair removed the pending side record"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// The durable pending across a restart (the bot-wave finding): the
+ /// record's persist failed on both attempts, so the side record
+ /// carries the moved-to identity — a boot reading the STALE record
+ /// applies the pending identity BEFORE any routing or relaunch can
+ /// act on it, and retries the record's persist: the routing serves
+ /// the moved identity, never the superseded one, and the side record
+ /// dies with the repair.
+ #[tokio::test]
+ async fn a_durable_pending_moves_the_boot_identity_before_any_routing() {
+ let dir = std::env::temp_dir().join(format!("pa-root-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = supervisor_with_movable_worker(&dir).await;
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+
+ // The double-failed persist leaves the durable pending beside the
+ // stale record.
+ std::fs::remove_file(&resident.descriptor_path).ok();
+ std::fs::create_dir_all(&resident.descriptor_path).unwrap();
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 1).await;
+ assert!(
+ resident.identity_persist_pending(),
+ "the in-memory marker armed"
+ );
+ assert!(
+ crate::descriptor::read_identity_pending(&resident.descriptor_path).is_some(),
+ "the side record landed"
+ );
+
+ // THE RESTART: the stale record back on disk (the boot's only word
+ // on the worker), the side record still carrying the moved-to
+ // identity. The boot's application moves the resident onto the
+ // moved-to identity — never the superseded one — and its own
+ // persist retry repairs the record.
+ std::fs::remove_dir_all(&resident.descriptor_path).unwrap();
+ let stale_record = std::fs::read_to_string(dir.join("stale.json"))
+ .ok()
+ .unwrap_or_else(|| {
+ // The fixture's stale record: the original identity
+ // (s0 / s0.jsonl) the restart must not serve.
+ serde_json::json!({
+ "version": 2,
+ "workerId": "w-a",
+ "pid": 0,
+ "socketPath": "/tmp/none.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "token-a",
+ "rootActiveSessionId": "w-a",
+ "rootSessionId": "s0",
+ "sessionFile": dir.join("s0.jsonl").to_string_lossy(),
+ "createdAt": "2026-09-30T00:00:00Z",
+ "updatedAt": "2026-09-30T00:00:00Z",
+ "lifecycle": "ready",
+ "createCommand": { "sessionPath": dir.join("s0.jsonl").to_string_lossy() },
+ "consecutiveFailures": 0,
+ })
+ .to_string()
+ });
+ std::fs::write(&resident.descriptor_path, &stale_record).unwrap();
+ supervisor.apply_identity_pending(&resident).await;
+ let (root_session_id, session_file) = {
+ let descriptor = resident.descriptor.lock().await;
+ (
+ descriptor.root_session_id.clone(),
+ descriptor.session_file.clone(),
+ )
+ };
+ assert_eq!(
+ root_session_id.as_deref(),
+ Some("sA"),
+ "the boot applies the moved-to identity, never the superseded one"
+ );
+ assert_eq!(
+ session_file.as_deref(),
+ Some(dir.join("a.jsonl").to_string_lossy().to_string().as_str())
+ );
+ assert!(
+ crate::descriptor::read_identity_pending(&resident.descriptor_path).is_none(),
+ "the boot's repair removed the side record"
+ );
+ assert!(
+ !resident.identity_persist_pending(),
+ "the repair cleared the marker"
+ );
+ let record: DaemonWorkerDescriptor =
+ serde_json::from_str(&std::fs::read_to_string(&resident.descriptor_path).unwrap())
+ .unwrap();
+ assert_eq!(record.root_session_id.as_deref(), Some("sA"));
+
+ // THE FRESHNESS GATE (the stale-rollback class): an OLDER side
+ // record left behind by a failed removal must never roll a newer
+ // persisted identity back onto its move — the boot ignores it
+ // and clears it.
+ let mut newer = record.clone();
+ newer.updated_at = crate::util::now_iso();
+ std::fs::write(
+ &resident.descriptor_path,
+ serde_json::to_string(&newer).unwrap(),
+ )
+ .unwrap();
+ crate::descriptor::write_identity_pending(
+ &resident.descriptor_path,
+ "sOld",
+ &dir.join("old.jsonl").to_string_lossy(),
+ "2020-01-01T00:00:00.000Z",
+ )
+ .unwrap();
+ supervisor.apply_identity_pending(&resident).await;
+ let (root_session_id, session_file) = {
+ let descriptor = resident.descriptor.lock().await;
+ (
+ descriptor.root_session_id.clone(),
+ descriptor.session_file.clone(),
+ )
+ };
+ assert_eq!(
+ root_session_id.as_deref(),
+ Some("sA"),
+ "the newer persisted identity wins over an older pending"
+ );
+ assert_eq!(
+ session_file.as_deref(),
+ Some(dir.join("a.jsonl").to_string_lossy().to_string().as_str())
+ );
+ assert!(
+ crate::descriptor::read_identity_pending(&resident.descriptor_path).is_none(),
+ "the obsolete pending is cleared, not applied"
+ );
+
+ // THE EQUAL-TIMESTAMP EDGE: a repair persist that lands at the
+ // exact moment of a stale pending's stamp carries the moved
+ // identity — the pending is obsolete at equality too, never
+ // applied (the rollback the equal comparison allowed).
+ let equal_stamped = newer.updated_at.clone();
+ {
+ let mut descriptor = resident.descriptor.lock().await;
+ descriptor.updated_at = equal_stamped.clone();
+ }
+ crate::descriptor::write_identity_pending(
+ &resident.descriptor_path,
+ "sOld",
+ &dir.join("old.jsonl").to_string_lossy(),
+ &equal_stamped,
+ )
+ .unwrap();
+ supervisor.apply_identity_pending(&resident).await;
+ let root_session_id = resident.descriptor.lock().await.root_session_id.clone();
+ assert_eq!(
+ root_session_id.as_deref(),
+ Some("sA"),
+ "an equal-timestamp pending never rolls the record back"
+ );
+ assert!(
+ crate::descriptor::read_identity_pending(&resident.descriptor_path).is_none(),
+ "the equal-timestamp pending is cleared, not applied"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// A subagent/child roster delta never lifts the root's boot
+ /// reconciliation quarantine (the bot-wave finding): the child's
+ /// summary rows key under its own address, so the root's follow
+ /// answers false — only the root's own roster write (or the
+ /// reconciliation pull) lifts the fence.
+ #[tokio::test]
+ async fn a_child_roster_delta_never_lifts_the_root_quarantine() {
+ let dir = std::env::temp_dir().join(format!("pa-root-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = supervisor_with_movable_worker(&dir).await;
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+ resident.mark_identity_quarantined();
+ assert!(resident.identity_quarantined());
+
+ // The worker's roster link delivers a CHILD summary under the
+ // root's token (the adopted family's first push): the row keys
+ // under the child's address, and the root's quarantine holds.
+ let child_summary = json!({
+ "id": "child-1",
+ "lifecycle": "live",
+ "activity": "idle",
+ "isSessionActive": false,
+ "activeSessionId": "child-1",
+ "sessionId": "s-child",
+ "sessionFile": dir.join("c.jsonl").to_string_lossy(),
+ "sessionName": "child",
+ "cwd": dir.to_string_lossy(),
+ "rlmDepth": 1,
+ "runtimeKind": "subagent",
+ "rlmChildId": "c1",
+ "parentActiveSessionId": "w-a",
+ "messageCount": 0,
+ "attachedClients": 0,
+ "thinkingLevel": "default",
+ "workerState": "ready",
+ });
+ let response = supervisor
+ .handle_worker_roster_delta(
+ "d1",
+ "worker_roster_delta",
+ WorkerRosterDelta {
+ worker_token: "token-a".to_string(),
+ summary: child_summary,
+ removed: Vec::new(),
+ sequence: Some(1),
+ worker_instance_id: Some("i1".to_string()),
+ },
+ )
+ .await;
+ assert!(response.success, "the child delta applied: {response:?}");
+ assert!(
+ resident.identity_quarantined(),
+ "a child delta never lifts the root's quarantine"
+ );
+
+ // The root's own roster write lifts the fence.
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 2).await;
+ assert!(
+ !resident.identity_quarantined(),
+ "the root's own write lifts the quarantine"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// FINDING 4's pin: a `noSession` worker that moved onto a persisted
+ /// file must drop the in-memory flag with the path — the durable
+ /// create command the relaunch replays never carries the
+ /// `noSession`+`sessionPath` combination the worker's create refuses.
+ #[tokio::test]
+ async fn a_path_backed_replacement_clears_the_no_session_replay_flag() {
+ let dir = std::env::temp_dir().join(format!("pa-root-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = Arc::new(
+ Supervisor::new(crate::supervisor::SupervisorOptions {
+ socket_path: dir.join("daemon.sock"),
+ agent_dir: dir.join("agent"),
+ })
+ .expect("supervisor"),
+ );
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(json!({
+ "version": 2,
+ "workerId": "w-a",
+ "pid": 0,
+ "socketPath": "/tmp/none.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "token-a",
+ "rootActiveSessionId": "w-a",
+ "createdAt": "2026-09-30T00:00:00Z",
+ "updatedAt": "2026-09-30T00:00:00Z",
+ "lifecycle": "ready",
+ "createCommand": { "noSession": true },
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ supervisor
+ .registry
+ .insert(ResidentWorker::new(
+ "w-a".to_string(),
+ descriptor,
+ dir.join("w-a.json"),
+ ))
+ .await;
+
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 1).await;
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+ let (session_path, no_session) = {
+ let descriptor = resident.descriptor.lock().await;
+ (
+ descriptor.create_command.session_path.clone(),
+ descriptor.create_command.no_session,
+ )
+ };
+ assert_eq!(
+ session_path.as_deref(),
+ Some(dir.join("a.jsonl").to_string_lossy().to_string().as_str())
+ );
+ assert_eq!(
+ no_session, None,
+ "the replay command drops the in-memory flag with the path"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+ /// The boot-reconciliation quarantine pin (the final review finding): a
+ /// resident whose boot reconciliation pull failed — a timeout is not
+ /// proof the worker is dead — never serves ANY identity route on the
+ /// unreconciled persisted record: the selector resolution, the stale
+ /// file-stem selector, and the by-file reuse all refuse. The worker's
+ /// own roster push (the live word, no command channel needed) carries
+ /// the identity follow, reconciles the identity, and opens the
+ /// routing — on the reconciled identity, never the persisted one.
+ #[tokio::test]
+ async fn a_quarantined_resident_never_serves_until_the_live_word_lands() {
+ let dir = std::env::temp_dir().join(format!("pa-root-id-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let supervisor = supervisor_with_movable_worker(&dir).await;
+ let resident = supervisor.registry.get("w-a").await.expect("resident");
+ let stale_file = dir.join("s0.jsonl").to_string_lossy().to_string();
+
+ // The boot outcome: the reconciliation pull refused (the resident
+ // has no worker channel), the quarantine fenced it.
+ assert!(
+ !supervisor.refresh_roster_entry(&resident).await,
+ "the pull refuses on the channel-less resident"
+ );
+ resident.mark_identity_quarantined();
+ assert!(resident.identity_quarantined());
+
+ // THE FENCES: the address, the stale file stem, and the by-file
+ // reuse all refuse — the failure reads as the unknown session,
+ // never the stale identity.
+ assert!(
+ supervisor.registry.resolve("w-a").await.is_err(),
+ "the quarantined address never resolves"
+ );
+ assert!(
+ supervisor.registry.resolve("s0").await.is_err(),
+ "the stale persisted file stem never resolves"
+ );
+ assert!(
+ supervisor
+ .registry
+ .find_by_session_file(&stale_file)
+ .await
+ .is_none(),
+ "the stale persisted file never reuses the quarantined worker"
+ );
+
+ // THE LIVE WORD: the worker's own roster push (the delta path —
+ // no command channel involved) carries the identity follow.
+ drive_delta(&supervisor, swap_summary(&dir, "sA", "a.jsonl"), 1).await;
+ assert!(
+ !resident.identity_quarantined(),
+ "the accepted roster write cleared the quarantine"
+ );
+
+ // THE ROUTING OPENS on the reconciled identity.
+ let resolved = supervisor
+ .registry
+ .resolve("w-a")
+ .await
+ .expect("the address resolves once reconciled");
+ let (root_session_id, session_file) = {
+ let descriptor = resolved.descriptor.lock().await;
+ (
+ descriptor.root_session_id.clone(),
+ descriptor.session_file.clone(),
+ )
+ };
+ assert_eq!(root_session_id.as_deref(), Some("sA"));
+ assert_eq!(
+ session_file.as_deref(),
+ Some(dir.join("a.jsonl").to_string_lossy().to_string().as_str())
+ );
+ let reconciled_file = dir.join("a.jsonl").to_string_lossy().to_string();
+ assert!(
+ supervisor
+ .registry
+ .find_by_session_file(&reconciled_file)
+ .await
+ .is_some(),
+ "the reconciled file reuses the worker"
+ );
+ assert!(
+ supervisor.registry.resolve("s0").await.is_err(),
+ "the superseded persisted stem stays unresolvable"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
index 343ce55de4..0dabfed5ed 100644
--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
@@ -818,6 +818,13 @@ impl Supervisor {
}
_ => {
let _ = std::fs::remove_file(&resident.descriptor_path);
+ // The identity-pending side record dies with the
+ // descriptor it shadows (an orphaned pending would
+ // shadow the next identity over the same worker id). A
+ // removal failure here is as inert as the descriptor
+ // removal beside it — the retire already provably killed
+ // the worker, so no later boot applies a shadowed record.
+ let _ = crate::descriptor::clear_identity_pending(&resident.descriptor_path);
}
}
}
diff --git a/crates/pa-daemon/src/supervisor_roster.rs b/crates/pa-daemon/src/supervisor_roster.rs
index 89c5925b42..a586fe8c9a 100644
--- a/crates/pa-daemon/src/supervisor_roster.rs
+++ b/crates/pa-daemon/src/supervisor_roster.rs
@@ -108,6 +108,13 @@ impl Supervisor {
None,
);
};
+ // One per-worker critical section spans the roster write AND the
+ // identity follow (the resident's descriptor lock — the same lock
+ // every identity reader takes): a routing reader can never observe
+ // a half-applied swap, and an older follow can never persist after
+ // a newer one (each accepted row carries its own follow inside the
+ // same guard, so the persists apply in accept order).
+ //
// The stale-delta gate and the write share ONE roster lock
// acquisition: two accepted deltas must never write in reverse
// order (each supervisor connection runs its own task), so the
@@ -123,22 +130,51 @@ impl Supervisor {
let mut changed = Vec::new();
let mut removed_ids = Vec::new();
{
- let mut roster = self.roster.lock().unwrap();
- if !roster.accept_delta_sequence(
- &resident.worker_id,
- worker_instance_id.as_deref().unwrap_or(""),
- sequence.unwrap_or(0),
- ) {
- return response_success(Some(command_id), type_name, None);
- }
- let entry = roster.write_summary(summary, Some(&resident.worker_id), None);
- changed.push(entry);
- for agent_id in removed {
- if roster.get(&agent_id).is_some() {
- roster.delete(&agent_id);
- removed_ids.push(agent_id);
+ let mut descriptor = resident.descriptor.lock().await;
+ {
+ let mut roster = self.roster.lock().unwrap();
+ if !roster.accept_delta_sequence(
+ &resident.worker_id,
+ worker_instance_id.as_deref().unwrap_or(""),
+ sequence.unwrap_or(0),
+ ) {
+ return response_success(Some(command_id), type_name, None);
+ }
+ let entry = roster.write_summary(summary.clone(), Some(&resident.worker_id), None);
+ // The worker's root slot can swap to a new durable session
+ // (a `new_session`/`switch_session`/`import_jsonl`/`fork`
+ // replacement serves a new file under the same address):
+ // the row it previously owned for that address described
+ // the superseded session, and the roster must not keep
+ // presenting it as the worker's live root (TS
+ // `flushRoster`'s swapped-in-place removal).
+ for swapped in roster.swapped_out_root_rows(&resident.worker_id, &entry) {
+ roster.delete(&swapped);
+ removed_ids.push(swapped);
+ }
+ changed.push(entry);
+ for agent_id in removed {
+ if roster.get(&agent_id).is_some() {
+ roster.delete(&agent_id);
+ removed_ids.push(agent_id);
+ }
}
}
+ // The roster write is the worker's live word on what it
+ // serves: the supervisor-side identity follows it inside the
+ // same critical section (the fork-isolation seam — the
+ // descriptor, the persisted record, the durable create
+ // command, and the binding table all move onto the worker's
+ // current session). The boot reconciliation quarantine lifts
+ // ONLY on a root-identity-bearing write: the sync answers
+ // whether the worker's own root row carried the live word —
+ // a subagent/child summary (keying under its own address)
+ // never lifts the root's fence.
+ let root_identity_bearing =
+ self.sync_root_identity_from_roster(&resident, &mut descriptor);
+ if root_identity_bearing {
+ resident.clear_identity_quarantine();
+ }
}
self.push_roster_update(changed, removed_ids);
response_success(Some(command_id), type_name, None)
@@ -194,20 +230,56 @@ impl Supervisor {
let counter = summary
.get("rosterDeltaSequence")
.and_then(serde_json::Value::as_u64);
- let entry = {
- let mut roster = self.roster.lock().unwrap();
- if !roster.accept_roster_pull(&resident.worker_id, &instance, counter) {
- return None;
+ let (entry, swapped) = {
+ // The pull shares the delta path's per-worker critical
+ // section (the resident's descriptor lock across the roster
+ // write and the identity follow): the registration and
+ // refresh pulls land their descriptor/persist/binding moves
+ // as one transition, in accept order, never observable
+ // half-applied.
+ let mut descriptor = resident.descriptor.lock().await;
+ let (entry, swapped) = {
+ let mut roster = self.roster.lock().unwrap();
+ if !roster.accept_roster_pull(&resident.worker_id, &instance, counter) {
+ return None;
+ }
+ let entry = roster.write_summary(summary.clone(), Some(&resident.worker_id), None);
+ // The pull sees the same root-slot swap the deltas do (a
+ // registration or refresh landing after a
+ // `new_session`/`switch_session`/`import_jsonl`/`fork`
+ // replacement): the superseded row retires with the write,
+ // and the identity follow below re-binds the
+ // supervisor-side identity onto the moved-to session.
+ let swapped = roster.swapped_out_root_rows(&resident.worker_id, &entry);
+ for agent_id in &swapped {
+ roster.delete(agent_id);
+ }
+ (entry, swapped)
+ };
+ // The pull is the worker's own root state by construction, so
+ // its accepted write lifts the boot reconciliation quarantine
+ // with the identity it just reconciled.
+ let root_identity_bearing =
+ self.sync_root_identity_from_roster(resident, &mut descriptor);
+ if root_identity_bearing {
+ resident.clear_identity_quarantine();
}
- roster.write_summary(summary.clone(), Some(&resident.worker_id), None)
+ (entry, swapped)
};
- self.push_roster_update(vec![entry.clone()], Vec::new());
+ self.push_roster_update(vec![entry.clone()], swapped);
Some(entry)
}
/// Refresh one resident worker's entry from its live `get_state`
- /// (registration, adoption, and create flows).
- pub(crate) async fn refresh_roster_entry(self: &Arc<Self>, resident: &Arc<ResidentWorker>) {
+ /// (registration, adoption, and create flows). Returns whether the
+ /// live state landed: the write carries the root-identity follow, so
+ /// a `false` answer means the reconciliation did not run — the caller
+ /// logs it and the persisted identity keeps serving until the next
+ /// roster write.
+ pub(crate) async fn refresh_roster_entry(
+ self: &Arc<Self>,
+ resident: &Arc<ResidentWorker>,
+ ) -> bool {
let response = self
.route_command_typed(
resident,
@@ -217,14 +289,18 @@ impl Supervisor {
RouteAdmission::SupervisorInternal,
)
.await;
- if let Ok(response) = response {
- if response.success {
- if let Some(data) = response.data {
- self.write_roster_summary_for_resident(resident, &data)
- .await;
- }
- }
+ let Ok(response) = response else {
+ return false;
+ };
+ if !response.success {
+ return false;
}
+ let Some(data) = response.data else {
+ return false;
+ };
+ self.write_roster_summary_for_resident(resident, &data)
+ .await
+ .is_some()
}
/// TS `flipWorkerRosterEntriesInactive` (the Rust form: one pass in
diff --git a/crates/pa-daemon/tests/fork_isolation_e2e.rs b/crates/pa-daemon/tests/fork_isolation_e2e.rs
new file mode 100644
index 0000000000..b8542c89f6
--- /dev/null
+++ b/crates/pa-daemon/tests/fork_isolation_e2e.rs
@@ -0,0 +1,912 @@
+//! The fork-isolation verifier (operator bug #5): a session forked with
+//! `/fork` must be a FULLY detached session. The worker replaces its live
+//! session file in place (a new durable id and file under the same worker
+//! address), and every supervisor-side route must follow that move: a
+//! message targeted at the ORIGINAL session file reaches the original
+//! (its own worker), never the fork; the fork's own sends flow to the
+//! fork; and the roster keeps both sessions visible, each owned by the
+//! worker that serves it.
+//!
+//! The pin battery: (a) the isolation pin — a create over the original
+//! file after the fork opens the ORIGINAL (a fresh worker over the
+//! file), and its prompt never lands in the fork's transcript; (b) the
+//! reverse pin — the fork's own prompt never lands in the original's
+//! transcript; (c) the independence pin — the fork's client keeps
+//! serving its own turns; (d) the visibility pin — the roster carries
+//! both sessions, and the fork's swap retires the stale row that still
+//! presented the original as the fork worker's live root; plus the
+//! stale-binding pin — after the fork's worker dies, the fork's old
+//! address does not rebind into the original's worker.
+// Pedantic-gate dispositions (fleet-uniform ruling; see this lane's PR
+// for the full rationale).
+#![allow(clippy::large_futures)]
+#![allow(
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap,
+ clippy::cast_sign_loss,
+ clippy::cast_precision_loss
+)]
+#![allow(clippy::too_many_lines)]
+#![allow(
+ clippy::unnecessary_wraps,
+ clippy::zero_sized_map_values,
+ clippy::struct_excessive_bools,
+ clippy::struct_field_names
+)]
+#![cfg(unix)]
+
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::net::UnixStream;
+use std::path::PathBuf;
+use std::process::{Child, Command, Stdio};
+use std::time::{Duration, Instant};
+
+struct Daemon {
+ child: Child,
+ #[allow(dead_code)]
+ socket: PathBuf,
+}
+
+impl Drop for Daemon {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+// The timeout panic path cannot wait on the child; the test process exits
+// immediately afterwards, reaping it.
+#[allow(clippy::zombie_processes)]
+fn spawn_daemon(socket: &std::path::Path, agent_dir: &std::path::Path) -> Daemon {
+ let binary = env!("CARGO_BIN_EXE_pa-daemon");
+ let child = Command::new(binary)
+ .arg("supervisor")
+ .arg("--socket")
+ .arg(socket)
+ .arg("--agent-dir")
+ .arg(agent_dir)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ )
+ .spawn()
+ .expect("spawn pa-daemon supervisor");
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while Instant::now() < deadline {
+ if socket.exists() {
+ return Daemon {
+ child,
+ socket: socket.to_path_buf(),
+ };
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ panic!("supervisor socket never appeared");
+}
+
+struct Client {
+ reader: BufReader<UnixStream>,
+ writer: UnixStream,
+}
+
+impl Client {
+ fn connect(socket: &std::path::Path) -> Self {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let stream = loop {
+ match UnixStream::connect(socket) {
+ Ok(stream) => break stream,
+ Err(_) if Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ Err(error) => panic!("connect supervisor: {error}"),
+ }
+ };
+ let write_stream = stream.try_clone().expect("clone socket");
+ let mut client = Client {
+ reader: BufReader::new(stream),
+ writer: write_stream,
+ };
+ let hello = client.read_line();
+ assert_eq!(hello["type"], "daemon_hello");
+ client
+ }
+
+ fn send_command(&mut self, id: &str, command: &serde_json::Value) {
+ let mut line = serde_json::to_string(&serde_json::json!({
+ "type": "command",
+ "id": id,
+ "protocol": { "name": "prime-agent.daemon", "version": 7 },
+ "command": command,
+ }))
+ .expect("serialize command");
+ line.push('\n');
+ self.writer.write_all(line.as_bytes()).expect("send");
+ self.writer.flush().expect("flush");
+ }
+
+ fn read_line(&mut self) -> serde_json::Value {
+ let mut line = String::new();
+ let deadline = Instant::now() + Duration::from_secs(20);
+ self.reader
+ .get_mut()
+ .set_read_timeout(Some(Duration::from_millis(100)))
+ .expect("set timeout");
+ loop {
+ line.clear();
+ match self.reader.read_line(&mut line) {
+ Ok(0) => panic!("supervisor closed the connection"),
+ Ok(_) if line.trim().is_empty() => {}
+ Ok(_) => {
+ return serde_json::from_str(line.trim()).expect("parse response line");
+ }
+ Err(error) => {
+ assert!(
+ Instant::now() < deadline,
+ "timed out waiting for supervisor line: {error}"
+ );
+ }
+ }
+ }
+ }
+
+ fn read_response(&mut self, id: &str) -> serde_json::Value {
+ let deadline = Instant::now() + Duration::from_secs(30);
+ loop {
+ assert!(Instant::now() < deadline, "no response for id {id}");
+ let line = self.read_line();
+ if line.get("id").and_then(|v| v.as_str()) == Some(id) {
+ return line;
+ }
+ }
+ }
+
+ /// The first `roster_update` push whose changed entries satisfy
+ /// `accept` (the roster observer's convergence wait).
+ fn next_roster_update<F>(&mut self, mut accept: F) -> serde_json::Value
+ where
+ F: FnMut(&serde_json::Value) -> bool,
+ {
+ let deadline = Instant::now() + Duration::from_secs(30);
+ loop {
+ assert!(
+ Instant::now() < deadline,
+ "no matching roster_update arrived"
+ );
+ let line = self.read_line();
+ if line["type"] == "roster_update" && accept(&line) {
+ return line;
+ }
+ }
+ }
+
+ /// One scripted prompt turn (`prompt_and_wait`) on the session `id`.
+ fn scripted_turn(&mut self, id: &str, session_id: &str, message: &str) -> serde_json::Value {
+ self.send_command(
+ id,
+ &serde_json::json!({
+ "type": "prompt_and_wait",
+ "activeSessionId": session_id,
+ "message": message,
+ }),
+ );
+ let response = self.read_response(id);
+ assert_eq!(response["success"], true, "prompt {id} failed: {response}");
+ response
+ }
+}
+
+/// The text of every message row in a `get_messages` response.
+fn message_texts(client: &mut Client, id: &str, session_id: &str) -> Vec<String> {
+ client.send_command(
+ id,
+ &serde_json::json!({ "type": "get_messages", "activeSessionId": session_id }),
+ );
+ let response = client.read_response(id);
+ assert_eq!(response["success"], true, "get_messages failed: {response}");
+ response["data"]["messages"]
+ .as_array()
+ .expect("messages")
+ .iter()
+ .map(|message| match message["content"].as_str() {
+ Some(text) => text.to_string(),
+ None => message["content"]
+ .as_array()
+ .map(|blocks| {
+ blocks
+ .iter()
+ .filter_map(|b| b["text"].as_str())
+ .collect::<String>()
+ })
+ .unwrap_or_default(),
+ })
+ .collect()
+}
+
+/// The session-dir files' concatenated content (the durable transcripts).
+fn session_dir_text(session_dir: &std::path::Path) -> String {
+ std::fs::read_dir(session_dir)
+ .expect("read session dir")
+ .flatten()
+ .filter(|entry| entry.path().extension().and_then(|e| e.to_str()) == Some("jsonl"))
+ .map(|entry| {
+ let content = std::fs::read_to_string(entry.path()).unwrap_or_default();
+ format!("--- {} ---\n{content}", entry.path().display())
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+#[test]
+fn the_fork_is_a_fully_detached_session() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("daemon.sock");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("agent dir");
+ let _daemon = spawn_daemon(&socket, &agent_dir);
+
+ let script_a = dir.path().join("script-a.json");
+ std::fs::write(
+ &script_a,
+ serde_json::json!({ "responses": [
+ { "text": "original turn one", "delayMs": 10 },
+ ] })
+ .to_string(),
+ )
+ .expect("write script");
+ let script_b = dir.path().join("script-b.json");
+ std::fs::write(
+ &script_b,
+ serde_json::json!({ "responses": [
+ { "text": "original turn answer", "delayMs": 10 },
+ ] })
+ .to_string(),
+ )
+ .expect("write script");
+ // Client A owns the ORIGINAL session, drives the fork, and stays
+ // attached to the fork (the client that ran /fork keeps its worker
+ // address and sees the forked session).
+ let mut client_a = Client::connect(&socket);
+ client_a.send_command(
+ "c1",
+ &serde_json::json!({ "type": "create", "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": session_dir.to_string_lossy(),
+ "script": script_a.to_string_lossy(),
+ } }),
+ );
+ let created = client_a.read_response("c1");
+ assert_eq!(created["success"], true, "create failed: {created}");
+ let original_active = created["data"]["id"]
+ .as_str()
+ .or_else(|| created["data"]["sessionId"].as_str())
+ .expect("the original's active id")
+ .to_string();
+ let original_durable = created["data"]["sessionId"]
+ .as_str()
+ .expect("the original's durable id")
+ .to_string();
+ let original_file = created["data"]["sessionFile"]
+ .as_str()
+ .expect("the original's session file")
+ .to_string();
+ client_a.send_command(
+ "a1",
+ &serde_json::json!({ "type": "attach", "activeSessionId": original_active }),
+ );
+ let attached = client_a.read_response("a1");
+ assert_eq!(attached["success"], true, "attach failed: {attached}");
+
+ client_a.scripted_turn("p1", &original_active, "fork point message");
+
+ // The roster observer: the agents-view surface that must keep seeing
+ // both sessions, each owned by the worker that serves it.
+ let mut observer = Client::connect(&socket);
+ observer.send_command("r1", &serde_json::json!({ "type": "roster_subscribe" }));
+ let subscribed = observer.read_response("r1");
+ assert_eq!(subscribed["success"], true, "roster_subscribe failed");
+
+ // THE FORK: branch before the user message; the worker moves onto the
+ // forked file under its unchanged address.
+ client_a.send_command(
+ "g1",
+ &serde_json::json!({
+ "type": "get_user_messages_for_forking",
+ "activeSessionId": original_active,
+ }),
+ );
+ let points = client_a.read_response("g1");
+ assert_eq!(points["success"], true, "fork points failed: {points}");
+ let entry_id = points["data"]["messages"]
+ .as_array()
+ .and_then(|messages| {
+ messages
+ .iter()
+ .find(|message| message["text"] == "fork point message")
+ .map(|message| message["entryId"].clone())
+ })
+ .unwrap_or_else(|| panic!("the fork point message: {points}"));
+ client_a.send_command(
+ "f1",
+ &serde_json::json!({
+ "type": "fork",
+ "activeSessionId": original_active,
+ "entryId": entry_id,
+ }),
+ );
+ let forked = client_a.read_response("f1");
+ assert_eq!(forked["success"], true, "fork failed: {forked}");
+ assert_eq!(
+ forked["data"]["selectedText"],
+ serde_json::json!("fork point message")
+ );
+
+ // The fork's identity moved: the worker serves a new durable id and
+ // file under the same address.
+ client_a.send_command(
+ "s1",
+ &serde_json::json!({ "type": "get_session_stats", "activeSessionId": original_active }),
+ );
+ let stats = client_a.read_response("s1");
+ let fork_durable = stats["data"]["sessionId"]
+ .as_str()
+ .expect("fork id")
+ .to_string();
+ let fork_file = stats["data"]["sessionFile"]
+ .as_str()
+ .expect("fork file")
+ .to_string();
+ assert_ne!(fork_durable, original_durable, "the fork minted an id");
+ assert_ne!(fork_file, original_file, "the fork wrote a new file");
+ assert!(
+ std::path::Path::new(&original_file).exists(),
+ "the original file survives the fork"
+ );
+
+ // The supervisor's roster saw the fork (the worker's roster push): the
+ // fork's row exists under the fork's durable id.
+ let fork_row = observer.next_roster_update(|line| {
+ line["changed"].as_array().is_some_and(|entries| {
+ entries.iter().any(|entry| {
+ entry["summary"]["sessionId"] == fork_durable.as_str()
+ && entry["summary"]["activeSessionId"] == original_active.as_str()
+ })
+ })
+ });
+ let fork_worker = fork_row["changed"]
+ .as_array()
+ .and_then(|entries| {
+ entries
+ .iter()
+ .find(|entry| entry["summary"]["sessionId"] == fork_durable.as_str())
+ })
+ .map(|entry| entry["workerId"].clone())
+ .expect("the fork row names its worker");
+ assert_eq!(fork_worker, original_active.as_str());
+
+ // THE SWAP PIN: the row the fork worker previously owned for the same
+ // address described the ORIGINAL session — it is dead now (the fork
+ // worker serves the fork, and the original file's open must not find a
+ // stale "live" row). A stale row here is what re-presents the
+ // original as the fork worker's live root and what later wakes by
+ // address would resolve to the wrong file.
+ observer.send_command("r2", &serde_json::json!({ "type": "roster_subscribe" }));
+ let snapshot = observer.read_response("r2");
+ assert_eq!(snapshot["success"], true, "re-subscribe failed");
+ let roster = snapshot["data"]["roster"].as_array().expect("roster");
+ let stale = roster
+ .iter()
+ .find(|entry| entry["agentId"] == original_durable.as_str());
+ assert!(
+ stale.is_none(),
+ "the fork's swap must retire the stale row for the original: {stale:?}"
+ );
+
+ // THE ISOLATION PIN: a create over the ORIGINAL file opens the
+ // ORIGINAL — a worker of its own, not the fork worker reused for the
+ // path it no longer serves.
+ let mut client_b = Client::connect(&socket);
+ client_b.send_command(
+ "c2",
+ &serde_json::json!({
+ "type": "create",
+ "sessionPath": original_file,
+ "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": session_dir.to_string_lossy(),
+ "script": script_b.to_string_lossy(),
+ },
+ }),
+ );
+ let reopened = client_b.read_response("c2");
+ assert_eq!(reopened["success"], true, "re-open failed: {reopened}");
+ let reopened_id = reopened["data"]["id"]
+ .as_str()
+ .or_else(|| reopened["data"]["sessionId"].as_str())
+ .expect("the re-opened session's id")
+ .to_string();
+ let reopened_durable = reopened["data"]["sessionId"]
+ .as_str()
+ .expect("the re-opened durable id")
+ .to_string();
+
+ client_b.send_command(
+ "a2",
+ &serde_json::json!({ "type": "attach", "activeSessionId": reopened_id }),
+ );
+ let attached_b = client_b.read_response("a2");
+ assert_eq!(attached_b["success"], true, "attach B failed: {attached_b}");
+
+ // The message the operator sent in the ORIGINAL session.
+ client_b.scripted_turn("p2", &reopened_id, "message for the original");
+
+ // The leak evidence: the fork's transcript and both files' durable
+ // content, gathered before the pins so every failure names the full
+ // matrix.
+ let fork_texts = message_texts(&mut client_a, "m1", &original_active);
+ let texts = session_dir_text(&session_dir);
+
+ // PIN 1: the re-open of the original resolved to the ORIGINAL session
+ // (its own worker), never the fork.
+ assert_eq!(
+ reopened_durable, original_durable,
+ "the create over the original file must open the original, not the fork (the values print above)"
+ );
+ assert_ne!(
+ reopened_id, original_active,
+ "the original's re-open must not reuse the fork worker's address"
+ );
+
+ // PIN 2 (the operator's report): the original's message never lands
+ // in the fork's transcript.
+ assert!(
+ !fork_texts
+ .iter()
+ .any(|text| text.contains("message for the original")),
+ "the fork received the original's message: {fork_texts:?}\nsession files: {texts}"
+ );
+ assert!(
+ !fork_file_text(&fork_file).contains("message for the original"),
+ "the fork's file received the original's message"
+ );
+ assert!(
+ std::fs::read_to_string(&original_file)
+ .unwrap_or_default()
+ .contains("message for the original"),
+ "the original's message must reach the original's file"
+ );
+
+ // THE REVERSE PIN: the fork's own message never lands in the original.
+ client_a.scripted_turn("p3", &original_active, "message for the fork");
+ let original_texts = message_texts(&mut client_b, "m2", &reopened_id);
+ assert!(
+ !original_texts
+ .iter()
+ .any(|text| text.contains("message for the fork")),
+ "the original received the fork's message: {original_texts:?}"
+ );
+ assert!(
+ !std::fs::read_to_string(&original_file)
+ .unwrap_or_default()
+ .contains("message for the fork"),
+ "the original's file received the fork's message"
+ );
+ assert!(
+ fork_file_text(&fork_file).contains("message for the fork"),
+ "the fork's own message must reach the fork's file"
+ );
+
+ // THE INDEPENDENCE PIN: the fork's client keeps serving its own turns.
+ let fork_texts = message_texts(&mut client_a, "m3", &original_active);
+ assert!(
+ fork_texts
+ .iter()
+ .any(|text| text.contains("message for the fork")),
+ "the fork's own message must appear in the fork's transcript: {fork_texts:?}"
+ );
+ assert!(
+ fork_texts.iter().any(|text| text.contains("original turn one")),
+ "the fork's turn must answer on the fork's transcript (the replacement restarts the script): {fork_texts:?}"
+ );
+
+ // THE VISIBILITY PIN: the roster carries BOTH sessions, each owned by
+ // the worker that serves it (the family edges are not the bug; the
+ // routing was).
+ observer.send_command("r3", &serde_json::json!({ "type": "roster_subscribe" }));
+ let snapshot = observer.read_response("r3");
+ assert_eq!(snapshot["success"], true, "final subscribe failed");
+ let roster = snapshot["data"]["roster"].as_array().expect("roster");
+ let original_row = roster
+ .iter()
+ .find(|entry| entry["agentId"] == original_durable.as_str())
+ .expect("the original's roster row after its re-open");
+ assert_eq!(
+ original_row["workerId"],
+ reopened_id.as_str(),
+ "the original's row names its own worker: {original_row:?}"
+ );
+ let fork_row = roster
+ .iter()
+ .find(|entry| entry["agentId"] == fork_durable.as_str())
+ .expect("the fork's roster row");
+ assert_eq!(
+ fork_row["workerId"],
+ original_active.as_str(),
+ "the fork's row names the fork worker: {fork_row:?}"
+ );
+
+ // THE STALE-BINDING PIN: the fork worker dies, and its old address
+ // must NOT rebind into the original's worker — the address's binding
+ // follows the fork (the fork's file), so the stale id answers the
+ // unknown-session failure instead of landing the fork's client in
+ // the original.
+ client_a.send_command(
+ "k1",
+ &serde_json::json!({ "type": "kill", "activeSessionId": original_active }),
+ );
+ let killed = client_a.read_response("k1");
+ assert_eq!(killed["success"], true, "kill failed: {killed}");
+ client_a.send_command(
+ "p4",
+ &serde_json::json!({
+ "type": "prompt",
+ "activeSessionId": original_active,
+ "message": "must not reach the original",
+ }),
+ );
+ let stale = client_a.read_response("p4");
+ assert_eq!(
+ stale["success"], false,
+ "the fork's stale id must not deliver: {stale}"
+ );
+ assert!(
+ stale["error"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("Unknown active session"),
+ "the stale id answers the unknown-session failure: {stale}"
+ );
+ assert!(
+ !std::fs::read_to_string(&original_file)
+ .unwrap_or_default()
+ .contains("must not reach the original"),
+ "the stale id's message must not reach the original"
+ );
+ assert!(
+ !message_texts(&mut client_b, "m4", &reopened_id)
+ .iter()
+ .any(|text| text.contains("must not reach the original")),
+ "the original's transcript must stay clean of the stale id's message"
+ );
+}
+
+/// One session file's content.
+fn fork_file_text(path: &str) -> String {
+ std::fs::read_to_string(path).unwrap_or_default()
+}
+
+/// Wait until the supervisor socket accepts connections (a restarted
+/// supervisor parks on the stale socket file for up to a second before
+/// replacing it, so file existence is not readiness).
+fn wait_socket_accepts(socket: &std::path::Path) {
+ let deadline = Instant::now() + Duration::from_secs(15);
+ loop {
+ if UnixStream::connect(socket).is_ok() {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "the restarted supervisor never accepted connections"
+ );
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+
+/// FINDING 3's restart pin: a daemon restart AFTER a failed identity
+/// persist, BEFORE any new roster write — the boot serves the NEW identity
+/// (never replays the old session) because the boot paths reconcile the
+/// resident from the live worker state before the routing opens.
+#[test]
+fn a_restart_after_a_failed_identity_persist_serves_the_moved_session() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("daemon.sock");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("agent dir");
+
+ let script_path = dir.path().join("script.json");
+ std::fs::write(
+ &script_path,
+ serde_json::json!({ "responses": [
+ { "text": "original turn one", "delayMs": 10 },
+ { "text": "restart turn answer", "delayMs": 10 },
+ ] })
+ .to_string(),
+ )
+ .expect("write script");
+
+ // Supervisor A: the original session, the fork, the failed persist.
+ let mut supervisor_a = spawn_supervisor_raw(&socket, &agent_dir);
+ let mut client_a = Client::connect(&socket);
+ // The roster observer: the fork's supervisor-side convergence signal
+ // (the worker's roster push carries the identity follow; the pins
+ // assert the settled state, so the test waits for the row like every
+ // other roster-observing surface).
+ let mut observer = Client::connect(&socket);
+ observer.send_command("r1", &serde_json::json!({ "type": "roster_subscribe" }));
+ assert_eq!(
+ observer.read_response("r1")["success"],
+ true,
+ "roster_subscribe failed"
+ );
+ client_a.send_command(
+ "c1",
+ &serde_json::json!({ "type": "create", "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": session_dir.to_string_lossy(),
+ "script": script_path.to_string_lossy(),
+ } }),
+ );
+ let created = client_a.read_response("c1");
+ assert_eq!(created["success"], true, "create failed: {created}");
+ let address = created["data"]["id"]
+ .as_str()
+ .or_else(|| created["data"]["sessionId"].as_str())
+ .expect("the worker address")
+ .to_string();
+ let original_durable = created["data"]["sessionId"]
+ .as_str()
+ .expect("the original's durable id")
+ .to_string();
+ let original_file = created["data"]["sessionFile"]
+ .as_str()
+ .expect("the original's file")
+ .to_string();
+ client_a.scripted_turn("p1", &address, "fork point message");
+
+ // The persisted record this boot owns: save the pre-fork record (the
+ // stale identity the restart must NOT serve), then break the record
+ // path so the fork's identity persist fails.
+ let descriptor_dir = pa_daemon::descriptor::descriptor_dir(&agent_dir, &socket);
+ let descriptor_path = descriptor_dir.join(format!("{address}.json"));
+ let stale_record = std::fs::read_to_string(&descriptor_path)
+ .expect("the worker's persisted record before the fork");
+ std::fs::remove_file(&descriptor_path).expect("remove the record file");
+ std::fs::create_dir_all(&descriptor_path).expect("the record path takes a directory");
+
+ // The fork: the worker moves onto the forked file; the identity
+ // persist fails against the directory (the in-memory identity moved,
+ // the marker armed).
+ client_a.send_command(
+ "g1",
+ &serde_json::json!({
+ "type": "get_user_messages_for_forking",
+ "activeSessionId": address,
+ }),
+ );
+ let points = client_a.read_response("g1");
+ let entry_id = points["data"]["messages"]
+ .as_array()
+ .and_then(|messages| {
+ messages
+ .iter()
+ .find(|message| message["text"] == "fork point message")
+ .map(|message| message["entryId"].clone())
+ })
+ .unwrap_or_else(|| panic!("the fork point message: {points}"));
+ client_a.send_command(
+ "f1",
+ &serde_json::json!({
+ "type": "fork",
+ "activeSessionId": address,
+ "entryId": entry_id,
+ }),
+ );
+ let forked = client_a.read_response("f1");
+ assert_eq!(forked["success"], true, "fork failed: {forked}");
+ client_a.send_command(
+ "s1",
+ &serde_json::json!({ "type": "get_session_stats", "activeSessionId": address }),
+ );
+ let stats = client_a.read_response("s1");
+ let fork_file = stats["data"]["sessionFile"]
+ .as_str()
+ .expect("the fork's file")
+ .to_string();
+ let fork_durable = stats["data"]["sessionId"]
+ .as_str()
+ .expect("the fork's durable id")
+ .to_string();
+ assert_ne!(fork_file, original_file, "the fork moved the worker");
+ // The supervisor-side convergence wait: the fork's roster push carries
+ // the identity follow (the worker's response does NOT wait for its
+ // landing — the TS-parity async flush — so the pins assert the
+ // settled identity, never the in-flight window).
+ let _ = observer.next_roster_update(|line| {
+ line["changed"].as_array().is_some_and(|entries| {
+ entries.iter().any(|entry| {
+ entry["summary"]["sessionId"] == fork_durable.as_str()
+ && entry["summary"]["activeSessionId"] == address.as_str()
+ })
+ })
+ });
+
+ // The LIVE isolation still holds with the failed persist (the
+ // in-memory identity follows the worker).
+ let mut prober = Client::connect(&socket);
+ prober.send_command(
+ "c2",
+ &serde_json::json!({
+ "type": "create",
+ "sessionPath": original_file,
+ "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": session_dir.to_string_lossy(),
+ "script": script_path.to_string_lossy(),
+ },
+ }),
+ );
+ let reopened = prober.read_response("c2");
+ assert_eq!(reopened["success"], true, "re-open failed: {reopened}");
+ assert_eq!(
+ reopened["data"]["sessionId"], original_durable,
+ "the original's re-open serves the original, not the fork"
+ );
+ prober.send_command(
+ "k2",
+ &serde_json::json!({ "type": "kill", "activeSessionId": reopened["data"]["id"] }),
+ );
+ assert_eq!(prober.read_response("k2")["success"], true, "kill failed");
+
+ // THE RESTART: the stale record back on disk (the boot's only word on
+ // the worker is the pre-fork identity), the supervisor killed, the
+ // WORKER left alive, a fresh supervisor over the same agent dir.
+ std::fs::remove_dir_all(&descriptor_path).expect("clear the record path");
+ std::fs::write(&descriptor_path, &stale_record).expect("restore the stale record");
+ supervisor_a.kill().expect("kill supervisor A");
+ let _ = supervisor_a.wait();
+
+ let mut supervisor_b = spawn_supervisor_raw(&socket, &agent_dir);
+ let _daemon_guard = DaemonKillOnDrop {
+ child: &mut supervisor_b,
+ };
+ wait_socket_accepts(&socket);
+
+ // The boot adopts the live worker and reconciles from its live state
+ // BEFORE the routing opens: the address serves the FORK.
+ let mut client_b = Client::connect(&socket);
+ let deadline = Instant::now() + Duration::from_secs(15);
+ let restarted = loop {
+ assert!(Instant::now() < deadline, "the worker never re-registered");
+ client_b.send_command(
+ "s2",
+ &serde_json::json!({ "type": "get_session_stats", "activeSessionId": address }),
+ );
+ let stats = client_b.read_response("s2");
+ if stats["success"] == true {
+ break stats;
+ }
+ assert_eq!(stats["success"], false, "the failed stats answer: {stats}");
+ };
+ assert_eq!(
+ restarted["data"]["sessionFile"], fork_file,
+ "the restart serves the fork's file (the boot reconciled the identity)"
+ );
+ assert_eq!(restarted["data"]["sessionId"], fork_durable);
+
+ // The reconciliation re-persisted the repaired record: a future
+ // restart reads the FORK's identity, never the original's.
+ let repaired_record = std::fs::read_to_string(&descriptor_path).expect("the repaired record");
+ assert!(
+ repaired_record.contains(&fork_durable),
+ "the durable record names the fork: {repaired_record}"
+ );
+ assert!(
+ !repaired_record.contains(&format!("\"{original_durable}\"")),
+ "the durable record dropped the original's identity"
+ );
+
+ // THE ISOLATION AT BOOT: the original's routes still open the
+ // original, never the fork worker.
+ let mut client_c = Client::connect(&socket);
+ client_c.send_command(
+ "c3",
+ &serde_json::json!({
+ "type": "create",
+ "sessionPath": original_file,
+ "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": session_dir.to_string_lossy(),
+ "script": script_path.to_string_lossy(),
+ },
+ }),
+ );
+ let reopened = client_c.read_response("c3");
+ assert_eq!(
+ reopened["success"], true,
+ "the boot re-open failed: {reopened}"
+ );
+ assert_eq!(
+ reopened["data"]["sessionId"], original_durable,
+ "the boot's create over the original opens the original, not the fork"
+ );
+ assert_ne!(
+ reopened["data"]["id"], address,
+ "the original's open never reuses the fork worker's address"
+ );
+ client_c.send_command(
+ "a3",
+ &serde_json::json!({ "type": "attach", "activeSessionId": reopened["data"]["id"] }),
+ );
+ let attached_c = client_c.read_response("a3");
+ assert_eq!(attached_c["success"], true, "attach C failed: {attached_c}");
+ let reopened_id = reopened["data"]["id"]
+ .as_str()
+ .expect("the re-opened id")
+ .to_string();
+ client_c.scripted_turn("p3", &reopened_id, "message for the original");
+ assert!(
+ !fork_file_text(&fork_file).contains("message for the original"),
+ "the original's message never reaches the fork's file"
+ );
+
+ // The fork's own sends still flow its own way after the restart.
+ client_b.scripted_turn("p4", &address, "message for the fork");
+ let fork_texts = message_texts(&mut client_b, "m1", &address);
+ assert!(
+ fork_texts
+ .iter()
+ .any(|text| text.contains("message for the fork")),
+ "the fork's own message reaches its transcript: {fork_texts:?}"
+ );
+ assert!(
+ !std::fs::read_to_string(&original_file)
+ .unwrap_or_default()
+ .contains("message for the fork"),
+ "the fork's message never reaches the original's file"
+ );
+}
+
+/// One raw supervisor child (no drop-time kill: the restart test manages
+/// the process itself). The timeout panic path cannot wait on the child;
+/// the test process exits immediately afterwards, reaping it.
+#[allow(clippy::zombie_processes)]
+fn spawn_supervisor_raw(socket: &std::path::Path, agent_dir: &std::path::Path) -> Child {
+ let binary = env!("CARGO_BIN_EXE_pa-daemon");
+ let child = Command::new(binary)
+ .arg("supervisor")
+ .arg("--socket")
+ .arg(socket)
+ .arg("--agent-dir")
+ .arg(agent_dir)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ )
+ .spawn()
+ .expect("spawn pa-daemon supervisor");
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while Instant::now() < deadline {
+ if socket.exists() {
+ return child;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ panic!("supervisor socket never appeared");
+}
+
+/// Kills the supervisor at scope exit (the restart test's supervisor B).
+struct DaemonKillOnDrop<'a> {
+ child: &'a mut Child,
+}
+
+impl Drop for DaemonKillOnDrop<'_> {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}