Skip to main content

rpi_cli/
session.rs

1//! Harness construction + session-storage wiring. Mirrors the Rust-side
2//! equivalent of the TS `packages/coding-agent/src/core/sdk.ts`
3//! (`createAgentSession`) — build the env, tools, durable session storage, and
4//! `AgentHarnessOptions`, then `AgentHarness::create`.
5//!
6//! v1 scope cuts vs the TS SDK (tracked in `docs/m6-cli-open-questions.md`):
7//! - **Skill / prompt-template / context-file discovery IS wired**
8//!   (`--no-skills`/`-ns`, `--no-prompt-templates`/`-np`, `--no-context-files`/
9//!   `-nc` each suppress one channel; project `.rpi/<sub>` + legacy
10//!   `.rpi/<sub>` + global
11//!   `agent_dir()<sub>` discovery with project-wins dedupe via
12//!   [`crate::resource_dirs`]; SYSTEM.md/APPEND_SYSTEM.md project-wins
13//!   precedence). **Extension `resources_discover` (B5b) feeds the SAME loaders:
14//!   a plugin's discovered skill/prompt paths merge with the static dirs and
15//!   re-run through `load_skills`/`load_prompt_templates` (individual `.md` files
16//!   load too — `load_skills` accepts both dirs and files). Package themes are
17//!   parsed by the TUI when selected via settings or `--theme`.**
18//!   Project resources load by default without a prompt. `--no-approve` or a
19//!   stored negative `trust.json` decision disables them explicitly.
20//! - **No `ModelRuntime`/multi-provider registry.** The resolver supports the
21//!   built-in Anthropic/OpenAI-compatible providers and `models.json`, but
22//!   runtime catalog mutation remains outside this layer.
23//! - **Built-in tools**: `read`, `bash`, `edit`, `write`, and the read-only
24//!   `docs` lookup tool. Windows also registers `powershell`.
25//! - **Session restore (`-c`/`-r`/`--session`)** opens the selected JSONL
26//!   journal. These launches enable `allow_existing_session` and replay its
27//!   active branch before appending new messages. See [`SessionSelection`].
28
29use std::collections::{BTreeMap, HashSet};
30use std::path::{Path, PathBuf};
31use std::sync::atomic::Ordering;
32use std::sync::{Arc, Mutex};
33
34use rpi_ai::Provider;
35use rpi_harness::agent_harness::AgentHarness;
36use rpi_harness::context_files::{format_project_context, load_project_context_files};
37use rpi_harness::session::jsonl::{JsonlSessionMetadata, PreparedJsonlRestore};
38use rpi_harness::session::memory::{InMemorySessionStorage, SystemClock};
39use rpi_harness::session::session::DefaultIdGenerator;
40use rpi_harness::session::types::{ForkOptions, SessionMetadata};
41use rpi_harness::session::Session;
42use rpi_harness::system_prompt::compose_system_prompt;
43use rpi_harness::types::{
44    AgentHarnessOptions, AgentHarnessResources, AgentHarnessStreamOptions, DrivingMode,
45    HarnessTool, HarnessToolExecution, ToolReplay,
46};
47#[cfg(windows)]
48use rpi_tools::create_powershell_tool;
49use rpi_tools::{
50    create_bash_tool, create_edit_tool, create_read_tool, create_write_tool, ExecutionToolContext,
51    MutationQueueRegistry, OsExecutionEnv,
52};
53
54use crate::args::Args;
55use crate::docs_tool::create_docs_tool;
56use crate::provider::ResolvedModel;
57use crate::resource_dirs::{
58    load_prompt_templates_with_precedence, load_skills_with_precedence, project_extension_dirs,
59    project_prompt_template_dirs, project_skill_dirs,
60};
61use crate::startup_diagnostics::{Phase, StartupSpan};
62use rpi_extensions::{
63    emit_resources_discover, ExtensionEmitter, ExtensionSession, PluginDiagnostics,
64    PluginToolAdapter, TeeEmitter, ToolPromptMetadata,
65};
66
67// Preserve the existing public modes::rpc signature. This CLI-only attachment
68// table holds no session/router alive and keys by storage allocation identity,
69// NOT by a durable ID (two independent restored hosts must never share routing).
70// The session/tools/ReloadContext own the actual router. RPC owns its client.
71// Reload MUST reuse ReloadContext::file_io, including a disconnected selected
72// client backend; rebuilding a default router would silently restore host file
73// authority. Missing attachments reject configuration (never infer a router or
74// install host-backed replacements). This compatibility bridge can be replaced
75// by an explicit neutral harness attachment when its public API is revised.
76type FileIOAttachment = (
77    std::sync::Weak<dyn rpi_harness::session::types::SessionStorage>,
78    std::sync::Weak<rpi_tools::file_io::FileIORouter>,
79);
80fn file_io_attachments() -> &'static Mutex<Vec<FileIOAttachment>> {
81    static ATTACHMENTS: std::sync::OnceLock<Mutex<Vec<FileIOAttachment>>> =
82        std::sync::OnceLock::new();
83    ATTACHMENTS.get_or_init(|| Mutex::new(Vec::new()))
84}
85pub(crate) fn register_file_io_router(
86    harness: &AgentHarness,
87    router: &Arc<rpi_tools::file_io::FileIORouter>,
88) {
89    let storage = harness.session().storage();
90    let mut attachments = file_io_attachments()
91        .lock()
92        .expect("file I/O attachments poisoned");
93    attachments.retain(|(s, r)| {
94        s.strong_count() > 0
95            && r.strong_count() > 0
96            && !s
97                .upgrade()
98                .is_some_and(|known| Arc::ptr_eq(&known, &storage))
99    });
100    attachments.push((Arc::downgrade(&storage), Arc::downgrade(router)));
101}
102pub(crate) fn file_io_router(
103    harness: &AgentHarness,
104) -> Option<Arc<rpi_tools::file_io::FileIORouter>> {
105    let storage = harness.session().storage();
106    let mut attachments = file_io_attachments()
107        .lock()
108        .expect("file I/O attachments poisoned");
109    attachments.retain(|(s, r)| s.strong_count() > 0 && r.strong_count() > 0);
110    attachments.iter().find_map(|(s, r)| {
111        s.upgrade()
112            .filter(|known| Arc::ptr_eq(known, &storage))
113            .and_then(|_| r.upgrade())
114    })
115}
116
117/// The coding tools registered by the CLI by default.
118pub const BUILTIN_TOOL_NAMES: &[&str] = &["read", "bash", "edit", "write", "docs"];
119
120/// The default coding system prompt for the CLI's built-in tools.
121///
122/// This retains the two-argument API for library callers. Session startup and
123/// reload use [`default_system_prompt_with_tool_prompts`] with the actual active
124/// tools and their winning extension metadata.
125pub fn default_system_prompt(cwd: &str, prior_reasoning_replayed: bool) -> String {
126    let tools = BUILTIN_TOOL_NAMES
127        .iter()
128        .map(|name| (*name).to_owned())
129        .collect::<Vec<_>>();
130    default_system_prompt_with_tools(cwd, prior_reasoning_replayed, &tools)
131}
132
133/// A coding system prompt for the selected tools. A condensed port of the TS
134/// `packages/coding-agent/src/core/system-prompt.ts` base prompt.
135///
136/// `tools` is the active tool set after `--tools`/`--exclude-tools` and
137/// extension merging. Like pi, the text list includes only tools with an
138/// explicit prompt snippet; other active tools remain available through their
139/// provider-facing schemas. Tool-specific guidelines still follow the full
140/// active set, so restricted runs get no guidance for unavailable tools.
141pub fn default_system_prompt_with_tools(
142    cwd: &str,
143    prior_reasoning_replayed: bool,
144    tools: &[String],
145) -> String {
146    default_system_prompt_with_tool_prompts(cwd, prior_reasoning_replayed, tools, &BTreeMap::new())
147}
148
149/// Render pi-style explicit prompt contributions for the active tool set.
150/// Entries override built-in metadata, including an empty entry for an
151/// extension that replaces a built-in without contributing a prompt snippet.
152/// Inactive metadata is ignored. Schemas and callable tools are not modified.
153pub fn default_system_prompt_with_tool_prompts(
154    cwd: &str,
155    prior_reasoning_replayed: bool,
156    tools: &[String],
157    overrides: &BTreeMap<String, ToolPromptMetadata>,
158) -> String {
159    let metadata: BTreeMap<_, _> = tools
160        .iter()
161        .map(|name| {
162            let prompt = overrides
163                .get(name)
164                .cloned()
165                .unwrap_or_else(|| ToolPromptMetadata {
166                    prompt_snippet: builtin_tool_snippet(name).map(str::to_owned),
167                    prompt_guidelines: Vec::new(),
168                })
169                .normalized();
170            (name.as_str(), prompt)
171        })
172        .collect();
173    // The working-state rule must match what actually comes back on the next
174    // request. With `compat.requiresThinkingAsText` (or the native thinking
175    // channels of anthropic/responses) the model *does* see its own reasoning
176    // again, and claiming otherwise makes it re-derive and restate the plan
177    // every turn — the re-plan symptom in `docs/llm-repetition-forensics.md`.
178    let working_state_rule = if prior_reasoning_replayed {
179        "- Your reasoning is carried back to you on the next turn: do not re-derive it or restate
180  the plan. Continue from the last unfinished step, and when a step lands, say which one.
181  Re-stating the same plan without acting on it is a bug, not progress."
182    } else {
183        "- Your reasoning is not carried into your next turn; only your visible replies and tool
184  output come back. Before each batch of tool calls, write one short line naming the step you
185  are on and what remains, and say which step is done when it lands.
186  Re-stating the same plan without acting on it is a bug, not progress."
187    };
188
189    // The text list is a selective summary, not the tool registry. In
190    // particular, do not repeat extension tool names without a prompt snippet.
191    let tool_lines = tools
192        .iter()
193        .filter_map(|name| {
194            metadata
195                .get(name.as_str())?
196                .prompt_snippet
197                .as_ref()
198                .map(|snippet| format!("- {name:<5} — {snippet}"))
199        })
200        .collect::<Vec<_>>()
201        .join("\n");
202    let tool_lines = if tool_lines.is_empty() {
203        "(none)".to_string()
204    } else {
205        tool_lines
206    };
207
208    // Tool-specific rules (Bash on Windows, docs before guessing) live in the
209    // tool's own line or description, not here a second time.
210    let guidelines = [
211        "- Reply in the same language as the user's latest message (the conversation's language when
212  that message is too short to tell), unless the user asks for another.",
213        "- Be concise in your responses",
214        "- Show file paths clearly when working with files",
215        "- Prefer the smallest change that solves the problem",
216        working_state_rule,
217        "- Read only what you need. If a file or search result was already shown earlier in this
218  conversation, use it instead of fetching it again.",
219    ];
220    // Tools contribute rules even without snippets. Like pi, trim and dedupe
221    // across the full active set and the core rules, preserving first occurrence.
222    let mut seen = HashSet::new();
223    let tool_rules = tools
224        .iter()
225        .flat_map(|name| &metadata[name.as_str()].prompt_guidelines)
226        .map(String::as_str);
227    let core_rules = guidelines
228        .iter()
229        .map(|rule| rule.strip_prefix("- ").unwrap_or(rule));
230    let guidelines = tool_rules
231        .chain(core_rules)
232        .map(str::trim)
233        .filter(|rule| !rule.is_empty() && seen.insert(*rule))
234        .map(|rule| format!("- {rule}"))
235        .collect::<Vec<_>>()
236        .join("\n");
237
238    format!(
239        "You are an expert coding assistant operating inside rpi, a coding agent harness. \
240You help users by reading files, executing commands, editing code, and writing new files.
241
242Available tools:
243{tool_lines}
244
245In addition to the tools above, you may have access to other custom tools depending on the project.
246
247Guidelines:
248{guidelines}
249
250Current working directory: {cwd}"
251    )
252}
253
254/// Take metadata from the same winning extension definitions used for tool
255/// merging, including empty metadata for overrides. Called on startup/reload.
256fn extension_tool_prompt_metadata(
257    session: &ExtensionSession,
258) -> BTreeMap<String, ToolPromptMetadata> {
259    session
260        .snapshot()
261        .map(|snapshot| {
262            snapshot
263                .tools()
264                .iter()
265                .map(|tool| (tool.tool.name.clone(), tool.prompt.clone()))
266                .collect()
267        })
268        .unwrap_or_default()
269}
270
271/// One-line prompt descriptions of the tools rpi itself registers.
272fn builtin_tool_snippet(name: &str) -> Option<&'static str> {
273    Some(match name {
274        "read" => "Read file contents",
275        "bash" => "Execute Bash commands (Bash/POSIX syntax, also on Windows)",
276        "edit" => "Find/replace edits to existing files",
277        "write" => "Create or overwrite files",
278        "docs" => "Look up rpi commands, extensions, Pi package compatibility and .rpi configuration instead of guessing",
279        "powershell" => "Execute PowerShell commands on Windows",
280        _ => return None,
281    })
282}
283
284/// How a launch selects its session. A restored session renders its transcript
285/// into the TUI on startup and continues appending to the selected JSONL file.
286#[derive(Debug, Clone)]
287pub enum SessionSelection {
288    /// `--no-session`: ephemeral, in-memory, nothing persisted.
289    Ephemeral,
290    /// Fresh durable JSONL session under `--session-dir` (or the default dir).
291    New { dir: PathBuf, name: Option<String> },
292    /// `-c`: restore the most recent resumable session in the configured dir.
293    Latest { dir: PathBuf },
294    /// `--session <id|path>`: restore a session by path or unambiguous selector.
295    ById { id: String, dir: PathBuf },
296    /// `--session-id <id>`: use the EXACT session id, creating it if missing.
297    ByExactId { id: String, dir: PathBuf },
298    /// `--fork <path|id>`: fork the given session into a new one and start in
299    /// the fork. `entry_id` optionally cuts the new branch at a message;
300    /// `position` says whether that message stays (`at`) or is dropped
301    /// (`before`). `None` keeps the harness default for an explicit entry
302    /// (`before`).
303    Fork {
304        source: String,
305        dir: PathBuf,
306        entry_id: Option<String>,
307        position: Option<rpi_harness::session::types::ForkPosition>,
308    },
309}
310
311/// Decide the session selection from parsed args + the resolved cwd.
312pub fn select_session(args: &Args, cwd: &Path) -> SessionSelection {
313    select_session_for(&crate::config::AgentHome::process(), args, cwd)
314}
315
316/// [`select_session`] for one agent home (library-embedded harnesses).
317pub fn select_session_for(
318    home: &crate::config::AgentHome,
319    args: &Args,
320    cwd: &Path,
321) -> SessionSelection {
322    select_session_in_dir(args, configured_session_dir_for(home, args, cwd))
323}
324
325/// Resolve the root once at startup; runtime actions retain this selection.
326pub(crate) fn configured_session_dir(args: &Args, cwd: &Path) -> PathBuf {
327    configured_session_dir_for(&crate::config::AgentHome::process(), args, cwd)
328}
329
330pub(crate) fn configured_session_dir_for(
331    home: &crate::config::AgentHome,
332    args: &Args,
333    cwd: &Path,
334) -> PathBuf {
335    let dir = args
336        .session_dir
337        .clone()
338        .or_else(|| {
339            home.settings()
340                .ok()
341                .and_then(|settings| settings.session_dir)
342        })
343        // An explicitly provided home owns its transcripts; the process-wide
344        // env override only applies when the home is the process home (CLI).
345        // Otherwise a library host that passes home B while the environment
346        // still names A would silently write B's sessions into A.
347        .or_else(|| {
348            home.is_explicit()
349                .then(|| home.root().ok().map(|root| root.join("sessions")))
350                .flatten()
351        })
352        .or_else(|| std::env::var_os("RPI_CODING_AGENT_SESSION_DIR").map(PathBuf::from))
353        .unwrap_or_else(|| default_session_dir(cwd));
354    // Relative roots belong to the launch project, even if an extension later
355    // changes the process working directory.
356    if dir.is_relative() && !dir.has_root() {
357        cwd.join(dir)
358    } else {
359        dir
360    }
361}
362
363pub(crate) fn select_session_in_dir(args: &Args, dir: PathBuf) -> SessionSelection {
364    if args.no_session {
365        return SessionSelection::Ephemeral;
366    }
367    // `--session-dir` wins; then the saved `sessionDir` (upstream's key, same
368    // format as the flag); then the built-in default. Keep this directory on
369    // restore selections too, not only on fresh sessions.
370    if args.continue_session || args.resume {
371        return SessionSelection::Latest { dir };
372    }
373    if let Some(s) = &args.fork {
374        return SessionSelection::Fork {
375            source: s.clone(),
376            dir,
377            entry_id: args.fork_entry.clone(),
378            position: args.fork_position,
379        };
380    }
381    if let Some(s) = &args.session_id {
382        return SessionSelection::ByExactId { id: s.clone(), dir };
383    }
384    if let Some(s) = &args.session {
385        return SessionSelection::ById { id: s.clone(), dir };
386    }
387    SessionSelection::New {
388        dir,
389        name: args.name.clone(),
390    }
391}
392
393/// The default session directory is `<cwd>/.rpi/sessions`, unless
394/// `RPI_CODING_AGENT_SESSION_DIR` is set (in which case its value is used).
395pub fn default_session_dir(cwd: &Path) -> PathBuf {
396    std::env::var("RPI_CODING_AGENT_SESSION_DIR")
397        .ok()
398        .map(PathBuf::from)
399        .unwrap_or_else(|| cwd.join(".rpi").join("sessions"))
400}
401
402#[cfg(unix)]
403type HostPluginImages = Arc<rpi_extensions::SharedPluginImages>;
404#[cfg(not(unix))]
405type HostPluginImages = ();
406
407/// Extensions are loaded exactly once before model resolution. Their action
408/// host remains unbound until the harness and authenticated catalog exist.
409pub struct PreparedExtensions {
410    plugin_cleanup: Arc<crate::host::cli_cleanup::PluginCleanupLedger>,
411    host_plugin_images: Option<HostPluginImages>,
412    resource_leases: Arc<Vec<crate::resource_management::Lease>>,
413    resource_selection: Option<crate::resource_selection::ResolvedSelection>,
414    session_selection: SessionSelection,
415    transition_session: Option<Session>,
416    pub extension_session: ExtensionSession,
417    session_dir: PathBuf,
418    runtime: tokio::runtime::Handle,
419    tool_context: rpi_extensions::ToolCallContext,
420    action_host: Arc<crate::extensions_actions::HarnessActionHost>,
421    harness_cell: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
422    reload_mailbox: rpi_extensions::ReloadMailbox,
423    ui_dialog_mailbox: rpi_extensions::UiDialogMailbox,
424    ext_status_mailbox: rpi_extensions::ExtensionStatusMailbox,
425    editor_text_mailbox: rpi_extensions::EditorTextMailbox,
426    action_bridge: Arc<rpi_extensions::ActionBridge>,
427    resolved_session: Option<JsonlSessionMetadata>,
428    prepared_restore: Option<PreparedJsonlRestore>,
429}
430
431/// Validate native durable resource ownership BEFORE loading any executable code.
432/// The synchronous public prepare_extensions API is retained: a scoped reader
433/// thread uses its own runtime so this also works inside current-thread Tokio.
434/// It does no registration, provider callbacks, session creation, or lock claiming.
435pub(crate) fn preflight_extension_startup(
436    args: &Args,
437    cwd: &Path,
438    trusted: bool,
439    restored: Option<&RestoredSessionCwd>,
440) -> Result<(), BuildError> {
441    preflight_extension_startup_with_restore(
442        &crate::config::AgentHome::process(),
443        args,
444        cwd,
445        trusted,
446        false,
447        restored,
448    )?;
449    Ok(())
450}
451
452struct SessionPreflight {
453    selection: SessionSelection,
454    resolved_session: Option<JsonlSessionMetadata>,
455    prepared_restore: Option<PreparedJsonlRestore>,
456}
457
458// A previous frontend can finish writing between replay and acquisition.
459// Retry only a stale replay, before registering any extensions, and keep the
460// same Session and workspace through the next preflight.
461async fn prepare_host_restore(
462    repo: &rpi_harness::session::jsonl::JsonlSessionRepo,
463    meta: &rpi_harness::session::jsonl::JsonlSessionMetadata,
464    mut validate: impl FnMut(&rpi_harness::session::SessionValues) -> Result<(), String>,
465) -> Result<rpi_harness::session::jsonl::PreparedJsonlRestore, BuildError> {
466    for _ in 0..2 {
467        let replay = StartupSpan::start(Phase::PreparedReplay);
468        let prepared = repo
469            .prepare_restore_by_jsonl_metadata(meta)
470            .await
471            .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
472        replay.finish();
473        let read_facts = StartupSpan::start(Phase::PreparedFacts);
474        let facts = prepared
475            .facts()
476            .await
477            .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
478        read_facts.finish();
479        if facts.metadata.cwd != meta.cwd || facts.metadata.created_at != meta.created_at {
480            return Err(BuildError::SessionOpen(
481                "session identity changed during restore preparation; reopen session".into(),
482            ));
483        }
484        validate(&facts.values).map_err(BuildError::SessionOpen)?;
485        if let Some(current) = prepared
486            .reserve_current_writer()
487            .await
488            .map_err(|e| BuildError::SessionOpen(e.to_string()))?
489        {
490            return Ok(current);
491        }
492    }
493    Err(BuildError::SessionOpen(
494        "session history changed during restore preparation; reopen session".into(),
495    ))
496}
497
498fn preflight_extension_startup_with_restore(
499    home: &crate::config::AgentHome,
500    args: &Args,
501    cwd: &Path,
502    trusted: bool,
503    prepare_restore: bool,
504    restored: Option<&RestoredSessionCwd>,
505) -> Result<
506    (
507        Option<crate::resource_selection::ResolvedSelection>,
508        SessionPreflight,
509    ),
510    BuildError,
511> {
512    let resource_selection_load = StartupSpan::start(Phase::ResourceSelectionLoad);
513    let mut resources =
514        crate::resource_selection::ResolvedSelection::load_for(home, args, cwd, trusted)
515            .map_err(BuildError::HarnessCreate)?;
516    let selection = select_session_for(home, args, cwd);
517    resource_selection_load.finish();
518    let (resolved_session, prepared_restore) = std::thread::scope(|scope| {
519        scope
520            .spawn(|| {
521                tokio::runtime::Builder::new_current_thread()
522                    .enable_all()
523                    .build()
524                    .map_err(|e| BuildError::SessionOpen(e.to_string()))?
525                    .block_on(async {
526                        if let Some(selected) = &mut resources {
527                            let skill_validate = StartupSpan::start(Phase::SkillValidate);
528                            let env: Arc<dyn rpi_tools::ExecutionEnv> =
529                                Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf()));
530                            selected
531                                .validate_skills(&env)
532                                .await
533                                .map_err(BuildError::HarnessCreate)?;
534                            skill_validate.finish();
535                        }
536                        let restore_target = StartupSpan::start(Phase::RestoreTarget);
537                        let cwd_str = cwd.to_string_lossy();
538                        let target = if let Some(restored) = restored {
539                            Some(restored.metadata_for_restore()?)
540                        } else {
541                            match &selection {
542                                SessionSelection::Fork { source, dir, .. } => {
543                                    Some(resolve_fork_source(source, &cwd_str, dir).await?)
544                                }
545                                _ => resolve_restore_target(&selection, &cwd_str).await?,
546                            }
547                        };
548                        restore_target.finish();
549                        let Some(mut meta) = target else {
550                            if resources.as_ref().is_some_and(|r| r.transition.is_some()) {
551                                return Err(BuildError::SessionOpen("resource transition requires an existing native session".into()));
552                            }
553                            return Ok((None, None));
554                        };
555                        if resources.as_ref().is_some_and(|r| r.transition.is_some()) && matches!(selection, SessionSelection::Fork { .. }) {
556                            return Err(BuildError::SessionOpen("resource transition cannot fork".into()));
557                        }
558                        use rpi_harness::session::jsonl::{
559                            JsonlSessionRepo, JsonlSessionRepoOptions,
560                        };
561                        let dir = selection_dir(&selection);
562                        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
563                            fs: Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())),
564                            sessions_root: dir.to_string_lossy().into_owned(),
565                            clock: Arc::new(SystemClock),
566                            ids: Arc::new(DefaultIdGenerator::new()),
567                        });
568                        let transition = resources.as_ref().is_some_and(|r| r.transition.is_some());
569                        let fork = matches!(selection, SessionSelection::Fork { .. });
570                        if transition || fork {
571                            meta.path = std::fs::canonicalize(&meta.path)
572                                .map_err(|error| BuildError::SessionOpen(format!("resolve {}: {error}", meta.path)))?
573                                .to_string_lossy()
574                                .into_owned();
575                        }
576                        let validate = |values: &rpi_harness::session::SessionValues| {
577                            let binding_validate = StartupSpan::start(Phase::BindingValidate);
578                            let result = crate::resource_selection::validate_session_binding(
579                                values,
580                                resources.as_ref(),
581                            );
582                            binding_validate.finish();
583                            result
584                        };
585                        let prepared = if prepare_restore && !transition && !fork {
586                            Some(prepare_host_restore(&repo, &meta, validate).await?)
587                        } else {
588                            let facts = if transition {
589                                rpi_harness::session::jsonl::JsonlSessionStorage::read_resource_transition_facts(
590                                    Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())), &meta.path,
591                                    Arc::new(SystemClock), Arc::new(DefaultIdGenerator::new()),
592                                )
593                                .await
594                            } else {
595                                repo.read_facts_by_jsonl_metadata(&meta).await
596                            }
597                            .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
598                            if let Some(restored) = restored {
599                                restored.verify_metadata(&facts.metadata)?;
600                            }
601                            validate(&facts.values).map_err(BuildError::SessionOpen)?;
602                            None
603                        };
604                        Ok((Some(meta), prepared))
605                    })
606            })
607            .join()
608            .map_err(|_| BuildError::SessionOpen("resource preflight reader panicked".into()))?
609    })?;
610    Ok((
611        resources,
612        SessionPreflight {
613            selection,
614            resolved_session,
615            prepared_restore,
616        },
617    ))
618}
619
620pub fn prepare_extensions(
621    home: &crate::config::AgentHome,
622    args: &Args,
623    cwd: &Path,
624    project_trusted: bool,
625) -> Result<PreparedExtensions, BuildError> {
626    prepare_extensions_inner(home, args, cwd, project_trusted, None, None)
627}
628
629pub(crate) fn prepare_cli_extensions(
630    args: &Args,
631    cwd: &Path,
632    project_trusted: bool,
633    restored: Option<&RestoredSessionCwd>,
634) -> Result<PreparedExtensions, BuildError> {
635    prepare_extensions_inner(
636        &crate::config::AgentHome::process(),
637        args,
638        cwd,
639        project_trusted,
640        None,
641        restored,
642    )
643}
644
645#[cfg(unix)]
646pub(crate) fn prepare_host_extensions(
647    home: &crate::config::AgentHome,
648    args: &Args,
649    cwd: &Path,
650    project_trusted: bool,
651    images: HostPluginImages,
652    restored: Option<&RestoredSessionCwd>,
653) -> Result<PreparedExtensions, BuildError> {
654    prepare_extensions_inner(home, args, cwd, project_trusted, Some(images), restored)
655}
656
657fn prepare_extensions_inner(
658    home: &crate::config::AgentHome,
659    args: &Args,
660    cwd: &Path,
661    project_trusted: bool,
662    host_plugin_images: Option<HostPluginImages>,
663    restored: Option<&RestoredSessionCwd>,
664) -> Result<PreparedExtensions, BuildError> {
665    let shared_host = host_plugin_images.is_some();
666    crate::native_durable::experimental_epoch::policy(args).map_err(BuildError::HarnessCreate)?;
667    let resource_leases = crate::resource_management::host_leases_for(home, cwd)
668        .map_err(BuildError::HarnessCreate)?;
669    let preflight_prepare = StartupSpan::start(Phase::PreflightPrepare);
670    let (
671        resource_selection,
672        SessionPreflight {
673            selection: session_selection,
674            resolved_session,
675            prepared_restore,
676        },
677    ) = preflight_extension_startup_with_restore(home, args, cwd, project_trusted, true, restored)?;
678    preflight_prepare.finish();
679    // Transition hosts own the writer before any DLL registration. The strict
680    // loader cannot repair history/progress or migrate metadata on rejection.
681    let transition_session = if resource_selection
682        .as_ref()
683        .is_some_and(|r| r.transition.is_some())
684    {
685        Some(std::thread::scope(|scope| {
686            scope.spawn(|| {
687            tokio::runtime::Builder::new_current_thread().enable_all().build()
688                .map_err(|e| BuildError::SessionOpen(e.to_string()))?.block_on(async {
689                    let meta = resolved_session.as_ref().ok_or_else(|| {
690                        BuildError::SessionOpen("transition session disappeared".into())
691                    })?;
692                    let storage = rpi_harness::session::jsonl::JsonlSessionStorage::load_for_resource_transition(
693                        Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())), &meta.path,
694                        Arc::new(SystemClock), Arc::new(DefaultIdGenerator::new()),
695                    ).await.map_err(|e| BuildError::SessionOpen(e.to_string()))?;
696                    if let Some(restored) = restored {
697                        restored.verify_metadata(&storage.jsonl_metadata())?;
698                    }
699                    storage.acquire_writer_lease().await.map_err(|e| BuildError::SessionOpen(e.to_string()))?;
700                    let session = Session::new(Arc::new(storage), None);
701                    crate::resource_selection::bind_session(&session, resource_selection.as_ref()).await.map_err(BuildError::SessionOpen)?;
702                    Ok::<_, BuildError>(session)
703                })
704        }).join().map_err(|_| BuildError::SessionOpen("transition writer preparation panicked".into()))?
705        })?)
706    } else {
707        None
708    };
709    let session_dir = if matches!(session_selection, SessionSelection::Ephemeral) {
710        configured_session_dir_for(home, args, cwd)
711    } else {
712        selection_dir(&session_selection)
713    };
714    let cwd_str = cwd.to_string_lossy().to_string();
715    let tool_context = rpi_extensions::ToolCallContext::new(cwd_str.clone());
716    tool_context.set_project_resources_allowed(project_trusted);
717    if !project_trusted && args.verbose {
718        eprintln!(
719            "warning: current-project settings, resources, and discovered extensions are explicitly disabled (use --approve or /trust yes to re-enable)"
720        );
721    }
722    // Pi packages are explicitly opt-in because discovery can start Node and
723    // execute package code. An explicit project opt-out limits discovery to
724    // global settings.
725
726    // ---- B5a: build the action bridge BEFORE extension load ----
727    // Extensions load before `AgentHarness::create` (extensions provide tools the
728    // harness is built with), but a plugin stores the `ActionBridge`'s raw
729    // `user_data` pointer during `register` and it must remain valid + the host
730    // must be ready for the whole session. So:
731    //  1. Capture the current tokio `Handle` (the async main-thread runtime) —
732    //     the bridge spawns dispatch from any thread via `Handle::spawn`.
733    //  2. Build an *empty* `HarnessActionHost` (its harness cell is unset; no
734    //     plugin can call a runtime action before the harness runs).
735    //  3. Wrap it as `Arc<dyn RuntimeActionHost>` + `ActionBridge`, thread
736    //     `Some(bridge)` into `load_extensions` so every plugin's `user_data`
737    //     points at this bridge.
738    //  4. After `AgentHarness::create` succeeds, call `set_harness(&cell, …)` to
739    //     fill the host cell the bridge recovers on the first action call.
740    let runtime = tokio::runtime::Handle::try_current().map_err(|e| {
741        BuildError::HarnessCreate(format!("no tokio runtime for action bridge: {e}"))
742    })?;
743    let catalog = Vec::new();
744    let (action_host, harness_cell) = crate::extensions_actions::HarnessActionHost::new_empty(
745        catalog.clone(),
746        cwd.to_path_buf(),
747        runtime.clone(),
748        args.unknown_flags.clone(),
749        tool_context.clone(),
750    );
751    let action_host = Arc::new(
752        action_host
753            .with_session_dir(session_dir.clone())
754            .with_ephemeral_sessions_only(args.mini)
755            .with_process_identity(!shared_host)
756            .with_native_durable(args.native_durable),
757    );
758    let host_arc: Arc<dyn rpi_extensions::RuntimeActionHost> = action_host.clone();
759    // `runtime` is reused below (B5c: `PluggableProvider` needs a captured
760    // `Handle` to `spawn_blocking` the sync `ProviderRequestFn`), so clone here.
761    //
762    // B5d: build the initial bridge WITH a reload callback backed by a session-
763    // long `ReloadMailbox` (cloned into `ReloadContext` + handed to the TUI). A
764    // plugin's `runtime_action(Reload)` then signals the TUI's main loop instead
765    // of hitting the "not configured" fallback. The same mailbox is reused on
766    // `/reload` (the fresh bridge carries `ctx.mailbox`), so the bridge always
767    // points at the one TUI-installed sender across reloads.
768    let reload_mailbox = rpi_extensions::ReloadMailbox::new();
769    // Session-scoped UI-dialog mailbox (runtime action 17 / `ask_user`). The
770    // initial bridge carries it and the TUI attaches itself once it starts
771    // polling; a headless run leaves it detached so `ask_user` fails loudly
772    // instead of fabricating a user answer. The SAME mailbox is reused across
773    // `/reload` so in-flight prompts + TUI attachment survive a plugin swap.
774    let ui_dialog_mailbox = rpi_extensions::UiDialogMailbox::new();
775    // Session-scoped extension status registry (runtime action 18 / `SetStatus`).
776    // The bridge lets plugins write; the TUI polls the revision and repaints its
777    // footer. Reused across `/reload` so a plugin's status survives the swap.
778    let ext_status_mailbox = rpi_extensions::ExtensionStatusMailbox::new();
779    // Session-scoped editor-text queue (runtime action 19 / `SetEditorText`).
780    // The bridge lets a plugin drop a draft into the prompt editor; the TUI
781    // drains it each tick. Reused across `/reload` so a pending transcription
782    // survives a plugin swap.
783    let editor_text_mailbox = rpi_extensions::EditorTextMailbox::new();
784    let action_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
785        runtime.clone(),
786        host_arc,
787        rpi_extensions::reload_callback_from_mailbox(reload_mailbox.clone()),
788        ui_dialog_mailbox.clone(),
789        ext_status_mailbox.clone(),
790        editor_text_mailbox.clone(),
791    );
792    if shared_host {
793        action_bridge.disable_stdio_claims();
794    }
795
796    let plugin_cleanup = crate::host::cli_cleanup::PluginCleanupLedger::new();
797    let diagnostics = crate::host::cli_cleanup::PluginLoadDiagnostics::new(plugin_cleanup.clone());
798    let extension_register = StartupSpan::start(Phase::ExtensionRegister);
799    let extension_session = if let Some(selected) = &resource_selection {
800        let session = rpi_extensions::load_session_mixed_guarded(
801            &[],
802            &selected.extensions,
803            diagnostics.clone(),
804            Some(Arc::clone(&action_bridge)),
805            Some(resource_leases.clone()),
806        );
807        if session.loaded_paths() != selected.extensions.as_slice() {
808            let mut details = vec!["selected native extension failed to load/register".to_owned()];
809            details.extend(diagnostics.take());
810            return Err(BuildError::HarnessCreate(details.join("\n")));
811        }
812        if session.owns_stdio() {
813            return Err(BuildError::HarnessCreate(
814                "stdio-owning extensions are unsupported with --resource-config".into(),
815            ));
816        }
817        session
818    } else if args.no_extensions {
819        ExtensionSession::none()
820    } else {
821        let dirs = startup_extension_dirs(home, args, cwd, project_trusted);
822        load_extensions_from_dirs(
823            home,
824            args,
825            &dirs,
826            Some(Arc::clone(&action_bridge)),
827            Some(resource_leases.clone()),
828            diagnostics.clone(),
829            host_plugin_images.as_ref(),
830        )
831    };
832    for detail in diagnostics.take() {
833        eprintln!("warning: {detail}");
834    }
835    if args.verbose {
836        if let Some(s) = extension_session.summary() {
837            eprintln!("extensions: {s}");
838        }
839        report_deferred_renderers(&extension_session);
840    }
841    validate_durable_extensions(&extension_session).map_err(BuildError::HarnessCreate)?;
842    extension_register.finish();
843    // Publish the extension registry so `ListCommands` can enumerate slash
844    // commands. Done here rather than at host construction because the registry
845    // only exists after extensions load; `/reload` republishes the new snapshot
846    // via `RuntimeActionHost::publish_registry`.
847    action_host.publish_registry_impl(extension_session.snapshot_arc());
848    Ok(PreparedExtensions {
849        plugin_cleanup,
850        host_plugin_images,
851        resource_leases,
852        resource_selection,
853        session_selection,
854        transition_session,
855        session_dir,
856        runtime,
857        tool_context,
858        action_host,
859        harness_cell,
860        reload_mailbox,
861        ui_dialog_mailbox,
862        ext_status_mailbox,
863        editor_text_mailbox,
864        action_bridge,
865        extension_session,
866        resolved_session,
867        prepared_restore,
868    })
869}
870
871/// Build the `AgentHarness` from the resolved model + parsed args + cwd.
872///
873/// This is the v1 equivalent of TS `createAgentSession`. It:
874/// 1. Builds the `OsExecutionEnv` rooted at `cwd`.
875/// 2. Constructs the built-in tools (optionally filtered by `--tools`/
876///    `--exclude-tools`/`--no-tools`/`--no-builtin-tools`).
877/// 3. Resolves the session storage (ephemeral vs fresh JSONL vs restore-error).
878/// 4. Assembles `AgentHarnessOptions` and calls `AgentHarness::create`.
879///
880/// Returns the harness plus a `broadcast::Receiver<AgentEvent>` carrying the
881/// live `AgentEvent` stream from every run (backed by a `BroadcastEmitter`
882/// installed on the harness). Interactive mode drains this to render streaming
883/// responses; the non-interactive modes simply drop it.
884/// Returns the harness, the live `AgentEvent` broadcast receiver, and a
885/// [`ReloadContext`] the interactive TUI holds to drive `/reload` (and a
886/// plugin's `runtime_action(Reload)` via the mailbox). Non-interactive modes
887/// drop the context (no `/reload` surface in print/json mode).
888///
889/// `home` is the one agent-home value for this session: settings/auth/models/
890/// trust, skills/prompts/extensions/SYSTEM.md discovery, resource leases and
891/// the native-package artifacts used by extension loading all read from it.
892/// CLI callers pass [`AgentHome::process`](crate::config::AgentHome::process),
893/// which preserves the historical `RPI_CODING_AGENT_DIR`/`~/.rpi/agent`
894/// behavior; embedding hosts pass an explicit home and can run several
895/// sessions with different homes in one process without mutating the process
896/// environment.
897pub async fn build(
898    home: &crate::config::AgentHome,
899    resolved: &ResolvedModel,
900    args: &Args,
901    cwd: &Path,
902    project_trusted: bool,
903) -> Result<
904    (
905        AgentHarness,
906        tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>,
907        ReloadContext,
908    ),
909    BuildError,
910> {
911    let prepared = prepare_extensions(home, args, cwd, project_trusted)?;
912    build_prepared(home, resolved, args, cwd, project_trusted, prepared).await
913}
914
915/// The three resource families that share the same project/global/trust
916/// selection ladder. Keeping one implementation prevents a new family (themes,
917/// packages) from silently missing the explicit home on one of the three call
918/// sites.
919#[derive(Clone, Copy, PartialEq, Eq)]
920enum ResourceRootKind {
921    Extensions,
922    Skills,
923    PromptTemplates,
924}
925
926fn resource_root_dirs(
927    home: &crate::config::AgentHome,
928    args: &Args,
929    cwd: &Path,
930    project_trusted: bool,
931    kind: ResourceRootKind,
932) -> Vec<PathBuf> {
933    if (kind == ResourceRootKind::Extensions && args.no_extensions)
934        || (kind == ResourceRootKind::Skills && args.no_skills)
935        || (kind == ResourceRootKind::PromptTemplates && args.no_prompt_templates)
936    {
937        return Vec::new();
938    }
939    let mut dirs = if kind == ResourceRootKind::Extensions && args.dev_local_only {
940        // `dev-local` never imports unrelated global/project extension dirs;
941        // explicit `--extensions-dir` paths are appended below.
942        Vec::new()
943    } else if args.project_only {
944        match kind {
945            ResourceRootKind::Extensions => project_extension_dirs(cwd),
946            ResourceRootKind::Skills => project_skill_dirs(cwd),
947            ResourceRootKind::PromptTemplates => project_prompt_template_dirs(cwd),
948        }
949    } else if project_trusted {
950        match kind {
951            ResourceRootKind::Extensions => home.extension_dirs(cwd),
952            ResourceRootKind::Skills => home.skill_dirs(cwd),
953            ResourceRootKind::PromptTemplates => home.prompt_template_dirs(cwd),
954        }
955    } else {
956        match kind {
957            ResourceRootKind::Extensions => home.global_extension_dirs(),
958            ResourceRootKind::Skills => home.global_skill_dirs(),
959            ResourceRootKind::PromptTemplates => home.global_prompt_template_dirs(),
960        }
961    };
962    match kind {
963        ResourceRootKind::Extensions => dirs.extend(args.extensions_dir.iter().cloned()),
964        ResourceRootKind::Skills => dirs.extend(args.skill.iter().cloned()),
965        ResourceRootKind::PromptTemplates => dirs.extend(args.prompt_template.iter().cloned()),
966    }
967    dirs
968}
969
970pub async fn build_prepared(
971    home: &crate::config::AgentHome,
972    resolved: &ResolvedModel,
973    args: &Args,
974    cwd: &Path,
975    project_trusted: bool,
976    prepared: PreparedExtensions,
977) -> Result<
978    (
979        AgentHarness,
980        tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>,
981        ReloadContext,
982    ),
983    BuildError,
984> {
985    let experimental_policy = crate::native_durable::experimental_epoch::policy(args)
986        .map_err(BuildError::HarnessCreate)?;
987    let cwd_str = cwd.to_string_lossy().to_string();
988    // Plugin tools get the session's identity injected into every call's
989    // arguments (see `rpi_extensions::ToolCallContext`). It is created here,
990    // before the tools are built, and completed with the session id below once
991    // the session exists — the tool set has to exist before the harness does.
992    let PreparedExtensions {
993        plugin_cleanup,
994        host_plugin_images,
995        resource_leases,
996        resource_selection,
997        session_selection: selection,
998        transition_session,
999        session_dir,
1000        runtime,
1001        tool_context,
1002        action_host,
1003        harness_cell,
1004        reload_mailbox,
1005        ui_dialog_mailbox,
1006        ext_status_mailbox,
1007        editor_text_mailbox,
1008        action_bridge,
1009        extension_session,
1010        resolved_session,
1011        prepared_restore,
1012    } = prepared;
1013    let shared_host = host_plugin_images.is_some();
1014    let build_tools = StartupSpan::start(Phase::BuildTools);
1015    let catalog = crate::provider::authenticated_catalog(resolved);
1016    action_host.set_catalog(catalog.clone());
1017
1018    // ---- Execution env + tools ----
1019    let env = Arc::new(execution_env(home, cwd));
1020    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
1021    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
1022    let _registry = Arc::new(MutationQueueRegistry::new());
1023    // `env_dyn` is shared between the tool context (moved in) and the resource
1024    // loaders below (borrowed); clone one branch so both hold a reference.
1025    let file_io = Arc::new(rpi_tools::file_io::FileIORouter::new());
1026    let ctx =
1027        ExecutionToolContext::new(env_dyn.clone(), Some(mut_env)).with_file_io(file_io.clone());
1028
1029    validate_durable_extensions(&extension_session).map_err(BuildError::HarnessCreate)?;
1030    let durable_binding = Arc::new(std::sync::OnceLock::new());
1031    let mut tools = build_tools_bound(home, &ctx, args, durable_binding.clone());
1032
1033    // ---- Extensions (Part B2) ----
1034    // Load cdylib plugins from the resolved extension dirs, merge their tools
1035    // into the built-in set (extension overrides same-named built-in; first-
1036    // extension-wins across plugins; explicit `--tools`/`--exclude-tools` still
1037    // apply to the merged set), and keep the loaded `Library` handles alive for
1038    // the harness lifetime via the returned session guard. `--no-extensions`
1039    // skips discovery entirely (no dirs scanned, no plugins loaded).
1040    merge_extension_tools(&mut tools, &extension_session, args, &tool_context);
1041    let active = if let Some(selected) = &resource_selection {
1042        selected
1043            .active_tools(
1044                &tools
1045                    .iter()
1046                    .map(|t| t.tool.schema().name.clone())
1047                    .collect::<Vec<_>>(),
1048            )
1049            .map_err(BuildError::HarnessCreate)?
1050    } else {
1051        filter_active_tool_names(active_tool_names(&tools, args), args)
1052    };
1053
1054    // ---- Session storage ----
1055    // The root is the one `prepare_extensions` froze at startup, never a fresh
1056    // `configured_session_dir(args, cwd)`: settings and `RPI_CODING_AGENT_SESSION_DIR`
1057    // can change while extensions load, and an adopted session cwd would point
1058    // at another project's tree. Both the cwd peek and this build must read the
1059    // same root, so the caller pins it into `args` before either runs.
1060    build_tools.finish();
1061    let writer_restore = StartupSpan::start(Phase::WriterRestore);
1062    let session = match transition_session {
1063        Some(session) => session,
1064        None => {
1065            build_session(
1066                &selection,
1067                &cwd_str,
1068                resource_selection.as_ref(),
1069                resolved_session.as_ref(),
1070                prepared_restore,
1071            )
1072            .await?
1073        }
1074    };
1075    writer_restore.finish();
1076    let session_bind = StartupSpan::start(Phase::SessionBind);
1077    crate::resource_selection::bind_session(&session, resource_selection.as_ref())
1078        .await
1079        .map_err(BuildError::SessionOpen)?;
1080    session_bind.finish();
1081    // Plugin tools now know which session they serve: `todo` and friends key
1082    // their per-session state off it. A session without an id (ephemeral) leaves
1083    // the field unset and a plugin is expected to fall back to project scope.
1084    if let Ok(metadata) = session.get_metadata().await {
1085        if !shared_host {
1086            publish_session_identity(&tool_context, &metadata.id);
1087        } else {
1088            tool_context.set_session_id(metadata.id);
1089        }
1090    }
1091    // `--name`/`-n` sets the session display name durably (a `name` fact in the
1092    // log). It applies to whichever session this launch works in — a fresh one
1093    // or a restored one — and an empty value clears a previous name. This is the
1094    // only place the flag is applied: `SessionSelection::New` carries it, but
1095    // builds that do not create a session (restore/fork) must still honor it.
1096    if let Some(requested) = args.name.as_deref() {
1097        let name = requested.trim();
1098        let name = if name.is_empty() { None } else { Some(name) };
1099        if let Err(error) = session.set_name(name).await {
1100            if args.verbose {
1101                eprintln!("warning: could not set session name: {error}");
1102            }
1103        }
1104    }
1105    // ---- System prompt base (precedence: --system-prompt > SYSTEM.md > default) ----
1106    // Mirrors pi `discoverSystemPromptFile` (`resource-loader.ts:1022-1034`):
1107    // an explicit `--system-prompt` flag wins; otherwise a discovered
1108    // `<cwd>/.rpi/SYSTEM.md` wins, then
1109    // `<agent_dir>/SYSTEM.md`.
1110    // (global); otherwise the built-in default. **Project-wins** — the same
1111    // direction as skills/prompts precedence.
1112    // Whether this model sees its own prior reasoning again decides how the
1113    // working-state rule is worded (see `default_system_prompt`).
1114    let prompt_resources = StartupSpan::start(Phase::PromptResources);
1115    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&resolved.model);
1116    let prompt_tools = active.clone();
1117    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
1118    let default_prompt = || {
1119        default_system_prompt_with_tool_prompts(
1120            &cwd_str,
1121            prior_reasoning_replayed,
1122            &prompt_tools,
1123            &prompt_metadata,
1124        )
1125    };
1126    let mut context_paths = Vec::new();
1127    let base_prompt = match args.system_prompt.as_deref() {
1128        Some(explicit) => explicit.to_string(),
1129        None if project_trusted && resource_selection.is_none() => {
1130            match home.discover_system_prompt_file(cwd, true) {
1131                Some(path) => {
1132                    read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
1133                }
1134                None => default_prompt(),
1135            }
1136        }
1137        None => default_prompt(),
1138    };
1139
1140    // ---- Append-text sources (precedence: --append-system-prompt > APPEND_SYSTEM.md) ----
1141    // Mirrors pi `appendSystemPrompt` (`resource-loader.ts:525-542`). Explicit
1142    // `--append-system-prompt` flags are joined together; when none are given, a
1143    // discovered `APPEND_SYSTEM.md` (project-wins over global) provides the
1144    // append text. `--append-system-prompt` takes a value that may be a literal
1145    // string OR a readable file path (mirrors TS `resolvePromptInput`).
1146    let mut append_texts: Vec<String> = Vec::new();
1147    for extra in &args.append_system_prompt {
1148        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
1149        append_texts.push(text);
1150    }
1151    if let Some(selected) = &resource_selection {
1152        if let Some(package) = selected
1153            .package
1154            .as_ref()
1155            .filter(|_| selected.package_commands.digest().is_some())
1156        {
1157            append_texts.push(format!(
1158                "Installed agent package root: {}. Resolve references to the package's skills/, optional-skills/, instructions/, and commands/ against this installed root. Resolve workspace files and project scripts against the current working directory.",
1159                package.root.display()
1160            ));
1161        }
1162        append_texts.extend(
1163            selected
1164                .instructions
1165                .iter()
1166                .map(|(_, _, text)| text.clone()),
1167        );
1168    }
1169    if args.append_system_prompt.is_empty() && resource_selection.is_none() {
1170        if let Some(path) = project_trusted
1171            .then(|| home.discover_append_system_prompt_file(cwd))
1172            .flatten()
1173        {
1174            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
1175                append_texts.push(text);
1176            }
1177        }
1178    }
1179    let append_join = if append_texts.is_empty() {
1180        None
1181    } else {
1182        Some(append_texts.join("\n\n"))
1183    };
1184
1185    // ---- Resource discovery (skills + prompt-templates + context-files) ----
1186    // The env is OS-backed, rooted at cwd. Each `--no-*` flag suppresses its
1187    // channel independently (pi parity). Skills/prompts load project→global,
1188    // explicit/plugin paths, then static packages; dedupe first-wins-by-name
1189    // keeps project and user resources ahead of packages. Context files walk
1190    // global→ancestor(cwd→root), deepest-last (pi parity).
1191    //
1192    // **Trust gate (v1 divergence):** pi gates project config discovery on
1193    // `isProjectTrusted()` (global resources are unconditional). rpi v1 has no
1194    // trust prompt — project resources are discovered unconditionally (a copied
1195    // `.rpi/` dir drops in and works). Full trust gating is deferred.
1196    let agent_dir = home.root().ok();
1197
1198    // ---- B5b: extension resources_discover ----
1199    // If any plugin registered a `resources_discover` handler, fan the event out
1200    // (reason "startup") and collect skill/prompt/theme paths. These plugin-
1201    // contributed paths merge WITH the static Part-A dirs (project
1202    // `.rpi/skills` +
1203    // `agent_dir/skills`, etc.) and the loaders re-run over the union — the
1204    // coherence point: a plugin's discovered skills land through the SAME loaders
1205    // as static skills. Static dirs load FIRST so project skills keep winning name
1206    // collisions (a plugin must not shadow a project skill of the same name —
1207    // mirrors pi `extendResources` running AFTER the default load's first-wins
1208    // map). `load_skills` now accepts both dirs and individual `.md` files, so a
1209    // plugin returning bare `SKILL.md` paths loads them (the gap this closes).
1210    // Theme paths are available to the TUI through the package resource list;
1211    // skill/prompt loaders are the only resources needed by the harness here.
1212    // A `--no-*` flag suppresses its channel for BOTH static and discovered paths.
1213    let discovered = extension_session
1214        .snapshot_arc()
1215        .filter(|_| resource_selection.is_none())
1216        .map(|snap| emit_resources_discover(&cwd_str, "startup", &snap))
1217        .unwrap_or_default();
1218
1219    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
1220    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
1221    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
1222    if let Some(selected) = &resource_selection {
1223        // Consume the preflight's parsed resources, never rediscover or reread
1224        // selected Skills after executable registration / writer opening.
1225        skills = selected
1226            .validated_skills()
1227            .map_err(BuildError::HarnessCreate)?
1228            .skills
1229            .clone();
1230    } else if !args.no_skills {
1231        let mut dirs =
1232            resource_root_dirs(home, args, cwd, project_trusted, ResourceRootKind::Skills);
1233        dirs.extend(discovered.skill_paths.iter().map(PathBuf::from));
1234        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
1235        skills = result.skills;
1236        skill_diags = result.diagnostics;
1237        resource_diags.extend(result.resource_diagnostics);
1238    }
1239
1240    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
1241    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
1242    if !args.no_prompt_templates && resource_selection.is_none() {
1243        let mut dirs = resource_root_dirs(
1244            home,
1245            args,
1246            cwd,
1247            project_trusted,
1248            ResourceRootKind::PromptTemplates,
1249        );
1250        dirs.extend(discovered.prompt_paths.iter().map(PathBuf::from));
1251        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
1252        prompt_templates = result.prompt_templates;
1253        prompt_diags = result.diagnostics;
1254        resource_diags.extend(result.resource_diagnostics);
1255    }
1256
1257    let context_block = if args.no_context_files || !project_trusted || resource_selection.is_some()
1258    {
1259        String::new()
1260    } else {
1261        // `load_project_context_files` walks the global agentDir first then
1262        // ancestor-walks cwd→root (deepest last). It needs a real agent_dir; if
1263        // none is resolvable, pass the cwd dir so only the ancestor-walk runs
1264        // (the global step returns None anyway).
1265        let agent_dir_path = agent_dir.clone().unwrap_or_else(|| cwd.to_path_buf());
1266        let files = load_project_context_files(&env_dyn, cwd, &agent_dir_path).await;
1267        context_paths.extend(
1268            files
1269                .iter()
1270                .map(|file| file.path.to_string_lossy().into_owned()),
1271        );
1272        format_project_context(&files)
1273    };
1274
1275    // Surface resource-discovery diagnostics as startup warnings (verbose-only).
1276    if args.verbose {
1277        for d in &skill_diags {
1278            eprintln!(
1279                "warning: skill {} ({}): {}",
1280                d.path,
1281                d.code.as_str(),
1282                d.message
1283            );
1284        }
1285        for d in &prompt_diags {
1286            eprintln!(
1287                "warning: prompt template {} ({}): {}",
1288                d.path,
1289                d.code.as_str(),
1290                d.message
1291            );
1292        }
1293        // Structured collisions: make the winner/loser explicit.
1294        for d in &resource_diags {
1295            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
1296                eprintln!(
1297                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
1298                    c.resource_type.as_str(),
1299                    c.name,
1300                    c.winner_path,
1301                    c.loser_path
1302                );
1303            }
1304        }
1305    }
1306
1307    // ---- Compose the full system prompt ----
1308    // Order mirrors pi `buildSystemPrompt` (`system-prompt.ts:28-72`):
1309    // base → append → context → skills. The skills listing is the harness's own
1310    // section: `AgentHarness::compose_prompt` appends `<available_skills>` (gated
1311    // on the `read` tool + `disable_model_invocation`, applied inside
1312    // `format_skills_for_system_prompt`). So we pass None for skills here (the
1313    // harness adds the listing itself) and fold only base+append+context into
1314    // the prompt we hand the harness.
1315    let system_prompt = compose_system_prompt(
1316        Some(&base_prompt),
1317        &[], // skills: harness appends the listing itself
1318        if context_block.is_empty() {
1319            None
1320        } else {
1321            Some(&context_block)
1322        },
1323        append_join.as_deref(),
1324    );
1325
1326    // ---- Debug: dump the resolved system-prompt sections (verification) ----
1327    // A verification affordance for Part-A resource discovery: prints the
1328    // composed sections + resource counts to stderr so a smoke can confirm
1329    // `<available_skills>` + `<project_context>` + appended text reached the
1330    // prompt without parsing a provider round-trip. The harness composes the
1331    // final prompt (base → append → context → skills); here we print the
1332    // pre-harness sections (the harness adds the skills listing itself, gated
1333    // on `read` + `disable_model_invocation`).
1334    if args.debug_system_prompt {
1335        eprintln!("=== --debug-system-prompt ===");
1336        let base_src = if args.system_prompt.is_some() {
1337            "--system-prompt"
1338        } else if home.discover_system_prompt_file(cwd, true).is_some() {
1339            "SYSTEM.md"
1340        } else {
1341            "default"
1342        };
1343        eprintln!("[base source: {base_src}]");
1344        eprintln!("--- base ---\n{base_prompt}");
1345        if let Some(append) = append_join.as_deref() {
1346            eprintln!("--- append ---\n{append}");
1347        } else {
1348            eprintln!("--- append: (none) ---");
1349        }
1350        if context_block.is_empty() {
1351            eprintln!("--- context: (none) ---");
1352        } else {
1353            eprintln!("--- context ---{context_block}");
1354        }
1355        let visible_skills = skills
1356            .iter()
1357            .filter(|s| s.disable_model_invocation != Some(true))
1358            .count();
1359        eprintln!(
1360            "--- skills: {} loaded ({} model-visible, {} hidden) ---",
1361            skills.len(),
1362            visible_skills,
1363            skills.len() - visible_skills
1364        );
1365        for s in &skills {
1366            let hidden = if s.disable_model_invocation == Some(true) {
1367                " [hidden]"
1368            } else {
1369                ""
1370            };
1371            eprintln!("    {}{hidden} — {}", s.name, s.description);
1372        }
1373        eprintln!("--- prompt templates: {} ---", prompt_templates.len());
1374        for t in &prompt_templates {
1375            eprintln!("    /{}", t.name);
1376        }
1377        // B5b: surface plugin-contributed discovery paths so a smoke can confirm
1378        // the resources_discover round-trip fed the loaders; package themes are
1379        // selected by the TUI rather than injected into the harness prompt.
1380        eprintln!(
1381            "--- discovered via resources_discover: {} skill(s), {} prompt(s), {} theme(s) ---",
1382            discovered.skill_paths.len(),
1383            discovered.prompt_paths.len(),
1384            discovered.theme_paths.len(),
1385        );
1386        for p in &discovered.skill_paths {
1387            eprintln!("    skill: {p}");
1388        }
1389        for p in &discovered.prompt_paths {
1390            eprintln!("    prompt: {p}");
1391        }
1392        eprintln!(
1393            "--- final composed base+append+context (skills listing added by harness) ---\n{system_prompt}"
1394        );
1395        eprintln!("=== end --debug-system-prompt ===");
1396    }
1397
1398    prompt_resources.finish();
1399    // ---- Options ----
1400    // Install a BroadcastEmitter so the caller (the interactive TUI) can drain
1401    // AgentEvents live as a run unfolds. The corresponding broadcast::Receiver
1402    // is returned alongside the harness; non-interactive modes simply drop it.
1403    let (broadcast, event_rx) = rpi_agent::events::BroadcastEmitter::new(256);
1404    let broadcast_emitter: Arc<dyn rpi_agent::AgentEmitter> = Arc::new(broadcast);
1405    // The broadcast half stays live for the whole session (the TUI's drain task
1406    // holds the receiver); reload re-wraps it in a fresh `TeeEmitter`, so keep
1407    // a clone for the `ReloadContext` before the tee match consumes the original.
1408    let broadcast_for_context: Arc<dyn rpi_agent::AgentEmitter> = Arc::clone(&broadcast_emitter);
1409
1410    // ---- Extensions emitter (Part B3a) ----
1411    // If extensions loaded + registered any `on()` handlers, wrap the
1412    // broadcast emitter in a `TeeEmitter` so every `AgentEvent` flows to BOTH
1413    // the TUI (via the broadcast receiver above) AND the plugin handlers (via
1414    // the `ExtensionEmitter`, which translates each `AgentEvent` →
1415    // `StablePluginEvent` and fans out to the handlers registered for its tag).
1416    // With no extensions the tee degrades to the bare broadcast emitter (a
1417    // one-child passthrough), so the TUI path is unchanged.
1418    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
1419        Some(snapshot) => {
1420            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
1421            Arc::new(TeeEmitter::new(vec![broadcast_emitter, Arc::new(ext)]))
1422        }
1423        None => broadcast_emitter,
1424    };
1425
1426    // Saved user defaults. Best-effort: a missing or malformed file must not stop
1427    // a session from starting, and every accessor falls back to the harness
1428    // default when its key is absent.
1429    let saved_settings = home.settings().unwrap_or_default();
1430
1431    // `httpProxy` applies to rpi's own HTTP clients. Setting the environment is how
1432    // they are configured (`pi-ai/src/http.rs`), and upstream does the same thing
1433    // with this key — an explicit environment variable still wins, so a shell-level
1434    // proxy override is not silently replaced by the setting.
1435    if !shared_host {
1436        apply_process_proxy(saved_settings.http_proxy.as_deref());
1437    }
1438
1439    // Share the live session cell with both /reload and the approval hook.
1440    // The hook is installed only when the current snapshot has a tool-call
1441    // handler; a later reload rebuilds the hook state together with the
1442    // extension session.
1443    let extension_session_cell = Arc::new(Mutex::new(extension_session.clone()));
1444    // Only install the approval hook when a plugin actually registered a
1445    // tool-call handler. An extension session may contain flags/resources but
1446    // no handler; dispatching through that empty session needlessly crosses
1447    // the plugin bridge and can leave a headless RPC tool call waiting.
1448    let before_tool_call = extension_session
1449        .snapshot()
1450        .filter(|snapshot| {
1451            !snapshot
1452                .handlers_for(rpi_plugin_sdk::EventTag::ToolCall)
1453                .is_empty()
1454        })
1455        .map(|_| {
1456            extension_tool_call_hook(
1457                Arc::clone(&extension_session_cell),
1458                ui_dialog_mailbox.clone(),
1459            )
1460        });
1461
1462    // Host-integrated approval gate: composes AFTER the extension hook (an
1463    // extension veto wins; the host gate only sees calls that would run).
1464    //
1465    // Field contract (harness `prepare_tool_call`): a returned
1466    // `BeforeToolCallResult` may carry `block`/`terminate`/`args`, and a
1467    // non-blocking result's `args` REPLACES the validated args for the call.
1468    // So the composite must (a) keep an extension's non-blocking rewrite and
1469    // `terminate` bit, and (b) run the approval gate against the *rewritten*
1470    // args — not the originals (review follow-up).
1471    let approval_binding = Arc::clone(&durable_binding);
1472    let before_tool_call: Option<rpi_agent::hooks::BeforeToolCall> = match before_tool_call {
1473        Some(extension_hook) => Some(Arc::new(
1474            move |context: rpi_agent::types::BeforeToolCallContext<'_>,
1475                  signal: tokio_util::sync::CancellationToken| {
1476                let extension_hook = Arc::clone(&extension_hook);
1477                let binding = Arc::clone(&approval_binding);
1478                let tool = context.tool_call.name.clone();
1479                let original_args = context.args.clone();
1480                // Call synchronously: the extension hook copies what it needs
1481                // and returns a 'static future, so the borrowed context never
1482                // enters our boxed future.
1483                let first = extension_hook(context, signal.clone());
1484                Box::pin(async move {
1485                    let extension_result = first.await;
1486                    if let Some(result) = extension_result.as_ref() {
1487                        if result.block {
1488                            return Some(result.clone());
1489                        }
1490                    }
1491                    let rewritten = extension_result
1492                        .as_ref()
1493                        .and_then(|result| result.args.clone())
1494                        .unwrap_or(original_args);
1495                    match crate::approval_gate::evaluate(&binding, &tool, &rewritten, &signal).await
1496                    {
1497                        Some(blocked) => {
1498                            // Keep the extension's own terminate intent when the
1499                            // host gate denies (both are "stop here" signals).
1500                            let terminate = extension_result
1501                                .as_ref()
1502                                .map(|result| result.terminate)
1503                                .unwrap_or(false);
1504                            Some(rpi_agent::types::BeforeToolCallResult {
1505                                terminate,
1506                                ..blocked
1507                            })
1508                        }
1509                        // Allowed: hand the extension's own result back so the
1510                        // harness applies its args rewrite / terminate bit.
1511                        None => extension_result,
1512                    }
1513                })
1514            },
1515        )),
1516        None => Some(crate::approval_gate::hook(approval_binding)),
1517    };
1518
1519    let options = AgentHarnessOptions {
1520        model: resolved.model.clone(),
1521        thinking_level: resolved.thinking_level,
1522        active_tool_names: active.clone(),
1523        tools,
1524        system_prompt: Some(system_prompt),
1525        resources: AgentHarnessResources {
1526            context_files: context_paths,
1527            skills: if skills.is_empty() {
1528                None
1529            } else {
1530                Some(skills)
1531            },
1532            prompt_templates: if prompt_templates.is_empty() {
1533                None
1534            } else {
1535                Some(prompt_templates)
1536            },
1537        },
1538        // A restored session (--continue/--resume/--session) already has
1539        // records — let the harness load it and keep appending.
1540        allow_existing_session: matches!(
1541            selection,
1542            SessionSelection::Latest { .. }
1543                | SessionSelection::ById { .. }
1544                | SessionSelection::ByExactId { .. }
1545                | SessionSelection::Fork { .. }
1546        ),
1547        require_native_durable: args.native_durable,
1548        stream_options: AgentHarnessStreamOptions {
1549            timeout: args.timeout,
1550            stream_idle_timeout: args.stream_idle_timeout.or_else(|| {
1551                saved_settings
1552                    .stream_idle_timeout
1553                    .map(std::time::Duration::from_secs)
1554            }),
1555            thinking_budgets: saved_settings.thinking_budgets,
1556            ..Default::default()
1557        },
1558        // Settings-backed harness options: upstream lets users tune retry,
1559        // compaction and queue drain modes from settings.json. Global only,
1560        // matching how `defaultTools` and the other settings-backed options in
1561        // this file are read.
1562        retry: saved_settings.retry_policy(),
1563        compaction: saved_settings.compaction_settings(),
1564        steering_mode: saved_settings.steering_mode(),
1565        follow_up_mode: saved_settings.follow_up_mode(),
1566        tool_execution: HarnessToolExecution::default(),
1567        drive: DrivingMode::default(),
1568        session,
1569        // B5c: inject the resolved gateway provider PLUS one `Arc<dyn Provider>`
1570        // per registered extension provider (`PluggableProvider` wraps a plugin's
1571        // sync `ProviderRequestFn`). The harness's `build_stream_fn` resolves a
1572        // provider lazily per call by `models.iter().find(|p| p.id() == model.provider)`,
1573        // so a catalog model whose `provider` matches an extension provider's id
1574        // routes to it. Extension providers land AFTER the gateway so the gateway
1575        // stays first-match for its own ids (first-wins on a `.find`).
1576        models: build_models_with_extensions(resolved, &extension_session, runtime.clone()),
1577        to_provider_messages: None,
1578        entry_projectors: Default::default(),
1579        agent_emitter: Some(emitter),
1580        // B3b loop hooks. `before_tool_call` dispatches the pi `on("tool_call")`
1581        // extension event and honors a veto (a permission gate can block a tool
1582        // before it runs). `after_tool_call` runs the plugin `tool_result`
1583        // transforms (pi's `on("tool_result")`) over every finished result,
1584        // error results included; it reads the session per call, so a plugin
1585        // that a `/reload` adds is covered. Extension context adapters remain
1586        // unwired. Native durable observes the committed service per model
1587        // request, using the same weak binding as its tool, even when model
1588        // tools are filtered.
1589        before_tool_call,
1590        after_tool_call: Some(extension_tool_result_hook(Arc::clone(
1591            &extension_session_cell,
1592        ))),
1593        transform_context: args
1594            .native_durable
1595            .then(|| crate::native_durable::context_hook(Arc::clone(&durable_binding))),
1596        entry_transforms: Vec::new(),
1597        // Extension provider hooks (B4): plugins subscribing to the
1598        // BeforeProviderRequest / BeforeProviderHeaders / AfterProviderResponse
1599        // events observe every provider call (observer semantics — the handler
1600        // ABI has no patch channel in v1). A session without provider-hook
1601        // subscribers runs hook-free.
1602        provider_hooks: rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
1603            .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
1604    };
1605
1606    let harness_create = StartupSpan::start(Phase::HarnessCreate);
1607    let harness = match experimental_policy {
1608        Some(policy) => AgentHarness::create_experimental(options, policy).await,
1609        None => AgentHarness::create(options).await,
1610    }
1611    .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
1612    harness.set_compaction_model_overrides(saved_settings.compaction_model_overrides());
1613    harness_create.finish();
1614
1615    if args.native_durable {
1616        let durable_validate = StartupSpan::start(Phase::DurableValidate);
1617        // Validate legacy/corrupt branch state before sealing resources or ready.
1618        rpi_harness::durable::DurableService::bind(
1619            &harness,
1620            rpi_harness::durable::DurableActor::owner("native-cli")
1621                .map_err(|e| BuildError::HarnessCreate(e.to_string()))?,
1622        )
1623        .snapshot()
1624        .await
1625        .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
1626        durable_validate.finish();
1627    }
1628    // Populate the weak tool binding before resource selection is published.
1629    // Unconditional: host-integrated tools (approval gate session id,
1630    // message_agent caller resolution) need the owning harness even when the
1631    // native DurableService path is off — host embeddings never set
1632    // `native_durable`, so an `if args.native_durable`-scoped set left the
1633    // binding permanently empty for them.
1634    let _ = durable_binding.set(harness.downgrade());
1635
1636    // The bus must retain these resources even if an embedding drops its reload
1637    // context early. Retain the shared owner, not an unretirable lease Arc.
1638    let providers = Arc::new(std::sync::RwLock::new(resolved.providers.clone()));
1639    let action_bridge_cell = Arc::new(Mutex::new(Some(Arc::clone(&action_bridge))));
1640    let plugin_resources = crate::host::cli_resources::CliPluginResources::new(
1641        plugin_cleanup.clone(),
1642        resource_leases.clone(),
1643        extension_session_cell.clone(),
1644        action_bridge_cell.clone(),
1645        providers.clone(),
1646    );
1647    let harness_resources = plugin_resources.clone();
1648    harness
1649        .events()
1650        .on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |_| {
1651            let _ = &harness_resources;
1652        });
1653    install_extension_settlement_bridge(harness.events(), extension_session_cell.clone());
1654    let resource_seal = StartupSpan::start(Phase::ResourceSeal);
1655    if let Some(selected) = &resource_selection {
1656        harness
1657            .seal_resources(active)
1658            .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
1659        crate::resource_selection::attach(
1660            &harness,
1661            serde_json::json!({
1662                "version": 1,
1663                "hostId": uuid::Uuid::new_v4().to_string(),
1664                "host": {"name": crate::APP_NAME, "version": crate::VERSION, "pid": std::process::id()},
1665                "selection": selected.selection,
1666                "package": selected.package,
1667                "selectedSkills": selected.skills,
1668                "skillDiagnostics": [],
1669                "loadedExtensions": extension_session.loaded_paths().iter().map(|p| serde_json::json!({"identity": p.file_stem().and_then(|s| s.to_str()), "path": p})).collect::<Vec<_>>(),
1670                "instructions": selected.provenance(),
1671                "baseSystemPrompt": "native-default",
1672                "projectContext": "disabled",
1673                "resourceDiscovery": "disabled",
1674                "changes": "restart-required"
1675            }),
1676            selected.package_commands.clone(),
1677        );
1678        crate::resource_selection::get_resource_state(&harness)
1679            .await
1680            .map_err(BuildError::HarnessCreate)?;
1681        if selected.transition.is_some() {
1682            // Re-read persisted facts at commit, not merely the startup mirror.
1683            // The canonical OS writer claim acquired before registration is
1684            // retained by the host for the entire session lifetime.
1685            let meta = resolved_session.as_ref().ok_or_else(|| {
1686                BuildError::SessionOpen("transition session disappeared before commit".into())
1687            })?;
1688            if !harness.session().storage().writer_lease_held() {
1689                return Err(BuildError::SessionOpen(
1690                    "resource transition lost storage-level writer ownership".into(),
1691                ));
1692            }
1693            let facts =
1694                rpi_harness::session::jsonl::JsonlSessionStorage::read_resource_transition_facts(
1695                    Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())),
1696                    &meta.path,
1697                    Arc::new(SystemClock),
1698                    Arc::new(DefaultIdGenerator::new()),
1699                )
1700                .await
1701                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
1702            crate::resource_selection::validate_session_binding(&facts.values, Some(selected))
1703                .map_err(BuildError::SessionOpen)?;
1704            let mirror = rpi_harness::session::SessionValues::load(harness.session())
1705                .await
1706                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
1707            if crate::resource_selection::binding_state(&mirror)
1708                != crate::resource_selection::binding_state(&facts.values)
1709            {
1710                return Err(BuildError::SessionOpen(
1711                    "resource binding changed before commit".into(),
1712                ));
1713            }
1714        }
1715        crate::resource_selection::bind_inventory(&harness, selected)
1716            .await
1717            .map_err(BuildError::SessionOpen)?;
1718    }
1719    resource_seal.finish();
1720    // Publish only after exact resources have been sealed and validated.
1721    crate::extensions_actions::HarnessActionHost::set_harness(
1722        &harness_cell,
1723        Arc::new(harness.clone()),
1724    );
1725    register_file_io_router(&harness, &file_io);
1726
1727    // ---- Durable operation recovery (runtime layer) ----
1728    // A previous process can die between `operation_started` and
1729    // `operation_finished`, leaving the lane with an orphaned operation. Sweep
1730    // every lane, surface what was found, and emit `run_start`/`run_end`
1731    // (aborted) pairs so a TUI that already attached sees the settle. This is
1732    // read-only: nothing is mutated here, so a failed sweep cannot corrupt the
1733    // log. A clean session (the common case) reports no findings.
1734    {
1735        let recovery_sweep = StartupSpan::start(Phase::RecoverySweep);
1736        let runtime = rpi_harness::runtime::SessionRuntime::new(harness.session().clone());
1737        match rpi_harness::runtime::recover_all_lanes(&runtime).await {
1738            Ok(reports) => {
1739                for (lane, report) in reports {
1740                    if report.is_clean() {
1741                        continue;
1742                    }
1743                    if report.is_corrupt() {
1744                        eprintln!(
1745                            "warning: session lane '{lane}' is corrupt ({} open operations); \
1746                             refusing to auto-repair — inspect the session file",
1747                            report.open_operations.len()
1748                        );
1749                        continue;
1750                    }
1751                    for decision in runtime.reconcile(&report) {
1752                        if let rpi_harness::runtime::RecoveryDecision::Abort { run_id } = decision {
1753                            if args.verbose {
1754                                eprintln!(
1755                                    "recovered interrupted run {run_id} on lane '{lane}' (aborted)"
1756                                );
1757                            }
1758                        }
1759                    }
1760                    runtime.emit_recovery_events(harness.events(), &report);
1761                }
1762            }
1763            Err(e) => {
1764                if args.verbose {
1765                    eprintln!("warning: session recovery sweep failed: {e}");
1766                }
1767            }
1768        }
1769        recovery_sweep.finish();
1770    }
1771
1772    // ---- B5d: assemble the ReloadContext the TUI holds ----
1773    // Every field is cheap to clone (Arc / Vec / args Clone). The cells own the
1774    // live session + bridge so `/reload` can swap them; the harness itself is
1775    // NOT held here (the TUI already owns a `&AgentHarness` / clone at the call
1776    // site — passing it into `reload_extension_resources` keeps this structfree
1777    // of a harness back-reference so it can be `Clone` into the reload callback).
1778    // Retain the resolved root in the existing args snapshot so reload never
1779    // reselects it from mutable settings or environment variables.
1780    let mut reload_args = args.clone();
1781    reload_args.session_dir = Some(session_dir);
1782    let reload_context = ReloadContext {
1783        plugin_cleanup,
1784        plugin_resources,
1785        host_plugin_images,
1786        ephemeral_sessions_only: args.mini,
1787        extension_session: extension_session_cell,
1788        durable_binding,
1789        action_bridge: action_bridge_cell,
1790        tool_context,
1791        file_io,
1792        execution_env: Arc::new(std::sync::Mutex::new(env)),
1793        catalog: Arc::new(std::sync::RwLock::new(catalog)),
1794        providers,
1795        runtime: runtime.clone(),
1796        cwd: cwd.to_path_buf(),
1797        project_trusted,
1798        discovered_theme_paths: Arc::new(std::sync::Mutex::new(discovered.theme_paths.clone())),
1799        args: reload_args,
1800        home: home.clone(),
1801        resolved_model: resolved.model.clone(),
1802        broadcast: broadcast_for_context,
1803        mailbox: reload_mailbox,
1804        ui_dialog: ui_dialog_mailbox,
1805        ext_status: ext_status_mailbox,
1806        editor_text: editor_text_mailbox,
1807        dev_extension: None,
1808        startup_notices: Vec::new(),
1809    };
1810
1811    Ok((harness, event_rx, reload_context))
1812}
1813
1814/// Project authoritative harness termination, not per-attempt AgentEnd, to
1815/// plugins. The bus owns this listener; its session cell follows reloads and
1816/// retains callback libraries, while the action host binds the harness weakly.
1817fn install_extension_settlement_bridge(
1818    events: &rpi_harness::events::HarnessEventBus,
1819    sessions: ExtensionSessionCell,
1820) {
1821    events.on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |event| {
1822        if event.lane != "main" {
1823            return;
1824        }
1825        let session = sessions.lock().unwrap().clone();
1826        if let Some(snapshot) = session.snapshot_arc() {
1827            rpi_extensions::dispatch_empty_event(&snapshot, rpi_plugin_sdk::EventTag::AgentSettled);
1828        }
1829    });
1830}
1831
1832/// Resolve the current plugin session for each call rather than keeping a
1833/// startup snapshot. A clone retains its libraries while approval is pending.
1834fn extension_tool_call_hook(
1835    sessions: ExtensionSessionCell,
1836    ui_dialog: rpi_extensions::UiDialogMailbox,
1837) -> rpi_agent::BeforeToolCall {
1838    Arc::new(move |ctx: rpi_agent::BeforeToolCallContext<'_>, signal| {
1839        let session = sessions
1840            .lock()
1841            .map(|session| session.clone())
1842            .map_err(|_| ());
1843        let ui_dialog = ui_dialog.clone();
1844        let tool_call_id = ctx.tool_call.id.clone();
1845        let tool_name = ctx.tool_call.name.clone();
1846        let params = ctx.args.clone();
1847        Box::pin(async move {
1848            let reason = match session {
1849                Ok(session) => {
1850                    let vetoed = rpi_extensions::dispatch_tool_call_event(
1851                        &session,
1852                        &tool_call_id,
1853                        &tool_name,
1854                        &params,
1855                        &signal,
1856                        &ui_dialog,
1857                    )
1858                    .await;
1859                    match vetoed {
1860                        Some(reason) => Some(
1861                            veto_reason_via_transforms(
1862                                &session,
1863                                &tool_call_id,
1864                                &tool_name,
1865                                &params,
1866                                reason,
1867                            )
1868                            .await,
1869                        ),
1870                        None => None,
1871                    }
1872                }
1873                Err(_) => Some("extension approval session is unavailable".to_string()),
1874            };
1875            reason.map(|reason| rpi_agent::BeforeToolCallResult {
1876                block: true,
1877                reason: Some(reason),
1878                terminate: false,
1879                args: None,
1880            })
1881        })
1882    })
1883}
1884
1885/// The text that replaces a tool result when the `tool_result` transforms
1886/// could not run. A plugin may use the transforms to remove values the model
1887/// must not see, so the host fails closed instead of passing the result on.
1888const TOOL_RESULT_WITHHELD: &str =
1889    "[tool result withheld: the extension tool_result transforms could not run]";
1890
1891/// Run the plugin `tool_result` transforms over one result on a blocking
1892/// thread. `None` means no transform is registered. When a transform ran, an
1893/// unchanged result is still returned so the caller can distinguish it from a
1894/// skipped dispatch.
1895async fn run_tool_result_transforms(
1896    session: &ExtensionSession,
1897    tool_call_id: String,
1898    tool_name: String,
1899    input: serde_json::Value,
1900    result: rpi_agent::AgentToolResult,
1901    is_error: bool,
1902) -> Option<rpi_agent::AgentToolResult> {
1903    let snapshot = session.snapshot_arc()?;
1904    if snapshot.tool_result().is_empty() {
1905        return None;
1906    }
1907    let keepalive = session.keepalive();
1908    let withheld = rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD);
1909    let transformed = tokio::task::spawn_blocking(move || {
1910        // A started blocking callback outlives a dropped awaiter: keep the
1911        // plugin libraries loaded until every handler has returned.
1912        let _keepalive = keepalive;
1913        if !snapshot.is_active() {
1914            return rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD);
1915        }
1916        match rpi_extensions::emit_tool_result_with_status(
1917            &tool_call_id,
1918            &tool_name,
1919            &input,
1920            &result,
1921            is_error,
1922            &snapshot,
1923        ) {
1924            Ok(Some(changed)) => changed,
1925            Ok(None) => result,
1926            // A concurrent /reload invalidated the snapshot before the
1927            // blocking callback could dispatch. Never pass the unchecked
1928            // output to the model: it may still contain secrets that a
1929            // plugin's transform was supposed to remove.
1930            Err(()) => rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD),
1931        }
1932    })
1933    .await;
1934    match transformed {
1935        Ok(changed) => Some(changed),
1936        Err(_) => Some(withheld),
1937    }
1938}
1939
1940/// `after_tool_call` hook: pass every finished tool result, success or error
1941/// (a bash exit != 0 returns its output as an error result), and every fresh
1942/// immediate failure through the plugin `tool_result` transforms. Resolves the
1943/// session per call, like the tool-call hook, so it follows `/reload`; child
1944/// harnesses inherit it. A stale or unavailable session fails closed.
1945fn extension_tool_result_hook(sessions: ExtensionSessionCell) -> rpi_agent::AfterToolCall {
1946    Arc::new(move |ctx: rpi_agent::AfterToolCallContext<'_>, _signal| {
1947        let session = sessions.lock().map(|session| session.clone()).ok();
1948        let tool_call_id = ctx.tool_call.id.clone();
1949        let tool_name = ctx.tool_call.name.clone();
1950        let input = ctx.args.clone();
1951        let result = ctx.result.clone();
1952        let is_error = ctx.is_error;
1953        Box::pin(async move {
1954            let changed = match session {
1955                Some(session) => {
1956                    match run_tool_result_transforms(
1957                        &session,
1958                        tool_call_id,
1959                        tool_name,
1960                        input,
1961                        result,
1962                        is_error,
1963                    )
1964                    .await
1965                    {
1966                        Some(changed) => changed,
1967                        // No transform is registered: leave the tool's result
1968                        // untouched, including its usage and terminate fields.
1969                        None => return None,
1970                    }
1971                }
1972                // A poisoned session lock: withhold rather than pass unchecked.
1973                None => rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD),
1974            };
1975            Some(rpi_agent::AfterToolCallResult {
1976                content: Some(changed.content),
1977                details: Some(changed.details),
1978                ..Default::default()
1979            })
1980        })
1981    })
1982}
1983
1984/// A vetoed call's reason, offered to the `tool_result` transforms as the text
1985/// of the blocked result (`isError: true`, `details: {"blocked": true}`). The
1986/// first non-empty text block of the changed result becomes the reason the
1987/// model reads, so the vetoing plugin can explain the block. With no change
1988/// the host's reason stays.
1989async fn veto_reason_via_transforms(
1990    session: &ExtensionSession,
1991    tool_call_id: &str,
1992    tool_name: &str,
1993    params: &serde_json::Value,
1994    reason: String,
1995) -> String {
1996    let mut blocked = rpi_agent::AgentToolResult::error_text(reason.clone());
1997    blocked.details = serde_json::json!({ "blocked": true });
1998    let changed = run_tool_result_transforms(
1999        session,
2000        tool_call_id.to_string(),
2001        tool_name.to_string(),
2002        params.clone(),
2003        blocked,
2004        true,
2005    )
2006    .await;
2007    changed
2008        .and_then(|result| {
2009            result.content.into_iter().find_map(|part| match part {
2010                rpi_agent::TextContentOrImage::Text(text) => {
2011                    (!text.text.trim().is_empty()).then_some(text.text)
2012                }
2013                _ => None,
2014            })
2015        })
2016        .unwrap_or(reason)
2017}
2018
2019// ===========================================================================
2020// B5d — `/reload`: re-run extension + resource discovery into a LIVE harness
2021// ===========================================================================
2022//
2023// `/reload` (interactive TUI command, or a plugin's `runtime_action(Reload)`)
2024// re-runs everything `build` did around resources/extensions WITHOUT rebuilding
2025// the `AgentHarness` itself (rebuilding would tear down the session/lane/event
2026// wiring + the broadcast drain task the TUI owns). Instead it:
2027//
2028//  1. Builds a fresh `ExtensionSession` (re-load the cdylibs) over the same
2029//     dir set, with a FRESH `ActionBridge` (the old one is `invalidate`d so
2030//     in-flight plugin→host calls on the old bridge fail fast).
2031//  2. Fans `resources_discover(_, "reload")` over the fresh snapshot.
2032//  3. Re-runs the Part-A loaders (skills/prompts/context/SYSTEM.md/
2033//     APPEND_SYSTEM.md) with the discovered paths merged in — same precedence
2034//     + `--no-*` gates as startup.
2035//  4. Rebuilds the harness's live state via the B5d setters
2036//     (`set_system_prompt`/`set_resources`/`set_agent_emitter`/`set_models`/
2037//     `set_provider_hooks`/`set_tools`) so the NEXT run observes the reloaded
2038//     config (in-flight runs finish on the old `ConfigSnapshot`).
2039//  5. Swaps the cells (`ExtensionSession`, `ActionBridge`, harness action
2040//     host's harness cell stays — the harness is the same object) and drops
2041//     the old session + bridge (their keepalives unmap the old cdylibs; the
2042//     new session's keepalive holds the fresh mappings).
2043//
2044// The reload is a `rpi-cli` concern (NOT a harness op): `rpi-extensions`
2045// carries only the `ActionBridge` staleness flag + a `ReloadMailbox` `()` signal
2046// (no pi-cli `TuiMessage` type — leaf DAG preserved). The TUI owns the mailbox
2047// receiver + the actual reload routine; a plugin's
2048// `runtime_action(Reload)` signals the mailbox and returns `Ok(null)`
2049// immediately so the calling plugin's cdylib is NOT unmapped while its
2050// `runtime_action` frame is still on the stack (the self-unmapping race a
2051// synchronous plugin-initiated reload would have).
2052//
2053// `reload_extension_resources` is the shared routine both `/reload` (TUI) and
2054// a plugin's `runtime_action(Reload)` (via the mailbox) drive. It is `pub` so
2055// the TUI's main-loop handler + the mailbox-driven path call the same code.
2056
2057/// The cell that holds the live `ExtensionSession` across a `/reload`. Cloned
2058/// into every site that needs the current session (the TUI, the reload
2059/// callback). On reload the old session is `replace`d out (its `active` flag
2060/// flipped) and the fresh one stored atomically. In-flight callbacks retain
2061/// the old keepalive until they return; callers never observe an empty
2062/// placeholder during the swap.
2063pub type ExtensionSessionCell = Arc<Mutex<ExtensionSession>>;
2064
2065/// The cell that holds the live `ActionBridge` across a `/reload`. A plugin
2066/// stores the bridge's raw `user_data` pointer during `register`; on reload the
2067/// old bridge is `invalidate`d (in-flight calls fail fast) and the fresh one
2068/// `store`d. The fresh session's plugins are handed the fresh bridge pointer.
2069pub type ActionBridgeCell = Arc<Mutex<Option<Arc<rpi_extensions::ActionBridge>>>>;
2070
2071/// Everything `/reload` needs to rebuild extension + resource state into a live
2072/// harness. Built once in [`build`] (alongside the harness) and held by the TUI
2073/// (cloned into the reload callback the bridge carries + the `/reload` command
2074/// handler). The harness itself is NOT held here — the TUI already owns a
2075/// `&AgentHarness` / a clone; passing it at the call site keeps this struct
2076/// free of a harness back-reference (so it can be `Clone` and moved into the
2077/// reload callback without borrowing the harness).
2078#[derive(Clone)]
2079pub struct ReloadContext {
2080    /// Non-owning evidence includes failed candidates and every reload generation.
2081    pub(crate) plugin_cleanup: Arc<crate::host::cli_cleanup::PluginCleanupLedger>,
2082    pub(crate) plugin_resources: Arc<crate::host::cli_resources::CliPluginResources>,
2083    host_plugin_images: Option<HostPluginImages>,
2084    /// Keep Mini's storage policy across extension reloads.
2085    ephemeral_sessions_only: bool,
2086    /// One neutral router for all built-ins, including those reconstructed on reload.
2087    pub file_io: Arc<rpi_tools::file_io::FileIORouter>,
2088    /// The shell environment currently bound to the built-in tools.
2089    execution_env: Arc<std::sync::Mutex<Arc<OsExecutionEnv>>>,
2090    /// The live extension-session cell (swapped on reload).
2091    pub extension_session: ExtensionSessionCell,
2092    /// The process-lifetime durable-tool binding. Reloaded tool instances must
2093    /// keep the same weak harness binding as the context hook installed at startup.
2094    durable_binding: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
2095    /// The session's plugin-tool context (`cwd` + session id), reused — not
2096    /// rebuilt — on reload so the rebuilt adapters keep serving the SAME
2097    /// session. A reload that made a fresh context would leave every plugin
2098    /// tool without a session id until the next launch.
2099    pub tool_context: rpi_extensions::ToolCallContext,
2100    /// The live action-bridge cell (swapped + old invalidated on reload).
2101    pub action_bridge: ActionBridgeCell,
2102    /// The extension status registry the TUI renders in its footer (`SetStatus`).
2103    /// Lives in the context (not the cell) so it survives a bridge swap.
2104    pub ext_status: rpi_extensions::ExtensionStatusMailbox,
2105    /// The extension editor-text queue the TUI drains into the prompt editor
2106    /// (`SetEditorText`, runtime action 19). Lives in the context (not the cell)
2107    /// so it survives a bridge swap — exactly like `ext_status`. A voice plugin
2108    /// writes a transcription here as a *draft*; the TUI applies it, starts the
2109    /// optional auto-send countdown, and submits through the normal path so the
2110    /// user bubble renders as usual.
2111    pub editor_text: rpi_extensions::EditorTextMailbox,
2112    /// Shared authenticated model catalog for runtime actions and the TUI.
2113    /// Provider-package reloads replace it together with the runtime bindings.
2114    pub catalog: Arc<std::sync::RwLock<Vec<rpi_ai::Model>>>,
2115    /// Current configured provider runtimes. Replaced after package reload so
2116    /// subsequent reloads cannot recover stale plugin snapshots.
2117    pub providers: Arc<std::sync::RwLock<Vec<Arc<dyn Provider>>>>,
2118    /// The ambient runtime handle (captured in `build`) — `PluggableProvider`
2119    /// and the fresh `ActionBridge` need a captured `Handle` to spawn from any
2120    /// thread.
2121    pub runtime: tokio::runtime::Handle,
2122    /// The cwd (for static resource-dir resolution + context-file walk).
2123    pub cwd: PathBuf,
2124    /// The project-trust decision captured before provider and session setup.
2125    /// Startup consumers reuse this value so extension code cannot change the
2126    /// effective policy by mutating the process cwd while it is loading.
2127    pub project_trusted: bool,
2128    /// Theme file paths contributed by extensions via `resources_discover`,
2129    /// shared so the TUI theme registry can merge them. Filled at startup,
2130    /// replaced on every `/reload` (paths are unattributed — the v1 divergence
2131    /// documented in `rpi-extensions::resources`).
2132    pub discovered_theme_paths: Arc<std::sync::Mutex<Vec<String>>>,
2133    /// The parsed args (cloned) — `--no-*`/`--tools`/`--exclude-tools`/
2134    /// `--extensions-dir`/`--no-extensions`/`--system-prompt`/etc all apply on
2135    /// reload exactly as at startup (a reload re-reads the same flags; it does
2136    /// not pick up argv changes mid-session, which is the right contract — pi's
2137    /// `/reload` re-runs discovery with the same config). `session_dir` holds
2138    /// the resolved startup root, including saved settings/environment defaults.
2139    pub args: Args,
2140    /// The session's agent home. `/reload` must re-read resources and settings
2141    /// from this value, never from a startup snapshot or the process home.
2142    pub home: crate::config::AgentHome,
2143    /// The resolved model + thinking level (the harness's active model stays
2144    /// unless `set_model` changed it; reload does not touch the model).
2145    pub resolved_model: rpi_ai::Model,
2146    /// The broadcast emitter the harness was built with. Reload rebuilds the
2147    /// `TeeEmitter` over the fresh `ExtensionEmitter` (the old tee's extension
2148    /// child is dropped, unsubscribing from the old registry). The broadcast
2149    /// half stays live the whole session (the TUI's drain task holds the
2150    /// receiver), so we keep a handle to re-wrap.
2151    pub broadcast: Arc<dyn rpi_agent::AgentEmitter>,
2152    /// The session-long reload mailbox (B5d). Build creates one, installs it on
2153    /// the initial `ActionBridge` via [`reload_callback_from_mailbox`], and hands
2154    /// a clone to the TUI. The TUI installs its `TuiMessage` sender so a plugin's
2155    /// `runtime_action(Reload)` signals the main loop — the reload routine reuses
2156    /// THIS mailbox (not a fresh default) when building the fresh bridge, so the
2157    /// bridge always carries the mailbox the TUI installed across reloads.
2158    pub mailbox: rpi_extensions::ReloadMailbox,
2159    /// Session-long UI-dialog mailbox (runtime action 17). The initial bridge
2160    /// carries it; the TUI attaches itself and polls `take_pending` from its key
2161    /// loop, and `/reload` reuses THIS mailbox when it builds the fresh bridge.
2162    /// A detached mailbox makes `ask_user` fail with "requires an interactive
2163    /// UI" (headless contract).
2164    pub ui_dialog: rpi_extensions::UiDialogMailbox,
2165    /// Active `rpi dev` extension builder. `/reload` rebuilds it before
2166    /// swapping plugin sessions; its watcher signals `mailbox` after a
2167    /// successful background build.
2168    pub dev_extension: Option<Arc<crate::dev_extension::DevExtension>>,
2169    /// One-line notices the host should show at startup (a session directory
2170    /// that fell back, an untrusted adopted directory). Filled by the CLI after
2171    /// the build and rendered as transcript notes in the TUI; headless modes
2172    /// print them to stderr. Kept as data — never `eprintln!`d from here, which
2173    /// would corrupt the alternate screen (issue #115).
2174    pub startup_notices: Vec<String>,
2175}
2176
2177impl ReloadContext {
2178    pub(crate) fn shell_execution_env(&self) -> Arc<dyn rpi_tools::ExecutionEnv> {
2179        self.execution_env.lock().unwrap().clone()
2180    }
2181
2182    pub(crate) fn session_dir(&self) -> PathBuf {
2183        // The fallback also supports contexts constructed by embedding hosts.
2184        self.args
2185            .session_dir
2186            .clone()
2187            .unwrap_or_else(|| configured_session_dir_for(&self.home, &self.args, &self.cwd))
2188    }
2189}
2190
2191/// Dispatch a no-payload lifecycle event using the live extension-session cell.
2192///
2193/// This is the cell-based counterpart to [`dispatch_session_event_async`]. It
2194/// lets headless RPC tasks retain the live session without borrowing the larger
2195/// [`ReloadContext`]. The snapshot and keepalive are cloned before awaiting, so
2196/// a concurrent `/reload` neither invalidates the plugin function pointers
2197/// mid-dispatch nor keeps a swapped-out registry alive.
2198///
2199/// Each handler runs on a blocking thread with a per-event timeout
2200/// ([`rpi_extensions::lifecycle_timeout_for`]); a handler returning
2201/// [`rpi_plugin_sdk::EVENT_HANDLER_ABORT`] is reported as `Some(reason)`.
2202/// Returns `None` when no plugins are loaded, no handler subscribes, or the
2203/// registry is stale (a `/reload` swapped the session out).
2204pub async fn dispatch_session_event_from_cell(
2205    extension_session: &ExtensionSessionCell,
2206    tag: rpi_plugin_sdk::EventTag,
2207) -> Option<String> {
2208    let (snapshot, keepalive) = {
2209        // A poisoned cell must not panic the caller (the TUI loop dispatches
2210        // these events between UI actions): the session contents are only ever
2211        // replaced wholesale, so recovering the guard is safe.
2212        let session = extension_session
2213            .lock()
2214            .unwrap_or_else(|error| error.into_inner());
2215        (session.snapshot_arc(), session.keepalive())
2216    };
2217    match snapshot {
2218        Some(snapshot) => rpi_extensions::dispatch_lifecycle_event(&snapshot, tag, keepalive).await,
2219        None => None,
2220    }
2221}
2222
2223/// Dispatch a no-payload lifecycle event through the current reload context.
2224///
2225/// Resolves the **current** extension session from the reload cell so a
2226/// `/reload`-swapped session is honored. The caller decides what a veto means:
2227/// a `BeforeTuiStart` veto aborts startup (never enter the TUI);
2228/// `SessionStart`/`SessionShutdown` and the session-tree events dispatched by
2229/// the interactive TUI and RPC paths are advisory — the host logs the reason
2230/// and continues.
2231pub async fn dispatch_session_event_async(
2232    reload_context: &ReloadContext,
2233    tag: rpi_plugin_sdk::EventTag,
2234) -> Option<String> {
2235    dispatch_session_event_from_cell(&reload_context.extension_session, tag).await
2236}
2237
2238/// Join plugin teardown before unloading modules. A detached timed-out handler
2239/// could still execute code in the old DLL, so it cannot safely permit a swap.
2240async fn shutdown_extensions_for_reload(
2241    snapshot: Option<Arc<rpi_extensions::RegistrySnapshot>>,
2242    keepalive: Arc<rpi_extensions::PluginKeepalive>,
2243) -> Result<(), String> {
2244    if let Some(snapshot) = snapshot {
2245        tokio::task::spawn_blocking(move || {
2246            let _keepalive = keepalive;
2247            rpi_extensions::dispatch_empty_event(
2248                &snapshot,
2249                rpi_plugin_sdk::EventTag::SessionShutdown,
2250            );
2251        })
2252        .await
2253        .map_err(|error| error.to_string())?;
2254    }
2255    Ok(())
2256}
2257
2258/// The outcome of a reload: a human-readable status line for the transcript
2259/// (counts of what reloaded), and whether any load diagnostics appeared.
2260pub struct ReloadOutcome {
2261    /// One-line summary for the transcript note (e.g. "Reloaded 2 plugin(s),
2262    /// 5 skill(s), 1 prompt(s).").
2263    pub summary: String,
2264    /// True iff at least one extension load warning fired (ABI mismatch / skip).
2265    pub had_warnings: bool,
2266    /// Formatted diagnostic lines (extension / package / skill / prompt-template warnings)
2267    /// that the caller should surface in its UI. Kept out of `eprintln!`
2268    /// because the TUI owns the terminal: direct stderr writes during a run
2269    /// would corrupt the alternate-screen input row.
2270    pub details: Vec<String>,
2271    /// True iff the reload itself failed hard (e.g. the extension build or
2272    /// settings reload errored) and the previous resources were kept. Soft
2273    /// diagnostics (skill shadowing, name validation) do not set this.
2274    pub had_errors: bool,
2275    /// The project-trust policy this reload actually resolved and applied.
2276    /// `None` when the reload failed hard and kept the previous resources, so
2277    /// consumers (e.g. theme discovery) should stay on the snapshot they
2278    /// already match instead of re-reading a stale startup bool.
2279    pub project_trusted: Option<bool>,
2280}
2281
2282struct PreparedReloadInputs {
2283    extension_dirs: Vec<PathBuf>,
2284    skill_base_dirs: Vec<PathBuf>,
2285    prompt_base_dirs: Vec<PathBuf>,
2286}
2287
2288/// Append the resource sources that are specific to a reload after the
2289/// conventional project/global directories. Keep this order aligned with the
2290/// initial build: explicit CLI paths must remain available after `/reload`,
2291/// while discovered and package resources retain their lower precedence.
2292fn append_reload_resource_paths(
2293    mut paths: Vec<PathBuf>,
2294    explicit: &[PathBuf],
2295    discovered: &[String],
2296    js_paths: &[PathBuf],
2297    package_paths: &[PathBuf],
2298) -> Vec<PathBuf> {
2299    paths.extend(explicit.iter().cloned());
2300    paths.extend(discovered.iter().map(PathBuf::from));
2301    paths.extend(js_paths.iter().cloned());
2302    paths.extend(package_paths.iter().cloned());
2303    paths
2304}
2305
2306/// Re-run extension + resource discovery and push the rebuilt state into the
2307/// live `harness` via the B5d setters. The old `ExtensionSession` +
2308/// `ActionBridge` are invalidated + swapped in [`ReloadContext`]'s cells. This
2309/// is the single routine both `/reload` (TUI) and a plugin's
2310/// `runtime_action(Reload)` drive (the latter via the mailbox signal).
2311///
2312/// Returns a [`ReloadOutcome`] for the transcript. Best-effort: a failure in
2313/// one channel (e.g. a plugin that fails to reload) does not abort the others —
2314/// the reload completes with whatever loaded, mirroring pi's per-plugin
2315/// skip-on-error. A hard failure (e.g. the harness is closed) surfaces as an
2316/// error summary.
2317pub async fn reload_extension_resources(
2318    harness: &AgentHarness,
2319    ctx: &ReloadContext,
2320) -> ReloadOutcome {
2321    reload_extension_resources_inner(harness, ctx, || {}).await
2322}
2323
2324async fn reload_extension_resources_inner<F>(
2325    harness: &AgentHarness,
2326    ctx: &ReloadContext,
2327    after_prepare: F,
2328) -> ReloadOutcome
2329where
2330    F: FnOnce() + Send,
2331{
2332    if harness.has_exact_resources()
2333        || ctx.args.resource_config.is_some()
2334        || ctx.args.resource_transition.is_some()
2335    {
2336        return ReloadOutcome {
2337            summary:
2338                "Exact resource selection is restart-required; reload/dev hot apply unsupported"
2339                    .into(),
2340            had_warnings: true,
2341            details: Vec::new(),
2342            had_errors: true,
2343            project_trusted: None,
2344        };
2345    }
2346    // Fence the whole candidate preparation, including dev builds and rejected
2347    // candidates; cleanup must not seal receipts while any reload can still load.
2348    let Some(reload_permit) = ctx.plugin_resources.begin_reload().await else {
2349        return ReloadOutcome {
2350            summary: "Session resources are retiring; reload rejected".into(),
2351            had_warnings: true,
2352            details: Vec::new(),
2353            had_errors: true,
2354            project_trusted: None,
2355        };
2356    };
2357    // Resolve the arguments once for this reload. `rpi dev` may append its
2358    // freshly staged extension directory; every subsequent loader and policy
2359    // decision must observe that same effective set rather than falling back
2360    // to the pre-dev snapshot held in `ctx.args`.
2361    let mut effective_args = ctx.args.clone();
2362    if let Some(dev) = &ctx.dev_extension {
2363        if let Err(error) = dev
2364            .rebuild()
2365            .and_then(|_| dev.apply_to_args(&mut effective_args))
2366        {
2367            return ReloadOutcome {
2368                summary: format!(
2369                    "Extension build failed for {}: {error}. Keeping the currently loaded version.",
2370                    dev.package_name()
2371                ),
2372                had_warnings: true,
2373                details: Vec::new(),
2374                had_errors: true,
2375                project_trusted: None,
2376            };
2377        }
2378    }
2379    let cwd_str = ctx.cwd.to_string_lossy().to_string();
2380    let project_trusted = resolve_project_trust_for(&ctx.home, &effective_args, &ctx.cwd);
2381    if !project_trusted {
2382        ctx.tool_context.set_project_resources_allowed(false);
2383    }
2384    let prepared =
2385        match prepare_reload_inputs_for(&ctx.home, &effective_args, &ctx.cwd, project_trusted) {
2386            Ok(prepared) => prepared,
2387            Err(error) => {
2388                return ReloadOutcome {
2389                    summary: format!(
2390                        "Settings reload failed: {error}. Keeping the currently loaded resources."
2391                    ),
2392                    had_warnings: true,
2393                    details: Vec::new(),
2394                    had_errors: true,
2395                    project_trusted: None,
2396                };
2397            }
2398        };
2399    let env = Arc::new(execution_env(&ctx.home, &ctx.cwd));
2400    after_prepare();
2401    let PreparedReloadInputs {
2402        extension_dirs,
2403        skill_base_dirs,
2404        prompt_base_dirs,
2405    } = prepared;
2406    let mut warnings = false;
2407
2408    // ---- 1. Build a fresh ActionBridge + ExtensionSession ----
2409    // The fresh bridge carries the SAME `HarnessActionHost` (the host's harness
2410    // cell already points at this harness; the host impl is reusable across
2411    // reloads — only the bridge's staleness flag + reload callback differ). We
2412    // re-use the host by reading it off the OLD bridge (it's the same
2413    // `Arc<dyn RuntimeActionHost>`).
2414    let old_bridge = ctx.action_bridge.lock().unwrap().clone();
2415    let host: Arc<dyn rpi_extensions::RuntimeActionHost> = match &old_bridge {
2416        Some(b) => b.clone_host(),
2417        None => {
2418            // No prior bridge (no extensions ever loaded). Build a fresh host so
2419            // a reload that newly discovers plugins can still drive actions.
2420            let (action_host, _cell) = crate::extensions_actions::HarnessActionHost::new_empty(
2421                ctx.catalog
2422                    .read()
2423                    .unwrap_or_else(|error| error.into_inner())
2424                    .clone(),
2425                ctx.cwd.clone(),
2426                ctx.runtime.clone(),
2427                ctx.args.unknown_flags.clone(),
2428                ctx.tool_context.clone(),
2429            );
2430            crate::extensions_actions::HarnessActionHost::set_harness(
2431                &_cell,
2432                Arc::new(harness.clone()),
2433            );
2434            Arc::new(
2435                action_host
2436                    .with_session_dir(ctx.session_dir())
2437                    .with_ephemeral_sessions_only(ctx.ephemeral_sessions_only)
2438                    .with_process_identity(ctx.host_plugin_images.is_none())
2439                    .with_native_durable(ctx.args.native_durable),
2440            )
2441        }
2442    };
2443
2444    let reload_cb = rpi_extensions::reload_callback_from_mailbox(ctx.mailbox.clone());
2445    let publish_host = Arc::clone(&host);
2446    let fresh_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
2447        ctx.runtime.clone(),
2448        host,
2449        reload_cb,
2450        ctx.ui_dialog.clone(),
2451        ctx.ext_status.clone(),
2452        ctx.editor_text.clone(),
2453    );
2454    if ctx.host_plugin_images.is_some() {
2455        fresh_bridge.disable_stdio_claims();
2456    }
2457
2458    let diagnostics =
2459        crate::host::cli_cleanup::PluginLoadDiagnostics::new(ctx.plugin_cleanup.clone());
2460    let extension_session = if effective_args.no_extensions {
2461        rpi_extensions::ExtensionSession::none()
2462    } else {
2463        let load = || {
2464            load_extensions_from_dirs(
2465                &ctx.home,
2466                &effective_args,
2467                &extension_dirs,
2468                Some(Arc::clone(&fresh_bridge)),
2469                Some(reload_permit.host_guard()),
2470                diagnostics.clone(),
2471                ctx.host_plugin_images.as_ref(),
2472            )
2473        };
2474        if ctx.host_plugin_images.is_some() {
2475            tokio::task::block_in_place(load)
2476        } else {
2477            load()
2478        }
2479    };
2480    if effective_args.native_durable {
2481        if let Err(error) = validate_durable_extensions(&extension_session) {
2482            return ReloadOutcome {
2483                summary: "Reload rejected because an extension conflicts with native durable"
2484                    .into(),
2485                had_warnings: true,
2486                details: vec![error],
2487                had_errors: true,
2488                project_trusted: None,
2489            };
2490        }
2491    }
2492    if extension_session.is_empty() && !effective_args.no_extensions {
2493        // The fresh session may be empty if no cdylibs are present — not a
2494        // warning per se, but note it.
2495    }
2496    if effective_args.verbose {
2497        if let Some(s) = extension_session.summary() {
2498            eprintln!("reload: {s}");
2499        }
2500        report_deferred_renderers(&extension_session);
2501    }
2502
2503    let has_package_providers = |session: &ExtensionSession| {
2504        session.snapshot().is_some_and(|snapshot| {
2505            snapshot
2506                .providers()
2507                .iter()
2508                .any(|provider| snapshot.provider_manifest(&provider.provider_id).is_some())
2509        })
2510    };
2511    let packaged = has_package_providers(&extension_session)
2512        || has_package_providers(&ctx.extension_session.lock().unwrap());
2513    let refreshed = if packaged {
2514        let mut args = effective_args.clone();
2515        if let Ok(current) = harness.lane("main").get_model().await {
2516            let was_package = ctx
2517                .extension_session
2518                .lock()
2519                .unwrap()
2520                .snapshot()
2521                .is_some_and(|snapshot| snapshot.provider_manifest(&current.provider).is_some());
2522            let has_replacement = extension_session.snapshot().is_some_and(|snapshot| {
2523                snapshot
2524                    .providers()
2525                    .iter()
2526                    .any(|provider| provider.provider_id == current.provider)
2527            });
2528            if was_package && !has_replacement {
2529                return ReloadOutcome {
2530                    summary: "Reload failed while resolving provider packages".into(),
2531                    had_warnings: true,
2532                    details: vec![format!(
2533                        "active provider package '{}' is no longer loaded",
2534                        current.provider
2535                    )],
2536                    had_errors: true,
2537                    project_trusted: None,
2538                };
2539            }
2540            args.provider = Some(current.provider.clone());
2541            args.model = Some(current.id);
2542            if current.provider != ctx.resolved_model.provider {
2543                args.api_key = None;
2544                args.base_url = None;
2545            }
2546        }
2547        match crate::provider::resolve_with_extensions(
2548            &ctx.home,
2549            &args,
2550            &ctx.cwd,
2551            ctx.project_trusted,
2552            &extension_session,
2553        ) {
2554            Ok(resolved) => Some(resolved),
2555            Err(error) => {
2556                return ReloadOutcome {
2557                    summary: "Reload failed while resolving provider packages".into(),
2558                    had_warnings: true,
2559                    details: vec![error.to_string()],
2560                    had_errors: true,
2561                    project_trusted: None,
2562                }
2563            }
2564        }
2565    } else {
2566        None
2567    };
2568
2569    // Candidate loading and provider resolution above are not yet published to
2570    // the live session. Do not tell existing extensions that their session is
2571    // shutting down until every rejectable preparation step has
2572    // succeeded; otherwise a rejected candidate would leave the old registry
2573    // live after it had already received SessionShutdown. Candidate DLLs remain
2574    // held by `extension_session`, so the old module is not unloaded before its
2575    // shutdown handlers have joined.
2576    let (shutdown_snapshot, shutdown_keepalive) = {
2577        let session = ctx.extension_session.lock().unwrap();
2578        (session.snapshot_arc(), session.keepalive())
2579    };
2580    if let Err(reason) = shutdown_extensions_for_reload(shutdown_snapshot, shutdown_keepalive).await
2581    {
2582        return ReloadOutcome {
2583            summary: "Reload failed during extension shutdown".into(),
2584            had_warnings: true,
2585            details: vec![reason],
2586            had_errors: true,
2587            project_trusted: None,
2588        };
2589    }
2590
2591    // ---- 2. Invalidate the old session + bridge BEFORE the swap ----
2592    // The old registry's `active` flag flips false so any in-flight
2593    // `emit_resources_discover`/event dispatch on the old snapshot no-ops; the
2594    // old bridge's flag flips false so in-flight `runtime_action` calls parked
2595    // on the old `user_data` hit the staleness guard. Invalidate under the
2596    // session lock before exposing the replacement to approval callbacks.
2597    //
2598    // Swap directly to the fresh session under the same lock that approvals
2599    // use. A temporary empty session would let a concurrent call bypass its gate.
2600    // In-flight approvals retain their old session until their callback exits;
2601    // its staleness flag prevents them from authorizing after this swap.
2602    let old_session = {
2603        let mut session_guard = ctx.extension_session.lock().unwrap();
2604        let old_session = std::mem::replace(&mut *session_guard, extension_session.clone());
2605        if let Some(old_snap) = old_session.snapshot_arc() {
2606            // `invalidate` is on the registry, but the snapshot shares the flag —
2607            // flipping the snapshot's flag invalidates the registry too (same Arc).
2608            // `RegistrySnapshot` exposes `active_flag()` for this.
2609            old_snap.active_flag().store(false, Ordering::SeqCst);
2610        }
2611        old_session
2612    };
2613    if let Some(old_b) = old_bridge {
2614        old_b.invalidate();
2615    }
2616    // Shutdown callbacks see stale host actions and run outside session locks.
2617    old_session.begin_shutdown();
2618
2619    // The session was swapped atomically above; expose its matching bridge.
2620    *ctx.action_bridge.lock().unwrap() = Some(Arc::clone(&fresh_bridge));
2621    // Republish the registry so `ListCommands` reflects the commands the reload
2622    // just discovered — without this a remote UI keeps serving the startup set
2623    // until the host process restarts. Via the trait method because all we hold
2624    // here is `Arc<dyn RuntimeActionHost>`.
2625    // Publish even when the reload found nothing: a nonempty -> empty reload
2626    // returns `ExtensionSession::none()`, and skipping it would leave the old
2627    // snapshot advertised.
2628    publish_host.publish_registry_opt(extension_session.snapshot_arc());
2629
2630    // ---- 3. resources_discover ("reload") over the fresh snapshot ----
2631    let discovered = extension_session
2632        .snapshot_arc()
2633        .map(|snap| rpi_extensions::emit_resources_discover(&cwd_str, "reload", &snap))
2634        .unwrap_or_default();
2635    // Publish the fresh theme paths so the TUI registry rebuild sees the same
2636    // set the skill/prompt loaders just consumed.
2637    if let Ok(mut guard) = ctx.discovered_theme_paths.lock() {
2638        *guard = discovered.theme_paths.clone();
2639    }
2640
2641    // ---- 4. Re-run the Part-A loaders (same precedence + --no-* gates) ----
2642    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
2643
2644    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
2645    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
2646    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
2647    if !effective_args.no_skills {
2648        // JS discovery is backed by the session-long lazy Node host. Until
2649        // that host is swapped as part of a future full JS reload, preserve
2650        // the paths it contributed at startup across `/reload`.
2651        let js_paths: &[PathBuf] = &[];
2652        let package_paths: &[PathBuf] = &[];
2653        let dirs = append_reload_resource_paths(
2654            skill_base_dirs,
2655            &effective_args.skill,
2656            &discovered.skill_paths,
2657            js_paths,
2658            package_paths,
2659        );
2660        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
2661        skills = result.skills;
2662        skill_diags = result.diagnostics;
2663        resource_diags.extend(result.resource_diagnostics);
2664    }
2665
2666    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
2667    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
2668    if !effective_args.no_prompt_templates {
2669        let js_paths: &[PathBuf] = &[];
2670        let package_paths: &[PathBuf] = &[];
2671        let dirs = append_reload_resource_paths(
2672            prompt_base_dirs,
2673            &effective_args.prompt_template,
2674            &discovered.prompt_paths,
2675            js_paths,
2676            package_paths,
2677        );
2678        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
2679        prompt_templates = result.prompt_templates;
2680        prompt_diags = result.diagnostics;
2681        resource_diags.extend(result.resource_diagnostics);
2682    }
2683
2684    let context_files = if effective_args.no_context_files || !project_trusted {
2685        Vec::new()
2686    } else {
2687        let agent_dir = ctx.home.root().ok();
2688        let agent_dir_path = agent_dir.unwrap_or_else(|| ctx.cwd.clone());
2689        load_project_context_files(&env_dyn, &ctx.cwd, &agent_dir_path).await
2690    };
2691    let context_block = format_project_context(&context_files);
2692
2693    let mut details = diagnostics.take();
2694    warnings |= !details.is_empty();
2695    if let Some(resolved) = &refreshed {
2696        warnings |= !resolved.compat_warnings.is_empty();
2697        details.extend(
2698            resolved
2699                .compat_warnings
2700                .iter()
2701                .map(|warning| format!("warning: models.json: {warning}")),
2702        );
2703    }
2704    if !skill_diags.is_empty() || !prompt_diags.is_empty() || !resource_diags.is_empty() {
2705        warnings = true;
2706        // Collect formatted diagnostics for the caller to surface in its UI
2707        // instead of writing to stderr directly: the TUI owns the terminal,
2708        // and a raw `eprintln!` during a run would scribble over the
2709        // alternate-screen input row.
2710        for d in &skill_diags {
2711            details.push(format!(
2712                "warning: skill {} ({}): {}",
2713                d.path,
2714                d.code.as_str(),
2715                d.message
2716            ));
2717        }
2718        for d in &prompt_diags {
2719            details.push(format!(
2720                "warning: prompt template {} ({}): {}",
2721                d.path,
2722                d.code.as_str(),
2723                d.message
2724            ));
2725        }
2726        // Structured collisions: winner (kept) · loser (shadowed).
2727        for d in &resource_diags {
2728            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
2729                details.push(format!(
2730                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
2731                    c.resource_type.as_str(),
2732                    c.name,
2733                    c.winner_path,
2734                    c.loser_path
2735                ));
2736            }
2737        }
2738    }
2739
2740    // ---- Re-compose the system prompt (same precedence as build) ----
2741    // Same working-state wording rule as `build`; a mid-session `/model` switch
2742    // re-composes the prompt on the next reload, which is the same staleness the
2743    // rest of this path already has (provider resolution is a startup concern).
2744    // Re-merge extension tools (a reloaded plugin may have added/removed a
2745    // tool). The built-in set is rebuilt from scratch + extension tools merged
2746    // on top, mirroring `build`. Built before the
2747    // prompt so the prompt lists exactly the active tools.
2748    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
2749    let tool_ctx = rpi_tools::ExecutionToolContext::new(env_dyn.clone(), Some(mut_env))
2750        .with_file_io(ctx.file_io.clone());
2751    // Reuse the binding installed in the durable context hook at startup;
2752    // constructing a fresh OnceLock here would register a durable tool that
2753    // can never resolve its owning harness.
2754    let mut tools = build_tools_bound(
2755        &ctx.home,
2756        &tool_ctx,
2757        &effective_args,
2758        ctx.durable_binding.clone(),
2759    );
2760    merge_extension_tools(
2761        &mut tools,
2762        &extension_session,
2763        &effective_args,
2764        &ctx.tool_context,
2765    );
2766    let mut active = active_tool_names(&tools, &effective_args);
2767    active = filter_active_tool_names(active, &effective_args);
2768    let prompt_tools = active.clone();
2769    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
2770    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&ctx.resolved_model);
2771    let default_prompt = || {
2772        default_system_prompt_with_tool_prompts(
2773            &cwd_str,
2774            prior_reasoning_replayed,
2775            &prompt_tools,
2776            &prompt_metadata,
2777        )
2778    };
2779    let mut context_paths = Vec::new();
2780    let base_prompt = match effective_args.system_prompt.as_deref() {
2781        Some(explicit) => explicit.to_string(),
2782        None if project_trusted => match ctx.home.discover_system_prompt_file(&ctx.cwd, true) {
2783            Some(path) => {
2784                read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
2785            }
2786            None => default_prompt(),
2787        },
2788        None => default_prompt(),
2789    };
2790    let mut append_texts: Vec<String> = Vec::new();
2791    for extra in &effective_args.append_system_prompt {
2792        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
2793        append_texts.push(text);
2794    }
2795    if effective_args.append_system_prompt.is_empty() {
2796        if let Some(path) = project_trusted
2797            .then(|| ctx.home.discover_append_system_prompt_file(&ctx.cwd))
2798            .flatten()
2799        {
2800            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
2801                append_texts.push(text);
2802            }
2803        }
2804    }
2805    context_paths.extend(
2806        context_files
2807            .iter()
2808            .map(|file| file.path.to_string_lossy().into_owned()),
2809    );
2810    let append_join = if append_texts.is_empty() {
2811        None
2812    } else {
2813        Some(append_texts.join("\n\n"))
2814    };
2815    let system_prompt = compose_system_prompt(
2816        Some(&base_prompt),
2817        &[],
2818        if context_block.is_empty() {
2819            None
2820        } else {
2821            Some(&context_block)
2822        },
2823        append_join.as_deref(),
2824    );
2825
2826    // ---- Rebuild the emitter (TeeEmitter over fresh ExtensionEmitter) ----
2827    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
2828        Some(snapshot) => {
2829            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
2830            Arc::new(TeeEmitter::new(vec![ctx.broadcast.clone(), Arc::new(ext)]))
2831        }
2832        None => ctx.broadcast.clone(),
2833    };
2834
2835    // ---- 5. Push the rebuilt state into the live harness via the B5d setters ----
2836    let resources = AgentHarnessResources {
2837        context_files: context_paths,
2838        skills: if skills.is_empty() {
2839            None
2840        } else {
2841            Some(skills.clone())
2842        },
2843        prompt_templates: if prompt_templates.is_empty() {
2844            None
2845        } else {
2846            Some(prompt_templates.clone())
2847        },
2848    };
2849    let _ = harness.set_system_prompt(Some(system_prompt)).await;
2850    let _ = harness.set_resources(resources).await;
2851    let _ = harness.set_agent_emitter(Some(emitter)).await;
2852    let _ = harness
2853        .set_models(build_models_with_extensions_for_reload(
2854            &refreshed
2855                .as_ref()
2856                .map(|resolved| resolved.providers.clone())
2857                .unwrap_or_else(|| {
2858                    ctx.providers
2859                        .read()
2860                        .unwrap_or_else(|error| error.into_inner())
2861                        .clone()
2862                }),
2863            &extension_session,
2864            ctx.runtime.clone(),
2865        ))
2866        .await;
2867    let _ = harness
2868        .set_provider_hooks(
2869            rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
2870                .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
2871        )
2872        .await;
2873
2874    if let Some(resolved) = &refreshed {
2875        *ctx.providers
2876            .write()
2877            .unwrap_or_else(|error| error.into_inner()) = resolved.providers.clone();
2878        let catalog = crate::provider::authenticated_catalog(resolved);
2879        fresh_bridge
2880            .clone_host()
2881            .replace_model_catalog(catalog.clone());
2882        *ctx.catalog
2883            .write()
2884            .unwrap_or_else(|error| error.into_inner()) = catalog;
2885        // Refresh the public descriptor. Credentials remain in the newly bound
2886        // provider instances installed above and never enter the lane model.
2887        let _ = harness.lane("main").set_model(resolved.model.clone()).await;
2888    }
2889
2890    ctx.tool_context
2891        .set_project_resources_allowed(project_trusted);
2892    if harness.set_tools(tools, Some(active)).await.is_ok() {
2893        *ctx.execution_env.lock().unwrap() = env;
2894    }
2895
2896    let summary = format!(
2897        "Reloaded {} plugin(s), {} skill(s), {} prompt(s).",
2898        extension_session.loaded_paths().len(),
2899        skills.len(),
2900        prompt_templates.len(),
2901    );
2902    ReloadOutcome {
2903        summary,
2904        had_warnings: warnings,
2905        details,
2906        // Reload completed; any diagnostics here are soft (shadowing / name
2907        // validation / skipped optional resources), not hard failures.
2908        had_errors: false,
2909        project_trusted: Some(project_trusted),
2910    }
2911}
2912
2913#[derive(Clone, Debug, PartialEq, Eq)]
2914struct ReloadSettingsFields {
2915    skill_dirs: Option<Vec<String>>,
2916    prompt_dirs: Option<Vec<String>>,
2917    extension_dirs: Option<Vec<String>>,
2918}
2919
2920impl From<crate::settings::Settings> for ReloadSettingsFields {
2921    fn from(settings: crate::settings::Settings) -> Self {
2922        Self {
2923            skill_dirs: settings.skill_dirs,
2924            prompt_dirs: settings.prompt_dirs,
2925            extension_dirs: settings.extension_dirs,
2926        }
2927    }
2928}
2929
2930#[derive(Clone, Debug, PartialEq, Eq)]
2931struct ReloadSettingsSnapshot {
2932    global: ReloadSettingsFields,
2933    project: Option<ReloadSettingsFields>,
2934}
2935
2936fn reload_reads_settings(args: &Args) -> bool {
2937    !args.dev_local_only && (!args.no_extensions || !args.no_skills || !args.no_prompt_templates)
2938}
2939
2940/// Strictly read the settings fields consumed while preparing a reload. The
2941/// snapshot intentionally excludes UI/model fields that `/reload` does not
2942/// use, so an unrelated settings save does not invalidate the operation.
2943fn load_reload_settings_snapshot(
2944    home: &crate::config::AgentHome,
2945    args: &Args,
2946    cwd: &Path,
2947    project_trusted: bool,
2948) -> Result<Option<ReloadSettingsSnapshot>, String> {
2949    if !reload_reads_settings(args) {
2950        return Ok(None);
2951    }
2952    let global = home
2953        .settings()
2954        .map_err(|error| format!("could not load global settings: {error}"))?
2955        .into();
2956    let project = if project_trusted {
2957        crate::settings::load_active_project_settings(cwd)
2958            .map_err(|error| format!("could not load project settings: {error}"))?
2959            .map(|(_, settings)| settings.into())
2960    } else {
2961        None
2962    };
2963    Ok(Some(ReloadSettingsSnapshot { global, project }))
2964}
2965
2966/// Build the execution environment rooted at `cwd` using the agent home's
2967/// `shellPath`. rpi-tools validates the configured path before spawning. On
2968/// Windows, it checks `RPI_BASH_PATH` before discovery when the setting is unset.
2969fn execution_env(home: &crate::config::AgentHome, cwd: &Path) -> OsExecutionEnv {
2970    let mut env = OsExecutionEnv::with_cwd(cwd.to_path_buf());
2971    match home.settings() {
2972        Ok(settings) => {
2973            if let Some(shell) = settings.shell_path.as_deref().map(str::trim) {
2974                if !shell.is_empty() {
2975                    env = env.with_shell_path(PathBuf::from(shell));
2976                }
2977            }
2978        }
2979        // Missing settings are `Ok(default)`; a broken file must still be
2980        // visible, but it should not stop the session from starting.
2981        Err(error) => tracing::warn!("settings unavailable; shellPath not applied: {error}"),
2982    }
2983    env
2984}
2985
2986/// Validate every settings document that this reload will consume before
2987/// replacing any live extension, bridge, or harness resource.
2988#[cfg(test)]
2989fn validate_settings_for_reload(
2990    args: &Args,
2991    cwd: &Path,
2992    project_trusted: bool,
2993) -> Result<(), String> {
2994    load_reload_settings_snapshot(
2995        &crate::config::AgentHome::process(),
2996        args,
2997        cwd,
2998        project_trusted,
2999    )
3000    .map(|_| ())
3001}
3002
3003fn prepare_reload_inputs_for(
3004    home: &crate::config::AgentHome,
3005    args: &Args,
3006    cwd: &Path,
3007    project_trusted: bool,
3008) -> Result<PreparedReloadInputs, String> {
3009    prepare_reload_inputs_inner_for(home, args, cwd, project_trusted, || {})
3010}
3011
3012#[cfg(test)]
3013fn prepare_reload_inputs_inner<F>(
3014    args: &Args,
3015    cwd: &Path,
3016    project_trusted: bool,
3017    before_verify: F,
3018) -> Result<PreparedReloadInputs, String>
3019where
3020    F: FnOnce(),
3021{
3022    prepare_reload_inputs_inner_for(
3023        &crate::config::AgentHome::process(),
3024        args,
3025        cwd,
3026        project_trusted,
3027        before_verify,
3028    )
3029}
3030
3031fn prepare_reload_inputs_inner_for<F>(
3032    home: &crate::config::AgentHome,
3033    args: &Args,
3034    cwd: &Path,
3035    project_trusted: bool,
3036    before_verify: F,
3037) -> Result<PreparedReloadInputs, String>
3038where
3039    F: FnOnce(),
3040{
3041    let settings_before = load_reload_settings_snapshot(home, args, cwd, project_trusted)?;
3042
3043    let extension_dirs = resource_root_dirs(
3044        home,
3045        args,
3046        cwd,
3047        project_trusted,
3048        ResourceRootKind::Extensions,
3049    );
3050    let skill_base_dirs =
3051        resource_root_dirs(home, args, cwd, project_trusted, ResourceRootKind::Skills);
3052    let prompt_base_dirs = resource_root_dirs(
3053        home,
3054        args,
3055        cwd,
3056        project_trusted,
3057        ResourceRootKind::PromptTemplates,
3058    );
3059
3060    before_verify();
3061    let settings_after = load_reload_settings_snapshot(home, args, cwd, project_trusted)?;
3062    if settings_before != settings_after {
3063        return Err(
3064            "settings changed while reload inputs were being prepared; retry /reload".to_string(),
3065        );
3066    }
3067
3068    Ok(PreparedReloadInputs {
3069        extension_dirs,
3070        skill_base_dirs,
3071        prompt_base_dirs,
3072    })
3073}
3074
3075/// `build_models_with_extensions` for the reload path: the resolved provider
3076/// runtimes (NOT `resolved` — the reload context carries the `Arc<dyn Provider>`
3077/// list directly, since provider/auth did not change) first, then one
3078/// `PluggableProvider` per registered extension provider in the fresh session.
3079fn build_models_with_extensions_for_reload(
3080    providers: &[Arc<dyn Provider>],
3081    extension_session: &ExtensionSession,
3082    runtime: tokio::runtime::Handle,
3083) -> Vec<Arc<dyn Provider>> {
3084    let mut models: Vec<Arc<dyn Provider>> = providers.to_vec();
3085    let pluggable = rpi_extensions::PluggableProvider::from_session(extension_session, runtime);
3086    for provider in pluggable {
3087        // Declared packages must enter through credential-bound factories.
3088        // Falling back to a raw adapter would reintroduce packages rejected by
3089        // auth filtering and would discard their configured model snapshot.
3090        if extension_session
3091            .snapshot()
3092            .is_some_and(|snapshot| snapshot.provider_manifest(provider.id()).is_some())
3093        {
3094            continue;
3095        }
3096        if !models.iter().any(|known| known.id() == provider.id()) {
3097            models.push(provider);
3098        }
3099    }
3100    models
3101}
3102
3103/// Diagnostic for registered TUI renderers. All three renderer kinds are
3104/// consumed by the interactive TUI's JSON component adapter; this line remains
3105/// useful under `--verbose` for extension authors.
3106fn report_deferred_renderers(session: &ExtensionSession) {
3107    let Some(snap) = session.snapshot_arc() else {
3108        return;
3109    };
3110    let all = snap.renderers();
3111    let markdown = all
3112        .iter()
3113        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Markdown)
3114        .count();
3115    let message = all
3116        .iter()
3117        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Message)
3118        .count();
3119    let entry = all
3120        .iter()
3121        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Entry)
3122        .count();
3123    if markdown + message + entry == 0 {
3124        return;
3125    }
3126    eprintln!(
3127        "renderers: {} markdown-transform, {} message-render, {} entry-render (active)",
3128        markdown, message, entry
3129    );
3130}
3131
3132/// A harness-build error.
3133#[derive(Debug, thiserror::Error)]
3134pub enum BuildError {
3135    #[error("Could not create the session directory: {0}")]
3136    SessionDir(String),
3137    #[error("Could not open the saved session: {0}")]
3138    SessionOpen(String),
3139    #[error(
3140        "No session found for {requested} in {dir}. Check the selector or start a fresh session."
3141    )]
3142    SessionNotFound { requested: String, dir: String },
3143    #[error("Could not build the harness: {0}")]
3144    HarnessCreate(String),
3145}
3146
3147/// Keep configured factories (including package-specific auth and catalogs)
3148/// first, then append legacy plugin registrations that have no runtime yet.
3149fn build_models_with_extensions(
3150    resolved: &ResolvedModel,
3151    extension_session: &ExtensionSession,
3152    runtime: tokio::runtime::Handle,
3153) -> Vec<Arc<dyn Provider>> {
3154    build_models_with_extensions_for_reload(&resolved.providers, extension_session, runtime)
3155}
3156
3157/// Resolve project resource loading without prompting. Explicit CLI overrides
3158/// win, then a stored decision; projects with no decision load by default.
3159pub(crate) fn resolve_project_trust(args: &Args, cwd: &Path) -> bool {
3160    resolve_project_trust_for(&crate::config::AgentHome::process(), args, cwd)
3161}
3162
3163pub(crate) fn resolve_project_trust_for(
3164    home: &crate::config::AgentHome,
3165    args: &Args,
3166    cwd: &Path,
3167) -> bool {
3168    if let Some(override_value) = args.trust_override {
3169        return override_value;
3170    }
3171    home.project_trust_decision(cwd)
3172        .ok()
3173        .flatten()
3174        .unwrap_or(true)
3175}
3176
3177/// Resolve the extension dirs to scan and load the cdylib plugins, returning
3178/// the loaded session guard (keeps the `Library` handles alive for the harness
3179/// lifetime). Scan order: configured project paths, project `.rpi/extensions`,
3180/// configured/global conventional paths, then any
3181/// `--extensions-dir` flags (scanned after the defaults — `args.rs`).
3182fn startup_extension_dirs(
3183    home: &crate::config::AgentHome,
3184    args: &Args,
3185    cwd: &Path,
3186    project_trusted: bool,
3187) -> Vec<PathBuf> {
3188    resource_root_dirs(
3189        home,
3190        args,
3191        cwd,
3192        project_trusted,
3193        ResourceRootKind::Extensions,
3194    )
3195}
3196
3197pub(crate) fn load_extensions(
3198    home: &crate::config::AgentHome,
3199    args: &Args,
3200    cwd: &Path,
3201    project_trusted: bool,
3202    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
3203) -> ExtensionSession {
3204    let diagnostics = crate::host::cli_cleanup::PluginLoadDiagnostics::new(
3205        crate::host::cli_cleanup::PluginCleanupLedger::new(),
3206    );
3207    let session = load_extensions_tracked(
3208        home,
3209        args,
3210        cwd,
3211        project_trusted,
3212        action_bridge,
3213        diagnostics.clone(),
3214    );
3215    for detail in diagnostics.take() {
3216        eprintln!("warning: {detail}");
3217    }
3218    session
3219}
3220
3221fn load_extensions_tracked(
3222    home: &crate::config::AgentHome,
3223    args: &Args,
3224    cwd: &Path,
3225    project_trusted: bool,
3226    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
3227    diagnostics: Arc<dyn PluginDiagnostics>,
3228) -> ExtensionSession {
3229    if args.no_extensions {
3230        return ExtensionSession::none();
3231    }
3232    let dirs = startup_extension_dirs(home, args, cwd, project_trusted);
3233    let leases = match crate::resource_management::host_leases_for(home, cwd) {
3234        Ok(leases) => leases,
3235        Err(error) => {
3236            eprintln!("warning: refusing extension loading: {error}");
3237            return ExtensionSession::none();
3238        }
3239    };
3240    load_extensions_from_dirs(
3241        home,
3242        args,
3243        &dirs,
3244        action_bridge,
3245        Some(leases),
3246        diagnostics,
3247        None,
3248    )
3249}
3250
3251/// Replace the default global extension directory with the registry-selected
3252/// file list. The loader otherwise scans every cdylib in that directory,
3253/// which re-loads retired versioned artifacts after an rpi-web update and
3254/// makes two `ownsStdio` extensions race for stdio ownership.
3255///
3256/// Only the conventional `<agent_dir>/extensions` directory is rewritten.
3257/// Project dirs and user-configured extension dirs stay directory-scanned;
3258/// unmanaged legacy cdylibs in the global dir are preserved explicitly.
3259fn registry_aware_extension_inputs(
3260    dirs: &[PathBuf],
3261    explicit_files: &[PathBuf],
3262    agent_dir_home: Option<&Path>,
3263) -> (Vec<PathBuf>, Vec<PathBuf>) {
3264    // `agent_dir` owns the registry file; `global_dir` is the directory the
3265    // loader would otherwise scan. Keep both: the helpers take the agent dir.
3266    // `agent_dir_home` is already resolved from the session's `AgentHome`;
3267    // never re-resolve it from the process environment here.
3268    let agent_dir = agent_dir_home.map(Path::to_path_buf);
3269    let global_dir = agent_dir.as_ref().map(|dir| dir.join("extensions"));
3270    let mut filtered_dirs = Vec::with_capacity(dirs.len());
3271    let mut files = explicit_files.to_vec();
3272    let mut global_dir_handled = false;
3273    for dir in dirs {
3274        let is_global = global_dir
3275            .as_ref()
3276            .is_some_and(|global| same_extension_dir(global, dir));
3277        if is_global {
3278            if !global_dir_handled {
3279                global_dir_handled = true;
3280                // An unreadable registry cannot tell us which artifacts are
3281                // retired, so fall back to the historical directory scan rather
3282                // than silently loading no global extension at all.
3283                let selection = agent_dir.as_ref().map(|agent| {
3284                    (
3285                        crate::install::active_global_native_package_artifacts_at(agent),
3286                        crate::install::unregistered_global_native_package_artifacts_at(agent),
3287                    )
3288                });
3289                match selection {
3290                    Some((Ok(active), Ok(legacy))) => {
3291                        files.extend(active);
3292                        files.extend(legacy);
3293                    }
3294                    _ => filtered_dirs.push(dir.clone()),
3295                }
3296            }
3297            continue;
3298        }
3299        filtered_dirs.push(dir.clone());
3300    }
3301    (filtered_dirs, files)
3302}
3303
3304fn same_extension_dir(left: &Path, right: &Path) -> bool {
3305    if left == right {
3306        return true;
3307    }
3308    match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
3309        (Ok(left), Ok(right)) => left == right,
3310        _ => false,
3311    }
3312}
3313
3314fn load_extensions_from_dirs(
3315    home: &crate::config::AgentHome,
3316    args: &Args,
3317    dirs: &[PathBuf],
3318    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
3319    host_guard: Option<Arc<dyn Send + Sync>>,
3320    diagnostics: Arc<dyn PluginDiagnostics>,
3321    _host_plugin_images: Option<&HostPluginImages>,
3322) -> ExtensionSession {
3323    let agent_dir = home.root().ok();
3324    let (dirs, files) =
3325        registry_aware_extension_inputs(dirs, &args.extension, agent_dir.as_deref());
3326    #[cfg(unix)]
3327    if let Some(images) = _host_plugin_images {
3328        return images.load_session(&dirs, &files, diagnostics, action_bridge, host_guard);
3329    }
3330    rpi_extensions::load_session_mixed_guarded(
3331        &dirs,
3332        &files,
3333        diagnostics,
3334        action_bridge,
3335        host_guard,
3336    )
3337}
3338
3339/// The host permanently owns both durable public names.
3340/// Refuse rather than override, fall back to, or dual-write a legacy extension
3341/// implementation. Stdio ownership is independent: adapters such as ACP and
3342/// Web use it only to keep their protocol/server lifecycle alive while the
3343/// native host still owns session durability.
3344fn validate_durable_extensions(session: &ExtensionSession) -> Result<(), String> {
3345    if let Some(snapshot) = session.snapshot() {
3346        if reserved_durable_name(
3347            snapshot.tools().iter().map(|tool| tool.tool.name.as_str()),
3348            snapshot
3349                .commands()
3350                .iter()
3351                .map(|command| command.name.as_str()),
3352        ) {
3353            return Err("extension durable tool or /durable command uses a host-reserved name; remove the legacy extension durable implementation (no automatic import or fallback)".into());
3354        }
3355    }
3356    Ok(())
3357}
3358
3359fn reserved_durable_name<'a>(
3360    mut tools: impl Iterator<Item = &'a str>,
3361    mut commands: impl Iterator<Item = &'a str>,
3362) -> bool {
3363    tools.any(|name| name == "durable")
3364        || commands.any(|name| name.trim_start_matches('/') == "durable")
3365}
3366
3367#[cfg(test)]
3368#[path = "native_durable/session_tests.rs"]
3369mod native_durable_session_tests;
3370
3371/// Merge extension tools into the built-ins. Ordinarily extensions override
3372/// same-named built-ins (first extension wins); host-reserved durable names
3373/// were already checked above. Both tool filters still apply to the merged set.
3374fn merge_extension_tools(
3375    tools: &mut Vec<HarnessTool>,
3376    session: &ExtensionSession,
3377    args: &Args,
3378    tool_context: &rpi_extensions::ToolCallContext,
3379) {
3380    let Some(snapshot) = session.snapshot() else {
3381        return;
3382    };
3383    for et in snapshot.tools() {
3384        let name = &et.tool.name;
3385        if !tool_name_allowed(name, args) {
3386            continue;
3387        }
3388        let adapter = PluginToolAdapter::new(et.tool.clone(), et.handle(), session.keepalive())
3389            .with_context(tool_context.clone());
3390        let harness_tool = HarnessTool::new(Arc::new(adapter));
3391        match tools.iter_mut().find(|t| t.tool.schema().name == *name) {
3392            Some(slot) => *slot = harness_tool,
3393            None => tools.push(harness_tool),
3394        }
3395    }
3396}
3397
3398/// Build the tool list per `--tools`/`--exclude-tools`/`--no-tools`/
3399/// `--no-builtin-tools`. Mirrors the TS `tools`/`excludeTools`/`noTools`
3400/// resolution in `createAgentSession`.
3401/// Default bash timeout: 120s when the model doesn't pass one (prevents a
3402/// forgotten `timeout` from hanging the run forever — the "卡住" report).
3403/// `RPI_BASH_TIMEOUT` overrides; a model-supplied timeout always wins.
3404pub fn bash_options() -> rpi_tools::tools::bash::BashToolOptions {
3405    bash_options_for(&crate::config::AgentHome::process())
3406}
3407
3408/// [`bash_options`] for one agent home.
3409pub fn bash_options_for(
3410    home: &crate::config::AgentHome,
3411) -> rpi_tools::tools::bash::BashToolOptions {
3412    use rpi_tools::tools::bash::BashToolOptions;
3413    let default = std::env::var("RPI_BASH_TIMEOUT")
3414        .ok()
3415        .and_then(|v| v.parse::<f64>().ok())
3416        .unwrap_or(rpi_tools::tools::bash::DEFAULT_BASH_TIMEOUT_SECONDS);
3417    // Saved user defaults, matching how `defaultTools` is read in `build_tools`.
3418    // `shellCommandPrefix` is prepended to every command (upstream's key for
3419    // alias/`shopt` setup). `shellPath` is applied earlier, when the session's
3420    // execution environment is built (see `execution_env`): `BashToolOptions`
3421    // itself still carries no shell binary.
3422    let settings = home.settings().unwrap_or_default();
3423    BashToolOptions {
3424        command_prefix: settings.shell_command_prefix.clone(),
3425        default_timeout: Some(default),
3426        prepare: None,
3427    }
3428}
3429
3430#[cfg(test)]
3431fn build_tools(ctx: &ExecutionToolContext, args: &Args) -> Vec<HarnessTool> {
3432    build_tools_bound(
3433        &crate::config::AgentHome::process(),
3434        ctx,
3435        args,
3436        Arc::new(std::sync::OnceLock::new()),
3437    )
3438}
3439
3440fn build_tools_bound(
3441    home: &crate::config::AgentHome,
3442    ctx: &ExecutionToolContext,
3443    args: &Args,
3444    durable_binding: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
3445) -> Vec<HarnessTool> {
3446    if args.no_tools {
3447        return Vec::new();
3448    }
3449    // Keep the coding tools aligned with Pi and expose rpi's read-only docs
3450    // lookup as a default assistant capability.
3451    //
3452    // Replay policy (native `ToolDeclaration.replay`): only tools that are
3453    // genuinely free of side effects may be re-run when a crash leaves their
3454    // outcome unknown — everything else must stay `Never`, because replaying
3455    // `bash`/`write`/`edit` would duplicate a side effect. `HarnessTool::new`
3456    // already defaults to `Never`, so this is opt-in per read-only tool.
3457    let mut all: Vec<(&'static str, HarnessTool)> = vec![
3458        (
3459            "read",
3460            HarnessTool::new(create_read_tool(
3461                ctx,
3462                Some(rpi_tools::tools::read::ReadToolOptions {
3463                    image_processor: Some(Arc::new(
3464                        rpi_tools::image_processing::InlineImageProcessor,
3465                    )),
3466                    ..Default::default()
3467                }),
3468            ))
3469            .with_replay(ToolReplay::Safe),
3470        ),
3471        (
3472            "bash",
3473            HarnessTool::new(create_bash_tool(ctx, Some(bash_options_for(home)))),
3474        ),
3475        ("edit", HarnessTool::new(create_edit_tool(ctx))),
3476        ("write", HarnessTool::new(create_write_tool(ctx))),
3477        (
3478            "docs",
3479            HarnessTool::new(create_docs_tool()).with_replay(ToolReplay::Safe),
3480        ),
3481    ];
3482
3483    if args.native_durable {
3484        // Mixed read/write tool is NEVER safe for automatic replay.
3485        all.push((
3486            "durable",
3487            HarnessTool::new(Arc::new(crate::native_durable::NativeDurableTool::new(
3488                durable_binding.clone(),
3489            ))),
3490        ));
3491    }
3492
3493    // Add PowerShell tool on Windows
3494    #[cfg(target_os = "windows")]
3495    all.push(("powershell", HarnessTool::new(create_powershell_tool(ctx))));
3496
3497    // Apply default_tools from settings (if no CLI override)
3498    if args.tools.is_none() && args.resource_config.is_none() && args.resource_transition.is_none()
3499    {
3500        if let Ok(settings) = home.settings() {
3501            if let Some(default_tools) = &settings.default_tools {
3502                all.retain(|(name, _)| default_tools.iter().any(|t| t == name));
3503            }
3504        }
3505    }
3506
3507    // Host-integrated agent-to-agent messaging: only when the embedding host
3508    // installed a delivery door. A bare CLI session never advertises a tool it
3509    // cannot service.
3510    if crate::message_agent::handler_installed()
3511        && tool_name_allowed(crate::message_agent::MESSAGE_AGENT_TOOL_NAME, args)
3512    {
3513        all.push((
3514            crate::message_agent::MESSAGE_AGENT_TOOL_NAME,
3515            HarnessTool::new(crate::message_agent::create_message_agent_tool(
3516                durable_binding.clone(),
3517            )),
3518        ));
3519    }
3520
3521    // `--no-builtin-tools` disables the built-in set but would keep
3522    // extension/custom tools — v1 has none, so it's equivalent to `--no-tools`
3523    // here. We honor it by clearing the built-ins.
3524    if args.no_builtin_tools {
3525        all.clear();
3526    }
3527
3528    // Allowlist (`--tools`): keep only named built-ins.
3529    if let Some(allow) = &args.tools {
3530        all.retain(|(name, _)| allow.iter().any(|a| a == name));
3531    }
3532    // Denylist (`--exclude-tools`): drop named tools.
3533    if let Some(deny) = &args.exclude_tools {
3534        all.retain(|(name, _)| !deny.iter().any(|d| d == name));
3535    }
3536
3537    all.into_iter().map(|(_, t)| t).collect()
3538}
3539
3540/// Resolve the active tool names from the constructed tools when no explicit
3541/// `--tools` allowlist was given. Mirrors the TS default: all registered tools
3542/// active.
3543fn active_tool_names(tools: &[HarnessTool], args: &Args) -> Vec<String> {
3544    filter_active_tool_names(
3545        tools.iter().map(|tool| tool.tool.schema().name.clone()),
3546        args,
3547    )
3548}
3549
3550/// Whether a tool name survives the command-line tool policy. Keep this check
3551/// centralized so extension-provided tools honor the same policy as built-ins.
3552pub(crate) fn tool_name_allowed(name: &str, args: &Args) -> bool {
3553    if args.no_tools {
3554        return false;
3555    }
3556    if args
3557        .tools
3558        .as_ref()
3559        .is_some_and(|allow| !allow.iter().any(|value| value == name))
3560    {
3561        return false;
3562    }
3563    if args
3564        .exclude_tools
3565        .as_ref()
3566        .is_some_and(|deny| deny.iter().any(|value| value == name))
3567    {
3568        return false;
3569    }
3570    true
3571}
3572
3573pub(crate) fn filter_active_tool_names<I>(names: I, args: &Args) -> Vec<String>
3574where
3575    I: IntoIterator<Item = String>,
3576{
3577    names
3578        .into_iter()
3579        .filter(|name| tool_name_allowed(name, args))
3580        .collect()
3581}
3582
3583/// Build the `Session` facade for the chosen selection.
3584async fn build_session(
3585    selection: &SessionSelection,
3586    cwd: &str,
3587    selected: Option<&crate::resource_selection::ResolvedSelection>,
3588    resolved_session: Option<&JsonlSessionMetadata>,
3589    prepared_restore: Option<PreparedJsonlRestore>,
3590) -> Result<Session, BuildError> {
3591    match selection {
3592        SessionSelection::Ephemeral => Ok(ephemeral_session()),
3593        SessionSelection::New { dir, .. } => {
3594            // Ensure the sessions directory exists, then create a fresh JSONL
3595            // session file inside it.
3596            std::fs::create_dir_all(dir)
3597                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3598            let session = create_jsonl_session(dir, cwd)
3599                .await
3600                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3601            Ok(session)
3602        }
3603        SessionSelection::Latest { .. }
3604        | SessionSelection::ById { .. }
3605        | SessionSelection::ByExactId { .. } => {
3606            restore_session(selection, cwd, prepared_restore).await
3607        }
3608        SessionSelection::Fork {
3609            source,
3610            dir,
3611            entry_id,
3612            position,
3613        } => {
3614            fork_session_at_launch(
3615                source,
3616                dir,
3617                cwd,
3618                selected,
3619                entry_id.as_deref(),
3620                *position,
3621                resolved_session,
3622            )
3623            .await
3624        }
3625    }
3626}
3627
3628/// Open an existing JSONL session for `Latest` / `ById`. Mirrors the TS
3629/// `SessionManager.resume`/`open` flow: list the session dir (newest-first),
3630/// match the request, then open the matched file and wrap it in a `Session`
3631/// facade. The restored transcript renders into the TUI at startup and the
3632/// harness continues appending to the same file.
3633async fn restore_session(
3634    selection: &SessionSelection,
3635    cwd: &str,
3636    prepared_restore: Option<PreparedJsonlRestore>,
3637) -> Result<Session, BuildError> {
3638    if let Some(prepared) = prepared_restore {
3639        // Preflight verified the selected file and reserved its writer. Commit
3640        // that replay without resolving an ID or a newest-file selection again.
3641        let path = prepared.metadata().path;
3642        let storage = prepared
3643            .commit()
3644            .await
3645            .map_err(|e| BuildError::SessionOpen(format!("open {path}: {e}")))?;
3646        let progress_upgrade = StartupSpan::start(Phase::ProgressUpgrade);
3647        let storage = storage
3648            .enable_progress_under_exclusive_lock()
3649            .await
3650            .map_err(|e| BuildError::SessionOpen(format!("upgrade {path}: {e}")))?;
3651        progress_upgrade.finish();
3652        return Ok(Session::new(Arc::new(storage), None));
3653    }
3654    let Some(meta) = resolve_restore_target(selection, cwd).await? else {
3655        return match selection {
3656            // Exact id match only (pi `--session-id`): a missing session is
3657            // created fresh under the selected dir instead of an error.
3658            SessionSelection::ByExactId { id, dir } => {
3659                std::fs::create_dir_all(dir)
3660                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3661                create_jsonl_session_with_id(dir, cwd, Some(id.clone()))
3662                    .await
3663                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))
3664            }
3665            SessionSelection::Latest { dir } => Err(BuildError::SessionNotFound {
3666                requested: "the most recent session".to_string(),
3667                dir: dir.display().to_string(),
3668            }),
3669            SessionSelection::ById { id, dir } => Err(BuildError::SessionNotFound {
3670                requested: format!("session {id}"),
3671                dir: dir.display().to_string(),
3672            }),
3673            _ => unreachable!("resolve_restore_target only returns None for restore selections"),
3674        };
3675    };
3676    let sessions_root = selection_dir(selection);
3677    open_session(&meta, cwd, &sessions_root)
3678        .await
3679        .map(|restored| restored.session)
3680}
3681
3682/// The sessions root a selection was resolved against.
3683fn selection_dir(selection: &SessionSelection) -> PathBuf {
3684    match selection {
3685        SessionSelection::Ephemeral => PathBuf::new(),
3686        SessionSelection::New { dir, .. }
3687        | SessionSelection::Latest { dir }
3688        | SessionSelection::ById { dir, .. }
3689        | SessionSelection::ByExactId { dir, .. }
3690        | SessionSelection::Fork { dir, .. } => dir.clone(),
3691    }
3692}
3693
3694/// Resolve the metadata a restore selection names, without opening the file.
3695///
3696/// Used by [`peek_restored_session_cwd`] and [`restore_session`]. No session
3697/// lock is claimed and nothing is created.
3698async fn resolve_restore_target(
3699    selection: &SessionSelection,
3700    cwd: &str,
3701) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3702    match selection {
3703        SessionSelection::Latest { dir } => {
3704            let metas = list_session_metadata_in_dir(cwd, dir).await?;
3705            Ok(first_resumable_session(&metas).cloned())
3706        }
3707        SessionSelection::ById { id, dir } => find_session_metadata(id, cwd, dir).await,
3708        SessionSelection::ByExactId { id, dir } => {
3709            let metas =
3710                list_session_metadata_with_id_check(cwd, dir, SessionScope::All, Some(id)).await?;
3711            unique_session_match(metas.iter().filter(|meta| meta.id == *id), id)
3712        }
3713        SessionSelection::Fork { .. }
3714        | SessionSelection::New { .. }
3715        | SessionSelection::Ephemeral => Ok(None),
3716    }
3717}
3718
3719/// Resolve a path in the configured session directory or a saved-session selector.
3720async fn find_session_metadata(
3721    selector: &str,
3722    cwd: &str,
3723    dir: &Path,
3724) -> Result<Option<JsonlSessionMetadata>, BuildError> {
3725    if is_session_path(selector) {
3726        let path = Path::new(cwd).join(selector);
3727        let root = std::fs::canonicalize(Path::new(cwd).join(dir)).ok();
3728        let is_under_root = root.is_some_and(|root| {
3729            // Normal sessions live one project directory down. The TUI All
3730            // picker also lists older files stored directly in the root.
3731            path.ancestors()
3732                .skip(1)
3733                .take(2)
3734                .any(|ancestor| std::fs::canonicalize(ancestor).is_ok_and(|parent| parent == root))
3735        });
3736        return Ok(path
3737            .file_name()
3738            .and_then(|name| name.to_str())
3739            .and_then(|name| {
3740                if is_under_root && name.ends_with(".jsonl") && !name.ends_with(".progress.jsonl") {
3741                    session_metadata_at(&path)
3742                } else {
3743                    None
3744                }
3745            }));
3746    }
3747    if selector.is_empty() {
3748        return Ok(None);
3749    }
3750    let metas =
3751        list_session_metadata_with_id_check(cwd, dir, SessionScope::All, Some(selector)).await?;
3752    if let Some(exact_id) =
3753        unique_session_match(metas.iter().filter(|m| m.id == selector), selector)?
3754    {
3755        return Ok(Some(exact_id));
3756    }
3757
3758    let exact_name = unique_session_match(
3759        metas.iter().filter(|m| {
3760            let path = Path::new(&m.path);
3761            path.file_name().and_then(|name| name.to_str()) == Some(selector)
3762                || path.file_stem().and_then(|stem| stem.to_str()) == Some(selector)
3763        }),
3764        selector,
3765    )?;
3766    if exact_name.is_some() || selector.ends_with(".jsonl") {
3767        return Ok(exact_name);
3768    }
3769
3770    unique_session_match(
3771        metas.iter().filter(|m| {
3772            m.id.starts_with(selector)
3773                || Path::new(&m.path)
3774                    .file_stem()
3775                    .and_then(|name| name.to_str())
3776                    .is_some_and(|name| name.contains(selector))
3777        }),
3778        selector,
3779    )
3780}
3781
3782fn is_session_path(selector: &str) -> bool {
3783    selector.contains(std::path::is_separator)
3784        || matches!(
3785            Path::new(selector).components().next(),
3786            Some(
3787                std::path::Component::Prefix(_)
3788                    | std::path::Component::CurDir
3789                    | std::path::Component::ParentDir
3790            )
3791        )
3792}
3793
3794fn unique_session_match<'a>(
3795    mut matches: impl Iterator<Item = &'a JsonlSessionMetadata>,
3796    selector: &str,
3797) -> Result<Option<JsonlSessionMetadata>, BuildError> {
3798    let first = matches.next();
3799    if matches.next().is_some() {
3800        return Err(BuildError::SessionOpen(format!(
3801            "multiple saved sessions match {selector:?}. Use an exact session file path."
3802        )));
3803    }
3804    Ok(first.cloned())
3805}
3806
3807async fn resolve_fork_source(
3808    source: &str,
3809    cwd: &str,
3810    dir: &Path,
3811) -> Result<JsonlSessionMetadata, BuildError> {
3812    // A fork can read an explicit session file outside the saved-session root.
3813    let file = session_metadata_at(&Path::new(cwd).join(source));
3814    let matched = if file.is_some() || is_session_path(source) {
3815        file
3816    } else {
3817        find_session_metadata(source, cwd, dir).await?
3818    };
3819    matched.ok_or_else(|| BuildError::SessionNotFound {
3820        requested: format!("--fork {source}"),
3821        dir: dir.display().to_string(),
3822    })
3823}
3824
3825/// What a launch that would restore a session says about the working directory.
3826pub(crate) struct RestoredSessionCwd {
3827    id: String,
3828    path: PathBuf,
3829    /// The directory recorded in the session header.
3830    pub recorded: PathBuf,
3831    /// `Some` when the recorded directory still exists and the run adopts it;
3832    /// `None` when the caller must fall back to the launch cwd and say so.
3833    pub adopted: Option<PathBuf>,
3834}
3835
3836impl RestoredSessionCwd {
3837    /// Verify the file whose cwd was used before trust and resource discovery.
3838    fn metadata_for_restore(
3839        &self,
3840    ) -> Result<rpi_harness::session::jsonl::JsonlSessionMetadata, BuildError> {
3841        let metadata = session_metadata_at(&self.path).ok_or_else(|| self.changed())?;
3842        self.verify_metadata(&metadata)?;
3843        Ok(metadata)
3844    }
3845
3846    fn verify_metadata(
3847        &self,
3848        metadata: &rpi_harness::session::jsonl::JsonlSessionMetadata,
3849    ) -> Result<(), BuildError> {
3850        if metadata.id != self.id
3851            || Path::new(&metadata.path) != self.path
3852            || Path::new(&metadata.cwd) != self.recorded
3853        {
3854            return Err(self.changed());
3855        }
3856        Ok(())
3857    }
3858
3859    fn changed(&self) -> BuildError {
3860        BuildError::SessionOpen(format!(
3861            "session changed or disappeared during startup: {}",
3862            self.path.display(),
3863        ))
3864    }
3865}
3866
3867/// The working directory the launch's restored session was created in, resolved
3868/// WITHOUT opening, locking, or creating anything.
3869///
3870/// Read-only by design: this runs before trust resolution and extension
3871/// preparation, where a failure must not take the run down — the real open
3872/// happens later and surfaces its own errors. Returns `None` when the selection
3873/// is not a restore (fresh/ephemeral/fork) or cannot be resolved.
3874pub(crate) async fn peek_restored_session_cwd(
3875    selection: &SessionSelection,
3876    launch_cwd: &Path,
3877) -> Option<RestoredSessionCwd> {
3878    let cwd_str = launch_cwd.to_string_lossy().into_owned();
3879    let meta = resolve_restore_target(selection, &cwd_str).await.ok()??;
3880    let recorded = PathBuf::from(&meta.cwd);
3881    if recorded.as_os_str().is_empty() {
3882        return None;
3883    }
3884    Some(RestoredSessionCwd {
3885        path: std::fs::canonicalize(meta.path).ok()?,
3886        id: meta.id,
3887        adopted: crate::session_cwd::resolve_session_cwd(&recorded),
3888        recorded,
3889    })
3890}
3891
3892/// `--fork <path|id>`: open the source session, fork it into a new JSONL
3893/// session (records the parent id), and start in the fork.
3894async fn fork_session_at_launch(
3895    source: &str,
3896    dir: &Path,
3897    cwd: &str,
3898    selected: Option<&crate::resource_selection::ResolvedSelection>,
3899    entry_id: Option<&str>,
3900    position: Option<rpi_harness::session::types::ForkPosition>,
3901    resolved_session: Option<&JsonlSessionMetadata>,
3902) -> Result<Session, BuildError> {
3903    use rpi_harness::session::jsonl::{
3904        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
3905    };
3906    use rpi_harness::session::types::SessionStorage;
3907    use rpi_tools::FileSystem;
3908
3909    let source_meta = match resolved_session {
3910        Some(meta) => meta.clone(),
3911        None => resolve_fork_source(source, cwd, dir).await?,
3912    };
3913    std::fs::create_dir_all(&dir)
3914        .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3915    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3916    let fs: Arc<dyn FileSystem> = env.clone();
3917    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3918        fs: fs.clone(),
3919        sessions_root: dir.to_string_lossy().into_owned(),
3920        clock: Arc::new(SystemClock),
3921        ids: Arc::new(DefaultIdGenerator::new()),
3922    });
3923    let fork_storage = repo
3924        .fork_typed_with_value_initializer(
3925            &source_meta,
3926            &JsonlSessionCreateOptions {
3927                id: None,
3928                parent_session_id: Some(source_meta.id.clone()),
3929                cwd: cwd.to_string(),
3930                metadata: None,
3931            },
3932            &ForkOptions::Branch {
3933                entry_id: entry_id.map(str::to_owned),
3934                position,
3935            },
3936            |values| crate::resource_selection::fork_initial_values_for_selection(values, selected),
3937        )
3938        .await
3939        .map_err(|e| BuildError::SessionDir(format!("fork {}: {e}", source_meta.path)))?;
3940    fork_storage
3941        .acquire_writer_lease()
3942        .await
3943        .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
3944    let storage_arc: Arc<dyn SessionStorage> = Arc::new(fork_storage);
3945    Ok(Session::new(storage_arc, None))
3946}
3947
3948/// The metadata of the JSONL session file at `path`, or `None` when `path` is
3949/// not a readable session file.
3950pub(crate) fn session_metadata_at(path: &Path) -> Option<JsonlSessionMetadata> {
3951    use rpi_harness::session::jsonl::codec::{metadata_from_header, parse_header};
3952    use std::io::BufRead;
3953
3954    let path = std::fs::canonicalize(path).ok()?;
3955    let metadata = std::fs::metadata(&path).ok()?;
3956    if !metadata.is_file() {
3957        return None;
3958    }
3959    let modified_at = metadata
3960        .modified()
3961        .ok()?
3962        .duration_since(std::time::UNIX_EPOCH)
3963        .map_or(0, |duration| duration.as_millis() as i64);
3964    let mut first_line = String::new();
3965    std::io::BufReader::new(std::fs::File::open(&path).ok()?)
3966        .read_line(&mut first_line)
3967        .ok()?;
3968    let header = parse_header(first_line.trim_end()).ok()?;
3969    Some(metadata_from_header(
3970        &header,
3971        &path.to_string_lossy(),
3972        modified_at,
3973    ))
3974}
3975
3976/// Errors from [`open_session_by_id`], split so the CLI can map them to
3977/// [`BuildError`] while the TUI can surface a friendlier note.
3978pub enum OpenError {
3979    /// No session matched the request.
3980    NotFound { requested: String },
3981    /// The match existed but could not be opened/parsed.
3982    Other(String),
3983}
3984
3985impl From<BuildError> for OpenError {
3986    fn from(error: BuildError) -> Self {
3987        match error {
3988            BuildError::SessionOpen(reason) => Self::Other(reason),
3989            other => Self::Other(other.to_string()),
3990        }
3991    }
3992}
3993
3994impl std::fmt::Display for OpenError {
3995    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3996        match self {
3997            OpenError::NotFound { requested } => write!(f, "no session matches {requested}"),
3998            // `Other` carries the bare reason (see `open_session_by_id`); the
3999            // prefix lives here so the TUI and the CLI's
4000            // `BuildError::SessionOpen` wrapper each render it exactly once
4001            // (wrapping the already-prefixed `BuildError` string doubled it).
4002            OpenError::Other(msg) => write!(f, "Could not open the saved session: {msg}"),
4003        }
4004    }
4005}
4006
4007/// Which sessions a picker lists. The default is [`Self::Project`]: with a
4008/// shared `sessionDir`, a flat list over every cwd directory buries the current
4009/// project's history (fork issue DavidHinton-xcpc/pi-rust#13). `All` is an
4010/// explicit opt-in and rows carry their project so the list stays traceable.
4011#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4012pub enum SessionScope {
4013    #[default]
4014    Project,
4015    All,
4016}
4017
4018impl SessionScope {
4019    pub fn toggled(self) -> Self {
4020        match self {
4021            Self::Project => Self::All,
4022            Self::All => Self::Project,
4023        }
4024    }
4025
4026    pub fn label(self) -> &'static str {
4027        match self {
4028            Self::Project => "this project",
4029            Self::All => "all projects",
4030        }
4031    }
4032}
4033
4034/// List the JSONL session metadata under the default session dir, newest
4035/// first. Shared by startup restore and the TUI `/session` hot-switch.
4036///
4037/// `list_session_metadata` intentionally stays unscoped: it resolves sessions
4038/// to *open* (including `--continue`/`-c`), where filtering by cwd would make
4039/// a session that the caller named by id unopenable. Only pickers apply a scope.
4040pub async fn list_session_metadata(
4041    cwd: &str,
4042) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
4043    let dir = default_session_dir(Path::new(cwd));
4044    list_session_metadata_in_dir(cwd, &dir).await
4045}
4046
4047pub(crate) async fn list_session_metadata_in_dir(
4048    cwd: &str,
4049    dir: &Path,
4050) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
4051    list_session_metadata_in_scope_in_dir(cwd, dir, SessionScope::All).await
4052}
4053
4054/// Scope-aware metadata listing for pickers. `Project` passes the cwd to the
4055/// repo's typed list API, so the enumeration and the open path agree on which
4056/// directory belongs to this project.
4057pub(crate) async fn list_session_metadata_in_scope_in_dir(
4058    cwd: &str,
4059    dir: &Path,
4060    scope: SessionScope,
4061) -> Result<Vec<JsonlSessionMetadata>, BuildError> {
4062    list_session_metadata_with_id_check(cwd, dir, scope, None).await
4063}
4064
4065async fn list_session_metadata_with_id_check(
4066    cwd: &str,
4067    dir: &Path,
4068    scope: SessionScope,
4069    requested_id: Option<&str>,
4070) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
4071    use rpi_harness::session::jsonl::{
4072        JsonlSessionListOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
4073    };
4074    use rpi_tools::FileSystem;
4075
4076    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4077    let fs: Arc<dyn FileSystem> = env.clone();
4078    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4079        fs: fs.clone(),
4080        sessions_root: dir.to_string_lossy().into_owned(),
4081        clock: Arc::new(SystemClock),
4082        ids: Arc::new(DefaultIdGenerator::new()),
4083    });
4084    let options = JsonlSessionListOptions {
4085        cwd: match scope {
4086            SessionScope::Project => Some(cwd.to_string()),
4087            SessionScope::All => None,
4088        },
4089    };
4090    let metadata_lookup = StartupSpan::start(Phase::MetadataLookup);
4091    let result = match requested_id {
4092        Some(id) => repo.list_typed_for_id(&options, id).await,
4093        None => repo.list_typed(&options).await,
4094    }
4095    .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")));
4096    if result.is_ok() {
4097        metadata_lookup.finish();
4098    }
4099    result
4100}
4101
4102/// A cheap, display-oriented summary of one JSONL session file.
4103///
4104/// The session pickers (`-r` and `/session`) need enough context to tell saved
4105/// sessions apart. The header-only [`JsonlSessionMetadata`] carries no name and
4106/// no transcript, so a list built from it renders as a wall of identical
4107/// `2026-09-25T15-05-15-847Z_…` file names — including the many header-only
4108/// sessions an abandoned launch leaves behind. This reads just the head (and a
4109/// small tail, for a late `--name`/`/name` fact) of the file to recover:
4110///
4111/// - the session display name, when one was recorded;
4112/// - the first user prompt, single-lined and truncated, for a readable label;
4113/// - whether the file is header-only (nothing to resume).
4114///
4115/// It intentionally does **not** parse the whole log: sessions can be tens of
4116/// megabytes, and the picker runs over every session at startup.
4117#[derive(Debug, Clone, Default, PartialEq, Eq)]
4118pub struct SessionSummary {
4119    /// The session display name (`--name` / `/name`), if one was recorded.
4120    pub name: Option<String>,
4121    /// The first user prompt, single-lined and trimmed to a label-sized length.
4122    pub preview: Option<String>,
4123    /// True when the file holds only its header (a session with no content).
4124    pub empty: bool,
4125    /// On-disk size in bytes (a rough content-volume hint for the picker).
4126    pub bytes: u64,
4127}
4128
4129/// Bytes read from the head of a session file to recover a name + first prompt.
4130const SUMMARY_HEAD_BYTES: u64 = 256 * 1024;
4131/// Bytes read from the tail of a session file to recover a late name fact.
4132const SUMMARY_TAIL_BYTES: u64 = 8 * 1024;
4133/// Longest preview retained (characters, not bytes).
4134const SUMMARY_PREVIEW_CHARS: usize = 80;
4135
4136/// Summarize one session file for the pickers. Best-effort: an unreadable or
4137/// malformed file yields a summary with `empty: false` and no label, so it is
4138/// still selectable rather than silently dropped.
4139pub fn summarize_session_file(path: &Path) -> SessionSummary {
4140    use std::io::{Read, Seek, SeekFrom};
4141
4142    let Ok(mut file) = std::fs::File::open(path) else {
4143        return SessionSummary::default();
4144    };
4145    let Ok(size) = file.metadata().map(|m| m.len()) else {
4146        return SessionSummary::default();
4147    };
4148    if size == 0 {
4149        return SessionSummary {
4150            name: None,
4151            preview: None,
4152            empty: true,
4153            bytes: 0,
4154        };
4155    }
4156
4157    // Head: the header line (for the empty check) + a name fact + the first user
4158    // prompt. The whole window is scanned; it is already in memory.
4159    let mut head = vec![0u8; SUMMARY_HEAD_BYTES.min(size) as usize];
4160    let head_len = file.read(&mut head).unwrap_or(0);
4161    head.truncate(head_len);
4162    let head = String::from_utf8_lossy(&head);
4163    let mut lines: Vec<&str> = head.lines().collect();
4164    let header_len = lines.first().map(|line| line.len()).unwrap_or(0);
4165    // A header-only file is exactly the header plus an optional trailing `\n`.
4166    let empty = (size as usize) <= header_len + 1;
4167    // When the window stopped short of the file end, its final line is partial:
4168    // drop it so a half-read message can never be mistaken for a complete one.
4169    if (head_len as u64) < size && !lines.is_empty() {
4170        lines.pop();
4171    }
4172
4173    let mut summary = SessionSummary {
4174        name: None,
4175        preview: None,
4176        empty,
4177        bytes: size,
4178    };
4179    for line in lines {
4180        apply_summary_line(line, &mut summary);
4181    }
4182
4183    // Tail: a name set late in the session lives after the head window. Read the
4184    // last window and scan only complete lines so a torn/partial first line is
4185    // ignored. Only do this when the file is larger than the head window.
4186    if size > SUMMARY_HEAD_BYTES
4187        && file
4188            .seek(SeekFrom::End(-(SUMMARY_TAIL_BYTES as i64)))
4189            .is_ok()
4190    {
4191        let mut tail = Vec::new();
4192        if file.read_to_end(&mut tail).is_ok() {
4193            let tail = String::from_utf8_lossy(&tail);
4194            let mut tail_lines = tail.lines();
4195            // Drop the possibly-partial first line of the window.
4196            tail_lines.next();
4197            for line in tail_lines {
4198                if let Some(name) = name_from_line(line) {
4199                    summary.name = name;
4200                }
4201            }
4202        }
4203    }
4204    summary
4205}
4206
4207/// Extract the name from a `{"kind":"fact","fact":"name","name":…}` line.
4208/// Returns `Some(None)` for an explicit `name: null` (the fact was cleared).
4209fn name_from_line(line: &str) -> Option<Option<String>> {
4210    let value: serde_json::Value = serde_json::from_str(line).ok()?;
4211    if value.get("kind").and_then(|v| v.as_str()) != Some("fact") {
4212        return None;
4213    }
4214    if value.get("fact").and_then(|v| v.as_str()) != Some("name") {
4215        return None;
4216    }
4217    Some(match value.get("name") {
4218        Some(serde_json::Value::String(name)) => Some(name.clone()),
4219        _ => None,
4220    })
4221}
4222
4223/// Fold one JSONL line into `summary`: record a name fact, or capture the first
4224/// user prompt as the preview.
4225fn apply_summary_line(line: &str, summary: &mut SessionSummary) {
4226    if let Some(name) = name_from_line(line) {
4227        summary.name = name;
4228        return;
4229    }
4230    if summary.preview.is_some() {
4231        return;
4232    }
4233    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
4234        return;
4235    };
4236    if value.get("kind").and_then(|v| v.as_str()) != Some("entry") {
4237        return;
4238    }
4239    if value.get("type").and_then(|v| v.as_str()) != Some("message") {
4240        return;
4241    }
4242    let Some(message) = value.get("message") else {
4243        return;
4244    };
4245    if message.get("role").and_then(|v| v.as_str()) != Some("user") {
4246        return;
4247    }
4248    let text = match message.get("content") {
4249        Some(serde_json::Value::String(text)) => Some(text.as_str()),
4250        Some(serde_json::Value::Array(blocks)) => blocks.iter().find_map(|block| {
4251            (block.get("type").and_then(|v| v.as_str()) == Some("text"))
4252                .then(|| block.get("text").and_then(|v| v.as_str()))
4253                .flatten()
4254        }),
4255        _ => None,
4256    };
4257    let Some(text) = text else { return };
4258    let collapsed = text
4259        .lines()
4260        .map(str::trim)
4261        .filter(|line| !line.is_empty())
4262        .collect::<Vec<_>>()
4263        .join(" ");
4264    if collapsed.is_empty() {
4265        return;
4266    }
4267    summary.preview = Some(collapsed.chars().take(SUMMARY_PREVIEW_CHARS).collect());
4268}
4269
4270/// The human label for a session row: its recorded name, else the first user
4271/// prompt, else a marker that says the file has no transcript to show. Shared
4272/// by the startup picker and the in-TUI `/session` selector.
4273pub fn session_display_label(summary: &SessionSummary) -> String {
4274    if let Some(name) = summary.name.as_deref().map(str::trim) {
4275        if !name.is_empty() {
4276            return name.to_string();
4277        }
4278    }
4279    match summary.preview.as_deref().map(str::trim) {
4280        Some(preview) if !preview.is_empty() => preview.to_string(),
4281        _ => "(no messages)".to_string(),
4282    }
4283}
4284
4285/// Compact byte count (1.2MB / 34KB / 512B), shared by the startup picker and
4286/// the in-TUI `/session` selector.
4287pub fn format_session_bytes(bytes: u64) -> String {
4288    if bytes >= 1_048_576 {
4289        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
4290    } else if bytes >= 1024 {
4291        format!("{}KB", bytes / 1024)
4292    } else {
4293        format!("{bytes}B")
4294    }
4295}
4296
4297/// The first 8 characters of a session id, enough to disambiguate two rows that
4298/// share a timestamp without shouting the whole UUID.
4299pub fn short_session_id(id: &str) -> &str {
4300    id.char_indices().nth(8).map_or(id, |(end, _)| &id[..end])
4301}
4302
4303/// One listed session file. `project` is the cwd-encoded directory name when
4304/// the row comes from a project subdirectory; `None` for legacy files that sit
4305/// directly under the sessions root. The All view renders it so a flat list is
4306/// still attributable to a project.
4307#[derive(Debug, Clone, PartialEq, Eq)]
4308pub struct SessionFileEntry {
4309    pub path: PathBuf,
4310    pub project: Option<String>,
4311}
4312
4313/// Synchronously list every JSONL session file under `dir`, newest-first by
4314/// modification time. Kept for callers that explicitly want the full set (e.g.
4315/// resolving a session by id); pickers use [`list_session_files_in_scope_sync`].
4316///
4317/// The repo's [`list_session_metadata`] is async and scans one cwd-encoded
4318/// subdirectory level; the in-TUI `/session` selector runs on the blocking key
4319/// thread and cannot await it, so this walks the same layout directly. Both
4320/// `.jsonl` files directly under `dir` and one level of subdirectories are
4321/// accepted.
4322pub fn list_session_files_sync(dir: &Path) -> Vec<PathBuf> {
4323    list_entries_sync(dir, None)
4324        .into_iter()
4325        .map(|entry| entry.path)
4326        .collect()
4327}
4328
4329/// Scope-aware synchronous listing for the `/session` selector.
4330///
4331/// `Project` resolves the current project's directory with the *same* encoding
4332/// the repo uses for create/open (`jsonl_session_directory_name`), rather than
4333/// re-deriving it: the old flat walk and the open path disagreed about which
4334/// files belong to this project (fork issue #13). `All` keeps the old layout but
4335/// tags each row with its project directory.
4336pub fn list_session_files_in_scope_sync(
4337    cwd: &Path,
4338    dir: &Path,
4339    scope: SessionScope,
4340) -> Vec<SessionFileEntry> {
4341    let project_dir = match scope {
4342        SessionScope::Project => {
4343            let resolved = normalize_cwd(cwd);
4344            Some(rpi_harness::session::jsonl::jsonl_session_directory_name(
4345                &resolved.to_string_lossy(),
4346            ))
4347        }
4348        SessionScope::All => None,
4349    };
4350    match project_dir {
4351        Some(name) => list_entries_sync(&dir.join(&name), None),
4352        None => list_entries_sync(dir, Some(true)),
4353    }
4354}
4355
4356/// Mirror the repo's `absolute_path` normalization for a cwd path: the picker
4357/// runs on the blocking key thread and cannot await the `FileSystem` trait, so
4358/// this is the synchronous equivalent of `OsExecutionEnv::absolute_path`.
4359fn normalize_cwd(cwd: &Path) -> PathBuf {
4360    let absolute = if cwd.is_absolute() {
4361        cwd.to_path_buf()
4362    } else {
4363        std::env::current_dir()
4364            .unwrap_or_else(|_| PathBuf::from("."))
4365            .join(cwd)
4366    };
4367    // Lexical normalization only (`.` / `..` components), no symlink or FS
4368    // access — the repo's normalize_absolute is likewise purely lexical.
4369    let mut out = PathBuf::new();
4370    for component in absolute.components() {
4371        match component {
4372            std::path::Component::CurDir => {}
4373            std::path::Component::ParentDir => {
4374                out.pop();
4375            }
4376            other => out.push(other.as_os_str()),
4377        }
4378    }
4379    out
4380}
4381
4382fn list_entries_sync(dir: &Path, tag_projects: Option<bool>) -> Vec<SessionFileEntry> {
4383    let tag_projects = tag_projects.unwrap_or(false);
4384    let mut files: Vec<(SessionFileEntry, std::time::SystemTime)> = Vec::new();
4385    let mut visit = |path: PathBuf, project: Option<String>| {
4386        if path.extension().and_then(|e| e.to_str()) != Some("jsonl")
4387            || path.to_string_lossy().ends_with(".progress.jsonl")
4388        {
4389            return;
4390        }
4391        let modified = std::fs::metadata(&path)
4392            .and_then(|m| m.modified())
4393            .unwrap_or(std::time::UNIX_EPOCH);
4394        files.push((SessionFileEntry { path, project }, modified));
4395    };
4396    if let Ok(entries) = std::fs::read_dir(dir) {
4397        for entry in entries.flatten() {
4398            let path = entry.path();
4399            if path.is_dir() {
4400                let project = if tag_projects {
4401                    path.file_name()
4402                        .and_then(|name| name.to_str())
4403                        .map(str::to_owned)
4404                } else {
4405                    None
4406                };
4407                if let Ok(inner) = std::fs::read_dir(&path) {
4408                    for child in inner.flatten() {
4409                        visit(child.path(), project.clone());
4410                    }
4411                }
4412            } else {
4413                visit(path, None);
4414            }
4415        }
4416    }
4417    files.sort_by_key(|entry| std::cmp::Reverse(entry.1));
4418    files.into_iter().map(|(entry, _)| entry).collect()
4419}
4420
4421/// Pick the session `--continue`/`-c` should open: the newest session that has
4422/// content (a header-only session resumes to an empty transcript). Falls back to
4423/// the newest overall when every session is empty, and `None` only when the
4424/// list is empty.
4425fn first_resumable_session(
4426    metas: &[rpi_harness::session::jsonl::JsonlSessionMetadata],
4427) -> Option<&rpi_harness::session::jsonl::JsonlSessionMetadata> {
4428    metas
4429        .iter()
4430        .find(|meta| !summarize_session_file(Path::new(&meta.path)).empty)
4431        .or_else(|| metas.first())
4432}
4433
4434/// Open a saved session using the same selector as `--session`.
4435pub async fn open_session_by_id(id: &str, cwd: &str) -> Result<Session, OpenError> {
4436    let dir = default_session_dir(Path::new(cwd));
4437    open_session_by_id_in_dir(id, cwd, &dir)
4438        .await
4439        .map(|restored| restored.session)
4440}
4441
4442pub(crate) async fn open_session_by_id_in_dir(
4443    id: &str,
4444    cwd: &str,
4445    dir: &Path,
4446) -> Result<RestoredSession, OpenError> {
4447    let meta = find_session_metadata(id, cwd, dir)
4448        .await
4449        .map_err(OpenError::from)?;
4450    let Some(meta) = meta else {
4451        return Err(OpenError::NotFound {
4452            requested: format!("session {id}"),
4453        });
4454    };
4455    open_session(&meta, cwd, dir).await.map_err(OpenError::from)
4456}
4457
4458pub(crate) fn apply_process_proxy(proxy: Option<&str>) {
4459    if let Some(proxy) = proxy {
4460        for key in ["HTTP_PROXY", "HTTPS_PROXY"] {
4461            if std::env::var_os(key).is_none() {
4462                std::env::set_var(key, proxy);
4463            }
4464        }
4465    }
4466}
4467
4468/// Publish the active session's id to plugins, on both channels that carry it.
4469///
4470/// Called on **every** activation of a session — the startup build AND every
4471/// in-process swap (`switch_to_session`, `fork_session`, and the plugin
4472/// `NewSession`/`Fork`/`SwitchSession` runtime actions all route through
4473/// [`set_active_session_with_identity`]). Two things must stay in step:
4474///
4475/// - `ToolCallContext` — read per plugin **tool** call, which is why a stale
4476///   value there made a plugin's `todo`-style state follow the wrong session.
4477/// - `RPI_SESSION_ID` — read per **turn** by the provider hooks, which is the
4478///   only channel an observer gets for a pure-chat run. Process-global, which is
4479///   exactly the scope of "the session this process is serving".
4480///
4481/// The write overwrites unconditionally, deliberately. An inherited value is not
4482/// an override: `rpi` spawning `rpi` would otherwise hand the child the parent's
4483/// session id, and the child — which is *serving its own* session — would report
4484/// it forever. (Children no longer inherit the variable at all; see
4485/// `rpi_tools::HOST_PRIVATE_ENV`. This overwrite is the second line of defence,
4486/// for any other way a value can arrive pre-set.)
4487///
4488/// An embedder that genuinely wants to pin the id can revert to the old
4489/// behaviour by setting the variable *after* this runs; there is no supported
4490/// way to pin it before, because a session that does not match its own id is
4491/// never what the caller wants.
4492fn publish_session_identity(tool_context: &rpi_extensions::ToolCallContext, id: &str) {
4493    std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, id);
4494    tool_context.set_session_id(id);
4495}
4496
4497/// Swap the session the harness serves, republishing the identity to plugins.
4498///
4499/// The single funnel for an in-process session change. Prefer this over calling
4500/// `AgentHarness::set_session` directly: the harness holds no reference to the
4501/// plugin channels, so a bare `set_session` would leave every plugin reporting
4502/// the session it had before the swap.
4503///
4504/// A shared Host publishes the session ID only through its tool context.
4505/// A dedicated CLI process also publishes it through the environment.
4506pub(crate) async fn set_active_session_with_identity(
4507    harness: &AgentHarness,
4508    session: Session,
4509    tool_context: Option<&rpi_extensions::ToolCallContext>,
4510    publish_process_identity: bool,
4511) -> Result<(), String> {
4512    let metadata = session.get_metadata().await.ok();
4513    harness
4514        .set_session(session)
4515        .await
4516        .map_err(|e| e.to_string())?;
4517    if let Some(metadata) = metadata {
4518        if publish_process_identity {
4519            std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, &metadata.id);
4520        }
4521        if let Some(context) = tool_context {
4522            context.set_session_id(metadata.id);
4523        }
4524    }
4525    Ok(())
4526}
4527
4528/// Fork the harness's current session into a new JSONL session (new id, parent
4529/// set to the source) and wrap it in a `Session`. Mirrors the TUI's
4530/// `fork_session` flow (`interactive_tui.rs`) — hoisted here so both the TUI
4531/// and the plugin `runtime_action(Fork)` host share one implementation.
4532/// Returns the new `Session` (NOT yet swapped onto the harness — the caller
4533/// does `harness.set_session(...)`).
4534pub(crate) async fn fork_session_storage(
4535    harness: &AgentHarness,
4536    cwd: &str,
4537    dir: &Path,
4538) -> Result<Session, String> {
4539    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
4540    use rpi_tools::FileSystem;
4541
4542    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4543    let fs: Arc<dyn FileSystem> = env.clone();
4544    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4545        fs,
4546        sessions_root: dir.to_string_lossy().into_owned(),
4547        clock: Arc::new(SystemClock),
4548        ids: Arc::new(DefaultIdGenerator::new()),
4549    });
4550    // The fork needs the rich JSONL metadata (with the on-disk path); resolve
4551    // it from the session list by the current session's id.
4552    let id = harness.session().storage().metadata().id.clone();
4553    let metas = list_session_metadata_in_dir(cwd, dir)
4554        .await
4555        .map_err(|e| e.to_string())?;
4556    let Some(source) = metas.iter().find(|m| m.id == id) else {
4557        return Err(format!("current session {id} not found on disk"));
4558    };
4559    let fork_storage = repo
4560        .fork_typed_with_value_initializer(
4561            source,
4562            &rpi_harness::session::jsonl::JsonlSessionCreateOptions {
4563                id: None,
4564                parent_session_id: Some(source.id.clone()),
4565                cwd: cwd.to_string(),
4566                metadata: None,
4567            },
4568            &rpi_harness::session::types::ForkOptions::default(),
4569            crate::resource_selection::fork_initial_values,
4570        )
4571        .await
4572        .map_err(|e| e.to_string())?;
4573    fork_storage
4574        .acquire_writer_lease()
4575        .await
4576        .map_err(|e| e.to_string())?;
4577    Ok(Session::new(Arc::new(fork_storage), None))
4578}
4579
4580/// Validate a private copy before publishing it in the repo's normal cwd
4581/// directory. Keep the imported identity/history and never overwrite a saved
4582/// session (including when the source is already inside this repository).
4583pub(crate) async fn import_session_file(
4584    source: &Path,
4585    cwd: &str,
4586    dir: &Path,
4587) -> Result<Session, String> {
4588    use rpi_harness::session::jsonl::{
4589        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions, JsonlSessionStorage,
4590    };
4591    use rpi_harness::session::types::SessionStorage;
4592    use rpi_tools::FileSystem;
4593
4594    let dir = if dir.is_absolute() {
4595        dir.to_path_buf()
4596    } else {
4597        Path::new(cwd).join(dir)
4598    };
4599    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
4600    // External writers must be closed. This process deliberately retains locks
4601    // for previously opened sessions, so its own copies additionally verify a
4602    // stable history around the sidecar snapshot (bind/entry before retirement).
4603    let source_progress = PathBuf::from(format!("{}.progress.jsonl", source.display()));
4604    let _source_lock = if source_progress.try_exists().map_err(|e| e.to_string())? {
4605        let lock = std::fs::OpenOptions::new()
4606            .create(true)
4607            .write(true)
4608            .open(format!("{}.lock", source.display()))
4609            .map_err(|e| format!("lock import source: {e}"))?;
4610        fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| {
4611            "close the source session before importing its recovery pair".to_owned()
4612        })?;
4613        Some(lock)
4614    } else {
4615        None
4616    };
4617    let staging = tempfile::tempdir_in(&dir).map_err(|e| e.to_string())?;
4618    let staged = staging.path().join("history.stage");
4619    let staged_progress = PathBuf::from(format!("{}.progress.jsonl", staged.display()));
4620    let mut attempts = 0;
4621    let has_progress = loop {
4622        std::fs::copy(source, &staged).map_err(|e| format!("copy import: {e}"))?;
4623        let copied_history = std::fs::read(&staged).map_err(|e| e.to_string())?;
4624        let has_progress = match std::fs::copy(&source_progress, &staged_progress) {
4625            Ok(_) => true,
4626            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
4627                let _ = std::fs::remove_file(&staged_progress);
4628                false
4629            }
4630            Err(error) => return Err(format!("copy progress import: {error}")),
4631        };
4632        if copied_history == std::fs::read(source).map_err(|e| e.to_string())? {
4633            break has_progress;
4634        }
4635        attempts += 1;
4636        if attempts >= 4 {
4637            return Err(
4638                "source history changed during import; retry when the session is idle".into(),
4639            );
4640        }
4641        tokio::task::yield_now().await;
4642    };
4643    let fs: Arc<dyn FileSystem> = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4644    let validated = JsonlSessionStorage::load(
4645        fs.clone(),
4646        &staged.to_string_lossy(),
4647        Arc::new(SystemClock),
4648        Arc::new(DefaultIdGenerator::new()),
4649    )
4650    .await
4651    .map_err(|e| format!("invalid session import: {e}"))?;
4652    validated
4653        .read_progress("")
4654        .await
4655        .map_err(|e| format!("invalid recovery import: {e}"))?;
4656    let mut metadata = validated.jsonl_metadata().clone();
4657    drop(validated);
4658    let text = std::fs::read_to_string(&staged).map_err(|e| e.to_string())?;
4659    let (first, rest) = text
4660        .split_once('\n')
4661        .ok_or_else(|| "import has no complete header".to_owned())?;
4662    let mut header =
4663        rpi_harness::session::jsonl::codec::parse_header(first).map_err(|e| e.to_string())?;
4664    if has_progress && header.progress_format.is_none() {
4665        return Err("history-only artifact has an undeclared recovery companion".into());
4666    }
4667    // An imported history-only artifact receives the destination's empty store.
4668    // Imports of live-format sessions retain their validated companion instead.
4669    header.progress_format = Some("assistant-progress-v1".into());
4670    std::fs::write(
4671        &staged,
4672        format!(
4673            "{}{}",
4674            rpi_harness::session::jsonl::codec::encode_header(&header),
4675            rest
4676        ),
4677    )
4678    .map_err(|e| e.to_string())?;
4679    if list_session_metadata_in_dir(cwd, &dir)
4680        .await
4681        .map_err(|e| e.to_string())?
4682        .iter()
4683        .any(|saved| saved.id == metadata.id)
4684    {
4685        return Err(format!(
4686            "session {} already exists in {}",
4687            metadata.id,
4688            dir.display()
4689        ));
4690    }
4691    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4692        fs,
4693        sessions_root: dir.to_string_lossy().into_owned(),
4694        clock: Arc::new(SystemClock),
4695        ids: Arc::new(DefaultIdGenerator::new()),
4696    });
4697    // Let the repository validate the id and choose its canonical destination.
4698    let destination = repo
4699        .create_typed(&JsonlSessionCreateOptions {
4700            id: Some(metadata.id.clone()),
4701            parent_session_id: metadata.parent_session_id.clone(),
4702            cwd: cwd.to_string(),
4703            metadata: metadata.metadata.clone(),
4704        })
4705        .await
4706        .map_err(|e| e.to_string())?;
4707    let path = destination.jsonl_metadata().path.clone();
4708    drop(destination);
4709    // Do not claim the session-level `.lock` here. The destination storage
4710    // opened below owns the same OS lease; claiming it first would make this
4711    // process conflict with itself. The JSONL storage lease is the
4712    // authoritative writer fence for the imported session.
4713    let destination_progress = format!("{path}.progress.jsonl");
4714    let publish = (|| -> std::io::Result<()> {
4715        if has_progress {
4716            std::fs::rename(&staged_progress, &destination_progress)?;
4717        }
4718        std::fs::rename(&staged, &path)
4719    })();
4720    if let Err(error) = publish {
4721        let _ = std::fs::remove_file(&path);
4722        let _ = std::fs::remove_file(&destination_progress);
4723        return Err(format!("publish import: {error}"));
4724    }
4725    metadata.path = path;
4726    let storage = repo
4727        .open_by_jsonl_metadata(&metadata)
4728        .await
4729        .map_err(|e| e.to_string())?;
4730    Ok(Session::new(Arc::new(storage), None))
4731}
4732
4733/// A restored session together with the working directory it was created in.
4734///
4735/// The recorded cwd is data for the host's notices, never a silent adoption:
4736/// the launch path adopts the directory in [`app`](crate::app) before any
4737/// resource loads (tools, extensions, system prompt, and trust all key off it),
4738/// and the `/session` hot-switch does not move the running tools at all. Either
4739/// way the user hears about the directory instead of the process quietly
4740/// working somewhere unexpected.
4741pub(crate) struct RestoredSession {
4742    pub session: Session,
4743    /// The directory recorded in the session header, when it still exists.
4744    /// `None` when the record is empty or the path is gone (or is a file).
4745    pub recorded_cwd: Option<PathBuf>,
4746}
4747
4748/// Wrap an opened [`JsonlSessionStorage`] in the `Session` facade (shared by
4749/// startup restore + TUI hot-switch).
4750///
4751/// `sessions_root` is passed in rather than re-derived from `cwd`: after a
4752/// restore adopts the session's directory, `default_session_dir(cwd)` would
4753/// name the ADOPTED project's tree, which is not where this session was found.
4754async fn open_session(
4755    meta: &rpi_harness::session::jsonl::JsonlSessionMetadata,
4756    cwd: &str,
4757    sessions_root: &Path,
4758) -> Result<RestoredSession, BuildError> {
4759    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
4760    use rpi_harness::session::types::SessionStorage;
4761    use rpi_tools::FileSystem;
4762
4763    let dir = sessions_root;
4764    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4765    let fs: Arc<dyn FileSystem> = env.clone();
4766    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4767        fs: fs.clone(),
4768        sessions_root: dir.to_string_lossy().into_owned(),
4769        clock: Arc::new(SystemClock),
4770        ids: Arc::new(DefaultIdGenerator::new()),
4771    });
4772    let storage = repo
4773        .open_by_jsonl_metadata(meta)
4774        .await
4775        .map_err(|e| BuildError::SessionOpen(format!("open {}: {e}", meta.path)))?;
4776    storage
4777        .acquire_writer_lease()
4778        .await
4779        .map_err(|e| BuildError::SessionOpen(format!("lock {}: {e}", meta.path)))?;
4780    // Native saved sessions predating progressFormat remain read-only to plain
4781    // storage loaders. Only this locked, not-yet-shared restore opts into writes.
4782    let storage = storage
4783        .enable_progress_under_exclusive_lock()
4784        .await
4785        .map_err(|e| BuildError::SessionOpen(format!("upgrade {}: {e}", meta.path)))?;
4786    let storage_arc: Arc<dyn SessionStorage> = Arc::new(storage);
4787    Ok(RestoredSession {
4788        session: Session::new(storage_arc, None),
4789        recorded_cwd: crate::session_cwd::resolve_session_cwd(Path::new(&meta.cwd)),
4790    })
4791}
4792
4793/// A fresh ephemeral in-memory session (no persistence). Used for `--no-session`
4794/// and for `/new` inside such a run — an ephemeral launch keeps swapping in
4795/// in-memory sessions, never a JSONL file.
4796pub(crate) fn ephemeral_session() -> Session {
4797    let storage = Arc::new(InMemorySessionStorage::new(
4798        SessionMetadata {
4799            id: "ephemeral".into(),
4800            created_at: 0,
4801            parent_session_id: None,
4802        },
4803        Arc::new(SystemClock),
4804        Arc::new(DefaultIdGenerator::new()),
4805    ));
4806    Session::new(storage, None).with_volatile_progress()
4807}
4808
4809/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
4810///
4811/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
4812/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
4813/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
4814/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
4815///
4816/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
4817/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
4818/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
4819pub(crate) async fn create_jsonl_session(dir: &Path, cwd: &str) -> Result<Session, String> {
4820    create_jsonl_session_with_id(dir, cwd, None).await
4821}
4822
4823/// `create_jsonl_session` with an explicit id (the `--session-id` fixed-id
4824/// contract: the file is named with the given id so later `--session-id`
4825/// launches restore the same session).
4826pub(crate) async fn create_jsonl_session_with_id(
4827    dir: &Path,
4828    cwd: &str,
4829    id: Option<String>,
4830) -> Result<Session, String> {
4831    use rpi_harness::session::jsonl::{
4832        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
4833    };
4834    use rpi_tools::FileSystem;
4835
4836    // A dedicated OS env for session-file I/O, rooted at the cwd so the repo's
4837    // relative-path resolution matches the tool env.
4838    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4839    let fs: Arc<dyn FileSystem> = env.clone();
4840
4841    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4842        fs: fs.clone(),
4843        sessions_root: dir.to_string_lossy().into_owned(),
4844        clock: Arc::new(SystemClock),
4845        ids: Arc::new(DefaultIdGenerator::new()),
4846    });
4847
4848    let opts = JsonlSessionCreateOptions {
4849        id, // fresh uuidv7 when None (--session-id passes the fixed id)
4850        parent_session_id: None,
4851        cwd: cwd.to_string(),
4852        metadata: None,
4853    };
4854    let storage = repo
4855        .create_typed(&opts)
4856        .await
4857        .map_err(|e| format!("create session: {e}"))?;
4858    // `JsonlSessionStorage` acquires the storage-level lease during create;
4859    // wrap it in the facade without a second CLI-owned lock table.
4860    let storage_arc: Arc<dyn rpi_harness::session::types::SessionStorage> = Arc::new(storage);
4861    Ok(Session::new(storage_arc, None))
4862}
4863
4864/// Read an `--append-system-prompt` target: if it's a readable file path, return
4865/// its contents; otherwise return `None` and let the caller use the literal.
4866fn read_append_target(target: &str, sources: &mut Vec<String>) -> Option<String> {
4867    let path = Path::new(target);
4868    if path.is_file() {
4869        read_prompt_source(path, sources)
4870    } else {
4871        None
4872    }
4873}
4874
4875/// Record provenance at the successful read, rather than rediscovering files
4876/// during rendering (which could report a shadowed or unreadable file).
4877fn read_prompt_source(path: &Path, sources: &mut Vec<String>) -> Option<String> {
4878    let text = std::fs::read_to_string(path).ok()?;
4879    let absolute = if path.is_absolute() {
4880        path.to_path_buf()
4881    } else {
4882        std::env::current_dir()
4883            .map(|cwd| cwd.join(path))
4884            .unwrap_or_else(|_| path.to_path_buf())
4885    };
4886    let source = absolute.to_string_lossy().into_owned();
4887    if !sources.contains(&source) {
4888        sources.push(source);
4889    }
4890    Some(text)
4891}
4892
4893#[cfg(test)]
4894mod goal_outbox_smoke_tests;
4895#[cfg(test)]
4896mod runtime_session_tests;
4897
4898#[cfg(test)]
4899mod tests {
4900    use super::*;
4901
4902    #[tokio::test]
4903    async fn shell_path_follows_each_explicit_home_at_startup_and_reload() {
4904        async fn assert_shell_path(harness: &AgentHarness, expected: &Path) {
4905            let bash = harness
4906                .get_tools()
4907                .await
4908                .unwrap()
4909                .into_iter()
4910                .find(|tool| tool.tool.schema().name == "bash")
4911                .unwrap();
4912            // A missing executable reports the exact configured path on every platform.
4913            let error = bash
4914                .tool
4915                .execute(
4916                    "shell-path-test",
4917                    serde_json::json!({"command": "true"}),
4918                    tokio_util::sync::CancellationToken::new(),
4919                    Arc::new(|_| {}),
4920                )
4921                .await
4922                .expect_err("the configured shell does not exist");
4923            let rpi_agent::AgentError::StructuredTool(result) = error else {
4924                panic!("unexpected bash error: {error}");
4925            };
4926            let expected = format!("Configured shellPath not found: {}", expected.display());
4927            assert!(
4928                result.content.iter().any(|item| matches!(
4929                    item, rpi_agent::TextContentOrImage::Text(text) if text.text.contains(&expected)
4930                )),
4931                "{:?}",
4932                result.content
4933            );
4934        }
4935
4936        async fn assert_manual_shell_path(context: &ReloadContext, shell: &Path) {
4937            let error = context
4938                .shell_execution_env()
4939                .exec("true", Default::default())
4940                .await
4941                .expect_err("the configured shell does not exist");
4942            assert!(
4943                error.to_string().contains(&shell.display().to_string()),
4944                "{error}"
4945            );
4946        }
4947
4948        fn write_shell_path(agent: &Path, shell: &Path) {
4949            std::fs::write(
4950                agent.join("settings.json"),
4951                serde_json::json!({"shellPath": shell}).to_string(),
4952            )
4953            .unwrap();
4954        }
4955
4956        let temp = tempfile::tempdir().unwrap();
4957        let cwd = temp.path();
4958        let args = Args {
4959            trust_override: Some(false),
4960            no_session: true,
4961            no_extensions: true,
4962            no_skills: true,
4963            no_prompt_templates: true,
4964            no_context_files: true,
4965            ..Args::default()
4966        };
4967        let mut sessions = Vec::new();
4968        for name in ["first-agent", "second-agent"] {
4969            let agent = cwd.join(name);
4970            std::fs::create_dir(&agent).unwrap();
4971            let home = crate::config::AgentHome::from_option(Some(agent.clone())).unwrap();
4972            let shell = agent.join("missing-bash.exe");
4973            write_shell_path(&agent, &shell);
4974            let resolved = crate::provider::resolve(
4975                &home,
4976                Some("anthropic"),
4977                Some(crate::provider::DEFAULT_MODEL_ID),
4978                None,
4979                Some("test-key"),
4980                None,
4981            )
4982            .unwrap();
4983            let (harness, _, context) = build(&home, &resolved, &args, cwd, false).await.unwrap();
4984            sessions.push((harness, context, shell));
4985        }
4986        for (harness, _, shell) in &sessions {
4987            assert_shell_path(harness, shell).await;
4988        }
4989
4990        let (harness, context, original_shell) = &sessions[0];
4991        let updated_shell = cwd.join("updated-bash.exe");
4992        write_shell_path(original_shell.parent().unwrap(), &updated_shell);
4993        assert_manual_shell_path(context, original_shell).await;
4994        let outcome = reload_extension_resources(harness, context).await;
4995        assert!(!outcome.had_errors, "{}", outcome.summary);
4996        assert_shell_path(harness, &updated_shell).await;
4997        assert_manual_shell_path(context, &updated_shell).await;
4998        let (other_harness, _, other_shell) = &sessions[1];
4999        assert_shell_path(other_harness, other_shell).await;
5000    }
5001
5002    #[test]
5003    fn settlement_bridge_follows_reload_and_releases_its_session_with_the_bus() {
5004        use rpi_harness::events::{HarnessEvent, HarnessEventBus, RunEndEvent, RunEndOutcome};
5005        use std::sync::atomic::{AtomicUsize, Ordering};
5006        static OLD: AtomicUsize = AtomicUsize::new(0);
5007        static NEW: AtomicUsize = AtomicUsize::new(0);
5008        extern "C" fn old(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
5009            OLD.fetch_add(1, Ordering::SeqCst);
5010            0
5011        }
5012        extern "C" fn new(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
5013            NEW.fetch_add(1, Ordering::SeqCst);
5014            0
5015        }
5016        let make = |handler: rpi_plugin_sdk::EventHandlerFn| {
5017            let mut registry = rpi_extensions::ExtensionRegistry::new();
5018            registry.register_event_handler(
5019                "settlement".into(),
5020                rpi_plugin_sdk::EventTag::AgentSettled,
5021                handler,
5022                std::ptr::null_mut(),
5023            );
5024            ExtensionSession::from_parts(
5025                Arc::new(registry.snapshot()),
5026                rpi_extensions::PluginKeepalive::empty(),
5027                vec![],
5028                None,
5029            )
5030        };
5031        let sessions = Arc::new(Mutex::new(make(old)));
5032        let weak = Arc::downgrade(&sessions);
5033        let bus = HarnessEventBus::new();
5034        install_extension_settlement_bridge(&bus, sessions.clone());
5035        let ended = |outcome| {
5036            HarnessEvent::RunEnd(RunEndEvent {
5037                lane: "main".into(),
5038                run_id: "run".into(),
5039                outcome,
5040                leaf_id: "leaf".into(),
5041            })
5042        };
5043        bus.emit(&ended(RunEndOutcome::Completed));
5044        assert_eq!(OLD.load(Ordering::SeqCst), 1);
5045        *sessions.lock().unwrap() = make(new);
5046        for outcome in [RunEndOutcome::Aborted, RunEndOutcome::Failed] {
5047            bus.emit(&ended(outcome));
5048        }
5049        assert_eq!(OLD.load(Ordering::SeqCst), 1);
5050        assert_eq!(NEW.load(Ordering::SeqCst), 2);
5051        drop(sessions);
5052        assert!(weak.upgrade().is_some());
5053        drop(bus);
5054        assert!(
5055            weak.upgrade().is_none(),
5056            "settlement observer must not create an ownership cycle"
5057        );
5058    }
5059
5060    #[tokio::test]
5061    async fn unauthenticated_packages_are_not_reintroduced_as_legacy_adapters() {
5062        extern "C" fn request(
5063            _: rpi_plugin_sdk::StbStringRef,
5064            _: *mut rpi_plugin_sdk::StbString,
5065            _: *mut std::ffi::c_void,
5066        ) -> i32 {
5067            1
5068        }
5069        let mut registry = rpi_extensions::ExtensionRegistry::new();
5070        for id in ["package", "legacy"] {
5071            registry.register_provider(rpi_extensions::RegisteredProvider {
5072                provider_id: id.into(),
5073                base_url: "http://localhost".into(),
5074                api_style: "openai-completions".into(),
5075                request_fn: request,
5076                stream_fn: None,
5077                plugin_free_string: rpi_plugin_sdk::callbacks::free_string,
5078                user_data: std::ptr::null_mut(),
5079            });
5080        }
5081        assert!(registry.apply_declaration_json(&serde_json::json!({"providers":[{
5082            "id":"package", "requiresAuth":true,
5083            "models":[rpi_ai::Model::new("model", "Model", rpi_ai::Api::OpenaiCompletions, "package", "http://localhost")]
5084        }]}).to_string()));
5085        let session = ExtensionSession::from_parts(
5086            Arc::new(registry.snapshot()),
5087            rpi_extensions::PluginKeepalive::empty(),
5088            vec![],
5089            None,
5090        );
5091        let providers = build_models_with_extensions_for_reload(
5092            &[],
5093            &session,
5094            tokio::runtime::Handle::current(),
5095        );
5096        assert_eq!(
5097            providers
5098                .iter()
5099                .map(|provider| provider.id())
5100                .collect::<Vec<_>>(),
5101            ["legacy"]
5102        );
5103    }
5104    use crate::args::Args;
5105
5106    #[test]
5107    fn loaded_context_paths_track_precedence_and_reload() {
5108        const CHILD: &str = "RPI_CONTEXT_PATHS_REGRESSION_CHILD";
5109        if std::env::var_os(CHILD).is_none() {
5110            let dir = tempfile::tempdir().unwrap();
5111            let output = std::process::Command::new(std::env::current_exe().unwrap())
5112                .args([
5113                    "--exact",
5114                    "session::tests::loaded_context_paths_track_precedence_and_reload",
5115                    "--nocapture",
5116                ])
5117                .env(CHILD, "1")
5118                .env(crate::config::CONFIG_DIR_ENV, dir.path())
5119                .output()
5120                .unwrap();
5121            assert!(
5122                output.status.success(),
5123                "{}\n{}",
5124                String::from_utf8_lossy(&output.stdout),
5125                String::from_utf8_lossy(&output.stderr)
5126            );
5127            return;
5128        }
5129        tokio::runtime::Builder::new_current_thread()
5130            .enable_all()
5131            .build()
5132            .unwrap()
5133            .block_on(async {
5134                let agent = crate::config::agent_dir().unwrap();
5135                let cwd = agent.join("project");
5136                let project_config = cwd.join(".rpi");
5137                std::fs::create_dir_all(&project_config).unwrap();
5138                for (path, content) in [
5139                    (agent.join("SYSTEM.md"), "GLOBAL_BASE"),
5140                    (agent.join("APPEND_SYSTEM.md"), "GLOBAL_APPEND"),
5141                    (agent.join("AGENTS.md"), "GLOBAL_INSTRUCTIONS"),
5142                    (project_config.join("SYSTEM.md"), "PROJECT_BASE"),
5143                    (project_config.join("APPEND_SYSTEM.md"), "PROJECT_APPEND"),
5144                    (cwd.join("AGENTS.md"), "PROJECT_INSTRUCTIONS"),
5145                    (cwd.join("CLAUDE.md"), "SHADOWED_CLAUDE"),
5146                ] {
5147                    std::fs::write(path, content).unwrap();
5148                }
5149                let resolved = crate::provider::resolve(
5150                    &crate::config::AgentHome::process(),
5151                    Some("anthropic"),
5152                    Some(crate::provider::DEFAULT_MODEL_ID),
5153                    None,
5154                    Some("test-key"),
5155                    None,
5156                )
5157                .unwrap();
5158                let args = Args {
5159                    no_session: true,
5160                    no_extensions: true,
5161                    no_skills: true,
5162                    no_prompt_templates: true,
5163                    trust_override: Some(true),
5164                    ..Default::default()
5165                };
5166                let (harness, _events, mut context) = build(
5167                    &crate::config::AgentHome::process(),
5168                    &resolved,
5169                    &args,
5170                    &cwd,
5171                    true,
5172                )
5173                .await
5174                .unwrap();
5175                let resources = harness.get_resources().await.unwrap();
5176                let path = |p: PathBuf| p.to_string_lossy().into_owned();
5177                assert_eq!(
5178                    &resources.context_files[..2],
5179                    &[
5180                        path(project_config.join("SYSTEM.md")),
5181                        path(project_config.join("APPEND_SYSTEM.md")),
5182                    ]
5183                );
5184                assert!(resources
5185                    .context_files
5186                    .contains(&path(agent.join("AGENTS.md"))));
5187                assert!(resources
5188                    .context_files
5189                    .contains(&path(cwd.join("AGENTS.md"))));
5190                assert!(!resources
5191                    .context_files
5192                    .contains(&path(cwd.join("CLAUDE.md"))));
5193                assert!(!resources
5194                    .context_files
5195                    .contains(&path(agent.join("SYSTEM.md"))));
5196                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
5197                assert!(prompt.contains("PROJECT_BASE") && prompt.contains("PROJECT_APPEND"));
5198                assert!(!prompt.contains("GLOBAL_BASE") && !prompt.contains("SHADOWED_CLAUDE"));
5199
5200                // Removing the selected project files makes reload fall back to
5201                // globals; removed instruction paths must disappear as well.
5202                std::fs::remove_file(project_config.join("SYSTEM.md")).unwrap();
5203                std::fs::remove_file(project_config.join("APPEND_SYSTEM.md")).unwrap();
5204                std::fs::remove_file(cwd.join("AGENTS.md")).unwrap();
5205                assert!(
5206                    !reload_extension_resources(&harness, &context)
5207                        .await
5208                        .had_errors
5209                );
5210                let resources = harness.get_resources().await.unwrap();
5211                assert_eq!(
5212                    &resources.context_files[..2],
5213                    &[
5214                        path(agent.join("SYSTEM.md")),
5215                        path(agent.join("APPEND_SYSTEM.md")),
5216                    ]
5217                );
5218                assert!(resources
5219                    .context_files
5220                    .contains(&path(cwd.join("CLAUDE.md"))));
5221                assert!(!resources
5222                    .context_files
5223                    .contains(&path(project_config.join("SYSTEM.md"))));
5224
5225                // Explicit append files are listed; literal text and overridden
5226                // discovered base/append files are not invented as file sources.
5227                let explicit = agent.join("custom-append.md");
5228                std::fs::write(&explicit, "EXPLICIT_APPEND").unwrap();
5229                context.args.system_prompt = Some("EXPLICIT_BASE".into());
5230                context.args.append_system_prompt =
5231                    vec![path(explicit.clone()), "literal append".into()];
5232                context.args.no_context_files = true;
5233                assert!(
5234                    !reload_extension_resources(&harness, &context)
5235                        .await
5236                        .had_errors
5237                );
5238                assert_eq!(
5239                    harness.get_resources().await.unwrap().context_files,
5240                    vec![path(explicit)]
5241                );
5242
5243                // The reload must honor the startup opt-out from project context.
5244                context.args.system_prompt = None;
5245                context.args.append_system_prompt.clear();
5246                context.args.no_context_files = false;
5247                context.args.trust_override = Some(false);
5248                assert!(
5249                    !reload_extension_resources(&harness, &context)
5250                        .await
5251                        .had_errors
5252                );
5253                assert!(harness
5254                    .get_resources()
5255                    .await
5256                    .unwrap()
5257                    .context_files
5258                    .is_empty());
5259                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
5260                assert!(
5261                    !prompt.contains("SHADOWED_CLAUDE") && !prompt.contains("GLOBAL_INSTRUCTIONS")
5262                );
5263            });
5264    }
5265
5266    #[test]
5267    fn prompt_source_read_failures_and_literals_do_not_create_file_provenance() {
5268        let dir = tempfile::tempdir().unwrap();
5269        let file = dir.path().join("SYSTEM.md");
5270        let mut sources = Vec::new();
5271        assert!(read_prompt_source(&file, &mut sources).is_none());
5272        std::fs::write(&file, [0xff, 0xfe]).unwrap();
5273        assert!(read_prompt_source(&file, &mut sources).is_none());
5274        assert!(read_append_target("literal instructions", &mut sources).is_none());
5275        assert!(sources.is_empty());
5276        std::fs::write(&file, "loaded instructions").unwrap();
5277        assert_eq!(
5278            read_prompt_source(&file, &mut sources).as_deref(),
5279            Some("loaded instructions")
5280        );
5281        assert!(read_prompt_source(&file, &mut sources).is_some());
5282        assert_eq!(sources, vec![file.to_string_lossy().into_owned()]);
5283    }
5284
5285    extern "C" fn deny_test_tool_call(
5286        _event: rpi_plugin_sdk::StablePluginEvent,
5287        _data: *mut std::ffi::c_void,
5288    ) -> i32 {
5289        rpi_plugin_sdk::EVENT_HANDLER_ABORT
5290    }
5291
5292    async fn invoke_test_tool_hook(
5293        hook: &rpi_agent::BeforeToolCall,
5294    ) -> Option<rpi_agent::BeforeToolCallResult> {
5295        let message = rpi_ai::providers::faux::faux_assistant_message(
5296            "approval",
5297            rpi_ai::types::StopReason::ToolUse,
5298        );
5299        let rpi_ai::types::Content::ToolCall(call) =
5300            rpi_ai::types::Content::tool_call("call", "read", serde_json::json!({"path":"x"}))
5301        else {
5302            unreachable!()
5303        };
5304        hook(
5305            rpi_agent::BeforeToolCallContext {
5306                assistant_message: &message,
5307                tool_call: &call,
5308                args: &call.arguments,
5309                context: &rpi_agent::AgentContext::default(),
5310            },
5311            tokio_util::sync::CancellationToken::new(),
5312        )
5313        .await
5314    }
5315
5316    #[tokio::test]
5317    async fn tool_call_hook_uses_reloaded_session_and_newly_discovered_gate() {
5318        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
5319        let hook =
5320            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
5321        assert!(invoke_test_tool_hook(&hook).await.is_none());
5322        for name in ["first-gate", "reloaded-gate"] {
5323            let mut registry = rpi_extensions::ExtensionRegistry::new();
5324            registry.register_event_handler(
5325                name.into(),
5326                rpi_plugin_sdk::EventTag::ToolCall,
5327                deny_test_tool_call,
5328                std::ptr::null_mut(),
5329            );
5330            let fresh = ExtensionSession::from_parts(
5331                Arc::new(registry.snapshot()),
5332                rpi_extensions::PluginKeepalive::empty(),
5333                Vec::new(),
5334                None,
5335            );
5336            {
5337                let mut current = sessions.lock().unwrap();
5338                if let Some(snapshot) = current.snapshot() {
5339                    snapshot.active_flag().store(false, Ordering::SeqCst);
5340                }
5341                *current = fresh;
5342            }
5343            let result = invoke_test_tool_hook(&hook).await.unwrap();
5344            assert!(result.block);
5345            assert!(result.reason.unwrap().contains(name));
5346        }
5347        *sessions.lock().unwrap() = ExtensionSession::none();
5348        assert!(invoke_test_tool_hook(&hook).await.is_none());
5349    }
5350
5351    /// Replaces every result with one text block that names what it saw:
5352    /// `isError`, `details.blocked` and the first text of the result.
5353    extern "C" fn label_test_tool_result(
5354        event: rpi_plugin_sdk::StbStringRef,
5355        out: *mut rpi_plugin_sdk::StbString,
5356        _: *mut std::ffi::c_void,
5357    ) -> i32 {
5358        // SAFETY: the host keeps the envelope and the output slot live for the call.
5359        let event: serde_json::Value = serde_json::from_str(unsafe { event.as_str() }).unwrap();
5360        let text = format!(
5361            "isError={} blocked={} text={}",
5362            event["isError"],
5363            event["details"]["blocked"],
5364            event["content"][0]["text"].as_str().unwrap_or_default()
5365        );
5366        let patch = serde_json::json!({"content": [{"type": "text", "text": text}]});
5367        unsafe { *out = rpi_plugin_sdk::StbString::from_string(patch.to_string()) };
5368        0
5369    }
5370
5371    extern "C" fn whitespace_then_reason_transform(
5372        event: rpi_plugin_sdk::StbStringRef,
5373        out: *mut rpi_plugin_sdk::StbString,
5374        _: *mut std::ffi::c_void,
5375    ) -> i32 {
5376        // SAFETY: the host keeps the envelope and output slot live for the call.
5377        let event: serde_json::Value = serde_json::from_str(unsafe { event.as_str() }).unwrap();
5378        let reason = format!("REASON: {}", event["content"][0]["text"].as_str().unwrap());
5379        let patch = serde_json::json!({
5380            "content": [
5381                {"type": "text", "text": "   "},
5382                {"type": "text", "text": reason}
5383            ]
5384        });
5385        unsafe { *out = rpi_plugin_sdk::StbString::from_string(patch.to_string()) };
5386        0
5387    }
5388
5389    extern "C" fn redacting_test_tool_result(
5390        _event: rpi_plugin_sdk::StbStringRef,
5391        out: *mut rpi_plugin_sdk::StbString,
5392        _: *mut std::ffi::c_void,
5393    ) -> i32 {
5394        let patch = serde_json::json!({
5395            "content": [{"type": "text", "text": "REVIEW-REDACTED"}]
5396        });
5397        // SAFETY: the host keeps the output slot live for the callback.
5398        unsafe { *out = rpi_plugin_sdk::StbString::from_string(patch.to_string()) };
5399        0
5400    }
5401
5402    /// A session with a `ToolCall` gate that vetoes every call and/or the
5403    /// labelling `tool_result` transform.
5404    fn test_session(gate: bool, transform: bool) -> ExtensionSession {
5405        let mut registry = rpi_extensions::ExtensionRegistry::new();
5406        if gate {
5407            registry.register_event_handler(
5408                "gate".into(),
5409                rpi_plugin_sdk::EventTag::ToolCall,
5410                deny_test_tool_call,
5411                std::ptr::null_mut(),
5412            );
5413        }
5414        if transform {
5415            registry.register_tool_result(
5416                label_test_tool_result,
5417                rpi_plugin_sdk::callbacks::free_string,
5418                std::ptr::null_mut(),
5419            );
5420        }
5421        ExtensionSession::from_parts(
5422            Arc::new(registry.snapshot()),
5423            rpi_extensions::PluginKeepalive::empty(),
5424            Vec::new(),
5425            None,
5426        )
5427    }
5428
5429    fn invoke_test_result_hook_future(
5430        hook: &rpi_agent::AfterToolCall,
5431        result: &rpi_agent::AgentToolResult,
5432        is_error: bool,
5433    ) -> futures::future::BoxFuture<'static, Option<rpi_agent::AfterToolCallResult>> {
5434        let message = rpi_ai::providers::faux::faux_assistant_message(
5435            "result",
5436            rpi_ai::types::StopReason::ToolUse,
5437        );
5438        let rpi_ai::types::Content::ToolCall(call) =
5439            rpi_ai::types::Content::tool_call("call", "bash", serde_json::json!({"command":"x"}))
5440        else {
5441            unreachable!()
5442        };
5443        hook(
5444            rpi_agent::AfterToolCallContext {
5445                assistant_message: &message,
5446                tool_call: &call,
5447                args: &call.arguments,
5448                result,
5449                is_error,
5450                context: &rpi_agent::AgentContext::default(),
5451            },
5452            tokio_util::sync::CancellationToken::new(),
5453        )
5454    }
5455
5456    async fn invoke_test_result_hook(
5457        hook: &rpi_agent::AfterToolCall,
5458        result: &rpi_agent::AgentToolResult,
5459        is_error: bool,
5460    ) -> Option<rpi_agent::AfterToolCallResult> {
5461        invoke_test_result_hook_future(hook, result, is_error).await
5462    }
5463
5464    fn first_text(content: &[rpi_agent::TextContentOrImage]) -> &str {
5465        match content.first() {
5466            Some(rpi_agent::TextContentOrImage::Text(text)) => &text.text,
5467            _ => panic!("expected a text block"),
5468        }
5469    }
5470
5471    #[tokio::test]
5472    async fn tool_result_hook_transforms_success_and_error_results() {
5473        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
5474        let hook = extension_tool_result_hook(sessions.clone());
5475        let output = rpi_agent::AgentToolResult::text("exit 3: secret output");
5476        // No plugin, and a plugin without a transform: the result is untouched.
5477        assert!(invoke_test_result_hook(&hook, &output, true)
5478            .await
5479            .is_none());
5480        *sessions.lock().unwrap() = test_session(true, false);
5481        assert!(invoke_test_result_hook(&hook, &output, true)
5482            .await
5483            .is_none());
5484
5485        // A transform added later (as by /reload) sees success and error results.
5486        *sessions.lock().unwrap() = test_session(false, true);
5487        for is_error in [false, true] {
5488            let changed = invoke_test_result_hook(&hook, &output, is_error)
5489                .await
5490                .expect("the transform changed the result");
5491            assert_eq!(
5492                first_text(changed.content.as_deref().unwrap()),
5493                format!("isError={is_error} blocked=null text=exit 3: secret output")
5494            );
5495            assert!(
5496                changed.is_error.is_none(),
5497                "the transform does not change whether the call failed"
5498            );
5499        }
5500    }
5501
5502    #[tokio::test]
5503    async fn tool_result_hook_withholds_the_result_when_the_session_lock_is_poisoned() {
5504        let sessions = Arc::new(Mutex::new(test_session(false, true)));
5505        let poison = sessions.clone();
5506        let _ = std::thread::spawn(move || {
5507            let _guard = poison.lock().unwrap();
5508            panic!("poison the session lock");
5509        })
5510        .join();
5511        let hook = extension_tool_result_hook(sessions);
5512        let output = rpi_agent::AgentToolResult::text("secret output");
5513        let changed = invoke_test_result_hook(&hook, &output, false)
5514            .await
5515            .expect("withheld");
5516        assert_eq!(
5517            first_text(changed.content.as_deref().unwrap()),
5518            TOOL_RESULT_WITHHELD
5519        );
5520    }
5521
5522    #[tokio::test]
5523    async fn vetoed_call_reason_passes_through_the_tool_result_transforms() {
5524        // Without a transform the model reads the host's reason.
5525        let sessions = Arc::new(Mutex::new(test_session(true, false)));
5526        let hook =
5527            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
5528        let host_reason = invoke_test_tool_hook(&hook).await.unwrap().reason.unwrap();
5529        assert!(host_reason.contains("gate"));
5530
5531        // With one, the transform's text replaces it, and the transform can
5532        // tell a vetoed call from a failed one.
5533        *sessions.lock().unwrap() = test_session(true, true);
5534        let result = invoke_test_tool_hook(&hook).await.unwrap();
5535        assert!(result.block);
5536        assert_eq!(
5537            result.reason.unwrap(),
5538            format!("isError=true blocked=true text={host_reason}")
5539        );
5540    }
5541
5542    #[tokio::test]
5543    async fn review_reload_between_snapshot_capture_and_dispatch_withholds_result() {
5544        let old_session = test_session(false, true);
5545        let old_snapshot = old_session.snapshot_arc().expect("test transform");
5546        let sessions = Arc::new(Mutex::new(old_session));
5547        let hook = extension_tool_result_hook(sessions.clone());
5548        let output = rpi_agent::AgentToolResult::text("secret output");
5549        // Capture the hook's future without polling it: the session snapshot
5550        // is already fixed, exactly as it is before dispatch to the blocking
5551        // callback.
5552        let pending = invoke_test_result_hook_future(&hook, &output, false);
5553
5554        // Invalidate/swap as /reload does before the captured future runs.
5555        old_snapshot.active_flag().store(false, Ordering::SeqCst);
5556        *sessions.lock().unwrap() = test_session(false, true);
5557
5558        let changed = pending.await.expect("stale dispatch fails closed");
5559        assert_eq!(
5560            first_text(changed.content.as_deref().unwrap()),
5561            TOOL_RESULT_WITHHELD
5562        );
5563    }
5564
5565    #[tokio::test]
5566    async fn review_veto_uses_first_nonempty_text() {
5567        let sessions = Arc::new(Mutex::new(test_session(true, false)));
5568        let hook =
5569            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
5570        let host_reason = invoke_test_tool_hook(&hook).await.unwrap().reason.unwrap();
5571
5572        let mut registry = rpi_extensions::ExtensionRegistry::new();
5573        registry.register_event_handler(
5574            "gate".into(),
5575            rpi_plugin_sdk::EventTag::ToolCall,
5576            deny_test_tool_call,
5577            std::ptr::null_mut(),
5578        );
5579        registry.register_tool_result(
5580            whitespace_then_reason_transform,
5581            rpi_plugin_sdk::callbacks::free_string,
5582            std::ptr::null_mut(),
5583        );
5584        *sessions.lock().unwrap() = ExtensionSession::from_parts(
5585            Arc::new(registry.snapshot()),
5586            rpi_extensions::PluginKeepalive::empty(),
5587            Vec::new(),
5588            None,
5589        );
5590
5591        let result = invoke_test_tool_hook(&hook).await.unwrap();
5592        assert!(result.block);
5593        assert_eq!(result.reason.unwrap(), format!("REASON: {host_reason}"));
5594    }
5595
5596    #[tokio::test]
5597    async fn review_validation_error_passes_through_cli_result_transform() {
5598        let mut registry = rpi_extensions::ExtensionRegistry::new();
5599        registry.register_tool_result(
5600            redacting_test_tool_result,
5601            rpi_plugin_sdk::callbacks::free_string,
5602            std::ptr::null_mut(),
5603        );
5604        let sessions = Arc::new(Mutex::new(ExtensionSession::from_parts(
5605            Arc::new(registry.snapshot()),
5606            rpi_extensions::PluginKeepalive::empty(),
5607            Vec::new(),
5608            None,
5609        )));
5610        let after = extension_tool_result_hook(sessions);
5611        let mut context = rpi_agent::AgentContext::default();
5612        context.tools = vec![Arc::new(SchemaTool {
5613            schema: rpi_ai::types::Tool {
5614                name: "integer".into(),
5615                description: "accepts an integer".into(),
5616                parameters: rpi_ai::types::Schema::new(serde_json::json!({
5617                    "type": "object",
5618                    "properties": {"value": {"type": "integer"}},
5619                    "required": ["value"]
5620                })),
5621                constrained_sampling: None,
5622            },
5623        })];
5624        let tool_call = match rpi_ai::types::Content::tool_call(
5625            "call",
5626            "integer",
5627            serde_json::json!({"value": "invalid-secret"}),
5628        ) {
5629            rpi_ai::types::Content::ToolCall(call) => call,
5630            _ => unreachable!(),
5631        };
5632        let assistant = rpi_ai::providers::faux::faux_assistant_message(
5633            rpi_ai::providers::faux::FauxBlock::ToolCall {
5634                name: "integer".into(),
5635                id: "call".into(),
5636                arguments: tool_call.arguments.clone(),
5637            },
5638            rpi_ai::types::StopReason::ToolUse,
5639        );
5640        context
5641            .messages
5642            .push(rpi_agent::message::AgentMessage::Assistant(Box::new(
5643                assistant,
5644            )));
5645        let (collector, events) = rpi_agent::events::CollectorEmitter::new();
5646        let emit: Arc<dyn rpi_agent::AgentEmitter> = Arc::new(collector);
5647        let config = rpi_agent::hooks::AgentLoopConfig {
5648            model: rpi_ai::model::Model::new(
5649                "test",
5650                "test",
5651                rpi_ai::types::Api::Other("test".into()),
5652                "test",
5653                "",
5654            ),
5655            convert_to_llm: rpi_agent::hooks::default_convert_to_llm_fn(),
5656            convert_to_llm_incremental: None,
5657            transform_context: None,
5658            get_api_key: None,
5659            should_stop_after_turn: None,
5660            prepare_next_turn: None,
5661            after_tool_results: None,
5662            get_steering_messages: None,
5663            get_follow_up_messages: None,
5664            pending_message_count: None,
5665            before_tool_call: None,
5666            after_tool_call: Some(after),
5667            provider_hooks: None,
5668            tool_execution: rpi_agent::types::ToolExecutionMode::Sequential,
5669            thinking_level: rpi_ai::types::ThinkingLevel::default(),
5670            api_key: None,
5671            timeout: None,
5672            stream_idle_timeout: None,
5673            max_retries: None,
5674            max_retry_delay: None,
5675            cache_retention: rpi_ai::provider::CacheRetention::default(),
5676            session_id: None,
5677            signal: tokio_util::sync::CancellationToken::new(),
5678        };
5679        // Only the pending assistant's tool calls run; the empty stream fn is
5680        // never called before the loop finishes this batch.
5681        let stream_fn = rpi_agent::stream_fn::stream_fn(|_, _, opts| {
5682            let (mut producer, stream) =
5683                rpi_ai::event_stream::create_assistant_message_event_stream_with_cancellation(
5684                    &opts.signal,
5685                );
5686            tokio::spawn(async move {
5687                let message = rpi_ai::types::AssistantMessage::terminal(
5688                    rpi_ai::types::Api::Other("test".into()),
5689                    "test",
5690                    "test",
5691                    rpi_ai::types::StopReason::Stop,
5692                    "done",
5693                    0,
5694                );
5695                producer
5696                    .push(rpi_ai::types::AssistantMessageEvent::Done {
5697                        reason: rpi_ai::types::DoneReason::Stop,
5698                        message,
5699                    })
5700                    .await;
5701            });
5702            stream
5703        });
5704        rpi_agent::run_agent_loop_from_assistant(context, config, emit, stream_fn)
5705            .await
5706            .expect("agent loop finishes");
5707
5708        let events = events.lock().unwrap();
5709        let result = events.iter().find_map(|event| match event {
5710            rpi_agent::AgentEvent::ToolExecutionEnd { result, .. } => Some(result),
5711            _ => None,
5712        });
5713        let result = result.expect("validation failure reaches tool execution end");
5714        let text = match &result.content[0] {
5715            rpi_agent::TextContentOrImage::Text(text) => &text.text,
5716            _ => panic!("expected a text result"),
5717        };
5718        assert_eq!(text, "REVIEW-REDACTED");
5719        assert!(!text.contains("invalid-secret"));
5720        assert!(!text.contains("Received arguments"));
5721    }
5722
5723    /// Minimal schema-only tool for the immediate-validation regression.
5724    struct SchemaTool {
5725        schema: rpi_ai::types::Tool,
5726    }
5727
5728    #[async_trait::async_trait]
5729    impl rpi_agent::AgentTool for SchemaTool {
5730        fn schema(&self) -> &rpi_ai::types::Tool {
5731            &self.schema
5732        }
5733        fn label(&self) -> &str {
5734            "schema tool"
5735        }
5736        async fn execute(
5737            &self,
5738            _id: &str,
5739            _params: serde_json::Value,
5740            _signal: tokio_util::sync::CancellationToken,
5741            _on_update: Arc<dyn Fn(rpi_agent::types::ToolResultPartial) + Send + Sync>,
5742        ) -> Result<rpi_agent::types::AgentToolResult, rpi_agent::AgentError> {
5743            unreachable!("invalid arguments must not execute this tool")
5744        }
5745    }
5746
5747    /// A unique scratch file for one summary test.
5748    fn scratch(name: &str) -> PathBuf {
5749        let nanos = std::time::SystemTime::now()
5750            .duration_since(std::time::UNIX_EPOCH)
5751            .unwrap()
5752            .as_nanos();
5753        let path = std::env::temp_dir().join(format!(
5754            "rpi-summary-{}-{nanos}-{name}.jsonl",
5755            std::process::id()
5756        ));
5757        path
5758    }
5759
5760    #[test]
5761    fn summary_marks_a_header_only_session_empty() {
5762        let path = scratch("empty");
5763        std::fs::write(
5764            &path,
5765            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5766        )
5767        .unwrap();
5768        let summary = summarize_session_file(&path);
5769        assert!(summary.empty, "a header-only file has nothing to resume");
5770        assert!(summary.preview.is_none());
5771        assert_eq!(summary.bytes, std::fs::metadata(&path).unwrap().len());
5772        std::fs::remove_file(&path).ok();
5773    }
5774
5775    #[test]
5776    fn summary_reads_the_first_user_prompt_and_name() {
5777        let path = scratch("content");
5778        let body = concat!(
5779            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5780            "{\"kind\":\"fact\",\"seq\":1,\"fact\":\"name\",\"name\":\"fix resume picker\"}\n",
5781            "{\"kind\":\"record\",\"type\":\"operation_started\",\"id\":\"r1\"}\n",
5782            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"kind\":\"user\",\"role\":\"user\",\"content\":\"read the rpi -r picker\"}}\n",
5783            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e2\",\"message\":{\"kind\":\"assistant\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
5784        );
5785        std::fs::write(&path, body).unwrap();
5786        let summary = summarize_session_file(&path);
5787        assert!(!summary.empty);
5788        assert_eq!(summary.name.as_deref(), Some("fix resume picker"));
5789        assert_eq!(summary.preview.as_deref(), Some("read the rpi -r picker"));
5790        std::fs::remove_file(&path).ok();
5791    }
5792
5793    #[test]
5794    fn summary_extracts_a_block_style_user_prompt() {
5795        let path = scratch("blocks");
5796        let body = concat!(
5797            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5798            "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"line one\\nline two\"}]}}\n",
5799        );
5800        std::fs::write(&path, body).unwrap();
5801        let summary = summarize_session_file(&path);
5802        assert_eq!(summary.preview.as_deref(), Some("line one line two"));
5803        assert_eq!(session_display_label(&summary), "line one line two");
5804        std::fs::remove_file(&path).ok();
5805    }
5806
5807    fn meta_for(path: &Path, id: &str) -> rpi_harness::session::jsonl::JsonlSessionMetadata {
5808        rpi_harness::session::jsonl::JsonlSessionMetadata {
5809            id: id.to_string(),
5810            created_at: 0,
5811            cwd: ".".to_string(),
5812            path: path.to_string_lossy().into_owned(),
5813            modified_at: 0,
5814            source_format: rpi_harness::session::jsonl::JsonlSourceFormat::V4,
5815            parent_session_id: None,
5816            legacy_parent_session_path: None,
5817            metadata: None,
5818        }
5819    }
5820
5821    #[test]
5822    fn continue_skips_newer_empty_sessions() {
5823        let empty = scratch("newest-empty");
5824        std::fs::write(
5825            &empty,
5826            "{\"kind\":\"header\",\"version\":4,\"id\":\"empty\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5827        )
5828        .unwrap();
5829        let content = scratch("older-content");
5830        std::fs::write(
5831            &content,
5832            concat!(
5833                "{\"kind\":\"header\",\"version\":4,\"id\":\"old\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5834                "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n",
5835            ),
5836        )
5837        .unwrap();
5838
5839        let metas = vec![meta_for(&empty, "empty"), meta_for(&content, "old")];
5840        let picked = first_resumable_session(&metas).expect("a resumable session");
5841        assert_eq!(picked.id, "old");
5842
5843        // When every session is empty, fall back to the newest rather than
5844        // erroring.
5845        let all_empty = vec![meta_for(&empty, "empty")];
5846        assert_eq!(first_resumable_session(&all_empty).unwrap().id, "empty");
5847
5848        std::fs::remove_file(&empty).ok();
5849        std::fs::remove_file(&content).ok();
5850    }
5851
5852    #[tokio::test]
5853    async fn import_preserves_validates_and_locks_the_recovery_pair() {
5854        use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
5855        use rpi_harness::session::types::{
5856            AssistantFrameOp, AssistantFrameRecord, RecordBase, SessionStorage,
5857        };
5858        let tmp = tempfile::tempdir().unwrap();
5859        let source = tmp.path().join("source.jsonl");
5860        let progress = tmp.path().join("source.jsonl.progress.jsonl");
5861        let fs: Arc<dyn rpi_tools::FileSystem> =
5862            Arc::new(OsExecutionEnv::with_cwd(tmp.path().into()));
5863        let storage = JsonlSessionStorage::create(
5864            fs,
5865            &source.to_string_lossy(),
5866            JsonlV4Header::new("import-pair".into(), 1, "/".into(), None, None, None),
5867            Arc::new(SystemClock),
5868            Arc::new(DefaultIdGenerator::new()),
5869        )
5870        .await
5871        .unwrap();
5872        storage
5873            .append_progress(vec![AssistantFrameRecord {
5874                base: RecordBase {
5875                    id: "accepted-prefix".into(),
5876                    seq: 0,
5877                    lane: "main".into(),
5878                    timestamp: 0,
5879                },
5880                run_id: "run".into(),
5881                stream_index: 0,
5882                op: AssistantFrameOp::Append,
5883                frame: Some(serde_json::json!({"payload":"keep"})),
5884            }])
5885            .await
5886            .unwrap();
5887        drop(storage);
5888        let original = std::fs::read(&progress).unwrap();
5889        let destination = tmp.path().join("imported");
5890        let imported = import_session_file(&source, &tmp.path().to_string_lossy(), &destination)
5891            .await
5892            .unwrap();
5893        assert_eq!(
5894            imported.read_progress("run").await.unwrap()[0].base.id,
5895            "accepted-prefix"
5896        );
5897        assert_eq!(
5898            std::fs::read(&progress).unwrap(),
5899            original,
5900            "import must not repair or mutate its source"
5901        );
5902        let lock = std::fs::OpenOptions::new()
5903            .create(true)
5904            .write(true)
5905            .open(tmp.path().join("source.jsonl.lock"))
5906            .unwrap();
5907        fs2::FileExt::try_lock_exclusive(&lock).unwrap();
5908        assert!(import_session_file(
5909            &source,
5910            &tmp.path().to_string_lossy(),
5911            &tmp.path().join("busy")
5912        )
5913        .await
5914        .is_err());
5915        drop(lock);
5916        let mut corrupt = String::from_utf8(original.clone()).unwrap();
5917        corrupt = corrupt.replace(
5918            "\"session_id\":\"import-pair\"",
5919            "\"session_id\":\"foreign\"",
5920        );
5921        assert_ne!(corrupt.as_bytes(), original.as_slice());
5922        std::fs::write(&progress, corrupt).unwrap();
5923        assert!(import_session_file(
5924            &source,
5925            &tmp.path().to_string_lossy(),
5926            &tmp.path().join("foreign")
5927        )
5928        .await
5929        .is_err());
5930        std::fs::remove_file(&progress).unwrap();
5931        assert!(import_session_file(
5932            &source,
5933            &tmp.path().to_string_lossy(),
5934            &tmp.path().join("missing")
5935        )
5936        .await
5937        .is_err());
5938    }
5939
5940    #[test]
5941    fn list_session_files_sync_walks_the_cwd_subdirectory() {
5942        let root = std::env::temp_dir().join(format!("rpi-summary-{}-dir", std::process::id()));
5943        let nested = root.join("--proj--");
5944        std::fs::create_dir_all(&nested).unwrap();
5945        let file = nested.join("2026-01-01_a.jsonl");
5946        std::fs::write(&file, "{}\n").unwrap();
5947        let sidecar = nested.join("2026-01-01_a.jsonl.progress.jsonl");
5948        std::fs::write(&sidecar, "{}\n").unwrap();
5949        let found = list_session_files_sync(&root);
5950        assert!(found.iter().any(|p| p == &file));
5951        assert!(!found.contains(&sidecar));
5952        std::fs::remove_dir_all(&root).ok();
5953    }
5954
5955    /// Regression for fork issue #13: with a shared session root, the default
5956    /// picker scope must show only this project's sessions, and All must show
5957    /// every project with its directory tag so a flat list stays traceable.
5958    #[test]
5959    fn review_issue13_default_scope_is_this_project_and_all_is_tagged() {
5960        let tmp = tempfile::tempdir().unwrap();
5961        let root = tmp.path().join("sessions");
5962        let cwd = tmp.path().join("project");
5963        let own = root.join(rpi_harness::session::jsonl::jsonl_session_directory_name(
5964            &cwd.to_string_lossy(),
5965        ));
5966        let foreign = root.join("--some-other-project--");
5967        std::fs::create_dir_all(&own).unwrap();
5968        std::fs::create_dir_all(&foreign).unwrap();
5969        let own_file = own.join("2026-01-01_own.jsonl");
5970        let foreign_file = foreign.join("2026-01-02_foreign.jsonl");
5971        std::fs::write(&own_file, "{}\n").unwrap();
5972        std::fs::write(&foreign_file, "{}\n").unwrap();
5973        // A legacy file directly under the root is not a project subdirectory.
5974        let legacy = root.join("2026-01-03_legacy.jsonl");
5975        std::fs::write(&legacy, "{}\n").unwrap();
5976
5977        let project = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
5978        assert_eq!(project.len(), 1, "default scope must not flatten projects");
5979        assert_eq!(project[0].path, own_file);
5980        assert_eq!(project[0].project, None);
5981
5982        let all = list_session_files_in_scope_sync(&cwd, &root, SessionScope::All);
5983        assert_eq!(all.len(), 3);
5984        let own_project = own.file_name().unwrap().to_str().unwrap();
5985        assert!(all
5986            .iter()
5987            .any(|e| e.path == own_file && e.project.as_deref() == Some(own_project)));
5988        assert!(all
5989            .iter()
5990            .any(|e| e.path == foreign_file
5991                && e.project.as_deref() == Some("--some-other-project--")));
5992        assert!(all.iter().any(|e| e.path == legacy && e.project.is_none()));
5993
5994        assert_eq!(SessionScope::Project.toggled(), SessionScope::All);
5995        assert_eq!(SessionScope::All.toggled(), SessionScope::Project);
5996        assert_eq!(SessionScope::default(), SessionScope::Project);
5997    }
5998
5999    /// The project directory name must be the repo's own encoding, not a
6000    /// re-derivation that drifts from create/open. A relative cwd resolves
6001    /// against the process cwd the same way `OsExecutionEnv::absolute_path` does.
6002    #[test]
6003    fn review_issue13_project_scope_uses_the_repo_directory_encoding() {
6004        let tmp = tempfile::tempdir().unwrap();
6005        let root = tmp.path().join("sessions");
6006        let cwd = tmp.path().join("project");
6007        let name =
6008            rpi_harness::session::jsonl::jsonl_session_directory_name(&cwd.to_string_lossy());
6009        std::fs::create_dir_all(root.join(&name)).unwrap();
6010        let file = root.join(&name).join("a.jsonl");
6011        std::fs::write(&file, "{}\n").unwrap();
6012        // A look-alike directory that a naive "last path component" derivation
6013        // would pick instead. The repo encodes the *full* cwd, so this must not
6014        // be listed by the Project scope.
6015        let lookalike = root.join("--project--");
6016        std::fs::create_dir_all(&lookalike).unwrap();
6017        let other_file = lookalike.join("b.jsonl");
6018        std::fs::write(&other_file, "{}\n").unwrap();
6019        let found = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
6020        assert_eq!(
6021            found,
6022            vec![SessionFileEntry {
6023                path: file,
6024                project: None
6025            }]
6026        );
6027    }
6028
6029    /// Fork issue #13, async path: the `-r` picker's default scope must use the
6030    /// repo's typed list API with an explicit cwd, and the open path must stay
6031    /// unscoped so a row chosen from All still resolves by id.
6032    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6033    async fn review_issue13_resume_scope_and_open_path_agree() {
6034        let tmp = tempfile::tempdir().unwrap();
6035        let root = tmp.path().join("sessions");
6036        let cwd = tmp.path().join("project");
6037        std::fs::create_dir_all(&cwd).unwrap();
6038        let foreign_cwd = tmp.path().join("other");
6039        std::fs::create_dir_all(&foreign_cwd).unwrap();
6040        let cwd_text = cwd.to_string_lossy().into_owned();
6041        let own = create_jsonl_session(&root, &cwd_text).await.unwrap();
6042        let own_id = own.storage().metadata().id.clone();
6043        drop(own);
6044        let foreign = create_jsonl_session(&root, &foreign_cwd.to_string_lossy())
6045            .await
6046            .unwrap();
6047        let foreign_id = foreign.storage().metadata().id.clone();
6048        drop(foreign);
6049
6050        let project =
6051            list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::Project)
6052                .await
6053                .unwrap();
6054        assert_eq!(project.len(), 1, "-r default must not flatten projects");
6055        assert_eq!(project[0].id, own_id);
6056        let all = list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::All)
6057            .await
6058            .unwrap();
6059        assert_eq!(all.len(), 2);
6060        assert!(all.iter().any(|m| m.cwd == foreign_cwd.to_string_lossy()));
6061        // `list_session_metadata_in_dir` (the open path) must remain unscoped.
6062        let open = list_session_metadata_in_dir(&cwd_text, &root)
6063            .await
6064            .unwrap();
6065        assert_eq!(open.len(), 2);
6066        let found = find_session_metadata(&foreign_id, &cwd_text, &root)
6067            .await
6068            .unwrap();
6069        assert_eq!(found.unwrap().id, foreign_id);
6070    }
6071
6072    /// The default CLI tool set plus the `todo` tool its bundled plugins add.
6073    fn default_prompt_tools() -> Vec<String> {
6074        BUILTIN_TOOL_NAMES
6075            .iter()
6076            .copied()
6077            .chain(["todo"])
6078            .map(str::to_owned)
6079            .collect()
6080    }
6081
6082    #[test]
6083    fn default_prompt_lists_only_the_active_tools() {
6084        let tools = ["read", "docs"].map(str::to_owned);
6085        let p = default_system_prompt_with_tools("/tmp/proj", true, &tools);
6086        assert!(p.contains("- read  — Read file contents"));
6087        assert!(p.contains("- docs  — Look up rpi commands"));
6088        for absent in ["- edit", "- write", "- bash", "todo", "Windows"] {
6089            assert!(
6090                !p.contains(absent),
6091                "{absent} must not appear for a read-only run: {p}"
6092            );
6093        }
6094        assert!(p.contains("Re-stating the same plan without acting on it is a bug"));
6095        let none = default_system_prompt_with_tools("/tmp/proj", false, &[]);
6096        assert!(none.contains("Available tools:\n(none)"));
6097    }
6098
6099    #[test]
6100    fn default_prompt_mentions_cwd_and_tools() {
6101        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
6102        assert!(p.contains("/tmp/proj"));
6103        assert!(p.contains("read"));
6104        assert!(p.contains("bash"));
6105        assert!(p.contains("edit"));
6106        assert!(p.contains("write"));
6107        assert!(p.contains("docs"));
6108        assert!(!p.contains("- grep"));
6109        assert!(!p.contains("- find"));
6110        assert!(!p.contains("- ls"));
6111        assert!(!p.contains("- powershell"));
6112        assert!(p.contains("Bash/POSIX syntax, also on Windows"));
6113    }
6114
6115    #[test]
6116    fn default_prompt_instructs_language_matching() {
6117        // A Chinese (or any non-English) user gets a same-language reply
6118        // without having to ask every turn.
6119        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
6120        assert!(
6121            p.contains("same language as the user's latest message"),
6122            "the prompt must tell the model to mirror the user's language: {p}"
6123        );
6124    }
6125
6126    #[test]
6127    fn default_prompt_keeps_working_state_in_the_visible_channel() {
6128        // Regression guard for the re-plan loop: on openai-compatible providers
6129        // the assistant's `thinking` blocks are dropped when the next request is
6130        // built (`providers/openai_completions.rs`: `Content::text_only`), so a
6131        // plan that lives only in reasoning is re-derived every turn. One
6132        // observed session paid for that 112 times in a single run, and twice
6133        // hallucinated the user's input ("The user is greeting me with hello",
6134        // with no such message). See `docs/llm-repetition-forensics.md` §八.
6135        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
6136        let lower = p.to_lowercase();
6137        // The rule must state the mechanism, not just "be clear".
6138        assert!(
6139            lower.contains("reasoning is not") && lower.contains("carried into your next turn"),
6140            "the prompt must explain that reasoning does not survive the turn: {p}"
6141        );
6142        // Working state stays visible; extension-specific rules require opt-in.
6143        assert!(
6144            lower.contains("visible") && !lower.contains("todo tool"),
6145            "the prompt must keep state visible without inventing extension rules: {p}"
6146        );
6147        // …plus the anti-repetition rule itself.
6148        assert!(
6149            lower.contains("re-stating the same plan"),
6150            "the prompt must call out plan re-statement as a bug: {p}"
6151        );
6152        // And the guidance must not instruct re-reading what is already shown.
6153        assert!(
6154            lower.contains("already shown earlier"),
6155            "the prompt must discourage re-fetching known content: {p}"
6156        );
6157    }
6158
6159    #[test]
6160    fn default_prompt_does_not_claim_reasoning_is_lost_when_it_is_replayed() {
6161        // `compat.requiresThinkingAsText` (and the native thinking channels of
6162        // anthropic-messages / openai-responses) DO carry the model's reasoning
6163        // back on the next request. Telling such a model "reasoning is not
6164        // carried into your next turn" is false, and the instruction to restate
6165        // the plan every turn is exactly the busy-work the re-plan analysis
6166        // measured. The wording must flip with the mechanism.
6167        let p = default_system_prompt_with_tools("/tmp/proj", true, &default_prompt_tools());
6168        let lower = p.to_lowercase();
6169        assert!(
6170            lower.contains("carried back"),
6171            "a replaying model must be told its reasoning survives: {p}"
6172        );
6173        assert!(
6174            !lower.contains("reasoning is not"),
6175            "the replayed variant must not claim reasoning is dropped: {p}"
6176        );
6177        assert!(
6178            lower.contains("do not re-derive"),
6179            "the replayed variant must forbid re-deriving the plan: {p}"
6180        );
6181        assert!(
6182            lower.contains("do not re-derive") && lower.contains("re-stating the same plan"),
6183            "the anti-repetition rule must survive the flip: {p}"
6184        );
6185        assert!(
6186            lower.contains("already shown earlier"),
6187            "the re-read rule must survive the flip: {p}"
6188        );
6189    }
6190
6191    #[test]
6192    fn default_prompt_states_each_rule_once() {
6193        // The plan rule, the todo tool and the anti-repetition line used to be
6194        // spread over two guidelines that repeated each other.
6195        for replayed in [false, true] {
6196            let p =
6197                default_system_prompt_with_tools("/tmp/proj", replayed, &default_prompt_tools());
6198            for phrase in ["the same plan", "Windows", "guessing"] {
6199                assert_eq!(p.matches(phrase).count(), 1, "{phrase:?} repeated: {p}");
6200            }
6201            assert!(
6202                !p.contains("todo tool"),
6203                "extension rules require explicit metadata"
6204            );
6205        }
6206    }
6207
6208    /// Only side-effect-free tools may be replayed after a crash.
6209    ///
6210    /// Regression guard for an inverted default: `ToolReplay` used to default to
6211    /// `Safe` and the CLI then marked *every* tool `Safe`, so the first time
6212    /// recovery acted on the flag it would have re-run `bash`/`write`/`edit` and
6213    /// duplicated their side effects. upstream defaults to `"never"`
6214    /// (`drive/tools.ts: tool.replay ?? "never"`).
6215    #[test]
6216    fn only_read_only_tools_are_replayable() {
6217        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
6218        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
6219        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
6220        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
6221        let tools = build_tools(&context, &Args::default());
6222
6223        let replay_of = |name: &str| {
6224            tools
6225                .iter()
6226                .find(|tool| tool.tool.schema().name == name)
6227                .map(|tool| tool.replay)
6228        };
6229
6230        for read_only in ["read", "docs"] {
6231            assert_eq!(
6232                replay_of(read_only),
6233                Some(ToolReplay::Safe),
6234                "{read_only} is side-effect free, so recovery may re-run it"
6235            );
6236        }
6237        for mutating in ["bash", "edit", "write", "powershell"] {
6238            if let Some(replay) = replay_of(mutating) {
6239                assert_eq!(
6240                    replay,
6241                    ToolReplay::Never,
6242                    "{mutating} must never be replayed: re-running it would duplicate its effect"
6243                );
6244            }
6245        }
6246    }
6247
6248    #[test]
6249    fn default_tools_include_docs_lookup() {
6250        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
6251        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
6252        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
6253        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
6254        let names: Vec<String> = build_tools(&context, &Args::default())
6255            .iter()
6256            .map(|tool| tool.tool.schema().name.clone())
6257            .collect();
6258
6259        // `powershell` is Windows-only, and the defaultTools setting may narrow
6260        // the registered set in a developer's environment.
6261        assert!(names.contains(&"docs".to_string()));
6262        for legacy in ["grep", "find", "ls", "image"] {
6263            assert!(
6264                !names.contains(&legacy.to_string()),
6265                "legacy tool {legacy} should not be registered by default"
6266            );
6267        }
6268    }
6269
6270    #[test]
6271    fn reload_settings_preflight_respects_trust() {
6272        struct RestoreConfigDir(Option<std::ffi::OsString>);
6273
6274        impl Drop for RestoreConfigDir {
6275            fn drop(&mut self) {
6276                match self.0.take() {
6277                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6278                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6279                }
6280            }
6281        }
6282
6283        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6284        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6285        let tmp = tempfile::tempdir().unwrap();
6286        let agent = tmp.path().join("agent");
6287        let cwd = tmp.path().join("project");
6288        std::fs::create_dir_all(&agent).unwrap();
6289        std::fs::create_dir_all(cwd.join(".rpi")).unwrap();
6290        std::fs::write(agent.join("settings.json"), "{}").unwrap();
6291        std::fs::write(cwd.join(".rpi/settings.json"), "{ malformed").unwrap();
6292        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6293        let args = Args::default();
6294
6295        let trusted = validate_settings_for_reload(&args, &cwd, true);
6296        let untrusted = validate_settings_for_reload(&args, &cwd, false);
6297        assert!(trusted
6298            .unwrap_err()
6299            .contains("could not load project settings"));
6300        assert!(untrusted.is_ok());
6301
6302        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
6303        assert!(validate_settings_for_reload(&args, &cwd, false)
6304            .unwrap_err()
6305            .contains("could not load global settings"));
6306
6307        let local_only = Args {
6308            dev_local_only: true,
6309            ..Args::default()
6310        };
6311        assert!(validate_settings_for_reload(&local_only, &cwd, true).is_ok());
6312    }
6313
6314    #[tokio::test]
6315    async fn reload_collects_plugin_loader_warnings_for_the_ui() {
6316        let tmp = tempfile::tempdir().unwrap();
6317        let cwd = tmp.path().join("project");
6318        let extensions = tmp.path().join("extensions");
6319        std::fs::create_dir_all(&cwd).unwrap();
6320        std::fs::create_dir_all(&extensions).unwrap();
6321        let home = crate::config::AgentHome::from_option(Some(tmp.path().join("agent"))).unwrap();
6322        let resolved = crate::provider::resolve(
6323            &home,
6324            Some("anthropic"),
6325            Some(crate::provider::DEFAULT_MODEL_ID),
6326            None,
6327            Some("test-key"),
6328            None,
6329        )
6330        .unwrap();
6331        let args = Args {
6332            no_session: true,
6333            extensions_dir: vec![extensions.clone()],
6334            ..Args::default()
6335        };
6336        let (harness, _, context) = build(&home, &resolved, &args, &cwd, false).await.unwrap();
6337        let filename = format!("bad-reload{}", std::env::consts::DLL_SUFFIX);
6338        std::fs::write(extensions.join(&filename), "not a dynamic library").unwrap();
6339
6340        let outcome = reload_extension_resources(&harness, &context).await;
6341        assert!(!outcome.had_errors, "{}", outcome.summary);
6342        assert!(outcome.had_warnings);
6343        assert!(
6344            outcome
6345                .details
6346                .iter()
6347                .any(|line| line.contains("skipped plugin") && line.contains(&filename)),
6348            "{:?}",
6349            outcome.details
6350        );
6351    }
6352
6353    #[tokio::test(flavor = "current_thread")]
6354    async fn reload_preserves_live_resources_when_settings_break() {
6355        struct RestoreConfigDir(Option<std::ffi::OsString>);
6356
6357        impl Drop for RestoreConfigDir {
6358            fn drop(&mut self) {
6359                match self.0.take() {
6360                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6361                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6362                }
6363            }
6364        }
6365
6366        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6367        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6368        let tmp = tempfile::tempdir().unwrap();
6369        let agent = tmp.path().join("agent");
6370        let cwd = tmp.path().join("project");
6371        let skill_dir = tmp.path().join("configured-skills");
6372        std::fs::create_dir_all(&agent).unwrap();
6373        std::fs::create_dir_all(&cwd).unwrap();
6374        std::fs::create_dir_all(&skill_dir).unwrap();
6375        std::fs::write(
6376            skill_dir.join("SKILL.md"),
6377            "---\nname: keep-me\ndescription: Reload sentinel\n---\nKeep this skill loaded.",
6378        )
6379        .unwrap();
6380        std::fs::write(
6381            agent.join("settings.json"),
6382            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
6383        )
6384        .unwrap();
6385        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6386
6387        let resolved = crate::provider::resolve(
6388            &crate::config::AgentHome::process(),
6389            Some("anthropic"),
6390            Some(crate::provider::DEFAULT_MODEL_ID),
6391            None,
6392            Some("test-key"),
6393            None,
6394        )
6395        .unwrap();
6396        let args = Args {
6397            trust_override: Some(false),
6398            no_session: true,
6399            no_extensions: true,
6400            no_prompt_templates: true,
6401            no_context_files: true,
6402            system_prompt: Some("stable system prompt".into()),
6403            ..Args::default()
6404        };
6405        let (harness, _events, context) = build(
6406            &crate::config::AgentHome::process(),
6407            &resolved,
6408            &args,
6409            &cwd,
6410            false,
6411        )
6412        .await
6413        .unwrap();
6414        let before_resources = harness.get_resources().await.unwrap();
6415        assert_eq!(before_resources.skills.as_ref().unwrap().len(), 1);
6416        assert_eq!(before_resources.skills.as_ref().unwrap()[0].name, "keep-me");
6417        let before_prompt = harness.get_system_prompt().await.unwrap();
6418        let before_tools: Vec<String> = harness
6419            .get_tools()
6420            .await
6421            .unwrap()
6422            .iter()
6423            .map(|tool| tool.tool.schema().name.clone())
6424            .collect();
6425        let before_bridge = context
6426            .action_bridge
6427            .lock()
6428            .unwrap()
6429            .as_ref()
6430            .unwrap()
6431            .clone();
6432
6433        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
6434        let outcome = reload_extension_resources(&harness, &context).await;
6435
6436        assert!(outcome.had_warnings);
6437        assert!(outcome.summary.contains("Settings reload failed"));
6438        assert!(outcome.summary.contains("could not load global settings"));
6439        // Hard failure keeps the previous resources; the outcome must not
6440        // advertise a fresh trust policy either (theme discovery keeps the
6441        // registry it already matches).
6442        assert_eq!(outcome.project_trusted, None);
6443        assert_eq!(harness.get_resources().await.unwrap(), before_resources);
6444        assert_eq!(harness.get_system_prompt().await.unwrap(), before_prompt);
6445        let after_tools: Vec<String> = harness
6446            .get_tools()
6447            .await
6448            .unwrap()
6449            .iter()
6450            .map(|tool| tool.tool.schema().name.clone())
6451            .collect();
6452        assert_eq!(after_tools, before_tools);
6453        let after_bridge = context
6454            .action_bridge
6455            .lock()
6456            .unwrap()
6457            .as_ref()
6458            .unwrap()
6459            .clone();
6460        assert!(Arc::ptr_eq(&after_bridge, &before_bridge));
6461    }
6462
6463    #[tokio::test(flavor = "current_thread")]
6464    async fn reload_outcome_carries_the_current_project_trust() {
6465        struct RestoreConfigDir(Option<std::ffi::OsString>);
6466
6467        impl Drop for RestoreConfigDir {
6468            fn drop(&mut self) {
6469                match self.0.take() {
6470                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6471                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6472                }
6473            }
6474        }
6475
6476        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6477        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6478        let tmp = tempfile::tempdir().unwrap();
6479        let agent = tmp.path().join("agent");
6480        let cwd = tmp.path().join("project");
6481        std::fs::create_dir_all(&agent).unwrap();
6482        std::fs::create_dir_all(&cwd).unwrap();
6483        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6484
6485        // Startup snapshot: trusted.
6486        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
6487        let resolved = crate::provider::resolve(
6488            &crate::config::AgentHome::process(),
6489            Some("anthropic"),
6490            Some(crate::provider::DEFAULT_MODEL_ID),
6491            None,
6492            Some("test-key"),
6493            None,
6494        )
6495        .unwrap();
6496        let args = Args {
6497            no_session: true,
6498            no_extensions: true,
6499            no_prompt_templates: true,
6500            no_context_files: true,
6501            system_prompt: Some("stable system prompt".into()),
6502            ..Args::default()
6503        };
6504        let (harness, _events, context) = build(
6505            &crate::config::AgentHome::process(),
6506            &resolved,
6507            &args,
6508            &cwd,
6509            true,
6510        )
6511        .await
6512        .unwrap();
6513        assert!(context.project_trusted, "startup snapshot is trusted");
6514
6515        // /trust no, then /reload: the outcome must report the CURRENT
6516        // decision, not the immutable startup snapshot.
6517        crate::config::set_project_trust(&cwd, Some(false)).unwrap();
6518        let outcome = reload_extension_resources(&harness, &context).await;
6519        assert!(!outcome.had_errors, "{}", outcome.summary);
6520        assert_eq!(outcome.project_trusted, Some(false));
6521
6522        // And the opposite transition back to trusted.
6523        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
6524        let outcome = reload_extension_resources(&harness, &context).await;
6525        assert!(!outcome.had_errors, "{}", outcome.summary);
6526        assert_eq!(outcome.project_trusted, Some(true));
6527    }
6528
6529    /// An explicit agent home owns its transcripts: the default session root
6530    /// is `<home>/sessions`, while `--session-dir` still wins. The process
6531    /// session-dir env override must not bleed into an explicit home.
6532    #[test]
6533    fn agent_home_defaults_the_session_root_under_the_home() {
6534        let home = tempfile::tempdir().unwrap();
6535        let cwd = tempfile::tempdir().unwrap();
6536        let env_dir = cwd.path().join("env-sessions");
6537        let _env = crate::config::test_support::SessionDirEnv::new(Some(&env_dir));
6538        let agent_home =
6539            crate::config::AgentHome::from_option(Some(home.path().to_path_buf())).unwrap();
6540        let args = Args::default();
6541        assert_eq!(
6542            configured_session_dir_for(&agent_home, &args, cwd.path()),
6543            home.path().join("sessions")
6544        );
6545
6546        let explicit = cwd.path().join("explicit-sessions");
6547        let args = Args {
6548            session_dir: Some(explicit.clone()),
6549            ..Args::default()
6550        };
6551        assert_eq!(
6552            configured_session_dir_for(&agent_home, &args, cwd.path()),
6553            explicit
6554        );
6555    }
6556
6557    /// `/reload` must re-read resources from the session's explicit agent home,
6558    /// not the process default and not a startup snapshot.
6559    #[test]
6560    fn reload_inputs_reread_the_selected_agent_home() {
6561        struct RestoreConfigDir(Option<std::ffi::OsString>);
6562        impl Drop for RestoreConfigDir {
6563            fn drop(&mut self) {
6564                match self.0.take() {
6565                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6566                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6567                }
6568            }
6569        }
6570
6571        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6572        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6573        let process_home = tempfile::tempdir().unwrap();
6574        let selected_home = tempfile::tempdir().unwrap();
6575        let cwd = tempfile::tempdir().unwrap();
6576        std::env::set_var(crate::config::CONFIG_DIR_ENV, process_home.path());
6577        let process_skills = process_home.path().join("process-only-skills");
6578        std::fs::create_dir_all(&process_skills).unwrap();
6579        let selected_skills = selected_home.path().join("skills");
6580        std::fs::create_dir_all(selected_skills.join("base")).unwrap();
6581        std::fs::write(
6582            selected_skills.join("base").join("SKILL.md"),
6583            "---\nname: base\ndescription: base skill\n---\nbody\n",
6584        )
6585        .unwrap();
6586        std::fs::write(selected_home.path().join("settings.json"), "{}").unwrap();
6587
6588        let selected_agent_home =
6589            crate::config::AgentHome::from_option(Some(selected_home.path().to_path_buf()))
6590                .unwrap();
6591        let args = Args {
6592            no_session: true,
6593            no_extensions: true,
6594            no_prompt_templates: true,
6595            no_context_files: true,
6596            ..Args::default()
6597        };
6598
6599        let first =
6600            prepare_reload_inputs_for(&selected_agent_home, &args, cwd.path(), false).unwrap();
6601        assert!(
6602            first
6603                .skill_base_dirs
6604                .iter()
6605                .any(|dir| dir == &selected_skills),
6606            "{:?}",
6607            first.skill_base_dirs
6608        );
6609        assert!(
6610            first
6611                .skill_base_dirs
6612                .iter()
6613                .all(|dir| !dir.starts_with(process_home.path())),
6614            "{:?}",
6615            first.skill_base_dirs
6616        );
6617
6618        // A settings change in the selected home is observed by the next
6619        // reload pass (the file is re-read, not cached at startup).
6620        let extra = selected_home.path().join("extra-skills");
6621        std::fs::create_dir_all(&extra).unwrap();
6622        std::fs::write(
6623            selected_home.path().join("settings.json"),
6624            serde_json::json!({"skillDirs": [extra]}).to_string(),
6625        )
6626        .unwrap();
6627        let second =
6628            prepare_reload_inputs_for(&selected_agent_home, &args, cwd.path(), false).unwrap();
6629        assert!(
6630            second.skill_base_dirs.iter().any(|dir| dir == &extra),
6631            "{:?}",
6632            second.skill_base_dirs
6633        );
6634    }
6635
6636    #[test]
6637    fn registry_aware_global_selection_falls_back_when_the_registry_is_corrupt() {
6638        struct RestoreConfigDir(Option<std::ffi::OsString>);
6639
6640        impl Drop for RestoreConfigDir {
6641            fn drop(&mut self) {
6642                match self.0.take() {
6643                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6644                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6645                }
6646            }
6647        }
6648
6649        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6650        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6651        let tmp = tempfile::tempdir().unwrap();
6652        let agent = tmp.path().join("agent");
6653        let extensions = agent.join("extensions");
6654        std::fs::create_dir_all(&extensions).unwrap();
6655        std::fs::write(agent.join("native-packages.json"), b"{ this is not json").unwrap();
6656        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6657
6658        // An unreadable registry cannot tell us which artifacts are retired. Keep
6659        // the historical directory scan instead of silently loading nothing.
6660        let dirs = vec![extensions.clone()];
6661        let (scan_dirs, files) = registry_aware_extension_inputs(&dirs, &[], None);
6662        assert!(
6663            scan_dirs.contains(&extensions),
6664            "a corrupt registry must not disable every global extension"
6665        );
6666        assert!(files.is_empty());
6667    }
6668
6669    #[test]
6670    fn startup_and_reload_use_registry_aware_global_extension_selection() {
6671        struct RestoreConfigDir(Option<std::ffi::OsString>);
6672
6673        impl Drop for RestoreConfigDir {
6674            fn drop(&mut self) {
6675                match self.0.take() {
6676                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6677                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6678                }
6679            }
6680        }
6681
6682        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6683        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6684        let tmp = tempfile::tempdir().unwrap();
6685        let agent = tmp.path().join("agent");
6686        let cwd = tmp.path().join("project");
6687        let extensions = agent.join("extensions");
6688        std::fs::create_dir_all(&extensions).unwrap();
6689        std::fs::create_dir_all(&cwd).unwrap();
6690
6691        let active =
6692            extensions.join("librpi_web_extension-v0.1.64-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.so");
6693        let stale_same_version =
6694            extensions.join("librpi_web_extension-v0.1.64-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.so");
6695        let stale_rpi_web =
6696            extensions.join("librpi_web_extension-v0.1.63-cccccccccccccccccccccccccccccccc.so");
6697        let legacy = extensions.join("legacy_custom.so");
6698        for path in [&active, &stale_same_version, &stale_rpi_web, &legacy] {
6699            std::fs::write(path, b"cdylib").unwrap();
6700        }
6701        let registry = serde_json::json!([
6702            {
6703                "name": "rpi-web",
6704                "version": "0.1.64",
6705                "source": null,
6706                "artifacts": [active.file_name().unwrap().to_str().unwrap()]
6707            }
6708        ]);
6709        std::fs::write(agent.join("native-packages.json"), registry.to_string()).unwrap();
6710        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6711
6712        let args = Args {
6713            trust_override: Some(false),
6714            ..Args::default()
6715        };
6716        let home = crate::config::AgentHome::process();
6717        let startup_dirs = startup_extension_dirs(&home, &args, &cwd, false);
6718        let home_root = home.root().ok();
6719        assert!(startup_dirs.contains(&extensions));
6720        let (startup_scan_dirs, startup_files) =
6721            registry_aware_extension_inputs(&startup_dirs, &args.extension, home_root.as_deref());
6722        assert!(!startup_scan_dirs.contains(&extensions));
6723        assert!(startup_files.contains(&active));
6724        assert!(startup_files.contains(&legacy));
6725        assert!(!startup_files.contains(&stale_same_version));
6726        assert!(!startup_files.contains(&stale_rpi_web));
6727
6728        let prepared = prepare_reload_inputs_inner(&args, &cwd, false, || {}).unwrap();
6729        let (reload_scan_dirs, reload_files) = registry_aware_extension_inputs(
6730            &prepared.extension_dirs,
6731            &args.extension,
6732            home_root.as_deref(),
6733        );
6734        assert!(!reload_scan_dirs.contains(&extensions));
6735        assert_eq!(reload_files, startup_files);
6736    }
6737
6738    #[test]
6739    fn registry_aware_global_selection_keeps_unmanaged_legacy_cdylib() {
6740        struct RestoreConfigDir(Option<std::ffi::OsString>);
6741
6742        impl Drop for RestoreConfigDir {
6743            fn drop(&mut self) {
6744                match self.0.take() {
6745                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6746                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6747                }
6748            }
6749        }
6750
6751        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6752        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6753        let tmp = tempfile::tempdir().unwrap();
6754        let agent = tmp.path().join("agent");
6755        let extensions = agent.join("extensions");
6756        std::fs::create_dir_all(&extensions).unwrap();
6757        let legacy = extensions.join("legacy_custom.so");
6758        std::fs::write(&legacy, b"cdylib").unwrap();
6759        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6760
6761        let (dirs, files) =
6762            registry_aware_extension_inputs(&[extensions.clone()], &[], Some(agent.as_path()));
6763        assert!(dirs.is_empty());
6764        assert_eq!(files, vec![legacy]);
6765    }
6766
6767    #[test]
6768    fn reload_preparation_rejects_settings_changed_during_derivation() {
6769        struct RestoreConfigDir(Option<std::ffi::OsString>);
6770
6771        impl Drop for RestoreConfigDir {
6772            fn drop(&mut self) {
6773                match self.0.take() {
6774                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6775                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6776                }
6777            }
6778        }
6779
6780        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6781        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6782        let tmp = tempfile::tempdir().unwrap();
6783        let agent = tmp.path().join("agent");
6784        let cwd = tmp.path().join("project");
6785        let first_skill_dir = tmp.path().join("first-skills");
6786        let second_skill_dir = tmp.path().join("second-skills");
6787        std::fs::create_dir_all(&agent).unwrap();
6788        std::fs::create_dir_all(&cwd).unwrap();
6789        std::fs::write(
6790            agent.join("settings.json"),
6791            serde_json::json!({"skillDirs": [first_skill_dir]}).to_string(),
6792        )
6793        .unwrap();
6794        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6795        let args = Args {
6796            trust_override: Some(false),
6797            no_extensions: true,
6798            no_prompt_templates: true,
6799            ..Args::default()
6800        };
6801
6802        let result = prepare_reload_inputs_inner(&args, &cwd, false, || {
6803            std::fs::write(
6804                agent.join("settings.json"),
6805                serde_json::json!({"skillDirs": [second_skill_dir]}).to_string(),
6806            )
6807            .unwrap();
6808        });
6809
6810        let error = result
6811            .err()
6812            .expect("settings mutation must fail preparation");
6813        assert!(error.contains("settings changed while reload inputs were being prepared"));
6814    }
6815
6816    #[tokio::test(flavor = "current_thread")]
6817    async fn reload_uses_frozen_settings_inputs_after_preparation() {
6818        struct RestoreConfigDir(Option<std::ffi::OsString>);
6819
6820        impl Drop for RestoreConfigDir {
6821            fn drop(&mut self) {
6822                match self.0.take() {
6823                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6824                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6825                }
6826            }
6827        }
6828
6829        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6830        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6831        let tmp = tempfile::tempdir().unwrap();
6832        let agent = tmp.path().join("agent");
6833        let cwd = tmp.path().join("project");
6834        let skill_dir = tmp.path().join("configured-skills");
6835        std::fs::create_dir_all(&agent).unwrap();
6836        std::fs::create_dir_all(&cwd).unwrap();
6837        std::fs::create_dir_all(&skill_dir).unwrap();
6838        std::fs::write(
6839            skill_dir.join("SKILL.md"),
6840            "---\nname: frozen-skill\ndescription: Reload sentinel\n---\nFrozen input.",
6841        )
6842        .unwrap();
6843        std::fs::write(
6844            agent.join("settings.json"),
6845            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
6846        )
6847        .unwrap();
6848        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6849
6850        let resolved = crate::provider::resolve(
6851            &crate::config::AgentHome::process(),
6852            Some("anthropic"),
6853            Some(crate::provider::DEFAULT_MODEL_ID),
6854            None,
6855            Some("test-key"),
6856            None,
6857        )
6858        .unwrap();
6859        let args = Args {
6860            trust_override: Some(false),
6861            no_session: true,
6862            no_extensions: true,
6863            no_prompt_templates: true,
6864            no_context_files: true,
6865            system_prompt: Some("stable system prompt".into()),
6866            ..Args::default()
6867        };
6868        let (harness, _events, context) = build(
6869            &crate::config::AgentHome::process(),
6870            &resolved,
6871            &args,
6872            &cwd,
6873            false,
6874        )
6875        .await
6876        .unwrap();
6877
6878        let outcome = reload_extension_resources_inner(&harness, &context, || {
6879            std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
6880        })
6881        .await;
6882
6883        assert!(!outcome.summary.contains("Settings reload failed"));
6884        assert_eq!(
6885            outcome.summary,
6886            "Reloaded 0 plugin(s), 1 skill(s), 0 prompt(s)."
6887        );
6888        let resources = harness.get_resources().await.unwrap();
6889        let skills = resources.skills.as_ref().unwrap();
6890        assert_eq!(skills.len(), 1);
6891        assert_eq!(skills[0].name, "frozen-skill");
6892    }
6893
6894    #[tokio::test]
6895    async fn reload_resource_paths_include_explicit_skill_and_prompt_files() {
6896        let tmp = tempfile::tempdir().unwrap();
6897        let skill_path = tmp.path().join("explicit-skill.md");
6898        std::fs::write(
6899            &skill_path,
6900            "---\nname: explicit-skill\ndescription: Explicit skill\n---\nSkill body",
6901        )
6902        .unwrap();
6903        let prompt_path = tmp.path().join("explicit-prompt.md");
6904        std::fs::write(
6905            &prompt_path,
6906            "---\ndescription: Explicit prompt\n---\nPrompt body",
6907        )
6908        .unwrap();
6909
6910        let args = Args {
6911            skill: vec![skill_path.clone()],
6912            prompt_template: vec![prompt_path.clone()],
6913            ..Args::default()
6914        };
6915        let skill_paths = append_reload_resource_paths(Vec::new(), &args.skill, &[], &[], &[]);
6916        let prompt_paths =
6917            append_reload_resource_paths(Vec::new(), &args.prompt_template, &[], &[], &[]);
6918        let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
6919        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env;
6920
6921        let skills = load_skills_with_precedence(&env_dyn, &skill_paths).await;
6922        assert_eq!(skills.skills.len(), 1, "{:?}", skills.diagnostics);
6923        assert_eq!(skills.skills[0].name, "explicit-skill");
6924
6925        let prompts = load_prompt_templates_with_precedence(&env_dyn, &prompt_paths).await;
6926        assert_eq!(
6927            prompts.prompt_templates.len(),
6928            1,
6929            "{:?}",
6930            prompts.diagnostics
6931        );
6932        assert_eq!(prompts.prompt_templates[0].name, "explicit-prompt");
6933    }
6934
6935    #[test]
6936    fn tool_policy_applies_to_rust_and_js_active_names() {
6937        let names = vec![
6938            "read".to_string(),
6939            "ask_user_question".to_string(),
6940            "write".to_string(),
6941        ];
6942
6943        let args = Args {
6944            tools: Some(vec!["read".into(), "ask_user_question".into()]),
6945            ..Args::default()
6946        };
6947        assert_eq!(
6948            filter_active_tool_names(names.clone(), &args),
6949            vec!["read", "ask_user_question"]
6950        );
6951
6952        let args = Args {
6953            exclude_tools: Some(vec!["ask_user_question".into()]),
6954            ..Args::default()
6955        };
6956        assert_eq!(
6957            filter_active_tool_names(names.clone(), &args),
6958            vec!["read", "write"]
6959        );
6960
6961        let args = Args {
6962            no_tools: true,
6963            ..Args::default()
6964        };
6965        assert!(filter_active_tool_names(names, &args).is_empty());
6966    }
6967
6968    #[test]
6969    fn select_ephemeral_when_no_session() {
6970        let args = Args {
6971            no_session: true,
6972            ..Args::default()
6973        };
6974        let cwd = Path::new("/tmp");
6975        assert!(matches!(
6976            select_session(&args, cwd),
6977            SessionSelection::Ephemeral
6978        ));
6979    }
6980
6981    #[test]
6982    fn project_resources_load_by_default_and_allow_explicit_opt_out() {
6983        let defaults = Args::default();
6984        assert!(resolve_project_trust(
6985            &defaults,
6986            Path::new("C:/definitely-not-a-project")
6987        ));
6988
6989        let denied = Args {
6990            trust_override: Some(false),
6991            ..Args::default()
6992        };
6993        assert!(!resolve_project_trust(
6994            &denied,
6995            Path::new("C:/definitely-not-a-project")
6996        ));
6997    }
6998
6999    #[tokio::test(flavor = "current_thread")]
7000    async fn build_preserves_the_supplied_startup_project_snapshot() {
7001        struct RestoreConfigDir(Option<std::ffi::OsString>);
7002
7003        impl Drop for RestoreConfigDir {
7004            fn drop(&mut self) {
7005                match self.0.take() {
7006                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
7007                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
7008                }
7009            }
7010        }
7011
7012        let _guard = crate::config::test_support::env_lock().lock().unwrap();
7013        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
7014        let tmp = tempfile::tempdir().unwrap();
7015        let agent = tmp.path().join("agent");
7016        let cwd = tmp.path().join("project");
7017        std::fs::create_dir_all(&agent).unwrap();
7018        std::fs::create_dir_all(&cwd).unwrap();
7019        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
7020
7021        let resolved = crate::provider::resolve(
7022            &crate::config::AgentHome::process(),
7023            Some("anthropic"),
7024            Some(crate::provider::DEFAULT_MODEL_ID),
7025            None,
7026            Some("test-key"),
7027            None,
7028        )
7029        .unwrap();
7030        let args = Args {
7031            trust_override: Some(false),
7032            no_session: true,
7033            no_tools: true,
7034            no_extensions: true,
7035            no_skills: true,
7036            no_prompt_templates: true,
7037            no_context_files: true,
7038            system_prompt: Some("test prompt".into()),
7039            ..Args::default()
7040        };
7041
7042        let (_, _, context) = build(
7043            &crate::config::AgentHome::process(),
7044            &resolved,
7045            &args,
7046            &cwd,
7047            true,
7048        )
7049        .await
7050        .unwrap();
7051
7052        assert_eq!(context.cwd, cwd);
7053        assert!(context.project_trusted);
7054    }
7055
7056    #[tokio::test(flavor = "current_thread")]
7057    async fn build_applies_the_name_flag_to_the_session() {
7058        struct RestoreConfigDir(Option<std::ffi::OsString>);
7059
7060        impl Drop for RestoreConfigDir {
7061            fn drop(&mut self) {
7062                match self.0.take() {
7063                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
7064                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
7065                }
7066            }
7067        }
7068
7069        let _guard = crate::config::test_support::env_lock().lock().unwrap();
7070        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
7071        let tmp = tempfile::tempdir().unwrap();
7072        let agent = tmp.path().join("agent");
7073        let cwd = tmp.path().join("project");
7074        std::fs::create_dir_all(&agent).unwrap();
7075        std::fs::create_dir_all(&cwd).unwrap();
7076        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
7077
7078        let resolved = crate::provider::resolve(
7079            &crate::config::AgentHome::process(),
7080            Some("anthropic"),
7081            Some(crate::provider::DEFAULT_MODEL_ID),
7082            None,
7083            Some("test-key"),
7084            None,
7085        )
7086        .unwrap();
7087        let args = Args {
7088            trust_override: Some(false),
7089            no_tools: true,
7090            no_extensions: true,
7091            no_skills: true,
7092            no_prompt_templates: true,
7093            no_context_files: true,
7094            system_prompt: Some("test prompt".into()),
7095            name: Some("smoke name".into()),
7096            session_dir: Some(cwd.join("sessions")),
7097            ..Args::default()
7098        };
7099
7100        let (harness, _, _) = build(
7101            &crate::config::AgentHome::process(),
7102            &resolved,
7103            &args,
7104            &cwd,
7105            true,
7106        )
7107        .await
7108        .unwrap();
7109        assert_eq!(
7110            harness.get_name().await.unwrap().as_deref(),
7111            Some("smoke name")
7112        );
7113    }
7114
7115    #[test]
7116    fn select_latest_for_continue_and_resume() {
7117        let _env = crate::config::test_support::SessionDirEnv::new(None);
7118        let args = Args {
7119            continue_session: true,
7120            ..Args::default()
7121        };
7122        let cwd = Path::new("/tmp");
7123        assert!(matches!(
7124            select_session(&args, cwd),
7125            SessionSelection::Latest { .. }
7126        ));
7127
7128        let args = Args {
7129            resume: true,
7130            ..Args::default()
7131        };
7132        assert!(matches!(
7133            select_session(&args, cwd),
7134            SessionSelection::Latest { .. }
7135        ));
7136    }
7137
7138    #[test]
7139    fn select_by_id_for_session_flag() {
7140        let _env = crate::config::test_support::SessionDirEnv::new(None);
7141        let args = Args {
7142            session: Some("01a02ece".into()),
7143            ..Args::default()
7144        };
7145        let cwd = Path::new("/tmp");
7146        assert!(matches!(
7147            select_session(&args, cwd),
7148            SessionSelection::ById { id, .. } if id == "01a02ece"
7149        ));
7150    }
7151
7152    /// The cut flags have to survive selection: `select_session_in_dir` is the
7153    /// only place that copies them off `Args`, so a dropped field here would
7154    /// make `--fork-entry` silently fork at the lane leaf again.
7155    #[test]
7156    fn select_fork_carries_the_cut_flags() {
7157        use rpi_harness::session::types::ForkPosition;
7158
7159        let _env = crate::config::test_support::SessionDirEnv::new(None);
7160        let cwd = Path::new("/tmp");
7161
7162        // No cut: both stay absent so the build uses the harness defaults.
7163        let args = Args {
7164            fork: Some("parent".into()),
7165            ..Args::default()
7166        };
7167        match select_session(&args, cwd) {
7168            SessionSelection::Fork {
7169                source,
7170                entry_id,
7171                position,
7172                ..
7173            } => {
7174                assert_eq!(source, "parent");
7175                assert_eq!(entry_id, None);
7176                assert_eq!(position, None);
7177            }
7178            other => panic!("expected Fork, got {other:?}"),
7179        }
7180
7181        for (flag, expected) in [
7182            (None, None),
7183            (Some(ForkPosition::At), Some(ForkPosition::At)),
7184            (Some(ForkPosition::Before), Some(ForkPosition::Before)),
7185        ] {
7186            let args = Args {
7187                fork: Some("parent".into()),
7188                fork_entry: Some("message-2".into()),
7189                fork_position: flag,
7190                ..Args::default()
7191            };
7192            match select_session(&args, cwd) {
7193                SessionSelection::Fork {
7194                    entry_id, position, ..
7195                } => {
7196                    assert_eq!(entry_id.as_deref(), Some("message-2"));
7197                    assert_eq!(position, expected, "{flag:?}");
7198                }
7199                other => panic!("expected Fork, got {other:?}"),
7200            }
7201        }
7202    }
7203
7204    #[test]
7205    fn select_new_with_custom_dir() {
7206        let _env = crate::config::test_support::SessionDirEnv::new(None);
7207        let args = Args {
7208            session_dir: Some(PathBuf::from("/tmp/sess")),
7209            ..Args::default()
7210        };
7211        let cwd = Path::new("/tmp");
7212        match select_session(&args, cwd) {
7213            SessionSelection::New { dir, .. } => assert_eq!(dir, PathBuf::from("/tmp/sess")),
7214            other => panic!("expected New, got {other:?}"),
7215        }
7216    }
7217
7218    #[test]
7219    fn select_new_default_dir() {
7220        let _env = crate::config::test_support::SessionDirEnv::new(None);
7221        let args = Args::default();
7222        let cwd = Path::new("/proj");
7223        match select_session(&args, cwd) {
7224            SessionSelection::New { dir, .. } => {
7225                assert_eq!(dir, Path::new("/proj/.rpi/sessions"));
7226            }
7227            other => panic!("expected New, got {other:?}"),
7228        }
7229    }
7230
7231    #[test]
7232    fn default_session_dir_only_uses_rpi() {
7233        let _env = crate::config::test_support::SessionDirEnv::new(None);
7234        let tmp = tempfile::tempdir().unwrap();
7235        let cwd = tmp.path();
7236        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
7237        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
7238        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
7239        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
7240    }
7241
7242    #[test]
7243    fn default_session_dir_uses_env_var() {
7244        let tmp = tempfile::tempdir().unwrap();
7245        let cwd = tmp.path();
7246        let custom = tmp.path().join("custom_sessions");
7247        let _env = crate::config::test_support::SessionDirEnv::new(Some(&custom));
7248        assert_eq!(default_session_dir(cwd), custom);
7249    }
7250
7251    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7252    async fn ephemeral_session_builds_roundtrips() {
7253        // Sanity: the ephemeral path produces a usable Session facade (the
7254        // harness build itself needs a provider; tested via the integration
7255        // path in tests/build.rs instead).
7256        let s = ephemeral_session();
7257        let leaf = s.get_leaf_id().await;
7258        assert!(leaf.is_ok());
7259    }
7260
7261    // NOTE: `build_tools`/`active_tool_names` integration is exercised by the
7262    // `tests/build.rs` harness-build test (needs a provider + multi-thread rt).
7263
7264    /// The exclusion policy, checked against the constants rather than copies.
7265    ///
7266    /// `rpi-tools` builds its exclusion from `rpi-plugin-sdk`'s declarations, so
7267    /// within this repo a rename is a compile error — this test is not the link
7268    /// between those two crates any more. What it still guards is the part the
7269    /// compiler cannot see:
7270    ///
7271    /// - **The wire values.** `rpi-langfuse` lives in a different repository and
7272    ///   agrees on the *strings*, not the constant paths. Rewriting a constant's
7273    ///   value would compile here and silently stop matching there, so the exact
7274    ///   values are pinned below. Changing one is a deliberate, breaking change to
7275    ///   a cross-repo contract, and it should fail here first.
7276    /// - **Coverage.** Every name the SDK declares must actually be excluded.
7277    /// - **Narrowness.** The user's own configuration must still reach the shell.
7278    #[test]
7279    fn host_private_env_matches_the_declared_contract() {
7280        // 1. The wire values. Pinned literally on purpose: see the doc comment.
7281        assert_eq!(rpi_plugin_sdk::SESSION_ID_ENV, "RPI_SESSION_ID");
7282        assert_eq!(
7283            rpi_plugin_sdk::SUBAGENT_PARENT_ENV,
7284            [
7285                "LANGFUSE_PI_PARENT_TRACE_ID",
7286                "LANGFUSE_PI_PARENT_SPAN_ID",
7287                "LANGFUSE_PI_PARENT_SESSION_ID",
7288                "LANGFUSE_PI_PARENT_DEPTH",
7289            ],
7290            "these strings are what rpi-langfuse (a different repo) matches; a \
7291             change here is a breaking cross-repo change, not a refactor"
7292        );
7293
7294        // 2. Coverage — derived from the declarations, so a newly added family
7295        //    member is checked without anyone remembering to extend this test.
7296        for name in rpi_plugin_sdk::SUBAGENT_PARENT_ENV
7297            .iter()
7298            .chain(std::iter::once(&rpi_plugin_sdk::SESSION_ID_ENV))
7299        {
7300            assert!(
7301                rpi_tools::is_host_private_env(name),
7302                "`{name}` must not reach a spawned shell, but rpi-tools excludes only {:?}",
7303                rpi_tools::HOST_PRIVATE_ENV
7304            );
7305        }
7306
7307        // 3. Narrowness — these name how the *user* configured the run and are
7308        //    exactly what a command inside the shell should still see.
7309        for visible in [
7310            crate::args::RPI_OFFLINE_ENV,
7311            crate::config::CONFIG_DIR_ENV,
7312            "PATH",
7313        ] {
7314            assert!(
7315                !rpi_tools::is_host_private_env(visible),
7316                "{visible} describes the user's configuration and must still reach the shell"
7317            );
7318        }
7319    }
7320    #[tokio::test]
7321    async fn reload_shutdown_joins_all_handlers_even_after_veto() {
7322        use rpi_plugin_sdk::{EventTag, StablePluginEvent};
7323        use std::sync::atomic::AtomicUsize;
7324        static CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<AtomicUsize>> =
7325            rpi_plugin_sdk::handles::ToolHandles::new();
7326        struct ContextOwner(usize);
7327        impl Drop for ContextOwner {
7328            fn drop(&mut self) {
7329                drop(CONTEXTS.remove(self.0 as rpi_plugin_sdk::StepHandle));
7330            }
7331        }
7332        extern "C" fn stop(_: StablePluginEvent, data: *mut std::ffi::c_void) -> i32 {
7333            let context = CONTEXTS.get(data).expect("live test context");
7334            let calls = context.lock().clone();
7335            std::thread::sleep(std::time::Duration::from_millis(20));
7336            if calls.fetch_add(1, Ordering::SeqCst) == 0 {
7337                rpi_plugin_sdk::EVENT_HANDLER_ABORT
7338            } else {
7339                0
7340            }
7341        }
7342        let calls = Arc::new(AtomicUsize::new(0));
7343        let context = CONTEXTS.insert(calls.clone());
7344        let _owner = ContextOwner(context as usize);
7345        let mut registry = rpi_extensions::ExtensionRegistry::new();
7346        for name in ["first", "second"] {
7347            registry.register_event_handler(name.into(), EventTag::SessionShutdown, stop, context);
7348        }
7349        super::shutdown_extensions_for_reload(
7350            Some(Arc::new(registry.snapshot())),
7351            rpi_extensions::PluginKeepalive::empty(),
7352        )
7353        .await
7354        .unwrap();
7355        assert_eq!(calls.load(Ordering::SeqCst), 2);
7356    }
7357
7358    #[tokio::test(flavor = "multi_thread")]
7359    async fn host_restore_revalidates_history_after_the_previous_writer_settles() {
7360        use rpi_harness::session::jsonl::{
7361            JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
7362        };
7363        use rpi_harness::session::{SessionValueWriter, SessionValues};
7364
7365        for reject_binding in [false, true] {
7366            let project = tempfile::tempdir().unwrap();
7367            let cwd = project.path().canonicalize().unwrap();
7368            let dir = cwd.join("sessions");
7369            let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
7370                fs: Arc::new(OsExecutionEnv::with_cwd(cwd.clone())),
7371                sessions_root: dir.to_string_lossy().into_owned(),
7372                clock: Arc::new(SystemClock),
7373                ids: Arc::new(DefaultIdGenerator::new()),
7374            });
7375            let previous = Arc::new(
7376                repo.create_typed(&JsonlSessionCreateOptions {
7377                    id: None,
7378                    parent_session_id: None,
7379                    cwd: cwd.to_string_lossy().into_owned(),
7380                    metadata: None,
7381                })
7382                .await
7383                .unwrap(),
7384            );
7385            let meta = previous.jsonl_metadata();
7386            let previous = Session::new(previous, None);
7387            let writer = SessionValueWriter::new(previous.clone());
7388            let key = if reject_binding {
7389                "rpi.resource-selection.v1"
7390            } else {
7391                "test-handoff"
7392            };
7393            let mut checks = 0;
7394            let prepared = prepare_host_restore(&repo, &meta, |values| {
7395                checks += 1;
7396                if checks == 1 {
7397                    assert!(values.get(key).is_none());
7398                    tokio::task::block_in_place(|| {
7399                        tokio::runtime::Handle::current().block_on(async {
7400                            writer
7401                                .set(key, serde_json::json!("final write"))
7402                                .await
7403                                .unwrap();
7404                            previous.drain().await;
7405                        });
7406                    });
7407                    previous.storage().release_writer_lease();
7408                } else {
7409                    assert_eq!(values.get_as::<String>(key).as_deref(), Some("final write"));
7410                }
7411                crate::resource_selection::validate_session_binding(values, None)
7412            })
7413            .await;
7414            assert_eq!(checks, 2);
7415            if reject_binding {
7416                let Err(error) = prepared else {
7417                    panic!("Host accepted an invalid binding from the final write");
7418                };
7419                assert!(error
7420                    .to_string()
7421                    .contains("invalid persisted resource binding"));
7422                let lease_probe = repo.prepare_restore_by_jsonl_metadata(&meta).await.unwrap();
7423                assert!(lease_probe
7424                    .reserve_current_writer()
7425                    .await
7426                    .unwrap()
7427                    .is_some());
7428            } else {
7429                let selection = SessionSelection::ByExactId {
7430                    id: meta.id.clone(),
7431                    dir,
7432                };
7433                let restored = restore_session(&selection, &meta.cwd, Some(prepared.unwrap()))
7434                    .await
7435                    .unwrap();
7436                assert!(restored.storage().writer_lease_held());
7437                assert_eq!(restored.storage().metadata().id, meta.id);
7438                let values = SessionValues::load(&restored).await.unwrap();
7439                assert_eq!(values.get_as::<String>(key).as_deref(), Some("final write"));
7440            }
7441        }
7442    }
7443
7444    // ---- restored-session working directory ----
7445
7446    /// A restore peek must name the directory the session was created in —
7447    /// that is the whole point of recording it. Everything downstream (tool
7448    /// env, system prompt, context files, extensions) keys off the run's cwd,
7449    /// so a peek that falls back to the launch directory would leave the
7450    /// resumed agent editing files in whatever directory `rpi` happened to be
7451    /// started from.
7452    #[tokio::test]
7453    async fn a_restored_session_adopts_its_recorded_directory() {
7454        let tmp = tempfile::tempdir().unwrap();
7455        let project = tmp.path().join("project-a");
7456        let launch = tmp.path().join("launch-dir");
7457        let sessions = tmp.path().join("sessions");
7458        std::fs::create_dir_all(&project).unwrap();
7459        std::fs::create_dir_all(&launch).unwrap();
7460        std::fs::create_dir_all(&sessions).unwrap();
7461        create_jsonl_session_with_id(
7462            &sessions,
7463            &project.to_string_lossy(),
7464            Some("cwdadopt01".into()),
7465        )
7466        .await
7467        .unwrap();
7468
7469        let selection = SessionSelection::ById {
7470            id: "cwdadopt01".into(),
7471            dir: sessions.clone(),
7472        };
7473        let peeked = peek_restored_session_cwd(&selection, &launch)
7474            .await
7475            .expect("a resumable session with a recorded cwd");
7476        assert_eq!(peeked.recorded, project);
7477        assert_eq!(peeked.adopted, Some(project));
7478    }
7479
7480    /// A recorded directory that no longer exists must NOT be adopted: the run
7481    /// falls back to the launch cwd, and the peek hands back the record so the
7482    /// host can say so (instead of the old behaviour of eprintln-ing mid-TUI).
7483    #[tokio::test]
7484    async fn a_missing_recorded_directory_is_reported_not_adopted() {
7485        let tmp = tempfile::tempdir().unwrap();
7486        let gone = tmp.path().join("project-gone");
7487        let launch = tmp.path().join("launch-dir");
7488        let sessions = tmp.path().join("sessions");
7489        std::fs::create_dir_all(&launch).unwrap();
7490        std::fs::create_dir_all(&sessions).unwrap();
7491        create_jsonl_session_with_id(
7492            &sessions,
7493            &gone.to_string_lossy(),
7494            Some("cwdgone001".into()),
7495        )
7496        .await
7497        .unwrap();
7498
7499        let selection = SessionSelection::ById {
7500            id: "cwdgone001".into(),
7501            dir: sessions.clone(),
7502        };
7503        let peeked = peek_restored_session_cwd(&selection, &launch)
7504            .await
7505            .expect("the session itself is resumable");
7506        assert_eq!(peeked.recorded, gone);
7507        assert_eq!(peeked.adopted, None);
7508        let note = crate::session_cwd::missing_session_cwd_note(&peeked.recorded, &launch);
7509        assert!(note.contains("no longer exists"), "{note}");
7510        assert!(note.contains("launch-dir"), "{note}");
7511    }
7512
7513    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7514    async fn legacy_progress_upgrade_normal_open_runs_and_reopens() {
7515        use rpi_ai::providers::faux::{FauxProvider, FauxScript};
7516        use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
7517        use rpi_harness::session::jsonl::{
7518            encode_header, JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
7519            JsonlV4Header,
7520        };
7521        let tmp = tempfile::tempdir().unwrap();
7522        let sessions = tmp.path().join("sessions");
7523        std::fs::create_dir_all(&sessions).unwrap();
7524        let cwd = tmp.path().to_string_lossy().into_owned();
7525        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
7526            fs: Arc::new(OsExecutionEnv::with_cwd(tmp.path().into())),
7527            sessions_root: sessions.to_string_lossy().into_owned(),
7528            clock: Arc::new(SystemClock),
7529            ids: Arc::new(DefaultIdGenerator::new()),
7530        });
7531        let fixture = repo
7532            .create_typed(&JsonlSessionCreateOptions {
7533                id: Some("legacycli001".into()),
7534                parent_session_id: None,
7535                cwd: cwd.clone(),
7536                metadata: None,
7537            })
7538            .await
7539            .unwrap();
7540        let path = PathBuf::from(fixture.jsonl_metadata().path);
7541        drop(fixture);
7542        let sidecar = PathBuf::from(format!("{}.progress.jsonl", path.display()));
7543        std::fs::remove_file(&sidecar).unwrap();
7544        let header = JsonlV4Header::new("legacycli001".into(), 1, cwd.clone(), None, None, None);
7545        std::fs::write(&path, encode_header(&header)).unwrap();
7546        assert!(!sidecar.exists());
7547        for attempt in 0..2 {
7548            let restored = open_session_by_id_in_dir("legacycli001", &cwd, &sessions)
7549                .await
7550                .map_err(|e| e.to_string())
7551                .unwrap();
7552            // Hold the binding so the OS writer lease can be retired explicitly
7553            // below. Dropping the harness is NOT enough: any surviving `Arc` to
7554            // the storage keeps the lease alive until the last handle goes away,
7555            // so the next `open` of the SAME journal could still observe
7556            // "writer lease is already held". That ordering is not
7557            // deterministic, which is exactly how this test flaked under CI
7558            // concurrency.
7559            let storage = restored.session.storage();
7560            assert_eq!(storage.metadata().id, "legacycli001");
7561            assert!(
7562                storage.writer_lease_held(),
7563                "reopened binding must own the journal (attempt {attempt})"
7564            );
7565            let provider =
7566                FauxProvider::new(FauxScript::new().with_text("continued legacy session"));
7567            let harness = AgentHarness::create(AgentHarnessOptions {
7568                model: provider.default_model().clone(),
7569                models: vec![provider],
7570                session: restored.session,
7571                allow_existing_session: true,
7572                ..Default::default()
7573            })
7574            .await
7575            .unwrap();
7576            let run = harness.prompt_text("continue", vec![]).await.unwrap();
7577            assert!(matches!(run.outcome, HarnessRunOutcome::Completed { .. }));
7578            // Retire this binding before the next iteration reopens the journal.
7579            // `release_writer_lease` bumps the revocation flag and drops the OS
7580            // lease box, so ownership is released now rather than whenever the
7581            // last storage handle happens to be dropped.
7582            drop(run);
7583            drop(harness);
7584            storage.release_writer_lease();
7585            assert!(
7586                !storage.writer_lease_held(),
7587                "retired binding must not retain the writer lease"
7588            );
7589        }
7590        let content = std::fs::read_to_string(&path).unwrap();
7591        assert!(content.lines().next().unwrap().contains("progressFormat"));
7592        assert!(sidecar.exists());
7593    }
7594
7595    /// `open_session` hands back the recorded directory as data (for the
7596    /// `/session` hot-switch notes) while still opening the session normally.
7597    #[tokio::test]
7598    async fn open_session_reports_the_recorded_directory() {
7599        let tmp = tempfile::tempdir().unwrap();
7600        let project = tmp.path().join("project-open");
7601        let launch = tmp.path().join("launch-dir");
7602        let sessions = tmp.path().join("sessions");
7603        std::fs::create_dir_all(&project).unwrap();
7604        std::fs::create_dir_all(&launch).unwrap();
7605        std::fs::create_dir_all(&sessions).unwrap();
7606        create_jsonl_session_with_id(
7607            &sessions,
7608            &project.to_string_lossy(),
7609            Some("cwdopen001".into()),
7610        )
7611        .await
7612        .unwrap();
7613
7614        let restored =
7615            open_session_by_id_in_dir("cwdopen001", &launch.to_string_lossy(), &sessions)
7616                .await
7617                .map_err(|error| error.to_string())
7618                .unwrap();
7619        assert_eq!(restored.recorded_cwd, Some(project.clone()));
7620        assert_eq!(restored.session.storage().metadata().id, "cwdopen001");
7621    }
7622
7623    #[tokio::test]
7624    async fn the_peeked_session_is_the_one_the_build_opens() {
7625        let tmp = tempfile::tempdir().unwrap();
7626        let first_project = tmp.path().join("project-first");
7627        let second_project = tmp.path().join("project-second");
7628        let launch = tmp.path().join("launch-dir");
7629        let sessions = tmp.path().join("sessions");
7630        for dir in [&first_project, &second_project, &launch, &sessions] {
7631            std::fs::create_dir_all(dir).unwrap();
7632        }
7633        create_jsonl_session_with_id(
7634            &sessions,
7635            &first_project.to_string_lossy(),
7636            Some("cwdrace001".into()),
7637        )
7638        .await
7639        .unwrap();
7640
7641        let args = Args {
7642            continue_session: true,
7643            session_dir: Some(sessions.clone()),
7644            ..Default::default()
7645        };
7646        let selection = select_session_in_dir(&args, sessions.clone());
7647        let peeked = peek_restored_session_cwd(&selection, &launch)
7648            .await
7649            .expect("a resumable session");
7650        assert_eq!(peeked.adopted, Some(first_project.clone()));
7651
7652        // A newer file with the same ID appears in another workspace.
7653        let second_cwd = second_project.to_string_lossy();
7654        create_jsonl_session_with_id(&sessions, &second_cwd, Some(peeked.id.clone()))
7655            .await
7656            .unwrap();
7657        let newer =
7658            list_session_metadata_in_scope_in_dir(&second_cwd, &sessions, SessionScope::Project)
7659                .await
7660                .unwrap()
7661                .pop()
7662                .unwrap();
7663        let newer = PathBuf::from(newer.path);
7664        std::fs::File::options()
7665            .write(true)
7666            .open(&newer)
7667            .unwrap()
7668            .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(2))
7669            .unwrap();
7670        let newer = newer.canonicalize().unwrap();
7671        let home = crate::config::AgentHome::from_option(Some(tmp.path().join("agent"))).unwrap();
7672        let cwd = first_project.to_string_lossy();
7673        let duplicate = find_session_metadata(&peeked.id, &cwd, &sessions)
7674            .await
7675            .unwrap_err();
7676        assert!(duplicate.to_string().contains("multiple saved sessions"));
7677        let (
7678            _,
7679            SessionPreflight {
7680                selection,
7681                prepared_restore: prepared,
7682                ..
7683            },
7684        ) = preflight_extension_startup_with_restore(
7685            &home,
7686            &args,
7687            &first_project,
7688            false,
7689            true,
7690            Some(&peeked),
7691        )
7692        .unwrap();
7693        assert_eq!(
7694            Path::new(&prepared.as_ref().unwrap().metadata().path),
7695            peeked.path
7696        );
7697        let reopened = restore_session(&selection, &cwd, prepared).await.unwrap();
7698        assert_eq!(reopened.storage().metadata().id, peeked.id);
7699        drop(reopened);
7700
7701        let (
7702            _,
7703            SessionPreflight {
7704                selection,
7705                prepared_restore: prepared,
7706                ..
7707            },
7708        ) = preflight_extension_startup_with_restore(
7709            &home,
7710            &args,
7711            &first_project,
7712            false,
7713            true,
7714            Some(&peeked),
7715        )
7716        .unwrap();
7717        std::fs::remove_file(&peeked.path).unwrap();
7718        let missing_before_preflight = preflight_extension_startup_with_restore(
7719            &home,
7720            &args,
7721            &first_project,
7722            false,
7723            true,
7724            Some(&peeked),
7725        );
7726        assert!(matches!(
7727            missing_before_preflight,
7728            Err(BuildError::SessionOpen(_))
7729        ));
7730        assert!(restore_session(&selection, &cwd, prepared).await.is_err());
7731        let remaining = list_session_metadata_in_dir(&cwd, &sessions).await.unwrap();
7732        assert_eq!(remaining.len(), 1);
7733        assert_eq!(remaining[0].id, peeked.id);
7734        assert_eq!(Path::new(&remaining[0].path).canonicalize().unwrap(), newer);
7735    }
7736
7737    /// Trust must be resolved against the directory it is asked about. A
7738    /// session recorded in another project must not inherit the launch
7739    /// directory's decision — that would run an untrusted project's settings,
7740    /// skills, and context files with trusted privileges.
7741    #[test]
7742    fn trust_is_resolved_per_directory() {
7743        struct RestoreConfigDir(Option<std::ffi::OsString>);
7744
7745        impl Drop for RestoreConfigDir {
7746            fn drop(&mut self) {
7747                match self.0.take() {
7748                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
7749                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
7750                }
7751            }
7752        }
7753
7754        let _guard = crate::config::test_support::env_lock().lock().unwrap();
7755        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
7756        let tmp = tempfile::tempdir().unwrap();
7757        let agent = tmp.path().join("agent");
7758        std::fs::create_dir_all(&agent).unwrap();
7759        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
7760
7761        let untrusted = tmp.path().join("project-untrusted");
7762        let launch = tmp.path().join("project-launch");
7763        std::fs::create_dir_all(&untrusted).unwrap();
7764        std::fs::create_dir_all(&launch).unwrap();
7765        crate::config::set_project_trust(&untrusted, Some(false)).unwrap();
7766
7767        let args = Args::default();
7768        assert!(!resolve_project_trust(&args, &untrusted));
7769        // A directory with no stored decision loads by default.
7770        assert!(resolve_project_trust(&args, &launch));
7771    }
7772}
7773
7774#[cfg(test)]
7775#[path = "session/experimental_dialog_continuity_tests.rs"]
7776mod experimental_dialog_continuity_tests;
7777#[cfg(test)]
7778#[path = "session/experimental_reload_continuity_tests.rs"]
7779mod experimental_reload_continuity_tests;