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(OsExecutionEnv::with_cwd(cwd.to_path_buf()));
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        catalog: Arc::new(std::sync::RwLock::new(catalog)),
1793        providers,
1794        runtime: runtime.clone(),
1795        cwd: cwd.to_path_buf(),
1796        project_trusted,
1797        discovered_theme_paths: Arc::new(std::sync::Mutex::new(discovered.theme_paths.clone())),
1798        args: reload_args,
1799        home: home.clone(),
1800        resolved_model: resolved.model.clone(),
1801        broadcast: broadcast_for_context,
1802        mailbox: reload_mailbox,
1803        ui_dialog: ui_dialog_mailbox,
1804        ext_status: ext_status_mailbox,
1805        editor_text: editor_text_mailbox,
1806        dev_extension: None,
1807        startup_notices: Vec::new(),
1808    };
1809
1810    Ok((harness, event_rx, reload_context))
1811}
1812
1813/// Project authoritative harness termination, not per-attempt AgentEnd, to
1814/// plugins. The bus owns this listener; its session cell follows reloads and
1815/// retains callback libraries, while the action host binds the harness weakly.
1816fn install_extension_settlement_bridge(
1817    events: &rpi_harness::events::HarnessEventBus,
1818    sessions: ExtensionSessionCell,
1819) {
1820    events.on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |event| {
1821        if event.lane != "main" {
1822            return;
1823        }
1824        let session = sessions.lock().unwrap().clone();
1825        if let Some(snapshot) = session.snapshot_arc() {
1826            rpi_extensions::dispatch_empty_event(&snapshot, rpi_plugin_sdk::EventTag::AgentSettled);
1827        }
1828    });
1829}
1830
1831/// Resolve the current plugin session for each call rather than keeping a
1832/// startup snapshot. A clone retains its libraries while approval is pending.
1833fn extension_tool_call_hook(
1834    sessions: ExtensionSessionCell,
1835    ui_dialog: rpi_extensions::UiDialogMailbox,
1836) -> rpi_agent::BeforeToolCall {
1837    Arc::new(move |ctx: rpi_agent::BeforeToolCallContext<'_>, signal| {
1838        let session = sessions
1839            .lock()
1840            .map(|session| session.clone())
1841            .map_err(|_| ());
1842        let ui_dialog = ui_dialog.clone();
1843        let tool_call_id = ctx.tool_call.id.clone();
1844        let tool_name = ctx.tool_call.name.clone();
1845        let params = ctx.args.clone();
1846        Box::pin(async move {
1847            let reason = match session {
1848                Ok(session) => {
1849                    let vetoed = rpi_extensions::dispatch_tool_call_event(
1850                        &session,
1851                        &tool_call_id,
1852                        &tool_name,
1853                        &params,
1854                        &signal,
1855                        &ui_dialog,
1856                    )
1857                    .await;
1858                    match vetoed {
1859                        Some(reason) => Some(
1860                            veto_reason_via_transforms(
1861                                &session,
1862                                &tool_call_id,
1863                                &tool_name,
1864                                &params,
1865                                reason,
1866                            )
1867                            .await,
1868                        ),
1869                        None => None,
1870                    }
1871                }
1872                Err(_) => Some("extension approval session is unavailable".to_string()),
1873            };
1874            reason.map(|reason| rpi_agent::BeforeToolCallResult {
1875                block: true,
1876                reason: Some(reason),
1877                terminate: false,
1878                args: None,
1879            })
1880        })
1881    })
1882}
1883
1884/// The text that replaces a tool result when the `tool_result` transforms
1885/// could not run. A plugin may use the transforms to remove values the model
1886/// must not see, so the host fails closed instead of passing the result on.
1887const TOOL_RESULT_WITHHELD: &str =
1888    "[tool result withheld: the extension tool_result transforms could not run]";
1889
1890/// Run the plugin `tool_result` transforms over one result on a blocking
1891/// thread. `None` means no transform is registered. When a transform ran, an
1892/// unchanged result is still returned so the caller can distinguish it from a
1893/// skipped dispatch.
1894async fn run_tool_result_transforms(
1895    session: &ExtensionSession,
1896    tool_call_id: String,
1897    tool_name: String,
1898    input: serde_json::Value,
1899    result: rpi_agent::AgentToolResult,
1900    is_error: bool,
1901) -> Option<rpi_agent::AgentToolResult> {
1902    let snapshot = session.snapshot_arc()?;
1903    if snapshot.tool_result().is_empty() {
1904        return None;
1905    }
1906    let keepalive = session.keepalive();
1907    let withheld = rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD);
1908    let transformed = tokio::task::spawn_blocking(move || {
1909        // A started blocking callback outlives a dropped awaiter: keep the
1910        // plugin libraries loaded until every handler has returned.
1911        let _keepalive = keepalive;
1912        if !snapshot.is_active() {
1913            return rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD);
1914        }
1915        match rpi_extensions::emit_tool_result_with_status(
1916            &tool_call_id,
1917            &tool_name,
1918            &input,
1919            &result,
1920            is_error,
1921            &snapshot,
1922        ) {
1923            Ok(Some(changed)) => changed,
1924            Ok(None) => result,
1925            // A concurrent /reload invalidated the snapshot before the
1926            // blocking callback could dispatch. Never pass the unchecked
1927            // output to the model: it may still contain secrets that a
1928            // plugin's transform was supposed to remove.
1929            Err(()) => rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD),
1930        }
1931    })
1932    .await;
1933    match transformed {
1934        Ok(changed) => Some(changed),
1935        Err(_) => Some(withheld),
1936    }
1937}
1938
1939/// `after_tool_call` hook: pass every finished tool result, success or error
1940/// (a bash exit != 0 returns its output as an error result), and every fresh
1941/// immediate failure through the plugin `tool_result` transforms. Resolves the
1942/// session per call, like the tool-call hook, so it follows `/reload`; child
1943/// harnesses inherit it. A stale or unavailable session fails closed.
1944fn extension_tool_result_hook(sessions: ExtensionSessionCell) -> rpi_agent::AfterToolCall {
1945    Arc::new(move |ctx: rpi_agent::AfterToolCallContext<'_>, _signal| {
1946        let session = sessions.lock().map(|session| session.clone()).ok();
1947        let tool_call_id = ctx.tool_call.id.clone();
1948        let tool_name = ctx.tool_call.name.clone();
1949        let input = ctx.args.clone();
1950        let result = ctx.result.clone();
1951        let is_error = ctx.is_error;
1952        Box::pin(async move {
1953            let changed = match session {
1954                Some(session) => {
1955                    match run_tool_result_transforms(
1956                        &session,
1957                        tool_call_id,
1958                        tool_name,
1959                        input,
1960                        result,
1961                        is_error,
1962                    )
1963                    .await
1964                    {
1965                        Some(changed) => changed,
1966                        // No transform is registered: leave the tool's result
1967                        // untouched, including its usage and terminate fields.
1968                        None => return None,
1969                    }
1970                }
1971                // A poisoned session lock: withhold rather than pass unchecked.
1972                None => rpi_agent::AgentToolResult::error_text(TOOL_RESULT_WITHHELD),
1973            };
1974            Some(rpi_agent::AfterToolCallResult {
1975                content: Some(changed.content),
1976                details: Some(changed.details),
1977                ..Default::default()
1978            })
1979        })
1980    })
1981}
1982
1983/// A vetoed call's reason, offered to the `tool_result` transforms as the text
1984/// of the blocked result (`isError: true`, `details: {"blocked": true}`). The
1985/// first non-empty text block of the changed result becomes the reason the
1986/// model reads, so the vetoing plugin can explain the block. With no change
1987/// the host's reason stays.
1988async fn veto_reason_via_transforms(
1989    session: &ExtensionSession,
1990    tool_call_id: &str,
1991    tool_name: &str,
1992    params: &serde_json::Value,
1993    reason: String,
1994) -> String {
1995    let mut blocked = rpi_agent::AgentToolResult::error_text(reason.clone());
1996    blocked.details = serde_json::json!({ "blocked": true });
1997    let changed = run_tool_result_transforms(
1998        session,
1999        tool_call_id.to_string(),
2000        tool_name.to_string(),
2001        params.clone(),
2002        blocked,
2003        true,
2004    )
2005    .await;
2006    changed
2007        .and_then(|result| {
2008            result.content.into_iter().find_map(|part| match part {
2009                rpi_agent::TextContentOrImage::Text(text) => {
2010                    (!text.text.trim().is_empty()).then_some(text.text)
2011                }
2012                _ => None,
2013            })
2014        })
2015        .unwrap_or(reason)
2016}
2017
2018// ===========================================================================
2019// B5d — `/reload`: re-run extension + resource discovery into a LIVE harness
2020// ===========================================================================
2021//
2022// `/reload` (interactive TUI command, or a plugin's `runtime_action(Reload)`)
2023// re-runs everything `build` did around resources/extensions WITHOUT rebuilding
2024// the `AgentHarness` itself (rebuilding would tear down the session/lane/event
2025// wiring + the broadcast drain task the TUI owns). Instead it:
2026//
2027//  1. Builds a fresh `ExtensionSession` (re-load the cdylibs) over the same
2028//     dir set, with a FRESH `ActionBridge` (the old one is `invalidate`d so
2029//     in-flight plugin→host calls on the old bridge fail fast).
2030//  2. Fans `resources_discover(_, "reload")` over the fresh snapshot.
2031//  3. Re-runs the Part-A loaders (skills/prompts/context/SYSTEM.md/
2032//     APPEND_SYSTEM.md) with the discovered paths merged in — same precedence
2033//     + `--no-*` gates as startup.
2034//  4. Rebuilds the harness's live state via the B5d setters
2035//     (`set_system_prompt`/`set_resources`/`set_agent_emitter`/`set_models`/
2036//     `set_provider_hooks`/`set_tools`) so the NEXT run observes the reloaded
2037//     config (in-flight runs finish on the old `ConfigSnapshot`).
2038//  5. Swaps the cells (`ExtensionSession`, `ActionBridge`, harness action
2039//     host's harness cell stays — the harness is the same object) and drops
2040//     the old session + bridge (their keepalives unmap the old cdylibs; the
2041//     new session's keepalive holds the fresh mappings).
2042//
2043// The reload is a `rpi-cli` concern (NOT a harness op): `rpi-extensions`
2044// carries only the `ActionBridge` staleness flag + a `ReloadMailbox` `()` signal
2045// (no pi-cli `TuiMessage` type — leaf DAG preserved). The TUI owns the mailbox
2046// receiver + the actual reload routine; a plugin's
2047// `runtime_action(Reload)` signals the mailbox and returns `Ok(null)`
2048// immediately so the calling plugin's cdylib is NOT unmapped while its
2049// `runtime_action` frame is still on the stack (the self-unmapping race a
2050// synchronous plugin-initiated reload would have).
2051//
2052// `reload_extension_resources` is the shared routine both `/reload` (TUI) and
2053// a plugin's `runtime_action(Reload)` (via the mailbox) drive. It is `pub` so
2054// the TUI's main-loop handler + the mailbox-driven path call the same code.
2055
2056/// The cell that holds the live `ExtensionSession` across a `/reload`. Cloned
2057/// into every site that needs the current session (the TUI, the reload
2058/// callback). On reload the old session is `replace`d out (its `active` flag
2059/// flipped) and the fresh one stored atomically. In-flight callbacks retain
2060/// the old keepalive until they return; callers never observe an empty
2061/// placeholder during the swap.
2062pub type ExtensionSessionCell = Arc<Mutex<ExtensionSession>>;
2063
2064/// The cell that holds the live `ActionBridge` across a `/reload`. A plugin
2065/// stores the bridge's raw `user_data` pointer during `register`; on reload the
2066/// old bridge is `invalidate`d (in-flight calls fail fast) and the fresh one
2067/// `store`d. The fresh session's plugins are handed the fresh bridge pointer.
2068pub type ActionBridgeCell = Arc<Mutex<Option<Arc<rpi_extensions::ActionBridge>>>>;
2069
2070/// Everything `/reload` needs to rebuild extension + resource state into a live
2071/// harness. Built once in [`build`] (alongside the harness) and held by the TUI
2072/// (cloned into the reload callback the bridge carries + the `/reload` command
2073/// handler). The harness itself is NOT held here — the TUI already owns a
2074/// `&AgentHarness` / a clone; passing it at the call site keeps this struct
2075/// free of a harness back-reference (so it can be `Clone` and moved into the
2076/// reload callback without borrowing the harness).
2077#[derive(Clone)]
2078pub struct ReloadContext {
2079    /// Non-owning evidence includes failed candidates and every reload generation.
2080    pub(crate) plugin_cleanup: Arc<crate::host::cli_cleanup::PluginCleanupLedger>,
2081    pub(crate) plugin_resources: Arc<crate::host::cli_resources::CliPluginResources>,
2082    host_plugin_images: Option<HostPluginImages>,
2083    /// Keep Mini's storage policy across extension reloads.
2084    ephemeral_sessions_only: bool,
2085    /// One neutral router for all built-ins, including those reconstructed on reload.
2086    pub file_io: Arc<rpi_tools::file_io::FileIORouter>,
2087    /// The live extension-session cell (swapped on reload).
2088    pub extension_session: ExtensionSessionCell,
2089    /// The process-lifetime durable-tool binding. Reloaded tool instances must
2090    /// keep the same weak harness binding as the context hook installed at startup.
2091    durable_binding: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
2092    /// The session's plugin-tool context (`cwd` + session id), reused — not
2093    /// rebuilt — on reload so the rebuilt adapters keep serving the SAME
2094    /// session. A reload that made a fresh context would leave every plugin
2095    /// tool without a session id until the next launch.
2096    pub tool_context: rpi_extensions::ToolCallContext,
2097    /// The live action-bridge cell (swapped + old invalidated on reload).
2098    pub action_bridge: ActionBridgeCell,
2099    /// The extension status registry the TUI renders in its footer (`SetStatus`).
2100    /// Lives in the context (not the cell) so it survives a bridge swap.
2101    pub ext_status: rpi_extensions::ExtensionStatusMailbox,
2102    /// The extension editor-text queue the TUI drains into the prompt editor
2103    /// (`SetEditorText`, runtime action 19). Lives in the context (not the cell)
2104    /// so it survives a bridge swap — exactly like `ext_status`. A voice plugin
2105    /// writes a transcription here as a *draft*; the TUI applies it, starts the
2106    /// optional auto-send countdown, and submits through the normal path so the
2107    /// user bubble renders as usual.
2108    pub editor_text: rpi_extensions::EditorTextMailbox,
2109    /// Shared authenticated model catalog for runtime actions and the TUI.
2110    /// Provider-package reloads replace it together with the runtime bindings.
2111    pub catalog: Arc<std::sync::RwLock<Vec<rpi_ai::Model>>>,
2112    /// Current configured provider runtimes. Replaced after package reload so
2113    /// subsequent reloads cannot recover stale plugin snapshots.
2114    pub providers: Arc<std::sync::RwLock<Vec<Arc<dyn Provider>>>>,
2115    /// The ambient runtime handle (captured in `build`) — `PluggableProvider`
2116    /// and the fresh `ActionBridge` need a captured `Handle` to spawn from any
2117    /// thread.
2118    pub runtime: tokio::runtime::Handle,
2119    /// The cwd (for static resource-dir resolution + context-file walk).
2120    pub cwd: PathBuf,
2121    /// The project-trust decision captured before provider and session setup.
2122    /// Startup consumers reuse this value so extension code cannot change the
2123    /// effective policy by mutating the process cwd while it is loading.
2124    pub project_trusted: bool,
2125    /// Theme file paths contributed by extensions via `resources_discover`,
2126    /// shared so the TUI theme registry can merge them. Filled at startup,
2127    /// replaced on every `/reload` (paths are unattributed — the v1 divergence
2128    /// documented in `rpi-extensions::resources`).
2129    pub discovered_theme_paths: Arc<std::sync::Mutex<Vec<String>>>,
2130    /// The parsed args (cloned) — `--no-*`/`--tools`/`--exclude-tools`/
2131    /// `--extensions-dir`/`--no-extensions`/`--system-prompt`/etc all apply on
2132    /// reload exactly as at startup (a reload re-reads the same flags; it does
2133    /// not pick up argv changes mid-session, which is the right contract — pi's
2134    /// `/reload` re-runs discovery with the same config). `session_dir` holds
2135    /// the resolved startup root, including saved settings/environment defaults.
2136    pub args: Args,
2137    /// The session's agent home. `/reload` must re-read resources and settings
2138    /// from this value, never from a startup snapshot or the process home.
2139    pub home: crate::config::AgentHome,
2140    /// The resolved model + thinking level (the harness's active model stays
2141    /// unless `set_model` changed it; reload does not touch the model).
2142    pub resolved_model: rpi_ai::Model,
2143    /// The broadcast emitter the harness was built with. Reload rebuilds the
2144    /// `TeeEmitter` over the fresh `ExtensionEmitter` (the old tee's extension
2145    /// child is dropped, unsubscribing from the old registry). The broadcast
2146    /// half stays live the whole session (the TUI's drain task holds the
2147    /// receiver), so we keep a handle to re-wrap.
2148    pub broadcast: Arc<dyn rpi_agent::AgentEmitter>,
2149    /// The session-long reload mailbox (B5d). Build creates one, installs it on
2150    /// the initial `ActionBridge` via [`reload_callback_from_mailbox`], and hands
2151    /// a clone to the TUI. The TUI installs its `TuiMessage` sender so a plugin's
2152    /// `runtime_action(Reload)` signals the main loop — the reload routine reuses
2153    /// THIS mailbox (not a fresh default) when building the fresh bridge, so the
2154    /// bridge always carries the mailbox the TUI installed across reloads.
2155    pub mailbox: rpi_extensions::ReloadMailbox,
2156    /// Session-long UI-dialog mailbox (runtime action 17). The initial bridge
2157    /// carries it; the TUI attaches itself and polls `take_pending` from its key
2158    /// loop, and `/reload` reuses THIS mailbox when it builds the fresh bridge.
2159    /// A detached mailbox makes `ask_user` fail with "requires an interactive
2160    /// UI" (headless contract).
2161    pub ui_dialog: rpi_extensions::UiDialogMailbox,
2162    /// Active `rpi dev` extension builder. `/reload` rebuilds it before
2163    /// swapping plugin sessions; its watcher signals `mailbox` after a
2164    /// successful background build.
2165    pub dev_extension: Option<Arc<crate::dev_extension::DevExtension>>,
2166    /// One-line notices the host should show at startup (a session directory
2167    /// that fell back, an untrusted adopted directory). Filled by the CLI after
2168    /// the build and rendered as transcript notes in the TUI; headless modes
2169    /// print them to stderr. Kept as data — never `eprintln!`d from here, which
2170    /// would corrupt the alternate screen (issue #115).
2171    pub startup_notices: Vec<String>,
2172}
2173
2174impl ReloadContext {
2175    pub(crate) fn session_dir(&self) -> PathBuf {
2176        // The fallback also supports contexts constructed by embedding hosts.
2177        self.args
2178            .session_dir
2179            .clone()
2180            .unwrap_or_else(|| configured_session_dir_for(&self.home, &self.args, &self.cwd))
2181    }
2182}
2183
2184/// Dispatch a no-payload lifecycle event using the live extension-session cell.
2185///
2186/// This is the cell-based counterpart to [`dispatch_session_event_async`]. It
2187/// lets headless RPC tasks retain the live session without borrowing the larger
2188/// [`ReloadContext`]. The snapshot and keepalive are cloned before awaiting, so
2189/// a concurrent `/reload` neither invalidates the plugin function pointers
2190/// mid-dispatch nor keeps a swapped-out registry alive.
2191///
2192/// Each handler runs on a blocking thread with a per-event timeout
2193/// ([`rpi_extensions::lifecycle_timeout_for`]); a handler returning
2194/// [`rpi_plugin_sdk::EVENT_HANDLER_ABORT`] is reported as `Some(reason)`.
2195/// Returns `None` when no plugins are loaded, no handler subscribes, or the
2196/// registry is stale (a `/reload` swapped the session out).
2197pub async fn dispatch_session_event_from_cell(
2198    extension_session: &ExtensionSessionCell,
2199    tag: rpi_plugin_sdk::EventTag,
2200) -> Option<String> {
2201    let (snapshot, keepalive) = {
2202        // A poisoned cell must not panic the caller (the TUI loop dispatches
2203        // these events between UI actions): the session contents are only ever
2204        // replaced wholesale, so recovering the guard is safe.
2205        let session = extension_session
2206            .lock()
2207            .unwrap_or_else(|error| error.into_inner());
2208        (session.snapshot_arc(), session.keepalive())
2209    };
2210    match snapshot {
2211        Some(snapshot) => rpi_extensions::dispatch_lifecycle_event(&snapshot, tag, keepalive).await,
2212        None => None,
2213    }
2214}
2215
2216/// Dispatch a no-payload lifecycle event through the current reload context.
2217///
2218/// Resolves the **current** extension session from the reload cell so a
2219/// `/reload`-swapped session is honored. The caller decides what a veto means:
2220/// a `BeforeTuiStart` veto aborts startup (never enter the TUI);
2221/// `SessionStart`/`SessionShutdown` and the session-tree events dispatched by
2222/// the interactive TUI and RPC paths are advisory — the host logs the reason
2223/// and continues.
2224pub async fn dispatch_session_event_async(
2225    reload_context: &ReloadContext,
2226    tag: rpi_plugin_sdk::EventTag,
2227) -> Option<String> {
2228    dispatch_session_event_from_cell(&reload_context.extension_session, tag).await
2229}
2230
2231/// Join plugin teardown before unloading modules. A detached timed-out handler
2232/// could still execute code in the old DLL, so it cannot safely permit a swap.
2233async fn shutdown_extensions_for_reload(
2234    snapshot: Option<Arc<rpi_extensions::RegistrySnapshot>>,
2235    keepalive: Arc<rpi_extensions::PluginKeepalive>,
2236) -> Result<(), String> {
2237    if let Some(snapshot) = snapshot {
2238        tokio::task::spawn_blocking(move || {
2239            let _keepalive = keepalive;
2240            rpi_extensions::dispatch_empty_event(
2241                &snapshot,
2242                rpi_plugin_sdk::EventTag::SessionShutdown,
2243            );
2244        })
2245        .await
2246        .map_err(|error| error.to_string())?;
2247    }
2248    Ok(())
2249}
2250
2251/// The outcome of a reload: a human-readable status line for the transcript
2252/// (counts of what reloaded), and whether any load diagnostics appeared.
2253pub struct ReloadOutcome {
2254    /// One-line summary for the transcript note (e.g. "Reloaded 2 plugin(s),
2255    /// 5 skill(s), 1 prompt(s).").
2256    pub summary: String,
2257    /// True iff at least one extension load warning fired (ABI mismatch / skip).
2258    pub had_warnings: bool,
2259    /// Formatted diagnostic lines (extension / package / skill / prompt-template warnings)
2260    /// that the caller should surface in its UI. Kept out of `eprintln!`
2261    /// because the TUI owns the terminal: direct stderr writes during a run
2262    /// would corrupt the alternate-screen input row.
2263    pub details: Vec<String>,
2264    /// True iff the reload itself failed hard (e.g. the extension build or
2265    /// settings reload errored) and the previous resources were kept. Soft
2266    /// diagnostics (skill shadowing, name validation) do not set this.
2267    pub had_errors: bool,
2268    /// The project-trust policy this reload actually resolved and applied.
2269    /// `None` when the reload failed hard and kept the previous resources, so
2270    /// consumers (e.g. theme discovery) should stay on the snapshot they
2271    /// already match instead of re-reading a stale startup bool.
2272    pub project_trusted: Option<bool>,
2273}
2274
2275struct PreparedReloadInputs {
2276    extension_dirs: Vec<PathBuf>,
2277    skill_base_dirs: Vec<PathBuf>,
2278    prompt_base_dirs: Vec<PathBuf>,
2279}
2280
2281/// Append the resource sources that are specific to a reload after the
2282/// conventional project/global directories. Keep this order aligned with the
2283/// initial build: explicit CLI paths must remain available after `/reload`,
2284/// while discovered and package resources retain their lower precedence.
2285fn append_reload_resource_paths(
2286    mut paths: Vec<PathBuf>,
2287    explicit: &[PathBuf],
2288    discovered: &[String],
2289    js_paths: &[PathBuf],
2290    package_paths: &[PathBuf],
2291) -> Vec<PathBuf> {
2292    paths.extend(explicit.iter().cloned());
2293    paths.extend(discovered.iter().map(PathBuf::from));
2294    paths.extend(js_paths.iter().cloned());
2295    paths.extend(package_paths.iter().cloned());
2296    paths
2297}
2298
2299/// Re-run extension + resource discovery and push the rebuilt state into the
2300/// live `harness` via the B5d setters. The old `ExtensionSession` +
2301/// `ActionBridge` are invalidated + swapped in [`ReloadContext`]'s cells. This
2302/// is the single routine both `/reload` (TUI) and a plugin's
2303/// `runtime_action(Reload)` drive (the latter via the mailbox signal).
2304///
2305/// Returns a [`ReloadOutcome`] for the transcript. Best-effort: a failure in
2306/// one channel (e.g. a plugin that fails to reload) does not abort the others —
2307/// the reload completes with whatever loaded, mirroring pi's per-plugin
2308/// skip-on-error. A hard failure (e.g. the harness is closed) surfaces as an
2309/// error summary.
2310pub async fn reload_extension_resources(
2311    harness: &AgentHarness,
2312    ctx: &ReloadContext,
2313) -> ReloadOutcome {
2314    reload_extension_resources_inner(harness, ctx, || {}).await
2315}
2316
2317async fn reload_extension_resources_inner<F>(
2318    harness: &AgentHarness,
2319    ctx: &ReloadContext,
2320    after_prepare: F,
2321) -> ReloadOutcome
2322where
2323    F: FnOnce() + Send,
2324{
2325    if harness.has_exact_resources()
2326        || ctx.args.resource_config.is_some()
2327        || ctx.args.resource_transition.is_some()
2328    {
2329        return ReloadOutcome {
2330            summary:
2331                "Exact resource selection is restart-required; reload/dev hot apply unsupported"
2332                    .into(),
2333            had_warnings: true,
2334            details: Vec::new(),
2335            had_errors: true,
2336            project_trusted: None,
2337        };
2338    }
2339    // Fence the whole candidate preparation, including dev builds and rejected
2340    // candidates; cleanup must not seal receipts while any reload can still load.
2341    let Some(reload_permit) = ctx.plugin_resources.begin_reload().await else {
2342        return ReloadOutcome {
2343            summary: "Session resources are retiring; reload rejected".into(),
2344            had_warnings: true,
2345            details: Vec::new(),
2346            had_errors: true,
2347            project_trusted: None,
2348        };
2349    };
2350    // Resolve the arguments once for this reload. `rpi dev` may append its
2351    // freshly staged extension directory; every subsequent loader and policy
2352    // decision must observe that same effective set rather than falling back
2353    // to the pre-dev snapshot held in `ctx.args`.
2354    let mut effective_args = ctx.args.clone();
2355    if let Some(dev) = &ctx.dev_extension {
2356        if let Err(error) = dev
2357            .rebuild()
2358            .and_then(|_| dev.apply_to_args(&mut effective_args))
2359        {
2360            return ReloadOutcome {
2361                summary: format!(
2362                    "Extension build failed for {}: {error}. Keeping the currently loaded version.",
2363                    dev.package_name()
2364                ),
2365                had_warnings: true,
2366                details: Vec::new(),
2367                had_errors: true,
2368                project_trusted: None,
2369            };
2370        }
2371    }
2372    let cwd_str = ctx.cwd.to_string_lossy().to_string();
2373    let project_trusted = resolve_project_trust_for(&ctx.home, &effective_args, &ctx.cwd);
2374    if !project_trusted {
2375        ctx.tool_context.set_project_resources_allowed(false);
2376    }
2377    let prepared =
2378        match prepare_reload_inputs_for(&ctx.home, &effective_args, &ctx.cwd, project_trusted) {
2379            Ok(prepared) => prepared,
2380            Err(error) => {
2381                return ReloadOutcome {
2382                    summary: format!(
2383                        "Settings reload failed: {error}. Keeping the currently loaded resources."
2384                    ),
2385                    had_warnings: true,
2386                    details: Vec::new(),
2387                    had_errors: true,
2388                    project_trusted: None,
2389                };
2390            }
2391        };
2392    after_prepare();
2393    let PreparedReloadInputs {
2394        extension_dirs,
2395        skill_base_dirs,
2396        prompt_base_dirs,
2397    } = prepared;
2398    let mut warnings = false;
2399
2400    // ---- 1. Build a fresh ActionBridge + ExtensionSession ----
2401    // The fresh bridge carries the SAME `HarnessActionHost` (the host's harness
2402    // cell already points at this harness; the host impl is reusable across
2403    // reloads — only the bridge's staleness flag + reload callback differ). We
2404    // re-use the host by reading it off the OLD bridge (it's the same
2405    // `Arc<dyn RuntimeActionHost>`).
2406    let old_bridge = ctx.action_bridge.lock().unwrap().clone();
2407    let host: Arc<dyn rpi_extensions::RuntimeActionHost> = match &old_bridge {
2408        Some(b) => b.clone_host(),
2409        None => {
2410            // No prior bridge (no extensions ever loaded). Build a fresh host so
2411            // a reload that newly discovers plugins can still drive actions.
2412            let (action_host, _cell) = crate::extensions_actions::HarnessActionHost::new_empty(
2413                ctx.catalog
2414                    .read()
2415                    .unwrap_or_else(|error| error.into_inner())
2416                    .clone(),
2417                ctx.cwd.clone(),
2418                ctx.runtime.clone(),
2419                ctx.args.unknown_flags.clone(),
2420                ctx.tool_context.clone(),
2421            );
2422            crate::extensions_actions::HarnessActionHost::set_harness(
2423                &_cell,
2424                Arc::new(harness.clone()),
2425            );
2426            Arc::new(
2427                action_host
2428                    .with_session_dir(ctx.session_dir())
2429                    .with_ephemeral_sessions_only(ctx.ephemeral_sessions_only)
2430                    .with_process_identity(ctx.host_plugin_images.is_none())
2431                    .with_native_durable(ctx.args.native_durable),
2432            )
2433        }
2434    };
2435
2436    let reload_cb = rpi_extensions::reload_callback_from_mailbox(ctx.mailbox.clone());
2437    let publish_host = Arc::clone(&host);
2438    let fresh_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
2439        ctx.runtime.clone(),
2440        host,
2441        reload_cb,
2442        ctx.ui_dialog.clone(),
2443        ctx.ext_status.clone(),
2444        ctx.editor_text.clone(),
2445    );
2446    if ctx.host_plugin_images.is_some() {
2447        fresh_bridge.disable_stdio_claims();
2448    }
2449
2450    let diagnostics =
2451        crate::host::cli_cleanup::PluginLoadDiagnostics::new(ctx.plugin_cleanup.clone());
2452    let extension_session = if effective_args.no_extensions {
2453        rpi_extensions::ExtensionSession::none()
2454    } else {
2455        let load = || {
2456            load_extensions_from_dirs(
2457                &ctx.home,
2458                &effective_args,
2459                &extension_dirs,
2460                Some(Arc::clone(&fresh_bridge)),
2461                Some(reload_permit.host_guard()),
2462                diagnostics.clone(),
2463                ctx.host_plugin_images.as_ref(),
2464            )
2465        };
2466        if ctx.host_plugin_images.is_some() {
2467            tokio::task::block_in_place(load)
2468        } else {
2469            load()
2470        }
2471    };
2472    if effective_args.native_durable {
2473        if let Err(error) = validate_durable_extensions(&extension_session) {
2474            return ReloadOutcome {
2475                summary: "Reload rejected because an extension conflicts with native durable"
2476                    .into(),
2477                had_warnings: true,
2478                details: vec![error],
2479                had_errors: true,
2480                project_trusted: None,
2481            };
2482        }
2483    }
2484    if extension_session.is_empty() && !effective_args.no_extensions {
2485        // The fresh session may be empty if no cdylibs are present — not a
2486        // warning per se, but note it.
2487    }
2488    if effective_args.verbose {
2489        if let Some(s) = extension_session.summary() {
2490            eprintln!("reload: {s}");
2491        }
2492        report_deferred_renderers(&extension_session);
2493    }
2494
2495    let has_package_providers = |session: &ExtensionSession| {
2496        session.snapshot().is_some_and(|snapshot| {
2497            snapshot
2498                .providers()
2499                .iter()
2500                .any(|provider| snapshot.provider_manifest(&provider.provider_id).is_some())
2501        })
2502    };
2503    let packaged = has_package_providers(&extension_session)
2504        || has_package_providers(&ctx.extension_session.lock().unwrap());
2505    let refreshed = if packaged {
2506        let mut args = effective_args.clone();
2507        if let Ok(current) = harness.lane("main").get_model().await {
2508            let was_package = ctx
2509                .extension_session
2510                .lock()
2511                .unwrap()
2512                .snapshot()
2513                .is_some_and(|snapshot| snapshot.provider_manifest(&current.provider).is_some());
2514            let has_replacement = extension_session.snapshot().is_some_and(|snapshot| {
2515                snapshot
2516                    .providers()
2517                    .iter()
2518                    .any(|provider| provider.provider_id == current.provider)
2519            });
2520            if was_package && !has_replacement {
2521                return ReloadOutcome {
2522                    summary: "Reload failed while resolving provider packages".into(),
2523                    had_warnings: true,
2524                    details: vec![format!(
2525                        "active provider package '{}' is no longer loaded",
2526                        current.provider
2527                    )],
2528                    had_errors: true,
2529                    project_trusted: None,
2530                };
2531            }
2532            args.provider = Some(current.provider.clone());
2533            args.model = Some(current.id);
2534            if current.provider != ctx.resolved_model.provider {
2535                args.api_key = None;
2536                args.base_url = None;
2537            }
2538        }
2539        match crate::provider::resolve_with_extensions(
2540            &ctx.home,
2541            &args,
2542            &ctx.cwd,
2543            ctx.project_trusted,
2544            &extension_session,
2545        ) {
2546            Ok(resolved) => Some(resolved),
2547            Err(error) => {
2548                return ReloadOutcome {
2549                    summary: "Reload failed while resolving provider packages".into(),
2550                    had_warnings: true,
2551                    details: vec![error.to_string()],
2552                    had_errors: true,
2553                    project_trusted: None,
2554                }
2555            }
2556        }
2557    } else {
2558        None
2559    };
2560
2561    // Candidate loading and provider resolution above are not yet published to
2562    // the live session. Do not tell existing extensions that their session is
2563    // shutting down until every rejectable preparation step has
2564    // succeeded; otherwise a rejected candidate would leave the old registry
2565    // live after it had already received SessionShutdown. Candidate DLLs remain
2566    // held by `extension_session`, so the old module is not unloaded before its
2567    // shutdown handlers have joined.
2568    let (shutdown_snapshot, shutdown_keepalive) = {
2569        let session = ctx.extension_session.lock().unwrap();
2570        (session.snapshot_arc(), session.keepalive())
2571    };
2572    if let Err(reason) = shutdown_extensions_for_reload(shutdown_snapshot, shutdown_keepalive).await
2573    {
2574        return ReloadOutcome {
2575            summary: "Reload failed during extension shutdown".into(),
2576            had_warnings: true,
2577            details: vec![reason],
2578            had_errors: true,
2579            project_trusted: None,
2580        };
2581    }
2582
2583    // ---- 2. Invalidate the old session + bridge BEFORE the swap ----
2584    // The old registry's `active` flag flips false so any in-flight
2585    // `emit_resources_discover`/event dispatch on the old snapshot no-ops; the
2586    // old bridge's flag flips false so in-flight `runtime_action` calls parked
2587    // on the old `user_data` hit the staleness guard. Invalidate under the
2588    // session lock before exposing the replacement to approval callbacks.
2589    //
2590    // Swap directly to the fresh session under the same lock that approvals
2591    // use. A temporary empty session would let a concurrent call bypass its gate.
2592    // In-flight approvals retain their old session until their callback exits;
2593    // its staleness flag prevents them from authorizing after this swap.
2594    let old_session = {
2595        let mut session_guard = ctx.extension_session.lock().unwrap();
2596        let old_session = std::mem::replace(&mut *session_guard, extension_session.clone());
2597        if let Some(old_snap) = old_session.snapshot_arc() {
2598            // `invalidate` is on the registry, but the snapshot shares the flag —
2599            // flipping the snapshot's flag invalidates the registry too (same Arc).
2600            // `RegistrySnapshot` exposes `active_flag()` for this.
2601            old_snap.active_flag().store(false, Ordering::SeqCst);
2602        }
2603        old_session
2604    };
2605    if let Some(old_b) = old_bridge {
2606        old_b.invalidate();
2607    }
2608    // Shutdown callbacks see stale host actions and run outside session locks.
2609    old_session.begin_shutdown();
2610
2611    // The session was swapped atomically above; expose its matching bridge.
2612    *ctx.action_bridge.lock().unwrap() = Some(Arc::clone(&fresh_bridge));
2613    // Republish the registry so `ListCommands` reflects the commands the reload
2614    // just discovered — without this a remote UI keeps serving the startup set
2615    // until the host process restarts. Via the trait method because all we hold
2616    // here is `Arc<dyn RuntimeActionHost>`.
2617    // Publish even when the reload found nothing: a nonempty -> empty reload
2618    // returns `ExtensionSession::none()`, and skipping it would leave the old
2619    // snapshot advertised.
2620    publish_host.publish_registry_opt(extension_session.snapshot_arc());
2621
2622    // ---- 3. resources_discover ("reload") over the fresh snapshot ----
2623    let discovered = extension_session
2624        .snapshot_arc()
2625        .map(|snap| rpi_extensions::emit_resources_discover(&cwd_str, "reload", &snap))
2626        .unwrap_or_default();
2627    // Publish the fresh theme paths so the TUI registry rebuild sees the same
2628    // set the skill/prompt loaders just consumed.
2629    if let Ok(mut guard) = ctx.discovered_theme_paths.lock() {
2630        *guard = discovered.theme_paths.clone();
2631    }
2632
2633    // ---- 4. Re-run the Part-A loaders (same precedence + --no-* gates) ----
2634    let env = Arc::new(rpi_tools::OsExecutionEnv::with_cwd(ctx.cwd.clone()));
2635    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
2636
2637    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
2638    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
2639    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
2640    if !effective_args.no_skills {
2641        // JS discovery is backed by the session-long lazy Node host. Until
2642        // that host is swapped as part of a future full JS reload, preserve
2643        // the paths it contributed at startup across `/reload`.
2644        let js_paths: &[PathBuf] = &[];
2645        let package_paths: &[PathBuf] = &[];
2646        let dirs = append_reload_resource_paths(
2647            skill_base_dirs,
2648            &effective_args.skill,
2649            &discovered.skill_paths,
2650            js_paths,
2651            package_paths,
2652        );
2653        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
2654        skills = result.skills;
2655        skill_diags = result.diagnostics;
2656        resource_diags.extend(result.resource_diagnostics);
2657    }
2658
2659    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
2660    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
2661    if !effective_args.no_prompt_templates {
2662        let js_paths: &[PathBuf] = &[];
2663        let package_paths: &[PathBuf] = &[];
2664        let dirs = append_reload_resource_paths(
2665            prompt_base_dirs,
2666            &effective_args.prompt_template,
2667            &discovered.prompt_paths,
2668            js_paths,
2669            package_paths,
2670        );
2671        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
2672        prompt_templates = result.prompt_templates;
2673        prompt_diags = result.diagnostics;
2674        resource_diags.extend(result.resource_diagnostics);
2675    }
2676
2677    let context_files = if effective_args.no_context_files || !project_trusted {
2678        Vec::new()
2679    } else {
2680        let agent_dir = ctx.home.root().ok();
2681        let agent_dir_path = agent_dir.unwrap_or_else(|| ctx.cwd.clone());
2682        load_project_context_files(&env_dyn, &ctx.cwd, &agent_dir_path).await
2683    };
2684    let context_block = format_project_context(&context_files);
2685
2686    let mut details = diagnostics.take();
2687    warnings |= !details.is_empty();
2688    if let Some(resolved) = &refreshed {
2689        warnings |= !resolved.compat_warnings.is_empty();
2690        details.extend(
2691            resolved
2692                .compat_warnings
2693                .iter()
2694                .map(|warning| format!("warning: models.json: {warning}")),
2695        );
2696    }
2697    if !skill_diags.is_empty() || !prompt_diags.is_empty() || !resource_diags.is_empty() {
2698        warnings = true;
2699        // Collect formatted diagnostics for the caller to surface in its UI
2700        // instead of writing to stderr directly: the TUI owns the terminal,
2701        // and a raw `eprintln!` during a run would scribble over the
2702        // alternate-screen input row.
2703        for d in &skill_diags {
2704            details.push(format!(
2705                "warning: skill {} ({}): {}",
2706                d.path,
2707                d.code.as_str(),
2708                d.message
2709            ));
2710        }
2711        for d in &prompt_diags {
2712            details.push(format!(
2713                "warning: prompt template {} ({}): {}",
2714                d.path,
2715                d.code.as_str(),
2716                d.message
2717            ));
2718        }
2719        // Structured collisions: winner (kept) · loser (shadowed).
2720        for d in &resource_diags {
2721            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
2722                details.push(format!(
2723                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
2724                    c.resource_type.as_str(),
2725                    c.name,
2726                    c.winner_path,
2727                    c.loser_path
2728                ));
2729            }
2730        }
2731    }
2732
2733    // ---- Re-compose the system prompt (same precedence as build) ----
2734    // Same working-state wording rule as `build`; a mid-session `/model` switch
2735    // re-composes the prompt on the next reload, which is the same staleness the
2736    // rest of this path already has (provider resolution is a startup concern).
2737    // Re-merge extension tools (a reloaded plugin may have added/removed a
2738    // tool). The built-in set is rebuilt from scratch + extension tools merged
2739    // on top, mirroring `build`. Built before the
2740    // prompt so the prompt lists exactly the active tools.
2741    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
2742    let tool_ctx = rpi_tools::ExecutionToolContext::new(env_dyn.clone(), Some(mut_env))
2743        .with_file_io(ctx.file_io.clone());
2744    // Reuse the binding installed in the durable context hook at startup;
2745    // constructing a fresh OnceLock here would register a durable tool that
2746    // can never resolve its owning harness.
2747    let mut tools = build_tools_bound(
2748        &ctx.home,
2749        &tool_ctx,
2750        &effective_args,
2751        ctx.durable_binding.clone(),
2752    );
2753    merge_extension_tools(
2754        &mut tools,
2755        &extension_session,
2756        &effective_args,
2757        &ctx.tool_context,
2758    );
2759    let mut active = active_tool_names(&tools, &effective_args);
2760    active = filter_active_tool_names(active, &effective_args);
2761    let prompt_tools = active.clone();
2762    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
2763    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&ctx.resolved_model);
2764    let default_prompt = || {
2765        default_system_prompt_with_tool_prompts(
2766            &cwd_str,
2767            prior_reasoning_replayed,
2768            &prompt_tools,
2769            &prompt_metadata,
2770        )
2771    };
2772    let mut context_paths = Vec::new();
2773    let base_prompt = match effective_args.system_prompt.as_deref() {
2774        Some(explicit) => explicit.to_string(),
2775        None if project_trusted => match ctx.home.discover_system_prompt_file(&ctx.cwd, true) {
2776            Some(path) => {
2777                read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
2778            }
2779            None => default_prompt(),
2780        },
2781        None => default_prompt(),
2782    };
2783    let mut append_texts: Vec<String> = Vec::new();
2784    for extra in &effective_args.append_system_prompt {
2785        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
2786        append_texts.push(text);
2787    }
2788    if effective_args.append_system_prompt.is_empty() {
2789        if let Some(path) = project_trusted
2790            .then(|| ctx.home.discover_append_system_prompt_file(&ctx.cwd))
2791            .flatten()
2792        {
2793            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
2794                append_texts.push(text);
2795            }
2796        }
2797    }
2798    context_paths.extend(
2799        context_files
2800            .iter()
2801            .map(|file| file.path.to_string_lossy().into_owned()),
2802    );
2803    let append_join = if append_texts.is_empty() {
2804        None
2805    } else {
2806        Some(append_texts.join("\n\n"))
2807    };
2808    let system_prompt = compose_system_prompt(
2809        Some(&base_prompt),
2810        &[],
2811        if context_block.is_empty() {
2812            None
2813        } else {
2814            Some(&context_block)
2815        },
2816        append_join.as_deref(),
2817    );
2818
2819    // ---- Rebuild the emitter (TeeEmitter over fresh ExtensionEmitter) ----
2820    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
2821        Some(snapshot) => {
2822            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
2823            Arc::new(TeeEmitter::new(vec![ctx.broadcast.clone(), Arc::new(ext)]))
2824        }
2825        None => ctx.broadcast.clone(),
2826    };
2827
2828    // ---- 5. Push the rebuilt state into the live harness via the B5d setters ----
2829    let resources = AgentHarnessResources {
2830        context_files: context_paths,
2831        skills: if skills.is_empty() {
2832            None
2833        } else {
2834            Some(skills.clone())
2835        },
2836        prompt_templates: if prompt_templates.is_empty() {
2837            None
2838        } else {
2839            Some(prompt_templates.clone())
2840        },
2841    };
2842    let _ = harness.set_system_prompt(Some(system_prompt)).await;
2843    let _ = harness.set_resources(resources).await;
2844    let _ = harness.set_agent_emitter(Some(emitter)).await;
2845    let _ = harness
2846        .set_models(build_models_with_extensions_for_reload(
2847            &refreshed
2848                .as_ref()
2849                .map(|resolved| resolved.providers.clone())
2850                .unwrap_or_else(|| {
2851                    ctx.providers
2852                        .read()
2853                        .unwrap_or_else(|error| error.into_inner())
2854                        .clone()
2855                }),
2856            &extension_session,
2857            ctx.runtime.clone(),
2858        ))
2859        .await;
2860    let _ = harness
2861        .set_provider_hooks(
2862            rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
2863                .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
2864        )
2865        .await;
2866
2867    if let Some(resolved) = &refreshed {
2868        *ctx.providers
2869            .write()
2870            .unwrap_or_else(|error| error.into_inner()) = resolved.providers.clone();
2871        let catalog = crate::provider::authenticated_catalog(resolved);
2872        fresh_bridge
2873            .clone_host()
2874            .replace_model_catalog(catalog.clone());
2875        *ctx.catalog
2876            .write()
2877            .unwrap_or_else(|error| error.into_inner()) = catalog;
2878        // Refresh the public descriptor. Credentials remain in the newly bound
2879        // provider instances installed above and never enter the lane model.
2880        let _ = harness.lane("main").set_model(resolved.model.clone()).await;
2881    }
2882
2883    ctx.tool_context
2884        .set_project_resources_allowed(project_trusted);
2885    let _ = harness.set_tools(tools, Some(active)).await;
2886
2887    let summary = format!(
2888        "Reloaded {} plugin(s), {} skill(s), {} prompt(s).",
2889        extension_session.loaded_paths().len(),
2890        skills.len(),
2891        prompt_templates.len(),
2892    );
2893    ReloadOutcome {
2894        summary,
2895        had_warnings: warnings,
2896        details,
2897        // Reload completed; any diagnostics here are soft (shadowing / name
2898        // validation / skipped optional resources), not hard failures.
2899        had_errors: false,
2900        project_trusted: Some(project_trusted),
2901    }
2902}
2903
2904#[derive(Clone, Debug, PartialEq, Eq)]
2905struct ReloadSettingsFields {
2906    skill_dirs: Option<Vec<String>>,
2907    prompt_dirs: Option<Vec<String>>,
2908    extension_dirs: Option<Vec<String>>,
2909}
2910
2911impl From<crate::settings::Settings> for ReloadSettingsFields {
2912    fn from(settings: crate::settings::Settings) -> Self {
2913        Self {
2914            skill_dirs: settings.skill_dirs,
2915            prompt_dirs: settings.prompt_dirs,
2916            extension_dirs: settings.extension_dirs,
2917        }
2918    }
2919}
2920
2921#[derive(Clone, Debug, PartialEq, Eq)]
2922struct ReloadSettingsSnapshot {
2923    global: ReloadSettingsFields,
2924    project: Option<ReloadSettingsFields>,
2925}
2926
2927fn reload_reads_settings(args: &Args) -> bool {
2928    !args.dev_local_only && (!args.no_extensions || !args.no_skills || !args.no_prompt_templates)
2929}
2930
2931/// Strictly read the settings fields consumed while preparing a reload. The
2932/// snapshot intentionally excludes UI/model fields that `/reload` does not
2933/// use, so an unrelated settings save does not invalidate the operation.
2934fn load_reload_settings_snapshot(
2935    home: &crate::config::AgentHome,
2936    args: &Args,
2937    cwd: &Path,
2938    project_trusted: bool,
2939) -> Result<Option<ReloadSettingsSnapshot>, String> {
2940    if !reload_reads_settings(args) {
2941        return Ok(None);
2942    }
2943    let global = home
2944        .settings()
2945        .map_err(|error| format!("could not load global settings: {error}"))?
2946        .into();
2947    let project = if project_trusted {
2948        crate::settings::load_active_project_settings(cwd)
2949            .map_err(|error| format!("could not load project settings: {error}"))?
2950            .map(|(_, settings)| settings.into())
2951    } else {
2952        None
2953    };
2954    Ok(Some(ReloadSettingsSnapshot { global, project }))
2955}
2956
2957/// Validate every settings document that this reload will consume before
2958/// replacing any live extension, bridge, or harness resource.
2959#[cfg(test)]
2960fn validate_settings_for_reload(
2961    args: &Args,
2962    cwd: &Path,
2963    project_trusted: bool,
2964) -> Result<(), String> {
2965    load_reload_settings_snapshot(
2966        &crate::config::AgentHome::process(),
2967        args,
2968        cwd,
2969        project_trusted,
2970    )
2971    .map(|_| ())
2972}
2973
2974fn prepare_reload_inputs_for(
2975    home: &crate::config::AgentHome,
2976    args: &Args,
2977    cwd: &Path,
2978    project_trusted: bool,
2979) -> Result<PreparedReloadInputs, String> {
2980    prepare_reload_inputs_inner_for(home, args, cwd, project_trusted, || {})
2981}
2982
2983#[cfg(test)]
2984fn prepare_reload_inputs_inner<F>(
2985    args: &Args,
2986    cwd: &Path,
2987    project_trusted: bool,
2988    before_verify: F,
2989) -> Result<PreparedReloadInputs, String>
2990where
2991    F: FnOnce(),
2992{
2993    prepare_reload_inputs_inner_for(
2994        &crate::config::AgentHome::process(),
2995        args,
2996        cwd,
2997        project_trusted,
2998        before_verify,
2999    )
3000}
3001
3002fn prepare_reload_inputs_inner_for<F>(
3003    home: &crate::config::AgentHome,
3004    args: &Args,
3005    cwd: &Path,
3006    project_trusted: bool,
3007    before_verify: F,
3008) -> Result<PreparedReloadInputs, String>
3009where
3010    F: FnOnce(),
3011{
3012    let settings_before = load_reload_settings_snapshot(home, args, cwd, project_trusted)?;
3013
3014    let extension_dirs = resource_root_dirs(
3015        home,
3016        args,
3017        cwd,
3018        project_trusted,
3019        ResourceRootKind::Extensions,
3020    );
3021    let skill_base_dirs =
3022        resource_root_dirs(home, args, cwd, project_trusted, ResourceRootKind::Skills);
3023    let prompt_base_dirs = resource_root_dirs(
3024        home,
3025        args,
3026        cwd,
3027        project_trusted,
3028        ResourceRootKind::PromptTemplates,
3029    );
3030
3031    before_verify();
3032    let settings_after = load_reload_settings_snapshot(home, args, cwd, project_trusted)?;
3033    if settings_before != settings_after {
3034        return Err(
3035            "settings changed while reload inputs were being prepared; retry /reload".to_string(),
3036        );
3037    }
3038
3039    Ok(PreparedReloadInputs {
3040        extension_dirs,
3041        skill_base_dirs,
3042        prompt_base_dirs,
3043    })
3044}
3045
3046/// `build_models_with_extensions` for the reload path: the resolved provider
3047/// runtimes (NOT `resolved` — the reload context carries the `Arc<dyn Provider>`
3048/// list directly, since provider/auth did not change) first, then one
3049/// `PluggableProvider` per registered extension provider in the fresh session.
3050fn build_models_with_extensions_for_reload(
3051    providers: &[Arc<dyn Provider>],
3052    extension_session: &ExtensionSession,
3053    runtime: tokio::runtime::Handle,
3054) -> Vec<Arc<dyn Provider>> {
3055    let mut models: Vec<Arc<dyn Provider>> = providers.to_vec();
3056    let pluggable = rpi_extensions::PluggableProvider::from_session(extension_session, runtime);
3057    for provider in pluggable {
3058        // Declared packages must enter through credential-bound factories.
3059        // Falling back to a raw adapter would reintroduce packages rejected by
3060        // auth filtering and would discard their configured model snapshot.
3061        if extension_session
3062            .snapshot()
3063            .is_some_and(|snapshot| snapshot.provider_manifest(provider.id()).is_some())
3064        {
3065            continue;
3066        }
3067        if !models.iter().any(|known| known.id() == provider.id()) {
3068            models.push(provider);
3069        }
3070    }
3071    models
3072}
3073
3074/// Diagnostic for registered TUI renderers. All three renderer kinds are
3075/// consumed by the interactive TUI's JSON component adapter; this line remains
3076/// useful under `--verbose` for extension authors.
3077fn report_deferred_renderers(session: &ExtensionSession) {
3078    let Some(snap) = session.snapshot_arc() else {
3079        return;
3080    };
3081    let all = snap.renderers();
3082    let markdown = all
3083        .iter()
3084        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Markdown)
3085        .count();
3086    let message = all
3087        .iter()
3088        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Message)
3089        .count();
3090    let entry = all
3091        .iter()
3092        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Entry)
3093        .count();
3094    if markdown + message + entry == 0 {
3095        return;
3096    }
3097    eprintln!(
3098        "renderers: {} markdown-transform, {} message-render, {} entry-render (active)",
3099        markdown, message, entry
3100    );
3101}
3102
3103/// A harness-build error.
3104#[derive(Debug, thiserror::Error)]
3105pub enum BuildError {
3106    #[error("Could not create the session directory: {0}")]
3107    SessionDir(String),
3108    #[error("Could not open the saved session: {0}")]
3109    SessionOpen(String),
3110    #[error(
3111        "No session found for {requested} in {dir}. Check the selector or start a fresh session."
3112    )]
3113    SessionNotFound { requested: String, dir: String },
3114    #[error("Could not build the harness: {0}")]
3115    HarnessCreate(String),
3116}
3117
3118/// Keep configured factories (including package-specific auth and catalogs)
3119/// first, then append legacy plugin registrations that have no runtime yet.
3120fn build_models_with_extensions(
3121    resolved: &ResolvedModel,
3122    extension_session: &ExtensionSession,
3123    runtime: tokio::runtime::Handle,
3124) -> Vec<Arc<dyn Provider>> {
3125    build_models_with_extensions_for_reload(&resolved.providers, extension_session, runtime)
3126}
3127
3128/// Resolve project resource loading without prompting. Explicit CLI overrides
3129/// win, then a stored decision; projects with no decision load by default.
3130pub(crate) fn resolve_project_trust(args: &Args, cwd: &Path) -> bool {
3131    resolve_project_trust_for(&crate::config::AgentHome::process(), args, cwd)
3132}
3133
3134pub(crate) fn resolve_project_trust_for(
3135    home: &crate::config::AgentHome,
3136    args: &Args,
3137    cwd: &Path,
3138) -> bool {
3139    if let Some(override_value) = args.trust_override {
3140        return override_value;
3141    }
3142    home.project_trust_decision(cwd)
3143        .ok()
3144        .flatten()
3145        .unwrap_or(true)
3146}
3147
3148/// Resolve the extension dirs to scan and load the cdylib plugins, returning
3149/// the loaded session guard (keeps the `Library` handles alive for the harness
3150/// lifetime). Scan order: configured project paths, project `.rpi/extensions`,
3151/// configured/global conventional paths, then any
3152/// `--extensions-dir` flags (scanned after the defaults — `args.rs`).
3153fn startup_extension_dirs(
3154    home: &crate::config::AgentHome,
3155    args: &Args,
3156    cwd: &Path,
3157    project_trusted: bool,
3158) -> Vec<PathBuf> {
3159    resource_root_dirs(
3160        home,
3161        args,
3162        cwd,
3163        project_trusted,
3164        ResourceRootKind::Extensions,
3165    )
3166}
3167
3168pub(crate) fn load_extensions(
3169    home: &crate::config::AgentHome,
3170    args: &Args,
3171    cwd: &Path,
3172    project_trusted: bool,
3173    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
3174) -> ExtensionSession {
3175    let diagnostics = crate::host::cli_cleanup::PluginLoadDiagnostics::new(
3176        crate::host::cli_cleanup::PluginCleanupLedger::new(),
3177    );
3178    let session = load_extensions_tracked(
3179        home,
3180        args,
3181        cwd,
3182        project_trusted,
3183        action_bridge,
3184        diagnostics.clone(),
3185    );
3186    for detail in diagnostics.take() {
3187        eprintln!("warning: {detail}");
3188    }
3189    session
3190}
3191
3192fn load_extensions_tracked(
3193    home: &crate::config::AgentHome,
3194    args: &Args,
3195    cwd: &Path,
3196    project_trusted: bool,
3197    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
3198    diagnostics: Arc<dyn PluginDiagnostics>,
3199) -> ExtensionSession {
3200    if args.no_extensions {
3201        return ExtensionSession::none();
3202    }
3203    let dirs = startup_extension_dirs(home, args, cwd, project_trusted);
3204    let leases = match crate::resource_management::host_leases_for(home, cwd) {
3205        Ok(leases) => leases,
3206        Err(error) => {
3207            eprintln!("warning: refusing extension loading: {error}");
3208            return ExtensionSession::none();
3209        }
3210    };
3211    load_extensions_from_dirs(
3212        home,
3213        args,
3214        &dirs,
3215        action_bridge,
3216        Some(leases),
3217        diagnostics,
3218        None,
3219    )
3220}
3221
3222/// Replace the default global extension directory with the registry-selected
3223/// file list. The loader otherwise scans every cdylib in that directory,
3224/// which re-loads retired versioned artifacts after an rpi-web update and
3225/// makes two `ownsStdio` extensions race for stdio ownership.
3226///
3227/// Only the conventional `<agent_dir>/extensions` directory is rewritten.
3228/// Project dirs and user-configured extension dirs stay directory-scanned;
3229/// unmanaged legacy cdylibs in the global dir are preserved explicitly.
3230fn registry_aware_extension_inputs(
3231    dirs: &[PathBuf],
3232    explicit_files: &[PathBuf],
3233    agent_dir_home: Option<&Path>,
3234) -> (Vec<PathBuf>, Vec<PathBuf>) {
3235    // `agent_dir` owns the registry file; `global_dir` is the directory the
3236    // loader would otherwise scan. Keep both: the helpers take the agent dir.
3237    // `agent_dir_home` is already resolved from the session's `AgentHome`;
3238    // never re-resolve it from the process environment here.
3239    let agent_dir = agent_dir_home.map(Path::to_path_buf);
3240    let global_dir = agent_dir.as_ref().map(|dir| dir.join("extensions"));
3241    let mut filtered_dirs = Vec::with_capacity(dirs.len());
3242    let mut files = explicit_files.to_vec();
3243    let mut global_dir_handled = false;
3244    for dir in dirs {
3245        let is_global = global_dir
3246            .as_ref()
3247            .is_some_and(|global| same_extension_dir(global, dir));
3248        if is_global {
3249            if !global_dir_handled {
3250                global_dir_handled = true;
3251                // An unreadable registry cannot tell us which artifacts are
3252                // retired, so fall back to the historical directory scan rather
3253                // than silently loading no global extension at all.
3254                let selection = agent_dir.as_ref().map(|agent| {
3255                    (
3256                        crate::install::active_global_native_package_artifacts_at(agent),
3257                        crate::install::unregistered_global_native_package_artifacts_at(agent),
3258                    )
3259                });
3260                match selection {
3261                    Some((Ok(active), Ok(legacy))) => {
3262                        files.extend(active);
3263                        files.extend(legacy);
3264                    }
3265                    _ => filtered_dirs.push(dir.clone()),
3266                }
3267            }
3268            continue;
3269        }
3270        filtered_dirs.push(dir.clone());
3271    }
3272    (filtered_dirs, files)
3273}
3274
3275fn same_extension_dir(left: &Path, right: &Path) -> bool {
3276    if left == right {
3277        return true;
3278    }
3279    match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
3280        (Ok(left), Ok(right)) => left == right,
3281        _ => false,
3282    }
3283}
3284
3285fn load_extensions_from_dirs(
3286    home: &crate::config::AgentHome,
3287    args: &Args,
3288    dirs: &[PathBuf],
3289    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
3290    host_guard: Option<Arc<dyn Send + Sync>>,
3291    diagnostics: Arc<dyn PluginDiagnostics>,
3292    _host_plugin_images: Option<&HostPluginImages>,
3293) -> ExtensionSession {
3294    let agent_dir = home.root().ok();
3295    let (dirs, files) =
3296        registry_aware_extension_inputs(dirs, &args.extension, agent_dir.as_deref());
3297    #[cfg(unix)]
3298    if let Some(images) = _host_plugin_images {
3299        return images.load_session(&dirs, &files, diagnostics, action_bridge, host_guard);
3300    }
3301    rpi_extensions::load_session_mixed_guarded(
3302        &dirs,
3303        &files,
3304        diagnostics,
3305        action_bridge,
3306        host_guard,
3307    )
3308}
3309
3310/// The host permanently owns both durable public names.
3311/// Refuse rather than override, fall back to, or dual-write a legacy extension
3312/// implementation. Stdio ownership is independent: adapters such as ACP and
3313/// Web use it only to keep their protocol/server lifecycle alive while the
3314/// native host still owns session durability.
3315fn validate_durable_extensions(session: &ExtensionSession) -> Result<(), String> {
3316    if let Some(snapshot) = session.snapshot() {
3317        if reserved_durable_name(
3318            snapshot.tools().iter().map(|tool| tool.tool.name.as_str()),
3319            snapshot
3320                .commands()
3321                .iter()
3322                .map(|command| command.name.as_str()),
3323        ) {
3324            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());
3325        }
3326    }
3327    Ok(())
3328}
3329
3330fn reserved_durable_name<'a>(
3331    mut tools: impl Iterator<Item = &'a str>,
3332    mut commands: impl Iterator<Item = &'a str>,
3333) -> bool {
3334    tools.any(|name| name == "durable")
3335        || commands.any(|name| name.trim_start_matches('/') == "durable")
3336}
3337
3338#[cfg(test)]
3339#[path = "native_durable/session_tests.rs"]
3340mod native_durable_session_tests;
3341
3342/// Merge extension tools into the built-ins. Ordinarily extensions override
3343/// same-named built-ins (first extension wins); host-reserved durable names
3344/// were already checked above. Both tool filters still apply to the merged set.
3345fn merge_extension_tools(
3346    tools: &mut Vec<HarnessTool>,
3347    session: &ExtensionSession,
3348    args: &Args,
3349    tool_context: &rpi_extensions::ToolCallContext,
3350) {
3351    let Some(snapshot) = session.snapshot() else {
3352        return;
3353    };
3354    for et in snapshot.tools() {
3355        let name = &et.tool.name;
3356        if !tool_name_allowed(name, args) {
3357            continue;
3358        }
3359        let adapter = PluginToolAdapter::new(et.tool.clone(), et.handle(), session.keepalive())
3360            .with_context(tool_context.clone());
3361        let harness_tool = HarnessTool::new(Arc::new(adapter));
3362        match tools.iter_mut().find(|t| t.tool.schema().name == *name) {
3363            Some(slot) => *slot = harness_tool,
3364            None => tools.push(harness_tool),
3365        }
3366    }
3367}
3368
3369/// Build the tool list per `--tools`/`--exclude-tools`/`--no-tools`/
3370/// `--no-builtin-tools`. Mirrors the TS `tools`/`excludeTools`/`noTools`
3371/// resolution in `createAgentSession`.
3372/// Default bash timeout: 120s when the model doesn't pass one (prevents a
3373/// forgotten `timeout` from hanging the run forever — the "卡住" report).
3374/// `RPI_BASH_TIMEOUT` overrides; a model-supplied timeout always wins.
3375pub fn bash_options() -> rpi_tools::tools::bash::BashToolOptions {
3376    bash_options_for(&crate::config::AgentHome::process())
3377}
3378
3379/// [`bash_options`] for one agent home.
3380pub fn bash_options_for(
3381    home: &crate::config::AgentHome,
3382) -> rpi_tools::tools::bash::BashToolOptions {
3383    use rpi_tools::tools::bash::BashToolOptions;
3384    let default = std::env::var("RPI_BASH_TIMEOUT")
3385        .ok()
3386        .and_then(|v| v.parse::<f64>().ok())
3387        .unwrap_or(rpi_tools::tools::bash::DEFAULT_BASH_TIMEOUT_SECONDS);
3388    // Saved user defaults, matching how `defaultTools` is read in `build_tools`.
3389    // `shellCommandPrefix` is prepended to every command (upstream's key for
3390    // alias/`shopt` setup). Native's `shellPath` is *not* wired: neither
3391    // `BashToolOptions` nor `ShellCaptureOptions` carries a shell binary today, so
3392    // honouring it means plumbing one through pi-tools first.
3393    let settings = home.settings().unwrap_or_default();
3394    BashToolOptions {
3395        command_prefix: settings.shell_command_prefix.clone(),
3396        default_timeout: Some(default),
3397        prepare: None,
3398    }
3399}
3400
3401#[cfg(test)]
3402fn build_tools(ctx: &ExecutionToolContext, args: &Args) -> Vec<HarnessTool> {
3403    build_tools_bound(
3404        &crate::config::AgentHome::process(),
3405        ctx,
3406        args,
3407        Arc::new(std::sync::OnceLock::new()),
3408    )
3409}
3410
3411fn build_tools_bound(
3412    home: &crate::config::AgentHome,
3413    ctx: &ExecutionToolContext,
3414    args: &Args,
3415    durable_binding: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
3416) -> Vec<HarnessTool> {
3417    if args.no_tools {
3418        return Vec::new();
3419    }
3420    // Keep the coding tools aligned with Pi and expose rpi's read-only docs
3421    // lookup as a default assistant capability.
3422    //
3423    // Replay policy (native `ToolDeclaration.replay`): only tools that are
3424    // genuinely free of side effects may be re-run when a crash leaves their
3425    // outcome unknown — everything else must stay `Never`, because replaying
3426    // `bash`/`write`/`edit` would duplicate a side effect. `HarnessTool::new`
3427    // already defaults to `Never`, so this is opt-in per read-only tool.
3428    let mut all: Vec<(&'static str, HarnessTool)> = vec![
3429        (
3430            "read",
3431            HarnessTool::new(create_read_tool(
3432                ctx,
3433                Some(rpi_tools::tools::read::ReadToolOptions {
3434                    image_processor: Some(Arc::new(
3435                        rpi_tools::image_processing::InlineImageProcessor,
3436                    )),
3437                    ..Default::default()
3438                }),
3439            ))
3440            .with_replay(ToolReplay::Safe),
3441        ),
3442        (
3443            "bash",
3444            HarnessTool::new(create_bash_tool(ctx, Some(bash_options_for(home)))),
3445        ),
3446        ("edit", HarnessTool::new(create_edit_tool(ctx))),
3447        ("write", HarnessTool::new(create_write_tool(ctx))),
3448        (
3449            "docs",
3450            HarnessTool::new(create_docs_tool()).with_replay(ToolReplay::Safe),
3451        ),
3452    ];
3453
3454    if args.native_durable {
3455        // Mixed read/write tool is NEVER safe for automatic replay.
3456        all.push((
3457            "durable",
3458            HarnessTool::new(Arc::new(crate::native_durable::NativeDurableTool::new(
3459                durable_binding.clone(),
3460            ))),
3461        ));
3462    }
3463
3464    // Add PowerShell tool on Windows
3465    #[cfg(target_os = "windows")]
3466    all.push(("powershell", HarnessTool::new(create_powershell_tool(ctx))));
3467
3468    // Apply default_tools from settings (if no CLI override)
3469    if args.tools.is_none() && args.resource_config.is_none() && args.resource_transition.is_none()
3470    {
3471        if let Ok(settings) = home.settings() {
3472            if let Some(default_tools) = &settings.default_tools {
3473                all.retain(|(name, _)| default_tools.iter().any(|t| t == name));
3474            }
3475        }
3476    }
3477
3478    // Host-integrated agent-to-agent messaging: only when the embedding host
3479    // installed a delivery door. A bare CLI session never advertises a tool it
3480    // cannot service.
3481    if crate::message_agent::handler_installed()
3482        && tool_name_allowed(crate::message_agent::MESSAGE_AGENT_TOOL_NAME, args)
3483    {
3484        all.push((
3485            crate::message_agent::MESSAGE_AGENT_TOOL_NAME,
3486            HarnessTool::new(crate::message_agent::create_message_agent_tool(
3487                durable_binding.clone(),
3488            )),
3489        ));
3490    }
3491
3492    // `--no-builtin-tools` disables the built-in set but would keep
3493    // extension/custom tools — v1 has none, so it's equivalent to `--no-tools`
3494    // here. We honor it by clearing the built-ins.
3495    if args.no_builtin_tools {
3496        all.clear();
3497    }
3498
3499    // Allowlist (`--tools`): keep only named built-ins.
3500    if let Some(allow) = &args.tools {
3501        all.retain(|(name, _)| allow.iter().any(|a| a == name));
3502    }
3503    // Denylist (`--exclude-tools`): drop named tools.
3504    if let Some(deny) = &args.exclude_tools {
3505        all.retain(|(name, _)| !deny.iter().any(|d| d == name));
3506    }
3507
3508    all.into_iter().map(|(_, t)| t).collect()
3509}
3510
3511/// Resolve the active tool names from the constructed tools when no explicit
3512/// `--tools` allowlist was given. Mirrors the TS default: all registered tools
3513/// active.
3514fn active_tool_names(tools: &[HarnessTool], args: &Args) -> Vec<String> {
3515    filter_active_tool_names(
3516        tools.iter().map(|tool| tool.tool.schema().name.clone()),
3517        args,
3518    )
3519}
3520
3521/// Whether a tool name survives the command-line tool policy. Keep this check
3522/// centralized so extension-provided tools honor the same policy as built-ins.
3523pub(crate) fn tool_name_allowed(name: &str, args: &Args) -> bool {
3524    if args.no_tools {
3525        return false;
3526    }
3527    if args
3528        .tools
3529        .as_ref()
3530        .is_some_and(|allow| !allow.iter().any(|value| value == name))
3531    {
3532        return false;
3533    }
3534    if args
3535        .exclude_tools
3536        .as_ref()
3537        .is_some_and(|deny| deny.iter().any(|value| value == name))
3538    {
3539        return false;
3540    }
3541    true
3542}
3543
3544pub(crate) fn filter_active_tool_names<I>(names: I, args: &Args) -> Vec<String>
3545where
3546    I: IntoIterator<Item = String>,
3547{
3548    names
3549        .into_iter()
3550        .filter(|name| tool_name_allowed(name, args))
3551        .collect()
3552}
3553
3554/// Build the `Session` facade for the chosen selection.
3555async fn build_session(
3556    selection: &SessionSelection,
3557    cwd: &str,
3558    selected: Option<&crate::resource_selection::ResolvedSelection>,
3559    resolved_session: Option<&JsonlSessionMetadata>,
3560    prepared_restore: Option<PreparedJsonlRestore>,
3561) -> Result<Session, BuildError> {
3562    match selection {
3563        SessionSelection::Ephemeral => Ok(ephemeral_session()),
3564        SessionSelection::New { dir, .. } => {
3565            // Ensure the sessions directory exists, then create a fresh JSONL
3566            // session file inside it.
3567            std::fs::create_dir_all(dir)
3568                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3569            let session = create_jsonl_session(dir, cwd)
3570                .await
3571                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3572            Ok(session)
3573        }
3574        SessionSelection::Latest { .. }
3575        | SessionSelection::ById { .. }
3576        | SessionSelection::ByExactId { .. } => {
3577            restore_session(selection, cwd, prepared_restore).await
3578        }
3579        SessionSelection::Fork {
3580            source,
3581            dir,
3582            entry_id,
3583            position,
3584        } => {
3585            fork_session_at_launch(
3586                source,
3587                dir,
3588                cwd,
3589                selected,
3590                entry_id.as_deref(),
3591                *position,
3592                resolved_session,
3593            )
3594            .await
3595        }
3596    }
3597}
3598
3599/// Open an existing JSONL session for `Latest` / `ById`. Mirrors the TS
3600/// `SessionManager.resume`/`open` flow: list the session dir (newest-first),
3601/// match the request, then open the matched file and wrap it in a `Session`
3602/// facade. The restored transcript renders into the TUI at startup and the
3603/// harness continues appending to the same file.
3604async fn restore_session(
3605    selection: &SessionSelection,
3606    cwd: &str,
3607    prepared_restore: Option<PreparedJsonlRestore>,
3608) -> Result<Session, BuildError> {
3609    if let Some(prepared) = prepared_restore {
3610        // Preflight verified the selected file and reserved its writer. Commit
3611        // that replay without resolving an ID or a newest-file selection again.
3612        let path = prepared.metadata().path;
3613        let storage = prepared
3614            .commit()
3615            .await
3616            .map_err(|e| BuildError::SessionOpen(format!("open {path}: {e}")))?;
3617        let progress_upgrade = StartupSpan::start(Phase::ProgressUpgrade);
3618        let storage = storage
3619            .enable_progress_under_exclusive_lock()
3620            .await
3621            .map_err(|e| BuildError::SessionOpen(format!("upgrade {path}: {e}")))?;
3622        progress_upgrade.finish();
3623        return Ok(Session::new(Arc::new(storage), None));
3624    }
3625    let Some(meta) = resolve_restore_target(selection, cwd).await? else {
3626        return match selection {
3627            // Exact id match only (pi `--session-id`): a missing session is
3628            // created fresh under the selected dir instead of an error.
3629            SessionSelection::ByExactId { id, dir } => {
3630                std::fs::create_dir_all(dir)
3631                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3632                create_jsonl_session_with_id(dir, cwd, Some(id.clone()))
3633                    .await
3634                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))
3635            }
3636            SessionSelection::Latest { dir } => Err(BuildError::SessionNotFound {
3637                requested: "the most recent session".to_string(),
3638                dir: dir.display().to_string(),
3639            }),
3640            SessionSelection::ById { id, dir } => Err(BuildError::SessionNotFound {
3641                requested: format!("session {id}"),
3642                dir: dir.display().to_string(),
3643            }),
3644            _ => unreachable!("resolve_restore_target only returns None for restore selections"),
3645        };
3646    };
3647    let sessions_root = selection_dir(selection);
3648    open_session(&meta, cwd, &sessions_root)
3649        .await
3650        .map(|restored| restored.session)
3651}
3652
3653/// The sessions root a selection was resolved against.
3654fn selection_dir(selection: &SessionSelection) -> PathBuf {
3655    match selection {
3656        SessionSelection::Ephemeral => PathBuf::new(),
3657        SessionSelection::New { dir, .. }
3658        | SessionSelection::Latest { dir }
3659        | SessionSelection::ById { dir, .. }
3660        | SessionSelection::ByExactId { dir, .. }
3661        | SessionSelection::Fork { dir, .. } => dir.clone(),
3662    }
3663}
3664
3665/// Resolve the metadata a restore selection names, without opening the file.
3666///
3667/// Used by [`peek_restored_session_cwd`] and [`restore_session`]. No session
3668/// lock is claimed and nothing is created.
3669async fn resolve_restore_target(
3670    selection: &SessionSelection,
3671    cwd: &str,
3672) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3673    match selection {
3674        SessionSelection::Latest { dir } => {
3675            let metas = list_session_metadata_in_dir(cwd, dir).await?;
3676            Ok(first_resumable_session(&metas).cloned())
3677        }
3678        SessionSelection::ById { id, dir } => find_session_metadata(id, cwd, dir).await,
3679        SessionSelection::ByExactId { id, dir } => {
3680            let metas =
3681                list_session_metadata_with_id_check(cwd, dir, SessionScope::All, Some(id)).await?;
3682            unique_session_match(metas.iter().filter(|meta| meta.id == *id), id)
3683        }
3684        SessionSelection::Fork { .. }
3685        | SessionSelection::New { .. }
3686        | SessionSelection::Ephemeral => Ok(None),
3687    }
3688}
3689
3690/// Resolve a path in the configured session directory or a saved-session selector.
3691async fn find_session_metadata(
3692    selector: &str,
3693    cwd: &str,
3694    dir: &Path,
3695) -> Result<Option<JsonlSessionMetadata>, BuildError> {
3696    if is_session_path(selector) {
3697        let path = Path::new(cwd).join(selector);
3698        let root = std::fs::canonicalize(Path::new(cwd).join(dir)).ok();
3699        let is_under_root = root.is_some_and(|root| {
3700            // Normal sessions live one project directory down. The TUI All
3701            // picker also lists older files stored directly in the root.
3702            path.ancestors()
3703                .skip(1)
3704                .take(2)
3705                .any(|ancestor| std::fs::canonicalize(ancestor).is_ok_and(|parent| parent == root))
3706        });
3707        return Ok(path
3708            .file_name()
3709            .and_then(|name| name.to_str())
3710            .and_then(|name| {
3711                if is_under_root && name.ends_with(".jsonl") && !name.ends_with(".progress.jsonl") {
3712                    session_metadata_at(&path)
3713                } else {
3714                    None
3715                }
3716            }));
3717    }
3718    if selector.is_empty() {
3719        return Ok(None);
3720    }
3721    let metas =
3722        list_session_metadata_with_id_check(cwd, dir, SessionScope::All, Some(selector)).await?;
3723    if let Some(exact_id) =
3724        unique_session_match(metas.iter().filter(|m| m.id == selector), selector)?
3725    {
3726        return Ok(Some(exact_id));
3727    }
3728
3729    let exact_name = unique_session_match(
3730        metas.iter().filter(|m| {
3731            let path = Path::new(&m.path);
3732            path.file_name().and_then(|name| name.to_str()) == Some(selector)
3733                || path.file_stem().and_then(|stem| stem.to_str()) == Some(selector)
3734        }),
3735        selector,
3736    )?;
3737    if exact_name.is_some() || selector.ends_with(".jsonl") {
3738        return Ok(exact_name);
3739    }
3740
3741    unique_session_match(
3742        metas.iter().filter(|m| {
3743            m.id.starts_with(selector)
3744                || Path::new(&m.path)
3745                    .file_stem()
3746                    .and_then(|name| name.to_str())
3747                    .is_some_and(|name| name.contains(selector))
3748        }),
3749        selector,
3750    )
3751}
3752
3753fn is_session_path(selector: &str) -> bool {
3754    selector.contains(std::path::is_separator)
3755        || matches!(
3756            Path::new(selector).components().next(),
3757            Some(
3758                std::path::Component::Prefix(_)
3759                    | std::path::Component::CurDir
3760                    | std::path::Component::ParentDir
3761            )
3762        )
3763}
3764
3765fn unique_session_match<'a>(
3766    mut matches: impl Iterator<Item = &'a JsonlSessionMetadata>,
3767    selector: &str,
3768) -> Result<Option<JsonlSessionMetadata>, BuildError> {
3769    let first = matches.next();
3770    if matches.next().is_some() {
3771        return Err(BuildError::SessionOpen(format!(
3772            "multiple saved sessions match {selector:?}. Use an exact session file path."
3773        )));
3774    }
3775    Ok(first.cloned())
3776}
3777
3778async fn resolve_fork_source(
3779    source: &str,
3780    cwd: &str,
3781    dir: &Path,
3782) -> Result<JsonlSessionMetadata, BuildError> {
3783    // A fork can read an explicit session file outside the saved-session root.
3784    let file = session_metadata_at(&Path::new(cwd).join(source));
3785    let matched = if file.is_some() || is_session_path(source) {
3786        file
3787    } else {
3788        find_session_metadata(source, cwd, dir).await?
3789    };
3790    matched.ok_or_else(|| BuildError::SessionNotFound {
3791        requested: format!("--fork {source}"),
3792        dir: dir.display().to_string(),
3793    })
3794}
3795
3796/// What a launch that would restore a session says about the working directory.
3797pub(crate) struct RestoredSessionCwd {
3798    id: String,
3799    path: PathBuf,
3800    /// The directory recorded in the session header.
3801    pub recorded: PathBuf,
3802    /// `Some` when the recorded directory still exists and the run adopts it;
3803    /// `None` when the caller must fall back to the launch cwd and say so.
3804    pub adopted: Option<PathBuf>,
3805}
3806
3807impl RestoredSessionCwd {
3808    /// Verify the file whose cwd was used before trust and resource discovery.
3809    fn metadata_for_restore(
3810        &self,
3811    ) -> Result<rpi_harness::session::jsonl::JsonlSessionMetadata, BuildError> {
3812        let metadata = session_metadata_at(&self.path).ok_or_else(|| self.changed())?;
3813        self.verify_metadata(&metadata)?;
3814        Ok(metadata)
3815    }
3816
3817    fn verify_metadata(
3818        &self,
3819        metadata: &rpi_harness::session::jsonl::JsonlSessionMetadata,
3820    ) -> Result<(), BuildError> {
3821        if metadata.id != self.id
3822            || Path::new(&metadata.path) != self.path
3823            || Path::new(&metadata.cwd) != self.recorded
3824        {
3825            return Err(self.changed());
3826        }
3827        Ok(())
3828    }
3829
3830    fn changed(&self) -> BuildError {
3831        BuildError::SessionOpen(format!(
3832            "session changed or disappeared during startup: {}",
3833            self.path.display(),
3834        ))
3835    }
3836}
3837
3838/// The working directory the launch's restored session was created in, resolved
3839/// WITHOUT opening, locking, or creating anything.
3840///
3841/// Read-only by design: this runs before trust resolution and extension
3842/// preparation, where a failure must not take the run down — the real open
3843/// happens later and surfaces its own errors. Returns `None` when the selection
3844/// is not a restore (fresh/ephemeral/fork) or cannot be resolved.
3845pub(crate) async fn peek_restored_session_cwd(
3846    selection: &SessionSelection,
3847    launch_cwd: &Path,
3848) -> Option<RestoredSessionCwd> {
3849    let cwd_str = launch_cwd.to_string_lossy().into_owned();
3850    let meta = resolve_restore_target(selection, &cwd_str).await.ok()??;
3851    let recorded = PathBuf::from(&meta.cwd);
3852    if recorded.as_os_str().is_empty() {
3853        return None;
3854    }
3855    Some(RestoredSessionCwd {
3856        path: std::fs::canonicalize(meta.path).ok()?,
3857        id: meta.id,
3858        adopted: crate::session_cwd::resolve_session_cwd(&recorded),
3859        recorded,
3860    })
3861}
3862
3863/// `--fork <path|id>`: open the source session, fork it into a new JSONL
3864/// session (records the parent id), and start in the fork.
3865async fn fork_session_at_launch(
3866    source: &str,
3867    dir: &Path,
3868    cwd: &str,
3869    selected: Option<&crate::resource_selection::ResolvedSelection>,
3870    entry_id: Option<&str>,
3871    position: Option<rpi_harness::session::types::ForkPosition>,
3872    resolved_session: Option<&JsonlSessionMetadata>,
3873) -> Result<Session, BuildError> {
3874    use rpi_harness::session::jsonl::{
3875        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
3876    };
3877    use rpi_harness::session::types::SessionStorage;
3878    use rpi_tools::FileSystem;
3879
3880    let source_meta = match resolved_session {
3881        Some(meta) => meta.clone(),
3882        None => resolve_fork_source(source, cwd, dir).await?,
3883    };
3884    std::fs::create_dir_all(&dir)
3885        .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
3886    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3887    let fs: Arc<dyn FileSystem> = env.clone();
3888    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3889        fs: fs.clone(),
3890        sessions_root: dir.to_string_lossy().into_owned(),
3891        clock: Arc::new(SystemClock),
3892        ids: Arc::new(DefaultIdGenerator::new()),
3893    });
3894    let fork_storage = repo
3895        .fork_typed_with_value_initializer(
3896            &source_meta,
3897            &JsonlSessionCreateOptions {
3898                id: None,
3899                parent_session_id: Some(source_meta.id.clone()),
3900                cwd: cwd.to_string(),
3901                metadata: None,
3902            },
3903            &ForkOptions::Branch {
3904                entry_id: entry_id.map(str::to_owned),
3905                position,
3906            },
3907            |values| crate::resource_selection::fork_initial_values_for_selection(values, selected),
3908        )
3909        .await
3910        .map_err(|e| BuildError::SessionDir(format!("fork {}: {e}", source_meta.path)))?;
3911    fork_storage
3912        .acquire_writer_lease()
3913        .await
3914        .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
3915    let storage_arc: Arc<dyn SessionStorage> = Arc::new(fork_storage);
3916    Ok(Session::new(storage_arc, None))
3917}
3918
3919/// The metadata of the JSONL session file at `path`, or `None` when `path` is
3920/// not a readable session file.
3921pub(crate) fn session_metadata_at(path: &Path) -> Option<JsonlSessionMetadata> {
3922    use rpi_harness::session::jsonl::codec::{metadata_from_header, parse_header};
3923    use std::io::BufRead;
3924
3925    let path = std::fs::canonicalize(path).ok()?;
3926    let metadata = std::fs::metadata(&path).ok()?;
3927    if !metadata.is_file() {
3928        return None;
3929    }
3930    let modified_at = metadata
3931        .modified()
3932        .ok()?
3933        .duration_since(std::time::UNIX_EPOCH)
3934        .map_or(0, |duration| duration.as_millis() as i64);
3935    let mut first_line = String::new();
3936    std::io::BufReader::new(std::fs::File::open(&path).ok()?)
3937        .read_line(&mut first_line)
3938        .ok()?;
3939    let header = parse_header(first_line.trim_end()).ok()?;
3940    Some(metadata_from_header(
3941        &header,
3942        &path.to_string_lossy(),
3943        modified_at,
3944    ))
3945}
3946
3947/// Errors from [`open_session_by_id`], split so the CLI can map them to
3948/// [`BuildError`] while the TUI can surface a friendlier note.
3949pub enum OpenError {
3950    /// No session matched the request.
3951    NotFound { requested: String },
3952    /// The match existed but could not be opened/parsed.
3953    Other(String),
3954}
3955
3956impl From<BuildError> for OpenError {
3957    fn from(error: BuildError) -> Self {
3958        match error {
3959            BuildError::SessionOpen(reason) => Self::Other(reason),
3960            other => Self::Other(other.to_string()),
3961        }
3962    }
3963}
3964
3965impl std::fmt::Display for OpenError {
3966    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3967        match self {
3968            OpenError::NotFound { requested } => write!(f, "no session matches {requested}"),
3969            // `Other` carries the bare reason (see `open_session_by_id`); the
3970            // prefix lives here so the TUI and the CLI's
3971            // `BuildError::SessionOpen` wrapper each render it exactly once
3972            // (wrapping the already-prefixed `BuildError` string doubled it).
3973            OpenError::Other(msg) => write!(f, "Could not open the saved session: {msg}"),
3974        }
3975    }
3976}
3977
3978/// Which sessions a picker lists. The default is [`Self::Project`]: with a
3979/// shared `sessionDir`, a flat list over every cwd directory buries the current
3980/// project's history (fork issue DavidHinton-xcpc/pi-rust#13). `All` is an
3981/// explicit opt-in and rows carry their project so the list stays traceable.
3982#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3983pub enum SessionScope {
3984    #[default]
3985    Project,
3986    All,
3987}
3988
3989impl SessionScope {
3990    pub fn toggled(self) -> Self {
3991        match self {
3992            Self::Project => Self::All,
3993            Self::All => Self::Project,
3994        }
3995    }
3996
3997    pub fn label(self) -> &'static str {
3998        match self {
3999            Self::Project => "this project",
4000            Self::All => "all projects",
4001        }
4002    }
4003}
4004
4005/// List the JSONL session metadata under the default session dir, newest
4006/// first. Shared by startup restore and the TUI `/session` hot-switch.
4007///
4008/// `list_session_metadata` intentionally stays unscoped: it resolves sessions
4009/// to *open* (including `--continue`/`-c`), where filtering by cwd would make
4010/// a session that the caller named by id unopenable. Only pickers apply a scope.
4011pub async fn list_session_metadata(
4012    cwd: &str,
4013) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
4014    let dir = default_session_dir(Path::new(cwd));
4015    list_session_metadata_in_dir(cwd, &dir).await
4016}
4017
4018pub(crate) async fn list_session_metadata_in_dir(
4019    cwd: &str,
4020    dir: &Path,
4021) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
4022    list_session_metadata_in_scope_in_dir(cwd, dir, SessionScope::All).await
4023}
4024
4025/// Scope-aware metadata listing for pickers. `Project` passes the cwd to the
4026/// repo's typed list API, so the enumeration and the open path agree on which
4027/// directory belongs to this project.
4028pub(crate) async fn list_session_metadata_in_scope_in_dir(
4029    cwd: &str,
4030    dir: &Path,
4031    scope: SessionScope,
4032) -> Result<Vec<JsonlSessionMetadata>, BuildError> {
4033    list_session_metadata_with_id_check(cwd, dir, scope, None).await
4034}
4035
4036async fn list_session_metadata_with_id_check(
4037    cwd: &str,
4038    dir: &Path,
4039    scope: SessionScope,
4040    requested_id: Option<&str>,
4041) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
4042    use rpi_harness::session::jsonl::{
4043        JsonlSessionListOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
4044    };
4045    use rpi_tools::FileSystem;
4046
4047    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4048    let fs: Arc<dyn FileSystem> = env.clone();
4049    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4050        fs: fs.clone(),
4051        sessions_root: dir.to_string_lossy().into_owned(),
4052        clock: Arc::new(SystemClock),
4053        ids: Arc::new(DefaultIdGenerator::new()),
4054    });
4055    let options = JsonlSessionListOptions {
4056        cwd: match scope {
4057            SessionScope::Project => Some(cwd.to_string()),
4058            SessionScope::All => None,
4059        },
4060    };
4061    let metadata_lookup = StartupSpan::start(Phase::MetadataLookup);
4062    let result = match requested_id {
4063        Some(id) => repo.list_typed_for_id(&options, id).await,
4064        None => repo.list_typed(&options).await,
4065    }
4066    .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")));
4067    if result.is_ok() {
4068        metadata_lookup.finish();
4069    }
4070    result
4071}
4072
4073/// A cheap, display-oriented summary of one JSONL session file.
4074///
4075/// The session pickers (`-r` and `/session`) need enough context to tell saved
4076/// sessions apart. The header-only [`JsonlSessionMetadata`] carries no name and
4077/// no transcript, so a list built from it renders as a wall of identical
4078/// `2026-09-25T15-05-15-847Z_…` file names — including the many header-only
4079/// sessions an abandoned launch leaves behind. This reads just the head (and a
4080/// small tail, for a late `--name`/`/name` fact) of the file to recover:
4081///
4082/// - the session display name, when one was recorded;
4083/// - the first user prompt, single-lined and truncated, for a readable label;
4084/// - whether the file is header-only (nothing to resume).
4085///
4086/// It intentionally does **not** parse the whole log: sessions can be tens of
4087/// megabytes, and the picker runs over every session at startup.
4088#[derive(Debug, Clone, Default, PartialEq, Eq)]
4089pub struct SessionSummary {
4090    /// The session display name (`--name` / `/name`), if one was recorded.
4091    pub name: Option<String>,
4092    /// The first user prompt, single-lined and trimmed to a label-sized length.
4093    pub preview: Option<String>,
4094    /// True when the file holds only its header (a session with no content).
4095    pub empty: bool,
4096    /// On-disk size in bytes (a rough content-volume hint for the picker).
4097    pub bytes: u64,
4098}
4099
4100/// Bytes read from the head of a session file to recover a name + first prompt.
4101const SUMMARY_HEAD_BYTES: u64 = 256 * 1024;
4102/// Bytes read from the tail of a session file to recover a late name fact.
4103const SUMMARY_TAIL_BYTES: u64 = 8 * 1024;
4104/// Longest preview retained (characters, not bytes).
4105const SUMMARY_PREVIEW_CHARS: usize = 80;
4106
4107/// Summarize one session file for the pickers. Best-effort: an unreadable or
4108/// malformed file yields a summary with `empty: false` and no label, so it is
4109/// still selectable rather than silently dropped.
4110pub fn summarize_session_file(path: &Path) -> SessionSummary {
4111    use std::io::{Read, Seek, SeekFrom};
4112
4113    let Ok(mut file) = std::fs::File::open(path) else {
4114        return SessionSummary::default();
4115    };
4116    let Ok(size) = file.metadata().map(|m| m.len()) else {
4117        return SessionSummary::default();
4118    };
4119    if size == 0 {
4120        return SessionSummary {
4121            name: None,
4122            preview: None,
4123            empty: true,
4124            bytes: 0,
4125        };
4126    }
4127
4128    // Head: the header line (for the empty check) + a name fact + the first user
4129    // prompt. The whole window is scanned; it is already in memory.
4130    let mut head = vec![0u8; SUMMARY_HEAD_BYTES.min(size) as usize];
4131    let head_len = file.read(&mut head).unwrap_or(0);
4132    head.truncate(head_len);
4133    let head = String::from_utf8_lossy(&head);
4134    let mut lines: Vec<&str> = head.lines().collect();
4135    let header_len = lines.first().map(|line| line.len()).unwrap_or(0);
4136    // A header-only file is exactly the header plus an optional trailing `\n`.
4137    let empty = (size as usize) <= header_len + 1;
4138    // When the window stopped short of the file end, its final line is partial:
4139    // drop it so a half-read message can never be mistaken for a complete one.
4140    if (head_len as u64) < size && !lines.is_empty() {
4141        lines.pop();
4142    }
4143
4144    let mut summary = SessionSummary {
4145        name: None,
4146        preview: None,
4147        empty,
4148        bytes: size,
4149    };
4150    for line in lines {
4151        apply_summary_line(line, &mut summary);
4152    }
4153
4154    // Tail: a name set late in the session lives after the head window. Read the
4155    // last window and scan only complete lines so a torn/partial first line is
4156    // ignored. Only do this when the file is larger than the head window.
4157    if size > SUMMARY_HEAD_BYTES
4158        && file
4159            .seek(SeekFrom::End(-(SUMMARY_TAIL_BYTES as i64)))
4160            .is_ok()
4161    {
4162        let mut tail = Vec::new();
4163        if file.read_to_end(&mut tail).is_ok() {
4164            let tail = String::from_utf8_lossy(&tail);
4165            let mut tail_lines = tail.lines();
4166            // Drop the possibly-partial first line of the window.
4167            tail_lines.next();
4168            for line in tail_lines {
4169                if let Some(name) = name_from_line(line) {
4170                    summary.name = name;
4171                }
4172            }
4173        }
4174    }
4175    summary
4176}
4177
4178/// Extract the name from a `{"kind":"fact","fact":"name","name":…}` line.
4179/// Returns `Some(None)` for an explicit `name: null` (the fact was cleared).
4180fn name_from_line(line: &str) -> Option<Option<String>> {
4181    let value: serde_json::Value = serde_json::from_str(line).ok()?;
4182    if value.get("kind").and_then(|v| v.as_str()) != Some("fact") {
4183        return None;
4184    }
4185    if value.get("fact").and_then(|v| v.as_str()) != Some("name") {
4186        return None;
4187    }
4188    Some(match value.get("name") {
4189        Some(serde_json::Value::String(name)) => Some(name.clone()),
4190        _ => None,
4191    })
4192}
4193
4194/// Fold one JSONL line into `summary`: record a name fact, or capture the first
4195/// user prompt as the preview.
4196fn apply_summary_line(line: &str, summary: &mut SessionSummary) {
4197    if let Some(name) = name_from_line(line) {
4198        summary.name = name;
4199        return;
4200    }
4201    if summary.preview.is_some() {
4202        return;
4203    }
4204    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
4205        return;
4206    };
4207    if value.get("kind").and_then(|v| v.as_str()) != Some("entry") {
4208        return;
4209    }
4210    if value.get("type").and_then(|v| v.as_str()) != Some("message") {
4211        return;
4212    }
4213    let Some(message) = value.get("message") else {
4214        return;
4215    };
4216    if message.get("role").and_then(|v| v.as_str()) != Some("user") {
4217        return;
4218    }
4219    let text = match message.get("content") {
4220        Some(serde_json::Value::String(text)) => Some(text.as_str()),
4221        Some(serde_json::Value::Array(blocks)) => blocks.iter().find_map(|block| {
4222            (block.get("type").and_then(|v| v.as_str()) == Some("text"))
4223                .then(|| block.get("text").and_then(|v| v.as_str()))
4224                .flatten()
4225        }),
4226        _ => None,
4227    };
4228    let Some(text) = text else { return };
4229    let collapsed = text
4230        .lines()
4231        .map(str::trim)
4232        .filter(|line| !line.is_empty())
4233        .collect::<Vec<_>>()
4234        .join(" ");
4235    if collapsed.is_empty() {
4236        return;
4237    }
4238    summary.preview = Some(collapsed.chars().take(SUMMARY_PREVIEW_CHARS).collect());
4239}
4240
4241/// The human label for a session row: its recorded name, else the first user
4242/// prompt, else a marker that says the file has no transcript to show. Shared
4243/// by the startup picker and the in-TUI `/session` selector.
4244pub fn session_display_label(summary: &SessionSummary) -> String {
4245    if let Some(name) = summary.name.as_deref().map(str::trim) {
4246        if !name.is_empty() {
4247            return name.to_string();
4248        }
4249    }
4250    match summary.preview.as_deref().map(str::trim) {
4251        Some(preview) if !preview.is_empty() => preview.to_string(),
4252        _ => "(no messages)".to_string(),
4253    }
4254}
4255
4256/// Compact byte count (1.2MB / 34KB / 512B), shared by the startup picker and
4257/// the in-TUI `/session` selector.
4258pub fn format_session_bytes(bytes: u64) -> String {
4259    if bytes >= 1_048_576 {
4260        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
4261    } else if bytes >= 1024 {
4262        format!("{}KB", bytes / 1024)
4263    } else {
4264        format!("{bytes}B")
4265    }
4266}
4267
4268/// The first 8 characters of a session id, enough to disambiguate two rows that
4269/// share a timestamp without shouting the whole UUID.
4270pub fn short_session_id(id: &str) -> &str {
4271    id.char_indices().nth(8).map_or(id, |(end, _)| &id[..end])
4272}
4273
4274/// One listed session file. `project` is the cwd-encoded directory name when
4275/// the row comes from a project subdirectory; `None` for legacy files that sit
4276/// directly under the sessions root. The All view renders it so a flat list is
4277/// still attributable to a project.
4278#[derive(Debug, Clone, PartialEq, Eq)]
4279pub struct SessionFileEntry {
4280    pub path: PathBuf,
4281    pub project: Option<String>,
4282}
4283
4284/// Synchronously list every JSONL session file under `dir`, newest-first by
4285/// modification time. Kept for callers that explicitly want the full set (e.g.
4286/// resolving a session by id); pickers use [`list_session_files_in_scope_sync`].
4287///
4288/// The repo's [`list_session_metadata`] is async and scans one cwd-encoded
4289/// subdirectory level; the in-TUI `/session` selector runs on the blocking key
4290/// thread and cannot await it, so this walks the same layout directly. Both
4291/// `.jsonl` files directly under `dir` and one level of subdirectories are
4292/// accepted.
4293pub fn list_session_files_sync(dir: &Path) -> Vec<PathBuf> {
4294    list_entries_sync(dir, None)
4295        .into_iter()
4296        .map(|entry| entry.path)
4297        .collect()
4298}
4299
4300/// Scope-aware synchronous listing for the `/session` selector.
4301///
4302/// `Project` resolves the current project's directory with the *same* encoding
4303/// the repo uses for create/open (`jsonl_session_directory_name`), rather than
4304/// re-deriving it: the old flat walk and the open path disagreed about which
4305/// files belong to this project (fork issue #13). `All` keeps the old layout but
4306/// tags each row with its project directory.
4307pub fn list_session_files_in_scope_sync(
4308    cwd: &Path,
4309    dir: &Path,
4310    scope: SessionScope,
4311) -> Vec<SessionFileEntry> {
4312    let project_dir = match scope {
4313        SessionScope::Project => {
4314            let resolved = normalize_cwd(cwd);
4315            Some(rpi_harness::session::jsonl::jsonl_session_directory_name(
4316                &resolved.to_string_lossy(),
4317            ))
4318        }
4319        SessionScope::All => None,
4320    };
4321    match project_dir {
4322        Some(name) => list_entries_sync(&dir.join(&name), None),
4323        None => list_entries_sync(dir, Some(true)),
4324    }
4325}
4326
4327/// Mirror the repo's `absolute_path` normalization for a cwd path: the picker
4328/// runs on the blocking key thread and cannot await the `FileSystem` trait, so
4329/// this is the synchronous equivalent of `OsExecutionEnv::absolute_path`.
4330fn normalize_cwd(cwd: &Path) -> PathBuf {
4331    let absolute = if cwd.is_absolute() {
4332        cwd.to_path_buf()
4333    } else {
4334        std::env::current_dir()
4335            .unwrap_or_else(|_| PathBuf::from("."))
4336            .join(cwd)
4337    };
4338    // Lexical normalization only (`.` / `..` components), no symlink or FS
4339    // access — the repo's normalize_absolute is likewise purely lexical.
4340    let mut out = PathBuf::new();
4341    for component in absolute.components() {
4342        match component {
4343            std::path::Component::CurDir => {}
4344            std::path::Component::ParentDir => {
4345                out.pop();
4346            }
4347            other => out.push(other.as_os_str()),
4348        }
4349    }
4350    out
4351}
4352
4353fn list_entries_sync(dir: &Path, tag_projects: Option<bool>) -> Vec<SessionFileEntry> {
4354    let tag_projects = tag_projects.unwrap_or(false);
4355    let mut files: Vec<(SessionFileEntry, std::time::SystemTime)> = Vec::new();
4356    let mut visit = |path: PathBuf, project: Option<String>| {
4357        if path.extension().and_then(|e| e.to_str()) != Some("jsonl")
4358            || path.to_string_lossy().ends_with(".progress.jsonl")
4359        {
4360            return;
4361        }
4362        let modified = std::fs::metadata(&path)
4363            .and_then(|m| m.modified())
4364            .unwrap_or(std::time::UNIX_EPOCH);
4365        files.push((SessionFileEntry { path, project }, modified));
4366    };
4367    if let Ok(entries) = std::fs::read_dir(dir) {
4368        for entry in entries.flatten() {
4369            let path = entry.path();
4370            if path.is_dir() {
4371                let project = if tag_projects {
4372                    path.file_name()
4373                        .and_then(|name| name.to_str())
4374                        .map(str::to_owned)
4375                } else {
4376                    None
4377                };
4378                if let Ok(inner) = std::fs::read_dir(&path) {
4379                    for child in inner.flatten() {
4380                        visit(child.path(), project.clone());
4381                    }
4382                }
4383            } else {
4384                visit(path, None);
4385            }
4386        }
4387    }
4388    files.sort_by_key(|entry| std::cmp::Reverse(entry.1));
4389    files.into_iter().map(|(entry, _)| entry).collect()
4390}
4391
4392/// Pick the session `--continue`/`-c` should open: the newest session that has
4393/// content (a header-only session resumes to an empty transcript). Falls back to
4394/// the newest overall when every session is empty, and `None` only when the
4395/// list is empty.
4396fn first_resumable_session(
4397    metas: &[rpi_harness::session::jsonl::JsonlSessionMetadata],
4398) -> Option<&rpi_harness::session::jsonl::JsonlSessionMetadata> {
4399    metas
4400        .iter()
4401        .find(|meta| !summarize_session_file(Path::new(&meta.path)).empty)
4402        .or_else(|| metas.first())
4403}
4404
4405/// Open a saved session using the same selector as `--session`.
4406pub async fn open_session_by_id(id: &str, cwd: &str) -> Result<Session, OpenError> {
4407    let dir = default_session_dir(Path::new(cwd));
4408    open_session_by_id_in_dir(id, cwd, &dir)
4409        .await
4410        .map(|restored| restored.session)
4411}
4412
4413pub(crate) async fn open_session_by_id_in_dir(
4414    id: &str,
4415    cwd: &str,
4416    dir: &Path,
4417) -> Result<RestoredSession, OpenError> {
4418    let meta = find_session_metadata(id, cwd, dir)
4419        .await
4420        .map_err(OpenError::from)?;
4421    let Some(meta) = meta else {
4422        return Err(OpenError::NotFound {
4423            requested: format!("session {id}"),
4424        });
4425    };
4426    open_session(&meta, cwd, dir).await.map_err(OpenError::from)
4427}
4428
4429pub(crate) fn apply_process_proxy(proxy: Option<&str>) {
4430    if let Some(proxy) = proxy {
4431        for key in ["HTTP_PROXY", "HTTPS_PROXY"] {
4432            if std::env::var_os(key).is_none() {
4433                std::env::set_var(key, proxy);
4434            }
4435        }
4436    }
4437}
4438
4439/// Publish the active session's id to plugins, on both channels that carry it.
4440///
4441/// Called on **every** activation of a session — the startup build AND every
4442/// in-process swap (`switch_to_session`, `fork_session`, and the plugin
4443/// `NewSession`/`Fork`/`SwitchSession` runtime actions all route through
4444/// [`set_active_session_with_identity`]). Two things must stay in step:
4445///
4446/// - `ToolCallContext` — read per plugin **tool** call, which is why a stale
4447///   value there made a plugin's `todo`-style state follow the wrong session.
4448/// - `RPI_SESSION_ID` — read per **turn** by the provider hooks, which is the
4449///   only channel an observer gets for a pure-chat run. Process-global, which is
4450///   exactly the scope of "the session this process is serving".
4451///
4452/// The write overwrites unconditionally, deliberately. An inherited value is not
4453/// an override: `rpi` spawning `rpi` would otherwise hand the child the parent's
4454/// session id, and the child — which is *serving its own* session — would report
4455/// it forever. (Children no longer inherit the variable at all; see
4456/// `rpi_tools::HOST_PRIVATE_ENV`. This overwrite is the second line of defence,
4457/// for any other way a value can arrive pre-set.)
4458///
4459/// An embedder that genuinely wants to pin the id can revert to the old
4460/// behaviour by setting the variable *after* this runs; there is no supported
4461/// way to pin it before, because a session that does not match its own id is
4462/// never what the caller wants.
4463fn publish_session_identity(tool_context: &rpi_extensions::ToolCallContext, id: &str) {
4464    std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, id);
4465    tool_context.set_session_id(id);
4466}
4467
4468/// Swap the session the harness serves, republishing the identity to plugins.
4469///
4470/// The single funnel for an in-process session change. Prefer this over calling
4471/// `AgentHarness::set_session` directly: the harness holds no reference to the
4472/// plugin channels, so a bare `set_session` would leave every plugin reporting
4473/// the session it had before the swap.
4474///
4475/// A shared Host publishes the session ID only through its tool context.
4476/// A dedicated CLI process also publishes it through the environment.
4477pub(crate) async fn set_active_session_with_identity(
4478    harness: &AgentHarness,
4479    session: Session,
4480    tool_context: Option<&rpi_extensions::ToolCallContext>,
4481    publish_process_identity: bool,
4482) -> Result<(), String> {
4483    let metadata = session.get_metadata().await.ok();
4484    harness
4485        .set_session(session)
4486        .await
4487        .map_err(|e| e.to_string())?;
4488    if let Some(metadata) = metadata {
4489        if publish_process_identity {
4490            std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, &metadata.id);
4491        }
4492        if let Some(context) = tool_context {
4493            context.set_session_id(metadata.id);
4494        }
4495    }
4496    Ok(())
4497}
4498
4499/// Fork the harness's current session into a new JSONL session (new id, parent
4500/// set to the source) and wrap it in a `Session`. Mirrors the TUI's
4501/// `fork_session` flow (`interactive_tui.rs`) — hoisted here so both the TUI
4502/// and the plugin `runtime_action(Fork)` host share one implementation.
4503/// Returns the new `Session` (NOT yet swapped onto the harness — the caller
4504/// does `harness.set_session(...)`).
4505pub(crate) async fn fork_session_storage(
4506    harness: &AgentHarness,
4507    cwd: &str,
4508    dir: &Path,
4509) -> Result<Session, String> {
4510    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
4511    use rpi_tools::FileSystem;
4512
4513    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4514    let fs: Arc<dyn FileSystem> = env.clone();
4515    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4516        fs,
4517        sessions_root: dir.to_string_lossy().into_owned(),
4518        clock: Arc::new(SystemClock),
4519        ids: Arc::new(DefaultIdGenerator::new()),
4520    });
4521    // The fork needs the rich JSONL metadata (with the on-disk path); resolve
4522    // it from the session list by the current session's id.
4523    let id = harness.session().storage().metadata().id.clone();
4524    let metas = list_session_metadata_in_dir(cwd, dir)
4525        .await
4526        .map_err(|e| e.to_string())?;
4527    let Some(source) = metas.iter().find(|m| m.id == id) else {
4528        return Err(format!("current session {id} not found on disk"));
4529    };
4530    let fork_storage = repo
4531        .fork_typed_with_value_initializer(
4532            source,
4533            &rpi_harness::session::jsonl::JsonlSessionCreateOptions {
4534                id: None,
4535                parent_session_id: Some(source.id.clone()),
4536                cwd: cwd.to_string(),
4537                metadata: None,
4538            },
4539            &rpi_harness::session::types::ForkOptions::default(),
4540            crate::resource_selection::fork_initial_values,
4541        )
4542        .await
4543        .map_err(|e| e.to_string())?;
4544    fork_storage
4545        .acquire_writer_lease()
4546        .await
4547        .map_err(|e| e.to_string())?;
4548    Ok(Session::new(Arc::new(fork_storage), None))
4549}
4550
4551/// Validate a private copy before publishing it in the repo's normal cwd
4552/// directory. Keep the imported identity/history and never overwrite a saved
4553/// session (including when the source is already inside this repository).
4554pub(crate) async fn import_session_file(
4555    source: &Path,
4556    cwd: &str,
4557    dir: &Path,
4558) -> Result<Session, String> {
4559    use rpi_harness::session::jsonl::{
4560        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions, JsonlSessionStorage,
4561    };
4562    use rpi_harness::session::types::SessionStorage;
4563    use rpi_tools::FileSystem;
4564
4565    let dir = if dir.is_absolute() {
4566        dir.to_path_buf()
4567    } else {
4568        Path::new(cwd).join(dir)
4569    };
4570    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
4571    // External writers must be closed. This process deliberately retains locks
4572    // for previously opened sessions, so its own copies additionally verify a
4573    // stable history around the sidecar snapshot (bind/entry before retirement).
4574    let source_progress = PathBuf::from(format!("{}.progress.jsonl", source.display()));
4575    let _source_lock = if source_progress.try_exists().map_err(|e| e.to_string())? {
4576        let lock = std::fs::OpenOptions::new()
4577            .create(true)
4578            .write(true)
4579            .open(format!("{}.lock", source.display()))
4580            .map_err(|e| format!("lock import source: {e}"))?;
4581        fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| {
4582            "close the source session before importing its recovery pair".to_owned()
4583        })?;
4584        Some(lock)
4585    } else {
4586        None
4587    };
4588    let staging = tempfile::tempdir_in(&dir).map_err(|e| e.to_string())?;
4589    let staged = staging.path().join("history.stage");
4590    let staged_progress = PathBuf::from(format!("{}.progress.jsonl", staged.display()));
4591    let mut attempts = 0;
4592    let has_progress = loop {
4593        std::fs::copy(source, &staged).map_err(|e| format!("copy import: {e}"))?;
4594        let copied_history = std::fs::read(&staged).map_err(|e| e.to_string())?;
4595        let has_progress = match std::fs::copy(&source_progress, &staged_progress) {
4596            Ok(_) => true,
4597            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
4598                let _ = std::fs::remove_file(&staged_progress);
4599                false
4600            }
4601            Err(error) => return Err(format!("copy progress import: {error}")),
4602        };
4603        if copied_history == std::fs::read(source).map_err(|e| e.to_string())? {
4604            break has_progress;
4605        }
4606        attempts += 1;
4607        if attempts >= 4 {
4608            return Err(
4609                "source history changed during import; retry when the session is idle".into(),
4610            );
4611        }
4612        tokio::task::yield_now().await;
4613    };
4614    let fs: Arc<dyn FileSystem> = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4615    let validated = JsonlSessionStorage::load(
4616        fs.clone(),
4617        &staged.to_string_lossy(),
4618        Arc::new(SystemClock),
4619        Arc::new(DefaultIdGenerator::new()),
4620    )
4621    .await
4622    .map_err(|e| format!("invalid session import: {e}"))?;
4623    validated
4624        .read_progress("")
4625        .await
4626        .map_err(|e| format!("invalid recovery import: {e}"))?;
4627    let mut metadata = validated.jsonl_metadata().clone();
4628    drop(validated);
4629    let text = std::fs::read_to_string(&staged).map_err(|e| e.to_string())?;
4630    let (first, rest) = text
4631        .split_once('\n')
4632        .ok_or_else(|| "import has no complete header".to_owned())?;
4633    let mut header =
4634        rpi_harness::session::jsonl::codec::parse_header(first).map_err(|e| e.to_string())?;
4635    if has_progress && header.progress_format.is_none() {
4636        return Err("history-only artifact has an undeclared recovery companion".into());
4637    }
4638    // An imported history-only artifact receives the destination's empty store.
4639    // Imports of live-format sessions retain their validated companion instead.
4640    header.progress_format = Some("assistant-progress-v1".into());
4641    std::fs::write(
4642        &staged,
4643        format!(
4644            "{}{}",
4645            rpi_harness::session::jsonl::codec::encode_header(&header),
4646            rest
4647        ),
4648    )
4649    .map_err(|e| e.to_string())?;
4650    if list_session_metadata_in_dir(cwd, &dir)
4651        .await
4652        .map_err(|e| e.to_string())?
4653        .iter()
4654        .any(|saved| saved.id == metadata.id)
4655    {
4656        return Err(format!(
4657            "session {} already exists in {}",
4658            metadata.id,
4659            dir.display()
4660        ));
4661    }
4662    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4663        fs,
4664        sessions_root: dir.to_string_lossy().into_owned(),
4665        clock: Arc::new(SystemClock),
4666        ids: Arc::new(DefaultIdGenerator::new()),
4667    });
4668    // Let the repository validate the id and choose its canonical destination.
4669    let destination = repo
4670        .create_typed(&JsonlSessionCreateOptions {
4671            id: Some(metadata.id.clone()),
4672            parent_session_id: metadata.parent_session_id.clone(),
4673            cwd: cwd.to_string(),
4674            metadata: metadata.metadata.clone(),
4675        })
4676        .await
4677        .map_err(|e| e.to_string())?;
4678    let path = destination.jsonl_metadata().path.clone();
4679    drop(destination);
4680    // Do not claim the session-level `.lock` here. The destination storage
4681    // opened below owns the same OS lease; claiming it first would make this
4682    // process conflict with itself. The JSONL storage lease is the
4683    // authoritative writer fence for the imported session.
4684    let destination_progress = format!("{path}.progress.jsonl");
4685    let publish = (|| -> std::io::Result<()> {
4686        if has_progress {
4687            std::fs::rename(&staged_progress, &destination_progress)?;
4688        }
4689        std::fs::rename(&staged, &path)
4690    })();
4691    if let Err(error) = publish {
4692        let _ = std::fs::remove_file(&path);
4693        let _ = std::fs::remove_file(&destination_progress);
4694        return Err(format!("publish import: {error}"));
4695    }
4696    metadata.path = path;
4697    let storage = repo
4698        .open_by_jsonl_metadata(&metadata)
4699        .await
4700        .map_err(|e| e.to_string())?;
4701    Ok(Session::new(Arc::new(storage), None))
4702}
4703
4704/// A restored session together with the working directory it was created in.
4705///
4706/// The recorded cwd is data for the host's notices, never a silent adoption:
4707/// the launch path adopts the directory in [`app`](crate::app) before any
4708/// resource loads (tools, extensions, system prompt, and trust all key off it),
4709/// and the `/session` hot-switch does not move the running tools at all. Either
4710/// way the user hears about the directory instead of the process quietly
4711/// working somewhere unexpected.
4712pub(crate) struct RestoredSession {
4713    pub session: Session,
4714    /// The directory recorded in the session header, when it still exists.
4715    /// `None` when the record is empty or the path is gone (or is a file).
4716    pub recorded_cwd: Option<PathBuf>,
4717}
4718
4719/// Wrap an opened [`JsonlSessionStorage`] in the `Session` facade (shared by
4720/// startup restore + TUI hot-switch).
4721///
4722/// `sessions_root` is passed in rather than re-derived from `cwd`: after a
4723/// restore adopts the session's directory, `default_session_dir(cwd)` would
4724/// name the ADOPTED project's tree, which is not where this session was found.
4725async fn open_session(
4726    meta: &rpi_harness::session::jsonl::JsonlSessionMetadata,
4727    cwd: &str,
4728    sessions_root: &Path,
4729) -> Result<RestoredSession, BuildError> {
4730    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
4731    use rpi_harness::session::types::SessionStorage;
4732    use rpi_tools::FileSystem;
4733
4734    let dir = sessions_root;
4735    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4736    let fs: Arc<dyn FileSystem> = env.clone();
4737    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4738        fs: fs.clone(),
4739        sessions_root: dir.to_string_lossy().into_owned(),
4740        clock: Arc::new(SystemClock),
4741        ids: Arc::new(DefaultIdGenerator::new()),
4742    });
4743    let storage = repo
4744        .open_by_jsonl_metadata(meta)
4745        .await
4746        .map_err(|e| BuildError::SessionOpen(format!("open {}: {e}", meta.path)))?;
4747    storage
4748        .acquire_writer_lease()
4749        .await
4750        .map_err(|e| BuildError::SessionOpen(format!("lock {}: {e}", meta.path)))?;
4751    // Native saved sessions predating progressFormat remain read-only to plain
4752    // storage loaders. Only this locked, not-yet-shared restore opts into writes.
4753    let storage = storage
4754        .enable_progress_under_exclusive_lock()
4755        .await
4756        .map_err(|e| BuildError::SessionOpen(format!("upgrade {}: {e}", meta.path)))?;
4757    let storage_arc: Arc<dyn SessionStorage> = Arc::new(storage);
4758    Ok(RestoredSession {
4759        session: Session::new(storage_arc, None),
4760        recorded_cwd: crate::session_cwd::resolve_session_cwd(Path::new(&meta.cwd)),
4761    })
4762}
4763
4764/// A fresh ephemeral in-memory session (no persistence). Used for `--no-session`
4765/// and for `/new` inside such a run — an ephemeral launch keeps swapping in
4766/// in-memory sessions, never a JSONL file.
4767pub(crate) fn ephemeral_session() -> Session {
4768    let storage = Arc::new(InMemorySessionStorage::new(
4769        SessionMetadata {
4770            id: "ephemeral".into(),
4771            created_at: 0,
4772            parent_session_id: None,
4773        },
4774        Arc::new(SystemClock),
4775        Arc::new(DefaultIdGenerator::new()),
4776    ));
4777    Session::new(storage, None).with_volatile_progress()
4778}
4779
4780/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
4781///
4782/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
4783/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
4784/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
4785/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
4786///
4787/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
4788/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
4789/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
4790pub(crate) async fn create_jsonl_session(dir: &Path, cwd: &str) -> Result<Session, String> {
4791    create_jsonl_session_with_id(dir, cwd, None).await
4792}
4793
4794/// `create_jsonl_session` with an explicit id (the `--session-id` fixed-id
4795/// contract: the file is named with the given id so later `--session-id`
4796/// launches restore the same session).
4797pub(crate) async fn create_jsonl_session_with_id(
4798    dir: &Path,
4799    cwd: &str,
4800    id: Option<String>,
4801) -> Result<Session, String> {
4802    use rpi_harness::session::jsonl::{
4803        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
4804    };
4805    use rpi_tools::FileSystem;
4806
4807    // A dedicated OS env for session-file I/O, rooted at the cwd so the repo's
4808    // relative-path resolution matches the tool env.
4809    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
4810    let fs: Arc<dyn FileSystem> = env.clone();
4811
4812    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
4813        fs: fs.clone(),
4814        sessions_root: dir.to_string_lossy().into_owned(),
4815        clock: Arc::new(SystemClock),
4816        ids: Arc::new(DefaultIdGenerator::new()),
4817    });
4818
4819    let opts = JsonlSessionCreateOptions {
4820        id, // fresh uuidv7 when None (--session-id passes the fixed id)
4821        parent_session_id: None,
4822        cwd: cwd.to_string(),
4823        metadata: None,
4824    };
4825    let storage = repo
4826        .create_typed(&opts)
4827        .await
4828        .map_err(|e| format!("create session: {e}"))?;
4829    // `JsonlSessionStorage` acquires the storage-level lease during create;
4830    // wrap it in the facade without a second CLI-owned lock table.
4831    let storage_arc: Arc<dyn rpi_harness::session::types::SessionStorage> = Arc::new(storage);
4832    Ok(Session::new(storage_arc, None))
4833}
4834
4835/// Read an `--append-system-prompt` target: if it's a readable file path, return
4836/// its contents; otherwise return `None` and let the caller use the literal.
4837fn read_append_target(target: &str, sources: &mut Vec<String>) -> Option<String> {
4838    let path = Path::new(target);
4839    if path.is_file() {
4840        read_prompt_source(path, sources)
4841    } else {
4842        None
4843    }
4844}
4845
4846/// Record provenance at the successful read, rather than rediscovering files
4847/// during rendering (which could report a shadowed or unreadable file).
4848fn read_prompt_source(path: &Path, sources: &mut Vec<String>) -> Option<String> {
4849    let text = std::fs::read_to_string(path).ok()?;
4850    let absolute = if path.is_absolute() {
4851        path.to_path_buf()
4852    } else {
4853        std::env::current_dir()
4854            .map(|cwd| cwd.join(path))
4855            .unwrap_or_else(|_| path.to_path_buf())
4856    };
4857    let source = absolute.to_string_lossy().into_owned();
4858    if !sources.contains(&source) {
4859        sources.push(source);
4860    }
4861    Some(text)
4862}
4863
4864#[cfg(test)]
4865mod goal_outbox_smoke_tests;
4866#[cfg(test)]
4867mod runtime_session_tests;
4868
4869#[cfg(test)]
4870mod tests {
4871    use super::*;
4872
4873    #[test]
4874    fn settlement_bridge_follows_reload_and_releases_its_session_with_the_bus() {
4875        use rpi_harness::events::{HarnessEvent, HarnessEventBus, RunEndEvent, RunEndOutcome};
4876        use std::sync::atomic::{AtomicUsize, Ordering};
4877        static OLD: AtomicUsize = AtomicUsize::new(0);
4878        static NEW: AtomicUsize = AtomicUsize::new(0);
4879        extern "C" fn old(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
4880            OLD.fetch_add(1, Ordering::SeqCst);
4881            0
4882        }
4883        extern "C" fn new(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
4884            NEW.fetch_add(1, Ordering::SeqCst);
4885            0
4886        }
4887        let make = |handler: rpi_plugin_sdk::EventHandlerFn| {
4888            let mut registry = rpi_extensions::ExtensionRegistry::new();
4889            registry.register_event_handler(
4890                "settlement".into(),
4891                rpi_plugin_sdk::EventTag::AgentSettled,
4892                handler,
4893                std::ptr::null_mut(),
4894            );
4895            ExtensionSession::from_parts(
4896                Arc::new(registry.snapshot()),
4897                rpi_extensions::PluginKeepalive::empty(),
4898                vec![],
4899                None,
4900            )
4901        };
4902        let sessions = Arc::new(Mutex::new(make(old)));
4903        let weak = Arc::downgrade(&sessions);
4904        let bus = HarnessEventBus::new();
4905        install_extension_settlement_bridge(&bus, sessions.clone());
4906        let ended = |outcome| {
4907            HarnessEvent::RunEnd(RunEndEvent {
4908                lane: "main".into(),
4909                run_id: "run".into(),
4910                outcome,
4911                leaf_id: "leaf".into(),
4912            })
4913        };
4914        bus.emit(&ended(RunEndOutcome::Completed));
4915        assert_eq!(OLD.load(Ordering::SeqCst), 1);
4916        *sessions.lock().unwrap() = make(new);
4917        for outcome in [RunEndOutcome::Aborted, RunEndOutcome::Failed] {
4918            bus.emit(&ended(outcome));
4919        }
4920        assert_eq!(OLD.load(Ordering::SeqCst), 1);
4921        assert_eq!(NEW.load(Ordering::SeqCst), 2);
4922        drop(sessions);
4923        assert!(weak.upgrade().is_some());
4924        drop(bus);
4925        assert!(
4926            weak.upgrade().is_none(),
4927            "settlement observer must not create an ownership cycle"
4928        );
4929    }
4930
4931    #[tokio::test]
4932    async fn unauthenticated_packages_are_not_reintroduced_as_legacy_adapters() {
4933        extern "C" fn request(
4934            _: rpi_plugin_sdk::StbStringRef,
4935            _: *mut rpi_plugin_sdk::StbString,
4936            _: *mut std::ffi::c_void,
4937        ) -> i32 {
4938            1
4939        }
4940        let mut registry = rpi_extensions::ExtensionRegistry::new();
4941        for id in ["package", "legacy"] {
4942            registry.register_provider(rpi_extensions::RegisteredProvider {
4943                provider_id: id.into(),
4944                base_url: "http://localhost".into(),
4945                api_style: "openai-completions".into(),
4946                request_fn: request,
4947                stream_fn: None,
4948                plugin_free_string: rpi_plugin_sdk::callbacks::free_string,
4949                user_data: std::ptr::null_mut(),
4950            });
4951        }
4952        assert!(registry.apply_declaration_json(&serde_json::json!({"providers":[{
4953            "id":"package", "requiresAuth":true,
4954            "models":[rpi_ai::Model::new("model", "Model", rpi_ai::Api::OpenaiCompletions, "package", "http://localhost")]
4955        }]}).to_string()));
4956        let session = ExtensionSession::from_parts(
4957            Arc::new(registry.snapshot()),
4958            rpi_extensions::PluginKeepalive::empty(),
4959            vec![],
4960            None,
4961        );
4962        let providers = build_models_with_extensions_for_reload(
4963            &[],
4964            &session,
4965            tokio::runtime::Handle::current(),
4966        );
4967        assert_eq!(
4968            providers
4969                .iter()
4970                .map(|provider| provider.id())
4971                .collect::<Vec<_>>(),
4972            ["legacy"]
4973        );
4974    }
4975    use crate::args::Args;
4976
4977    #[test]
4978    fn loaded_context_paths_track_precedence_and_reload() {
4979        const CHILD: &str = "RPI_CONTEXT_PATHS_REGRESSION_CHILD";
4980        if std::env::var_os(CHILD).is_none() {
4981            let dir = tempfile::tempdir().unwrap();
4982            let output = std::process::Command::new(std::env::current_exe().unwrap())
4983                .args([
4984                    "--exact",
4985                    "session::tests::loaded_context_paths_track_precedence_and_reload",
4986                    "--nocapture",
4987                ])
4988                .env(CHILD, "1")
4989                .env(crate::config::CONFIG_DIR_ENV, dir.path())
4990                .output()
4991                .unwrap();
4992            assert!(
4993                output.status.success(),
4994                "{}\n{}",
4995                String::from_utf8_lossy(&output.stdout),
4996                String::from_utf8_lossy(&output.stderr)
4997            );
4998            return;
4999        }
5000        tokio::runtime::Builder::new_current_thread()
5001            .enable_all()
5002            .build()
5003            .unwrap()
5004            .block_on(async {
5005                let agent = crate::config::agent_dir().unwrap();
5006                let cwd = agent.join("project");
5007                let project_config = cwd.join(".rpi");
5008                std::fs::create_dir_all(&project_config).unwrap();
5009                for (path, content) in [
5010                    (agent.join("SYSTEM.md"), "GLOBAL_BASE"),
5011                    (agent.join("APPEND_SYSTEM.md"), "GLOBAL_APPEND"),
5012                    (agent.join("AGENTS.md"), "GLOBAL_INSTRUCTIONS"),
5013                    (project_config.join("SYSTEM.md"), "PROJECT_BASE"),
5014                    (project_config.join("APPEND_SYSTEM.md"), "PROJECT_APPEND"),
5015                    (cwd.join("AGENTS.md"), "PROJECT_INSTRUCTIONS"),
5016                    (cwd.join("CLAUDE.md"), "SHADOWED_CLAUDE"),
5017                ] {
5018                    std::fs::write(path, content).unwrap();
5019                }
5020                let resolved = crate::provider::resolve(
5021                    &crate::config::AgentHome::process(),
5022                    Some("anthropic"),
5023                    Some(crate::provider::DEFAULT_MODEL_ID),
5024                    None,
5025                    Some("test-key"),
5026                    None,
5027                )
5028                .unwrap();
5029                let args = Args {
5030                    no_session: true,
5031                    no_extensions: true,
5032                    no_skills: true,
5033                    no_prompt_templates: true,
5034                    trust_override: Some(true),
5035                    ..Default::default()
5036                };
5037                let (harness, _events, mut context) = build(
5038                    &crate::config::AgentHome::process(),
5039                    &resolved,
5040                    &args,
5041                    &cwd,
5042                    true,
5043                )
5044                .await
5045                .unwrap();
5046                let resources = harness.get_resources().await.unwrap();
5047                let path = |p: PathBuf| p.to_string_lossy().into_owned();
5048                assert_eq!(
5049                    &resources.context_files[..2],
5050                    &[
5051                        path(project_config.join("SYSTEM.md")),
5052                        path(project_config.join("APPEND_SYSTEM.md")),
5053                    ]
5054                );
5055                assert!(resources
5056                    .context_files
5057                    .contains(&path(agent.join("AGENTS.md"))));
5058                assert!(resources
5059                    .context_files
5060                    .contains(&path(cwd.join("AGENTS.md"))));
5061                assert!(!resources
5062                    .context_files
5063                    .contains(&path(cwd.join("CLAUDE.md"))));
5064                assert!(!resources
5065                    .context_files
5066                    .contains(&path(agent.join("SYSTEM.md"))));
5067                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
5068                assert!(prompt.contains("PROJECT_BASE") && prompt.contains("PROJECT_APPEND"));
5069                assert!(!prompt.contains("GLOBAL_BASE") && !prompt.contains("SHADOWED_CLAUDE"));
5070
5071                // Removing the selected project files makes reload fall back to
5072                // globals; removed instruction paths must disappear as well.
5073                std::fs::remove_file(project_config.join("SYSTEM.md")).unwrap();
5074                std::fs::remove_file(project_config.join("APPEND_SYSTEM.md")).unwrap();
5075                std::fs::remove_file(cwd.join("AGENTS.md")).unwrap();
5076                assert!(
5077                    !reload_extension_resources(&harness, &context)
5078                        .await
5079                        .had_errors
5080                );
5081                let resources = harness.get_resources().await.unwrap();
5082                assert_eq!(
5083                    &resources.context_files[..2],
5084                    &[
5085                        path(agent.join("SYSTEM.md")),
5086                        path(agent.join("APPEND_SYSTEM.md")),
5087                    ]
5088                );
5089                assert!(resources
5090                    .context_files
5091                    .contains(&path(cwd.join("CLAUDE.md"))));
5092                assert!(!resources
5093                    .context_files
5094                    .contains(&path(project_config.join("SYSTEM.md"))));
5095
5096                // Explicit append files are listed; literal text and overridden
5097                // discovered base/append files are not invented as file sources.
5098                let explicit = agent.join("custom-append.md");
5099                std::fs::write(&explicit, "EXPLICIT_APPEND").unwrap();
5100                context.args.system_prompt = Some("EXPLICIT_BASE".into());
5101                context.args.append_system_prompt =
5102                    vec![path(explicit.clone()), "literal append".into()];
5103                context.args.no_context_files = true;
5104                assert!(
5105                    !reload_extension_resources(&harness, &context)
5106                        .await
5107                        .had_errors
5108                );
5109                assert_eq!(
5110                    harness.get_resources().await.unwrap().context_files,
5111                    vec![path(explicit)]
5112                );
5113
5114                // The reload must honor the startup opt-out from project context.
5115                context.args.system_prompt = None;
5116                context.args.append_system_prompt.clear();
5117                context.args.no_context_files = false;
5118                context.args.trust_override = Some(false);
5119                assert!(
5120                    !reload_extension_resources(&harness, &context)
5121                        .await
5122                        .had_errors
5123                );
5124                assert!(harness
5125                    .get_resources()
5126                    .await
5127                    .unwrap()
5128                    .context_files
5129                    .is_empty());
5130                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
5131                assert!(
5132                    !prompt.contains("SHADOWED_CLAUDE") && !prompt.contains("GLOBAL_INSTRUCTIONS")
5133                );
5134            });
5135    }
5136
5137    #[test]
5138    fn prompt_source_read_failures_and_literals_do_not_create_file_provenance() {
5139        let dir = tempfile::tempdir().unwrap();
5140        let file = dir.path().join("SYSTEM.md");
5141        let mut sources = Vec::new();
5142        assert!(read_prompt_source(&file, &mut sources).is_none());
5143        std::fs::write(&file, [0xff, 0xfe]).unwrap();
5144        assert!(read_prompt_source(&file, &mut sources).is_none());
5145        assert!(read_append_target("literal instructions", &mut sources).is_none());
5146        assert!(sources.is_empty());
5147        std::fs::write(&file, "loaded instructions").unwrap();
5148        assert_eq!(
5149            read_prompt_source(&file, &mut sources).as_deref(),
5150            Some("loaded instructions")
5151        );
5152        assert!(read_prompt_source(&file, &mut sources).is_some());
5153        assert_eq!(sources, vec![file.to_string_lossy().into_owned()]);
5154    }
5155
5156    extern "C" fn deny_test_tool_call(
5157        _event: rpi_plugin_sdk::StablePluginEvent,
5158        _data: *mut std::ffi::c_void,
5159    ) -> i32 {
5160        rpi_plugin_sdk::EVENT_HANDLER_ABORT
5161    }
5162
5163    async fn invoke_test_tool_hook(
5164        hook: &rpi_agent::BeforeToolCall,
5165    ) -> Option<rpi_agent::BeforeToolCallResult> {
5166        let message = rpi_ai::providers::faux::faux_assistant_message(
5167            "approval",
5168            rpi_ai::types::StopReason::ToolUse,
5169        );
5170        let rpi_ai::types::Content::ToolCall(call) =
5171            rpi_ai::types::Content::tool_call("call", "read", serde_json::json!({"path":"x"}))
5172        else {
5173            unreachable!()
5174        };
5175        hook(
5176            rpi_agent::BeforeToolCallContext {
5177                assistant_message: &message,
5178                tool_call: &call,
5179                args: &call.arguments,
5180                context: &rpi_agent::AgentContext::default(),
5181            },
5182            tokio_util::sync::CancellationToken::new(),
5183        )
5184        .await
5185    }
5186
5187    #[tokio::test]
5188    async fn tool_call_hook_uses_reloaded_session_and_newly_discovered_gate() {
5189        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
5190        let hook =
5191            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
5192        assert!(invoke_test_tool_hook(&hook).await.is_none());
5193        for name in ["first-gate", "reloaded-gate"] {
5194            let mut registry = rpi_extensions::ExtensionRegistry::new();
5195            registry.register_event_handler(
5196                name.into(),
5197                rpi_plugin_sdk::EventTag::ToolCall,
5198                deny_test_tool_call,
5199                std::ptr::null_mut(),
5200            );
5201            let fresh = ExtensionSession::from_parts(
5202                Arc::new(registry.snapshot()),
5203                rpi_extensions::PluginKeepalive::empty(),
5204                Vec::new(),
5205                None,
5206            );
5207            {
5208                let mut current = sessions.lock().unwrap();
5209                if let Some(snapshot) = current.snapshot() {
5210                    snapshot.active_flag().store(false, Ordering::SeqCst);
5211                }
5212                *current = fresh;
5213            }
5214            let result = invoke_test_tool_hook(&hook).await.unwrap();
5215            assert!(result.block);
5216            assert!(result.reason.unwrap().contains(name));
5217        }
5218        *sessions.lock().unwrap() = ExtensionSession::none();
5219        assert!(invoke_test_tool_hook(&hook).await.is_none());
5220    }
5221
5222    /// Replaces every result with one text block that names what it saw:
5223    /// `isError`, `details.blocked` and the first text of the result.
5224    extern "C" fn label_test_tool_result(
5225        event: rpi_plugin_sdk::StbStringRef,
5226        out: *mut rpi_plugin_sdk::StbString,
5227        _: *mut std::ffi::c_void,
5228    ) -> i32 {
5229        // SAFETY: the host keeps the envelope and the output slot live for the call.
5230        let event: serde_json::Value = serde_json::from_str(unsafe { event.as_str() }).unwrap();
5231        let text = format!(
5232            "isError={} blocked={} text={}",
5233            event["isError"],
5234            event["details"]["blocked"],
5235            event["content"][0]["text"].as_str().unwrap_or_default()
5236        );
5237        let patch = serde_json::json!({"content": [{"type": "text", "text": text}]});
5238        unsafe { *out = rpi_plugin_sdk::StbString::from_string(patch.to_string()) };
5239        0
5240    }
5241
5242    extern "C" fn whitespace_then_reason_transform(
5243        event: rpi_plugin_sdk::StbStringRef,
5244        out: *mut rpi_plugin_sdk::StbString,
5245        _: *mut std::ffi::c_void,
5246    ) -> i32 {
5247        // SAFETY: the host keeps the envelope and output slot live for the call.
5248        let event: serde_json::Value = serde_json::from_str(unsafe { event.as_str() }).unwrap();
5249        let reason = format!("REASON: {}", event["content"][0]["text"].as_str().unwrap());
5250        let patch = serde_json::json!({
5251            "content": [
5252                {"type": "text", "text": "   "},
5253                {"type": "text", "text": reason}
5254            ]
5255        });
5256        unsafe { *out = rpi_plugin_sdk::StbString::from_string(patch.to_string()) };
5257        0
5258    }
5259
5260    extern "C" fn redacting_test_tool_result(
5261        _event: rpi_plugin_sdk::StbStringRef,
5262        out: *mut rpi_plugin_sdk::StbString,
5263        _: *mut std::ffi::c_void,
5264    ) -> i32 {
5265        let patch = serde_json::json!({
5266            "content": [{"type": "text", "text": "REVIEW-REDACTED"}]
5267        });
5268        // SAFETY: the host keeps the output slot live for the callback.
5269        unsafe { *out = rpi_plugin_sdk::StbString::from_string(patch.to_string()) };
5270        0
5271    }
5272
5273    /// A session with a `ToolCall` gate that vetoes every call and/or the
5274    /// labelling `tool_result` transform.
5275    fn test_session(gate: bool, transform: bool) -> ExtensionSession {
5276        let mut registry = rpi_extensions::ExtensionRegistry::new();
5277        if gate {
5278            registry.register_event_handler(
5279                "gate".into(),
5280                rpi_plugin_sdk::EventTag::ToolCall,
5281                deny_test_tool_call,
5282                std::ptr::null_mut(),
5283            );
5284        }
5285        if transform {
5286            registry.register_tool_result(
5287                label_test_tool_result,
5288                rpi_plugin_sdk::callbacks::free_string,
5289                std::ptr::null_mut(),
5290            );
5291        }
5292        ExtensionSession::from_parts(
5293            Arc::new(registry.snapshot()),
5294            rpi_extensions::PluginKeepalive::empty(),
5295            Vec::new(),
5296            None,
5297        )
5298    }
5299
5300    fn invoke_test_result_hook_future(
5301        hook: &rpi_agent::AfterToolCall,
5302        result: &rpi_agent::AgentToolResult,
5303        is_error: bool,
5304    ) -> futures::future::BoxFuture<'static, Option<rpi_agent::AfterToolCallResult>> {
5305        let message = rpi_ai::providers::faux::faux_assistant_message(
5306            "result",
5307            rpi_ai::types::StopReason::ToolUse,
5308        );
5309        let rpi_ai::types::Content::ToolCall(call) =
5310            rpi_ai::types::Content::tool_call("call", "bash", serde_json::json!({"command":"x"}))
5311        else {
5312            unreachable!()
5313        };
5314        hook(
5315            rpi_agent::AfterToolCallContext {
5316                assistant_message: &message,
5317                tool_call: &call,
5318                args: &call.arguments,
5319                result,
5320                is_error,
5321                context: &rpi_agent::AgentContext::default(),
5322            },
5323            tokio_util::sync::CancellationToken::new(),
5324        )
5325    }
5326
5327    async fn invoke_test_result_hook(
5328        hook: &rpi_agent::AfterToolCall,
5329        result: &rpi_agent::AgentToolResult,
5330        is_error: bool,
5331    ) -> Option<rpi_agent::AfterToolCallResult> {
5332        invoke_test_result_hook_future(hook, result, is_error).await
5333    }
5334
5335    fn first_text(content: &[rpi_agent::TextContentOrImage]) -> &str {
5336        match content.first() {
5337            Some(rpi_agent::TextContentOrImage::Text(text)) => &text.text,
5338            _ => panic!("expected a text block"),
5339        }
5340    }
5341
5342    #[tokio::test]
5343    async fn tool_result_hook_transforms_success_and_error_results() {
5344        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
5345        let hook = extension_tool_result_hook(sessions.clone());
5346        let output = rpi_agent::AgentToolResult::text("exit 3: secret output");
5347        // No plugin, and a plugin without a transform: the result is untouched.
5348        assert!(invoke_test_result_hook(&hook, &output, true)
5349            .await
5350            .is_none());
5351        *sessions.lock().unwrap() = test_session(true, false);
5352        assert!(invoke_test_result_hook(&hook, &output, true)
5353            .await
5354            .is_none());
5355
5356        // A transform added later (as by /reload) sees success and error results.
5357        *sessions.lock().unwrap() = test_session(false, true);
5358        for is_error in [false, true] {
5359            let changed = invoke_test_result_hook(&hook, &output, is_error)
5360                .await
5361                .expect("the transform changed the result");
5362            assert_eq!(
5363                first_text(changed.content.as_deref().unwrap()),
5364                format!("isError={is_error} blocked=null text=exit 3: secret output")
5365            );
5366            assert!(
5367                changed.is_error.is_none(),
5368                "the transform does not change whether the call failed"
5369            );
5370        }
5371    }
5372
5373    #[tokio::test]
5374    async fn tool_result_hook_withholds_the_result_when_the_session_lock_is_poisoned() {
5375        let sessions = Arc::new(Mutex::new(test_session(false, true)));
5376        let poison = sessions.clone();
5377        let _ = std::thread::spawn(move || {
5378            let _guard = poison.lock().unwrap();
5379            panic!("poison the session lock");
5380        })
5381        .join();
5382        let hook = extension_tool_result_hook(sessions);
5383        let output = rpi_agent::AgentToolResult::text("secret output");
5384        let changed = invoke_test_result_hook(&hook, &output, false)
5385            .await
5386            .expect("withheld");
5387        assert_eq!(
5388            first_text(changed.content.as_deref().unwrap()),
5389            TOOL_RESULT_WITHHELD
5390        );
5391    }
5392
5393    #[tokio::test]
5394    async fn vetoed_call_reason_passes_through_the_tool_result_transforms() {
5395        // Without a transform the model reads the host's reason.
5396        let sessions = Arc::new(Mutex::new(test_session(true, false)));
5397        let hook =
5398            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
5399        let host_reason = invoke_test_tool_hook(&hook).await.unwrap().reason.unwrap();
5400        assert!(host_reason.contains("gate"));
5401
5402        // With one, the transform's text replaces it, and the transform can
5403        // tell a vetoed call from a failed one.
5404        *sessions.lock().unwrap() = test_session(true, true);
5405        let result = invoke_test_tool_hook(&hook).await.unwrap();
5406        assert!(result.block);
5407        assert_eq!(
5408            result.reason.unwrap(),
5409            format!("isError=true blocked=true text={host_reason}")
5410        );
5411    }
5412
5413    #[tokio::test]
5414    async fn review_reload_between_snapshot_capture_and_dispatch_withholds_result() {
5415        let old_session = test_session(false, true);
5416        let old_snapshot = old_session.snapshot_arc().expect("test transform");
5417        let sessions = Arc::new(Mutex::new(old_session));
5418        let hook = extension_tool_result_hook(sessions.clone());
5419        let output = rpi_agent::AgentToolResult::text("secret output");
5420        // Capture the hook's future without polling it: the session snapshot
5421        // is already fixed, exactly as it is before dispatch to the blocking
5422        // callback.
5423        let pending = invoke_test_result_hook_future(&hook, &output, false);
5424
5425        // Invalidate/swap as /reload does before the captured future runs.
5426        old_snapshot.active_flag().store(false, Ordering::SeqCst);
5427        *sessions.lock().unwrap() = test_session(false, true);
5428
5429        let changed = pending.await.expect("stale dispatch fails closed");
5430        assert_eq!(
5431            first_text(changed.content.as_deref().unwrap()),
5432            TOOL_RESULT_WITHHELD
5433        );
5434    }
5435
5436    #[tokio::test]
5437    async fn review_veto_uses_first_nonempty_text() {
5438        let sessions = Arc::new(Mutex::new(test_session(true, false)));
5439        let hook =
5440            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
5441        let host_reason = invoke_test_tool_hook(&hook).await.unwrap().reason.unwrap();
5442
5443        let mut registry = rpi_extensions::ExtensionRegistry::new();
5444        registry.register_event_handler(
5445            "gate".into(),
5446            rpi_plugin_sdk::EventTag::ToolCall,
5447            deny_test_tool_call,
5448            std::ptr::null_mut(),
5449        );
5450        registry.register_tool_result(
5451            whitespace_then_reason_transform,
5452            rpi_plugin_sdk::callbacks::free_string,
5453            std::ptr::null_mut(),
5454        );
5455        *sessions.lock().unwrap() = ExtensionSession::from_parts(
5456            Arc::new(registry.snapshot()),
5457            rpi_extensions::PluginKeepalive::empty(),
5458            Vec::new(),
5459            None,
5460        );
5461
5462        let result = invoke_test_tool_hook(&hook).await.unwrap();
5463        assert!(result.block);
5464        assert_eq!(result.reason.unwrap(), format!("REASON: {host_reason}"));
5465    }
5466
5467    #[tokio::test]
5468    async fn review_validation_error_passes_through_cli_result_transform() {
5469        let mut registry = rpi_extensions::ExtensionRegistry::new();
5470        registry.register_tool_result(
5471            redacting_test_tool_result,
5472            rpi_plugin_sdk::callbacks::free_string,
5473            std::ptr::null_mut(),
5474        );
5475        let sessions = Arc::new(Mutex::new(ExtensionSession::from_parts(
5476            Arc::new(registry.snapshot()),
5477            rpi_extensions::PluginKeepalive::empty(),
5478            Vec::new(),
5479            None,
5480        )));
5481        let after = extension_tool_result_hook(sessions);
5482        let mut context = rpi_agent::AgentContext::default();
5483        context.tools = vec![Arc::new(SchemaTool {
5484            schema: rpi_ai::types::Tool {
5485                name: "integer".into(),
5486                description: "accepts an integer".into(),
5487                parameters: rpi_ai::types::Schema::new(serde_json::json!({
5488                    "type": "object",
5489                    "properties": {"value": {"type": "integer"}},
5490                    "required": ["value"]
5491                })),
5492                constrained_sampling: None,
5493            },
5494        })];
5495        let tool_call = match rpi_ai::types::Content::tool_call(
5496            "call",
5497            "integer",
5498            serde_json::json!({"value": "invalid-secret"}),
5499        ) {
5500            rpi_ai::types::Content::ToolCall(call) => call,
5501            _ => unreachable!(),
5502        };
5503        let assistant = rpi_ai::providers::faux::faux_assistant_message(
5504            rpi_ai::providers::faux::FauxBlock::ToolCall {
5505                name: "integer".into(),
5506                id: "call".into(),
5507                arguments: tool_call.arguments.clone(),
5508            },
5509            rpi_ai::types::StopReason::ToolUse,
5510        );
5511        context
5512            .messages
5513            .push(rpi_agent::message::AgentMessage::Assistant(Box::new(
5514                assistant,
5515            )));
5516        let (collector, events) = rpi_agent::events::CollectorEmitter::new();
5517        let emit: Arc<dyn rpi_agent::AgentEmitter> = Arc::new(collector);
5518        let config = rpi_agent::hooks::AgentLoopConfig {
5519            model: rpi_ai::model::Model::new(
5520                "test",
5521                "test",
5522                rpi_ai::types::Api::Other("test".into()),
5523                "test",
5524                "",
5525            ),
5526            convert_to_llm: rpi_agent::hooks::default_convert_to_llm_fn(),
5527            convert_to_llm_incremental: None,
5528            transform_context: None,
5529            get_api_key: None,
5530            should_stop_after_turn: None,
5531            prepare_next_turn: None,
5532            after_tool_results: None,
5533            get_steering_messages: None,
5534            get_follow_up_messages: None,
5535            pending_message_count: None,
5536            before_tool_call: None,
5537            after_tool_call: Some(after),
5538            provider_hooks: None,
5539            tool_execution: rpi_agent::types::ToolExecutionMode::Sequential,
5540            thinking_level: rpi_ai::types::ThinkingLevel::default(),
5541            api_key: None,
5542            timeout: None,
5543            stream_idle_timeout: None,
5544            max_retries: None,
5545            max_retry_delay: None,
5546            cache_retention: rpi_ai::provider::CacheRetention::default(),
5547            session_id: None,
5548            signal: tokio_util::sync::CancellationToken::new(),
5549        };
5550        // Only the pending assistant's tool calls run; the empty stream fn is
5551        // never called before the loop finishes this batch.
5552        let stream_fn = rpi_agent::stream_fn::stream_fn(|_, _, opts| {
5553            let (mut producer, stream) =
5554                rpi_ai::event_stream::create_assistant_message_event_stream_with_cancellation(
5555                    &opts.signal,
5556                );
5557            tokio::spawn(async move {
5558                let message = rpi_ai::types::AssistantMessage::terminal(
5559                    rpi_ai::types::Api::Other("test".into()),
5560                    "test",
5561                    "test",
5562                    rpi_ai::types::StopReason::Stop,
5563                    "done",
5564                    0,
5565                );
5566                producer
5567                    .push(rpi_ai::types::AssistantMessageEvent::Done {
5568                        reason: rpi_ai::types::DoneReason::Stop,
5569                        message,
5570                    })
5571                    .await;
5572            });
5573            stream
5574        });
5575        rpi_agent::run_agent_loop_from_assistant(context, config, emit, stream_fn)
5576            .await
5577            .expect("agent loop finishes");
5578
5579        let events = events.lock().unwrap();
5580        let result = events.iter().find_map(|event| match event {
5581            rpi_agent::AgentEvent::ToolExecutionEnd { result, .. } => Some(result),
5582            _ => None,
5583        });
5584        let result = result.expect("validation failure reaches tool execution end");
5585        let text = match &result.content[0] {
5586            rpi_agent::TextContentOrImage::Text(text) => &text.text,
5587            _ => panic!("expected a text result"),
5588        };
5589        assert_eq!(text, "REVIEW-REDACTED");
5590        assert!(!text.contains("invalid-secret"));
5591        assert!(!text.contains("Received arguments"));
5592    }
5593
5594    /// Minimal schema-only tool for the immediate-validation regression.
5595    struct SchemaTool {
5596        schema: rpi_ai::types::Tool,
5597    }
5598
5599    #[async_trait::async_trait]
5600    impl rpi_agent::AgentTool for SchemaTool {
5601        fn schema(&self) -> &rpi_ai::types::Tool {
5602            &self.schema
5603        }
5604        fn label(&self) -> &str {
5605            "schema tool"
5606        }
5607        async fn execute(
5608            &self,
5609            _id: &str,
5610            _params: serde_json::Value,
5611            _signal: tokio_util::sync::CancellationToken,
5612            _on_update: Arc<dyn Fn(rpi_agent::types::ToolResultPartial) + Send + Sync>,
5613        ) -> Result<rpi_agent::types::AgentToolResult, rpi_agent::AgentError> {
5614            unreachable!("invalid arguments must not execute this tool")
5615        }
5616    }
5617
5618    /// A unique scratch file for one summary test.
5619    fn scratch(name: &str) -> PathBuf {
5620        let nanos = std::time::SystemTime::now()
5621            .duration_since(std::time::UNIX_EPOCH)
5622            .unwrap()
5623            .as_nanos();
5624        let path = std::env::temp_dir().join(format!(
5625            "rpi-summary-{}-{nanos}-{name}.jsonl",
5626            std::process::id()
5627        ));
5628        path
5629    }
5630
5631    #[test]
5632    fn summary_marks_a_header_only_session_empty() {
5633        let path = scratch("empty");
5634        std::fs::write(
5635            &path,
5636            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5637        )
5638        .unwrap();
5639        let summary = summarize_session_file(&path);
5640        assert!(summary.empty, "a header-only file has nothing to resume");
5641        assert!(summary.preview.is_none());
5642        assert_eq!(summary.bytes, std::fs::metadata(&path).unwrap().len());
5643        std::fs::remove_file(&path).ok();
5644    }
5645
5646    #[test]
5647    fn summary_reads_the_first_user_prompt_and_name() {
5648        let path = scratch("content");
5649        let body = concat!(
5650            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5651            "{\"kind\":\"fact\",\"seq\":1,\"fact\":\"name\",\"name\":\"fix resume picker\"}\n",
5652            "{\"kind\":\"record\",\"type\":\"operation_started\",\"id\":\"r1\"}\n",
5653            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"kind\":\"user\",\"role\":\"user\",\"content\":\"read the rpi -r picker\"}}\n",
5654            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e2\",\"message\":{\"kind\":\"assistant\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
5655        );
5656        std::fs::write(&path, body).unwrap();
5657        let summary = summarize_session_file(&path);
5658        assert!(!summary.empty);
5659        assert_eq!(summary.name.as_deref(), Some("fix resume picker"));
5660        assert_eq!(summary.preview.as_deref(), Some("read the rpi -r picker"));
5661        std::fs::remove_file(&path).ok();
5662    }
5663
5664    #[test]
5665    fn summary_extracts_a_block_style_user_prompt() {
5666        let path = scratch("blocks");
5667        let body = concat!(
5668            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5669            "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"line one\\nline two\"}]}}\n",
5670        );
5671        std::fs::write(&path, body).unwrap();
5672        let summary = summarize_session_file(&path);
5673        assert_eq!(summary.preview.as_deref(), Some("line one line two"));
5674        assert_eq!(session_display_label(&summary), "line one line two");
5675        std::fs::remove_file(&path).ok();
5676    }
5677
5678    fn meta_for(path: &Path, id: &str) -> rpi_harness::session::jsonl::JsonlSessionMetadata {
5679        rpi_harness::session::jsonl::JsonlSessionMetadata {
5680            id: id.to_string(),
5681            created_at: 0,
5682            cwd: ".".to_string(),
5683            path: path.to_string_lossy().into_owned(),
5684            modified_at: 0,
5685            source_format: rpi_harness::session::jsonl::JsonlSourceFormat::V4,
5686            parent_session_id: None,
5687            legacy_parent_session_path: None,
5688            metadata: None,
5689        }
5690    }
5691
5692    #[test]
5693    fn continue_skips_newer_empty_sessions() {
5694        let empty = scratch("newest-empty");
5695        std::fs::write(
5696            &empty,
5697            "{\"kind\":\"header\",\"version\":4,\"id\":\"empty\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5698        )
5699        .unwrap();
5700        let content = scratch("older-content");
5701        std::fs::write(
5702            &content,
5703            concat!(
5704                "{\"kind\":\"header\",\"version\":4,\"id\":\"old\",\"createdAt\":1,\"cwd\":\"x\"}\n",
5705                "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n",
5706            ),
5707        )
5708        .unwrap();
5709
5710        let metas = vec![meta_for(&empty, "empty"), meta_for(&content, "old")];
5711        let picked = first_resumable_session(&metas).expect("a resumable session");
5712        assert_eq!(picked.id, "old");
5713
5714        // When every session is empty, fall back to the newest rather than
5715        // erroring.
5716        let all_empty = vec![meta_for(&empty, "empty")];
5717        assert_eq!(first_resumable_session(&all_empty).unwrap().id, "empty");
5718
5719        std::fs::remove_file(&empty).ok();
5720        std::fs::remove_file(&content).ok();
5721    }
5722
5723    #[tokio::test]
5724    async fn import_preserves_validates_and_locks_the_recovery_pair() {
5725        use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
5726        use rpi_harness::session::types::{
5727            AssistantFrameOp, AssistantFrameRecord, RecordBase, SessionStorage,
5728        };
5729        let tmp = tempfile::tempdir().unwrap();
5730        let source = tmp.path().join("source.jsonl");
5731        let progress = tmp.path().join("source.jsonl.progress.jsonl");
5732        let fs: Arc<dyn rpi_tools::FileSystem> =
5733            Arc::new(OsExecutionEnv::with_cwd(tmp.path().into()));
5734        let storage = JsonlSessionStorage::create(
5735            fs,
5736            &source.to_string_lossy(),
5737            JsonlV4Header::new("import-pair".into(), 1, "/".into(), None, None, None),
5738            Arc::new(SystemClock),
5739            Arc::new(DefaultIdGenerator::new()),
5740        )
5741        .await
5742        .unwrap();
5743        storage
5744            .append_progress(vec![AssistantFrameRecord {
5745                base: RecordBase {
5746                    id: "accepted-prefix".into(),
5747                    seq: 0,
5748                    lane: "main".into(),
5749                    timestamp: 0,
5750                },
5751                run_id: "run".into(),
5752                stream_index: 0,
5753                op: AssistantFrameOp::Append,
5754                frame: Some(serde_json::json!({"payload":"keep"})),
5755            }])
5756            .await
5757            .unwrap();
5758        drop(storage);
5759        let original = std::fs::read(&progress).unwrap();
5760        let destination = tmp.path().join("imported");
5761        let imported = import_session_file(&source, &tmp.path().to_string_lossy(), &destination)
5762            .await
5763            .unwrap();
5764        assert_eq!(
5765            imported.read_progress("run").await.unwrap()[0].base.id,
5766            "accepted-prefix"
5767        );
5768        assert_eq!(
5769            std::fs::read(&progress).unwrap(),
5770            original,
5771            "import must not repair or mutate its source"
5772        );
5773        let lock = std::fs::OpenOptions::new()
5774            .create(true)
5775            .write(true)
5776            .open(tmp.path().join("source.jsonl.lock"))
5777            .unwrap();
5778        fs2::FileExt::try_lock_exclusive(&lock).unwrap();
5779        assert!(import_session_file(
5780            &source,
5781            &tmp.path().to_string_lossy(),
5782            &tmp.path().join("busy")
5783        )
5784        .await
5785        .is_err());
5786        drop(lock);
5787        let mut corrupt = String::from_utf8(original.clone()).unwrap();
5788        corrupt = corrupt.replace(
5789            "\"session_id\":\"import-pair\"",
5790            "\"session_id\":\"foreign\"",
5791        );
5792        assert_ne!(corrupt.as_bytes(), original.as_slice());
5793        std::fs::write(&progress, corrupt).unwrap();
5794        assert!(import_session_file(
5795            &source,
5796            &tmp.path().to_string_lossy(),
5797            &tmp.path().join("foreign")
5798        )
5799        .await
5800        .is_err());
5801        std::fs::remove_file(&progress).unwrap();
5802        assert!(import_session_file(
5803            &source,
5804            &tmp.path().to_string_lossy(),
5805            &tmp.path().join("missing")
5806        )
5807        .await
5808        .is_err());
5809    }
5810
5811    #[test]
5812    fn list_session_files_sync_walks_the_cwd_subdirectory() {
5813        let root = std::env::temp_dir().join(format!("rpi-summary-{}-dir", std::process::id()));
5814        let nested = root.join("--proj--");
5815        std::fs::create_dir_all(&nested).unwrap();
5816        let file = nested.join("2026-01-01_a.jsonl");
5817        std::fs::write(&file, "{}\n").unwrap();
5818        let sidecar = nested.join("2026-01-01_a.jsonl.progress.jsonl");
5819        std::fs::write(&sidecar, "{}\n").unwrap();
5820        let found = list_session_files_sync(&root);
5821        assert!(found.iter().any(|p| p == &file));
5822        assert!(!found.contains(&sidecar));
5823        std::fs::remove_dir_all(&root).ok();
5824    }
5825
5826    /// Regression for fork issue #13: with a shared session root, the default
5827    /// picker scope must show only this project's sessions, and All must show
5828    /// every project with its directory tag so a flat list stays traceable.
5829    #[test]
5830    fn review_issue13_default_scope_is_this_project_and_all_is_tagged() {
5831        let tmp = tempfile::tempdir().unwrap();
5832        let root = tmp.path().join("sessions");
5833        let cwd = tmp.path().join("project");
5834        let own = root.join(rpi_harness::session::jsonl::jsonl_session_directory_name(
5835            &cwd.to_string_lossy(),
5836        ));
5837        let foreign = root.join("--some-other-project--");
5838        std::fs::create_dir_all(&own).unwrap();
5839        std::fs::create_dir_all(&foreign).unwrap();
5840        let own_file = own.join("2026-01-01_own.jsonl");
5841        let foreign_file = foreign.join("2026-01-02_foreign.jsonl");
5842        std::fs::write(&own_file, "{}\n").unwrap();
5843        std::fs::write(&foreign_file, "{}\n").unwrap();
5844        // A legacy file directly under the root is not a project subdirectory.
5845        let legacy = root.join("2026-01-03_legacy.jsonl");
5846        std::fs::write(&legacy, "{}\n").unwrap();
5847
5848        let project = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
5849        assert_eq!(project.len(), 1, "default scope must not flatten projects");
5850        assert_eq!(project[0].path, own_file);
5851        assert_eq!(project[0].project, None);
5852
5853        let all = list_session_files_in_scope_sync(&cwd, &root, SessionScope::All);
5854        assert_eq!(all.len(), 3);
5855        let own_project = own.file_name().unwrap().to_str().unwrap();
5856        assert!(all
5857            .iter()
5858            .any(|e| e.path == own_file && e.project.as_deref() == Some(own_project)));
5859        assert!(all
5860            .iter()
5861            .any(|e| e.path == foreign_file
5862                && e.project.as_deref() == Some("--some-other-project--")));
5863        assert!(all.iter().any(|e| e.path == legacy && e.project.is_none()));
5864
5865        assert_eq!(SessionScope::Project.toggled(), SessionScope::All);
5866        assert_eq!(SessionScope::All.toggled(), SessionScope::Project);
5867        assert_eq!(SessionScope::default(), SessionScope::Project);
5868    }
5869
5870    /// The project directory name must be the repo's own encoding, not a
5871    /// re-derivation that drifts from create/open. A relative cwd resolves
5872    /// against the process cwd the same way `OsExecutionEnv::absolute_path` does.
5873    #[test]
5874    fn review_issue13_project_scope_uses_the_repo_directory_encoding() {
5875        let tmp = tempfile::tempdir().unwrap();
5876        let root = tmp.path().join("sessions");
5877        let cwd = tmp.path().join("project");
5878        let name =
5879            rpi_harness::session::jsonl::jsonl_session_directory_name(&cwd.to_string_lossy());
5880        std::fs::create_dir_all(root.join(&name)).unwrap();
5881        let file = root.join(&name).join("a.jsonl");
5882        std::fs::write(&file, "{}\n").unwrap();
5883        // A look-alike directory that a naive "last path component" derivation
5884        // would pick instead. The repo encodes the *full* cwd, so this must not
5885        // be listed by the Project scope.
5886        let lookalike = root.join("--project--");
5887        std::fs::create_dir_all(&lookalike).unwrap();
5888        let other_file = lookalike.join("b.jsonl");
5889        std::fs::write(&other_file, "{}\n").unwrap();
5890        let found = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
5891        assert_eq!(
5892            found,
5893            vec![SessionFileEntry {
5894                path: file,
5895                project: None
5896            }]
5897        );
5898    }
5899
5900    /// Fork issue #13, async path: the `-r` picker's default scope must use the
5901    /// repo's typed list API with an explicit cwd, and the open path must stay
5902    /// unscoped so a row chosen from All still resolves by id.
5903    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5904    async fn review_issue13_resume_scope_and_open_path_agree() {
5905        let tmp = tempfile::tempdir().unwrap();
5906        let root = tmp.path().join("sessions");
5907        let cwd = tmp.path().join("project");
5908        std::fs::create_dir_all(&cwd).unwrap();
5909        let foreign_cwd = tmp.path().join("other");
5910        std::fs::create_dir_all(&foreign_cwd).unwrap();
5911        let cwd_text = cwd.to_string_lossy().into_owned();
5912        let own = create_jsonl_session(&root, &cwd_text).await.unwrap();
5913        let own_id = own.storage().metadata().id.clone();
5914        drop(own);
5915        let foreign = create_jsonl_session(&root, &foreign_cwd.to_string_lossy())
5916            .await
5917            .unwrap();
5918        let foreign_id = foreign.storage().metadata().id.clone();
5919        drop(foreign);
5920
5921        let project =
5922            list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::Project)
5923                .await
5924                .unwrap();
5925        assert_eq!(project.len(), 1, "-r default must not flatten projects");
5926        assert_eq!(project[0].id, own_id);
5927        let all = list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::All)
5928            .await
5929            .unwrap();
5930        assert_eq!(all.len(), 2);
5931        assert!(all.iter().any(|m| m.cwd == foreign_cwd.to_string_lossy()));
5932        // `list_session_metadata_in_dir` (the open path) must remain unscoped.
5933        let open = list_session_metadata_in_dir(&cwd_text, &root)
5934            .await
5935            .unwrap();
5936        assert_eq!(open.len(), 2);
5937        let found = find_session_metadata(&foreign_id, &cwd_text, &root)
5938            .await
5939            .unwrap();
5940        assert_eq!(found.unwrap().id, foreign_id);
5941    }
5942
5943    /// The default CLI tool set plus the `todo` tool its bundled plugins add.
5944    fn default_prompt_tools() -> Vec<String> {
5945        BUILTIN_TOOL_NAMES
5946            .iter()
5947            .copied()
5948            .chain(["todo"])
5949            .map(str::to_owned)
5950            .collect()
5951    }
5952
5953    #[test]
5954    fn default_prompt_lists_only_the_active_tools() {
5955        let tools = ["read", "docs"].map(str::to_owned);
5956        let p = default_system_prompt_with_tools("/tmp/proj", true, &tools);
5957        assert!(p.contains("- read  — Read file contents"));
5958        assert!(p.contains("- docs  — Look up rpi commands"));
5959        for absent in ["- edit", "- write", "- bash", "todo", "Windows"] {
5960            assert!(
5961                !p.contains(absent),
5962                "{absent} must not appear for a read-only run: {p}"
5963            );
5964        }
5965        assert!(p.contains("Re-stating the same plan without acting on it is a bug"));
5966        let none = default_system_prompt_with_tools("/tmp/proj", false, &[]);
5967        assert!(none.contains("Available tools:\n(none)"));
5968    }
5969
5970    #[test]
5971    fn default_prompt_mentions_cwd_and_tools() {
5972        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
5973        assert!(p.contains("/tmp/proj"));
5974        assert!(p.contains("read"));
5975        assert!(p.contains("bash"));
5976        assert!(p.contains("edit"));
5977        assert!(p.contains("write"));
5978        assert!(p.contains("docs"));
5979        assert!(!p.contains("- grep"));
5980        assert!(!p.contains("- find"));
5981        assert!(!p.contains("- ls"));
5982        assert!(!p.contains("- powershell"));
5983        assert!(p.contains("Bash/POSIX syntax, also on Windows"));
5984    }
5985
5986    #[test]
5987    fn default_prompt_instructs_language_matching() {
5988        // A Chinese (or any non-English) user gets a same-language reply
5989        // without having to ask every turn.
5990        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
5991        assert!(
5992            p.contains("same language as the user's latest message"),
5993            "the prompt must tell the model to mirror the user's language: {p}"
5994        );
5995    }
5996
5997    #[test]
5998    fn default_prompt_keeps_working_state_in_the_visible_channel() {
5999        // Regression guard for the re-plan loop: on openai-compatible providers
6000        // the assistant's `thinking` blocks are dropped when the next request is
6001        // built (`providers/openai_completions.rs`: `Content::text_only`), so a
6002        // plan that lives only in reasoning is re-derived every turn. One
6003        // observed session paid for that 112 times in a single run, and twice
6004        // hallucinated the user's input ("The user is greeting me with hello",
6005        // with no such message). See `docs/llm-repetition-forensics.md` §八.
6006        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
6007        let lower = p.to_lowercase();
6008        // The rule must state the mechanism, not just "be clear".
6009        assert!(
6010            lower.contains("reasoning is not") && lower.contains("carried into your next turn"),
6011            "the prompt must explain that reasoning does not survive the turn: {p}"
6012        );
6013        // Working state stays visible; extension-specific rules require opt-in.
6014        assert!(
6015            lower.contains("visible") && !lower.contains("todo tool"),
6016            "the prompt must keep state visible without inventing extension rules: {p}"
6017        );
6018        // …plus the anti-repetition rule itself.
6019        assert!(
6020            lower.contains("re-stating the same plan"),
6021            "the prompt must call out plan re-statement as a bug: {p}"
6022        );
6023        // And the guidance must not instruct re-reading what is already shown.
6024        assert!(
6025            lower.contains("already shown earlier"),
6026            "the prompt must discourage re-fetching known content: {p}"
6027        );
6028    }
6029
6030    #[test]
6031    fn default_prompt_does_not_claim_reasoning_is_lost_when_it_is_replayed() {
6032        // `compat.requiresThinkingAsText` (and the native thinking channels of
6033        // anthropic-messages / openai-responses) DO carry the model's reasoning
6034        // back on the next request. Telling such a model "reasoning is not
6035        // carried into your next turn" is false, and the instruction to restate
6036        // the plan every turn is exactly the busy-work the re-plan analysis
6037        // measured. The wording must flip with the mechanism.
6038        let p = default_system_prompt_with_tools("/tmp/proj", true, &default_prompt_tools());
6039        let lower = p.to_lowercase();
6040        assert!(
6041            lower.contains("carried back"),
6042            "a replaying model must be told its reasoning survives: {p}"
6043        );
6044        assert!(
6045            !lower.contains("reasoning is not"),
6046            "the replayed variant must not claim reasoning is dropped: {p}"
6047        );
6048        assert!(
6049            lower.contains("do not re-derive"),
6050            "the replayed variant must forbid re-deriving the plan: {p}"
6051        );
6052        assert!(
6053            lower.contains("do not re-derive") && lower.contains("re-stating the same plan"),
6054            "the anti-repetition rule must survive the flip: {p}"
6055        );
6056        assert!(
6057            lower.contains("already shown earlier"),
6058            "the re-read rule must survive the flip: {p}"
6059        );
6060    }
6061
6062    #[test]
6063    fn default_prompt_states_each_rule_once() {
6064        // The plan rule, the todo tool and the anti-repetition line used to be
6065        // spread over two guidelines that repeated each other.
6066        for replayed in [false, true] {
6067            let p =
6068                default_system_prompt_with_tools("/tmp/proj", replayed, &default_prompt_tools());
6069            for phrase in ["the same plan", "Windows", "guessing"] {
6070                assert_eq!(p.matches(phrase).count(), 1, "{phrase:?} repeated: {p}");
6071            }
6072            assert!(
6073                !p.contains("todo tool"),
6074                "extension rules require explicit metadata"
6075            );
6076        }
6077    }
6078
6079    /// Only side-effect-free tools may be replayed after a crash.
6080    ///
6081    /// Regression guard for an inverted default: `ToolReplay` used to default to
6082    /// `Safe` and the CLI then marked *every* tool `Safe`, so the first time
6083    /// recovery acted on the flag it would have re-run `bash`/`write`/`edit` and
6084    /// duplicated their side effects. upstream defaults to `"never"`
6085    /// (`drive/tools.ts: tool.replay ?? "never"`).
6086    #[test]
6087    fn only_read_only_tools_are_replayable() {
6088        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
6089        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
6090        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
6091        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
6092        let tools = build_tools(&context, &Args::default());
6093
6094        let replay_of = |name: &str| {
6095            tools
6096                .iter()
6097                .find(|tool| tool.tool.schema().name == name)
6098                .map(|tool| tool.replay)
6099        };
6100
6101        for read_only in ["read", "docs"] {
6102            assert_eq!(
6103                replay_of(read_only),
6104                Some(ToolReplay::Safe),
6105                "{read_only} is side-effect free, so recovery may re-run it"
6106            );
6107        }
6108        for mutating in ["bash", "edit", "write", "powershell"] {
6109            if let Some(replay) = replay_of(mutating) {
6110                assert_eq!(
6111                    replay,
6112                    ToolReplay::Never,
6113                    "{mutating} must never be replayed: re-running it would duplicate its effect"
6114                );
6115            }
6116        }
6117    }
6118
6119    #[test]
6120    fn default_tools_include_docs_lookup() {
6121        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
6122        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
6123        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
6124        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
6125        let names: Vec<String> = build_tools(&context, &Args::default())
6126            .iter()
6127            .map(|tool| tool.tool.schema().name.clone())
6128            .collect();
6129
6130        // `powershell` is Windows-only, and the defaultTools setting may narrow
6131        // the registered set in a developer's environment.
6132        assert!(names.contains(&"docs".to_string()));
6133        for legacy in ["grep", "find", "ls", "image"] {
6134            assert!(
6135                !names.contains(&legacy.to_string()),
6136                "legacy tool {legacy} should not be registered by default"
6137            );
6138        }
6139    }
6140
6141    #[test]
6142    fn reload_settings_preflight_respects_trust() {
6143        struct RestoreConfigDir(Option<std::ffi::OsString>);
6144
6145        impl Drop for RestoreConfigDir {
6146            fn drop(&mut self) {
6147                match self.0.take() {
6148                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6149                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6150                }
6151            }
6152        }
6153
6154        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6155        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6156        let tmp = tempfile::tempdir().unwrap();
6157        let agent = tmp.path().join("agent");
6158        let cwd = tmp.path().join("project");
6159        std::fs::create_dir_all(&agent).unwrap();
6160        std::fs::create_dir_all(cwd.join(".rpi")).unwrap();
6161        std::fs::write(agent.join("settings.json"), "{}").unwrap();
6162        std::fs::write(cwd.join(".rpi/settings.json"), "{ malformed").unwrap();
6163        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6164        let args = Args::default();
6165
6166        let trusted = validate_settings_for_reload(&args, &cwd, true);
6167        let untrusted = validate_settings_for_reload(&args, &cwd, false);
6168        assert!(trusted
6169            .unwrap_err()
6170            .contains("could not load project settings"));
6171        assert!(untrusted.is_ok());
6172
6173        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
6174        assert!(validate_settings_for_reload(&args, &cwd, false)
6175            .unwrap_err()
6176            .contains("could not load global settings"));
6177
6178        let local_only = Args {
6179            dev_local_only: true,
6180            ..Args::default()
6181        };
6182        assert!(validate_settings_for_reload(&local_only, &cwd, true).is_ok());
6183    }
6184
6185    #[tokio::test]
6186    async fn reload_collects_plugin_loader_warnings_for_the_ui() {
6187        let tmp = tempfile::tempdir().unwrap();
6188        let cwd = tmp.path().join("project");
6189        let extensions = tmp.path().join("extensions");
6190        std::fs::create_dir_all(&cwd).unwrap();
6191        std::fs::create_dir_all(&extensions).unwrap();
6192        let home = crate::config::AgentHome::from_option(Some(tmp.path().join("agent"))).unwrap();
6193        let resolved = crate::provider::resolve(
6194            &home,
6195            Some("anthropic"),
6196            Some(crate::provider::DEFAULT_MODEL_ID),
6197            None,
6198            Some("test-key"),
6199            None,
6200        )
6201        .unwrap();
6202        let args = Args {
6203            no_session: true,
6204            extensions_dir: vec![extensions.clone()],
6205            ..Args::default()
6206        };
6207        let (harness, _, context) = build(&home, &resolved, &args, &cwd, false).await.unwrap();
6208        let filename = format!("bad-reload{}", std::env::consts::DLL_SUFFIX);
6209        std::fs::write(extensions.join(&filename), "not a dynamic library").unwrap();
6210
6211        let outcome = reload_extension_resources(&harness, &context).await;
6212        assert!(!outcome.had_errors, "{}", outcome.summary);
6213        assert!(outcome.had_warnings);
6214        assert!(
6215            outcome
6216                .details
6217                .iter()
6218                .any(|line| line.contains("skipped plugin") && line.contains(&filename)),
6219            "{:?}",
6220            outcome.details
6221        );
6222    }
6223
6224    #[tokio::test(flavor = "current_thread")]
6225    async fn reload_preserves_live_resources_when_settings_break() {
6226        struct RestoreConfigDir(Option<std::ffi::OsString>);
6227
6228        impl Drop for RestoreConfigDir {
6229            fn drop(&mut self) {
6230                match self.0.take() {
6231                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6232                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6233                }
6234            }
6235        }
6236
6237        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6238        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6239        let tmp = tempfile::tempdir().unwrap();
6240        let agent = tmp.path().join("agent");
6241        let cwd = tmp.path().join("project");
6242        let skill_dir = tmp.path().join("configured-skills");
6243        std::fs::create_dir_all(&agent).unwrap();
6244        std::fs::create_dir_all(&cwd).unwrap();
6245        std::fs::create_dir_all(&skill_dir).unwrap();
6246        std::fs::write(
6247            skill_dir.join("SKILL.md"),
6248            "---\nname: keep-me\ndescription: Reload sentinel\n---\nKeep this skill loaded.",
6249        )
6250        .unwrap();
6251        std::fs::write(
6252            agent.join("settings.json"),
6253            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
6254        )
6255        .unwrap();
6256        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6257
6258        let resolved = crate::provider::resolve(
6259            &crate::config::AgentHome::process(),
6260            Some("anthropic"),
6261            Some(crate::provider::DEFAULT_MODEL_ID),
6262            None,
6263            Some("test-key"),
6264            None,
6265        )
6266        .unwrap();
6267        let args = Args {
6268            trust_override: Some(false),
6269            no_session: true,
6270            no_extensions: true,
6271            no_prompt_templates: true,
6272            no_context_files: true,
6273            system_prompt: Some("stable system prompt".into()),
6274            ..Args::default()
6275        };
6276        let (harness, _events, context) = build(
6277            &crate::config::AgentHome::process(),
6278            &resolved,
6279            &args,
6280            &cwd,
6281            false,
6282        )
6283        .await
6284        .unwrap();
6285        let before_resources = harness.get_resources().await.unwrap();
6286        assert_eq!(before_resources.skills.as_ref().unwrap().len(), 1);
6287        assert_eq!(before_resources.skills.as_ref().unwrap()[0].name, "keep-me");
6288        let before_prompt = harness.get_system_prompt().await.unwrap();
6289        let before_tools: Vec<String> = harness
6290            .get_tools()
6291            .await
6292            .unwrap()
6293            .iter()
6294            .map(|tool| tool.tool.schema().name.clone())
6295            .collect();
6296        let before_bridge = context
6297            .action_bridge
6298            .lock()
6299            .unwrap()
6300            .as_ref()
6301            .unwrap()
6302            .clone();
6303
6304        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
6305        let outcome = reload_extension_resources(&harness, &context).await;
6306
6307        assert!(outcome.had_warnings);
6308        assert!(outcome.summary.contains("Settings reload failed"));
6309        assert!(outcome.summary.contains("could not load global settings"));
6310        // Hard failure keeps the previous resources; the outcome must not
6311        // advertise a fresh trust policy either (theme discovery keeps the
6312        // registry it already matches).
6313        assert_eq!(outcome.project_trusted, None);
6314        assert_eq!(harness.get_resources().await.unwrap(), before_resources);
6315        assert_eq!(harness.get_system_prompt().await.unwrap(), before_prompt);
6316        let after_tools: Vec<String> = harness
6317            .get_tools()
6318            .await
6319            .unwrap()
6320            .iter()
6321            .map(|tool| tool.tool.schema().name.clone())
6322            .collect();
6323        assert_eq!(after_tools, before_tools);
6324        let after_bridge = context
6325            .action_bridge
6326            .lock()
6327            .unwrap()
6328            .as_ref()
6329            .unwrap()
6330            .clone();
6331        assert!(Arc::ptr_eq(&after_bridge, &before_bridge));
6332    }
6333
6334    #[tokio::test(flavor = "current_thread")]
6335    async fn reload_outcome_carries_the_current_project_trust() {
6336        struct RestoreConfigDir(Option<std::ffi::OsString>);
6337
6338        impl Drop for RestoreConfigDir {
6339            fn drop(&mut self) {
6340                match self.0.take() {
6341                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6342                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6343                }
6344            }
6345        }
6346
6347        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6348        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6349        let tmp = tempfile::tempdir().unwrap();
6350        let agent = tmp.path().join("agent");
6351        let cwd = tmp.path().join("project");
6352        std::fs::create_dir_all(&agent).unwrap();
6353        std::fs::create_dir_all(&cwd).unwrap();
6354        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6355
6356        // Startup snapshot: trusted.
6357        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
6358        let resolved = crate::provider::resolve(
6359            &crate::config::AgentHome::process(),
6360            Some("anthropic"),
6361            Some(crate::provider::DEFAULT_MODEL_ID),
6362            None,
6363            Some("test-key"),
6364            None,
6365        )
6366        .unwrap();
6367        let args = Args {
6368            no_session: true,
6369            no_extensions: true,
6370            no_prompt_templates: true,
6371            no_context_files: true,
6372            system_prompt: Some("stable system prompt".into()),
6373            ..Args::default()
6374        };
6375        let (harness, _events, context) = build(
6376            &crate::config::AgentHome::process(),
6377            &resolved,
6378            &args,
6379            &cwd,
6380            true,
6381        )
6382        .await
6383        .unwrap();
6384        assert!(context.project_trusted, "startup snapshot is trusted");
6385
6386        // /trust no, then /reload: the outcome must report the CURRENT
6387        // decision, not the immutable startup snapshot.
6388        crate::config::set_project_trust(&cwd, Some(false)).unwrap();
6389        let outcome = reload_extension_resources(&harness, &context).await;
6390        assert!(!outcome.had_errors, "{}", outcome.summary);
6391        assert_eq!(outcome.project_trusted, Some(false));
6392
6393        // And the opposite transition back to trusted.
6394        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
6395        let outcome = reload_extension_resources(&harness, &context).await;
6396        assert!(!outcome.had_errors, "{}", outcome.summary);
6397        assert_eq!(outcome.project_trusted, Some(true));
6398    }
6399
6400    /// An explicit agent home owns its transcripts: the default session root
6401    /// is `<home>/sessions`, while `--session-dir` still wins. The process
6402    /// session-dir env override must not bleed into an explicit home.
6403    #[test]
6404    fn agent_home_defaults_the_session_root_under_the_home() {
6405        let home = tempfile::tempdir().unwrap();
6406        let cwd = tempfile::tempdir().unwrap();
6407        let env_dir = cwd.path().join("env-sessions");
6408        let _env = crate::config::test_support::SessionDirEnv::new(Some(&env_dir));
6409        let agent_home =
6410            crate::config::AgentHome::from_option(Some(home.path().to_path_buf())).unwrap();
6411        let args = Args::default();
6412        assert_eq!(
6413            configured_session_dir_for(&agent_home, &args, cwd.path()),
6414            home.path().join("sessions")
6415        );
6416
6417        let explicit = cwd.path().join("explicit-sessions");
6418        let args = Args {
6419            session_dir: Some(explicit.clone()),
6420            ..Args::default()
6421        };
6422        assert_eq!(
6423            configured_session_dir_for(&agent_home, &args, cwd.path()),
6424            explicit
6425        );
6426    }
6427
6428    /// `/reload` must re-read resources from the session's explicit agent home,
6429    /// not the process default and not a startup snapshot.
6430    #[test]
6431    fn reload_inputs_reread_the_selected_agent_home() {
6432        struct RestoreConfigDir(Option<std::ffi::OsString>);
6433        impl Drop for RestoreConfigDir {
6434            fn drop(&mut self) {
6435                match self.0.take() {
6436                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6437                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6438                }
6439            }
6440        }
6441
6442        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6443        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6444        let process_home = tempfile::tempdir().unwrap();
6445        let selected_home = tempfile::tempdir().unwrap();
6446        let cwd = tempfile::tempdir().unwrap();
6447        std::env::set_var(crate::config::CONFIG_DIR_ENV, process_home.path());
6448        let process_skills = process_home.path().join("process-only-skills");
6449        std::fs::create_dir_all(&process_skills).unwrap();
6450        let selected_skills = selected_home.path().join("skills");
6451        std::fs::create_dir_all(selected_skills.join("base")).unwrap();
6452        std::fs::write(
6453            selected_skills.join("base").join("SKILL.md"),
6454            "---\nname: base\ndescription: base skill\n---\nbody\n",
6455        )
6456        .unwrap();
6457        std::fs::write(selected_home.path().join("settings.json"), "{}").unwrap();
6458
6459        let selected_agent_home =
6460            crate::config::AgentHome::from_option(Some(selected_home.path().to_path_buf()))
6461                .unwrap();
6462        let args = Args {
6463            no_session: true,
6464            no_extensions: true,
6465            no_prompt_templates: true,
6466            no_context_files: true,
6467            ..Args::default()
6468        };
6469
6470        let first =
6471            prepare_reload_inputs_for(&selected_agent_home, &args, cwd.path(), false).unwrap();
6472        assert!(
6473            first
6474                .skill_base_dirs
6475                .iter()
6476                .any(|dir| dir == &selected_skills),
6477            "{:?}",
6478            first.skill_base_dirs
6479        );
6480        assert!(
6481            first
6482                .skill_base_dirs
6483                .iter()
6484                .all(|dir| !dir.starts_with(process_home.path())),
6485            "{:?}",
6486            first.skill_base_dirs
6487        );
6488
6489        // A settings change in the selected home is observed by the next
6490        // reload pass (the file is re-read, not cached at startup).
6491        let extra = selected_home.path().join("extra-skills");
6492        std::fs::create_dir_all(&extra).unwrap();
6493        std::fs::write(
6494            selected_home.path().join("settings.json"),
6495            serde_json::json!({"skillDirs": [extra]}).to_string(),
6496        )
6497        .unwrap();
6498        let second =
6499            prepare_reload_inputs_for(&selected_agent_home, &args, cwd.path(), false).unwrap();
6500        assert!(
6501            second.skill_base_dirs.iter().any(|dir| dir == &extra),
6502            "{:?}",
6503            second.skill_base_dirs
6504        );
6505    }
6506
6507    #[test]
6508    fn registry_aware_global_selection_falls_back_when_the_registry_is_corrupt() {
6509        struct RestoreConfigDir(Option<std::ffi::OsString>);
6510
6511        impl Drop for RestoreConfigDir {
6512            fn drop(&mut self) {
6513                match self.0.take() {
6514                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6515                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6516                }
6517            }
6518        }
6519
6520        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6521        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6522        let tmp = tempfile::tempdir().unwrap();
6523        let agent = tmp.path().join("agent");
6524        let extensions = agent.join("extensions");
6525        std::fs::create_dir_all(&extensions).unwrap();
6526        std::fs::write(agent.join("native-packages.json"), b"{ this is not json").unwrap();
6527        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6528
6529        // An unreadable registry cannot tell us which artifacts are retired. Keep
6530        // the historical directory scan instead of silently loading nothing.
6531        let dirs = vec![extensions.clone()];
6532        let (scan_dirs, files) = registry_aware_extension_inputs(&dirs, &[], None);
6533        assert!(
6534            scan_dirs.contains(&extensions),
6535            "a corrupt registry must not disable every global extension"
6536        );
6537        assert!(files.is_empty());
6538    }
6539
6540    #[test]
6541    fn startup_and_reload_use_registry_aware_global_extension_selection() {
6542        struct RestoreConfigDir(Option<std::ffi::OsString>);
6543
6544        impl Drop for RestoreConfigDir {
6545            fn drop(&mut self) {
6546                match self.0.take() {
6547                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6548                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6549                }
6550            }
6551        }
6552
6553        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6554        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6555        let tmp = tempfile::tempdir().unwrap();
6556        let agent = tmp.path().join("agent");
6557        let cwd = tmp.path().join("project");
6558        let extensions = agent.join("extensions");
6559        std::fs::create_dir_all(&extensions).unwrap();
6560        std::fs::create_dir_all(&cwd).unwrap();
6561
6562        let active =
6563            extensions.join("librpi_web_extension-v0.1.64-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.so");
6564        let stale_same_version =
6565            extensions.join("librpi_web_extension-v0.1.64-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.so");
6566        let stale_rpi_web =
6567            extensions.join("librpi_web_extension-v0.1.63-cccccccccccccccccccccccccccccccc.so");
6568        let legacy = extensions.join("legacy_custom.so");
6569        for path in [&active, &stale_same_version, &stale_rpi_web, &legacy] {
6570            std::fs::write(path, b"cdylib").unwrap();
6571        }
6572        let registry = serde_json::json!([
6573            {
6574                "name": "rpi-web",
6575                "version": "0.1.64",
6576                "source": null,
6577                "artifacts": [active.file_name().unwrap().to_str().unwrap()]
6578            }
6579        ]);
6580        std::fs::write(agent.join("native-packages.json"), registry.to_string()).unwrap();
6581        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6582
6583        let args = Args {
6584            trust_override: Some(false),
6585            ..Args::default()
6586        };
6587        let home = crate::config::AgentHome::process();
6588        let startup_dirs = startup_extension_dirs(&home, &args, &cwd, false);
6589        let home_root = home.root().ok();
6590        assert!(startup_dirs.contains(&extensions));
6591        let (startup_scan_dirs, startup_files) =
6592            registry_aware_extension_inputs(&startup_dirs, &args.extension, home_root.as_deref());
6593        assert!(!startup_scan_dirs.contains(&extensions));
6594        assert!(startup_files.contains(&active));
6595        assert!(startup_files.contains(&legacy));
6596        assert!(!startup_files.contains(&stale_same_version));
6597        assert!(!startup_files.contains(&stale_rpi_web));
6598
6599        let prepared = prepare_reload_inputs_inner(&args, &cwd, false, || {}).unwrap();
6600        let (reload_scan_dirs, reload_files) = registry_aware_extension_inputs(
6601            &prepared.extension_dirs,
6602            &args.extension,
6603            home_root.as_deref(),
6604        );
6605        assert!(!reload_scan_dirs.contains(&extensions));
6606        assert_eq!(reload_files, startup_files);
6607    }
6608
6609    #[test]
6610    fn registry_aware_global_selection_keeps_unmanaged_legacy_cdylib() {
6611        struct RestoreConfigDir(Option<std::ffi::OsString>);
6612
6613        impl Drop for RestoreConfigDir {
6614            fn drop(&mut self) {
6615                match self.0.take() {
6616                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6617                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6618                }
6619            }
6620        }
6621
6622        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6623        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6624        let tmp = tempfile::tempdir().unwrap();
6625        let agent = tmp.path().join("agent");
6626        let extensions = agent.join("extensions");
6627        std::fs::create_dir_all(&extensions).unwrap();
6628        let legacy = extensions.join("legacy_custom.so");
6629        std::fs::write(&legacy, b"cdylib").unwrap();
6630        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6631
6632        let (dirs, files) =
6633            registry_aware_extension_inputs(&[extensions.clone()], &[], Some(agent.as_path()));
6634        assert!(dirs.is_empty());
6635        assert_eq!(files, vec![legacy]);
6636    }
6637
6638    #[test]
6639    fn reload_preparation_rejects_settings_changed_during_derivation() {
6640        struct RestoreConfigDir(Option<std::ffi::OsString>);
6641
6642        impl Drop for RestoreConfigDir {
6643            fn drop(&mut self) {
6644                match self.0.take() {
6645                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6646                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6647                }
6648            }
6649        }
6650
6651        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6652        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6653        let tmp = tempfile::tempdir().unwrap();
6654        let agent = tmp.path().join("agent");
6655        let cwd = tmp.path().join("project");
6656        let first_skill_dir = tmp.path().join("first-skills");
6657        let second_skill_dir = tmp.path().join("second-skills");
6658        std::fs::create_dir_all(&agent).unwrap();
6659        std::fs::create_dir_all(&cwd).unwrap();
6660        std::fs::write(
6661            agent.join("settings.json"),
6662            serde_json::json!({"skillDirs": [first_skill_dir]}).to_string(),
6663        )
6664        .unwrap();
6665        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6666        let args = Args {
6667            trust_override: Some(false),
6668            no_extensions: true,
6669            no_prompt_templates: true,
6670            ..Args::default()
6671        };
6672
6673        let result = prepare_reload_inputs_inner(&args, &cwd, false, || {
6674            std::fs::write(
6675                agent.join("settings.json"),
6676                serde_json::json!({"skillDirs": [second_skill_dir]}).to_string(),
6677            )
6678            .unwrap();
6679        });
6680
6681        let error = result
6682            .err()
6683            .expect("settings mutation must fail preparation");
6684        assert!(error.contains("settings changed while reload inputs were being prepared"));
6685    }
6686
6687    #[tokio::test(flavor = "current_thread")]
6688    async fn reload_uses_frozen_settings_inputs_after_preparation() {
6689        struct RestoreConfigDir(Option<std::ffi::OsString>);
6690
6691        impl Drop for RestoreConfigDir {
6692            fn drop(&mut self) {
6693                match self.0.take() {
6694                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6695                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6696                }
6697            }
6698        }
6699
6700        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6701        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6702        let tmp = tempfile::tempdir().unwrap();
6703        let agent = tmp.path().join("agent");
6704        let cwd = tmp.path().join("project");
6705        let skill_dir = tmp.path().join("configured-skills");
6706        std::fs::create_dir_all(&agent).unwrap();
6707        std::fs::create_dir_all(&cwd).unwrap();
6708        std::fs::create_dir_all(&skill_dir).unwrap();
6709        std::fs::write(
6710            skill_dir.join("SKILL.md"),
6711            "---\nname: frozen-skill\ndescription: Reload sentinel\n---\nFrozen input.",
6712        )
6713        .unwrap();
6714        std::fs::write(
6715            agent.join("settings.json"),
6716            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
6717        )
6718        .unwrap();
6719        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6720
6721        let resolved = crate::provider::resolve(
6722            &crate::config::AgentHome::process(),
6723            Some("anthropic"),
6724            Some(crate::provider::DEFAULT_MODEL_ID),
6725            None,
6726            Some("test-key"),
6727            None,
6728        )
6729        .unwrap();
6730        let args = Args {
6731            trust_override: Some(false),
6732            no_session: true,
6733            no_extensions: true,
6734            no_prompt_templates: true,
6735            no_context_files: true,
6736            system_prompt: Some("stable system prompt".into()),
6737            ..Args::default()
6738        };
6739        let (harness, _events, context) = build(
6740            &crate::config::AgentHome::process(),
6741            &resolved,
6742            &args,
6743            &cwd,
6744            false,
6745        )
6746        .await
6747        .unwrap();
6748
6749        let outcome = reload_extension_resources_inner(&harness, &context, || {
6750            std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
6751        })
6752        .await;
6753
6754        assert!(!outcome.summary.contains("Settings reload failed"));
6755        assert_eq!(
6756            outcome.summary,
6757            "Reloaded 0 plugin(s), 1 skill(s), 0 prompt(s)."
6758        );
6759        let resources = harness.get_resources().await.unwrap();
6760        let skills = resources.skills.as_ref().unwrap();
6761        assert_eq!(skills.len(), 1);
6762        assert_eq!(skills[0].name, "frozen-skill");
6763    }
6764
6765    #[tokio::test]
6766    async fn reload_resource_paths_include_explicit_skill_and_prompt_files() {
6767        let tmp = tempfile::tempdir().unwrap();
6768        let skill_path = tmp.path().join("explicit-skill.md");
6769        std::fs::write(
6770            &skill_path,
6771            "---\nname: explicit-skill\ndescription: Explicit skill\n---\nSkill body",
6772        )
6773        .unwrap();
6774        let prompt_path = tmp.path().join("explicit-prompt.md");
6775        std::fs::write(
6776            &prompt_path,
6777            "---\ndescription: Explicit prompt\n---\nPrompt body",
6778        )
6779        .unwrap();
6780
6781        let args = Args {
6782            skill: vec![skill_path.clone()],
6783            prompt_template: vec![prompt_path.clone()],
6784            ..Args::default()
6785        };
6786        let skill_paths = append_reload_resource_paths(Vec::new(), &args.skill, &[], &[], &[]);
6787        let prompt_paths =
6788            append_reload_resource_paths(Vec::new(), &args.prompt_template, &[], &[], &[]);
6789        let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
6790        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env;
6791
6792        let skills = load_skills_with_precedence(&env_dyn, &skill_paths).await;
6793        assert_eq!(skills.skills.len(), 1, "{:?}", skills.diagnostics);
6794        assert_eq!(skills.skills[0].name, "explicit-skill");
6795
6796        let prompts = load_prompt_templates_with_precedence(&env_dyn, &prompt_paths).await;
6797        assert_eq!(
6798            prompts.prompt_templates.len(),
6799            1,
6800            "{:?}",
6801            prompts.diagnostics
6802        );
6803        assert_eq!(prompts.prompt_templates[0].name, "explicit-prompt");
6804    }
6805
6806    #[test]
6807    fn tool_policy_applies_to_rust_and_js_active_names() {
6808        let names = vec![
6809            "read".to_string(),
6810            "ask_user_question".to_string(),
6811            "write".to_string(),
6812        ];
6813
6814        let args = Args {
6815            tools: Some(vec!["read".into(), "ask_user_question".into()]),
6816            ..Args::default()
6817        };
6818        assert_eq!(
6819            filter_active_tool_names(names.clone(), &args),
6820            vec!["read", "ask_user_question"]
6821        );
6822
6823        let args = Args {
6824            exclude_tools: Some(vec!["ask_user_question".into()]),
6825            ..Args::default()
6826        };
6827        assert_eq!(
6828            filter_active_tool_names(names.clone(), &args),
6829            vec!["read", "write"]
6830        );
6831
6832        let args = Args {
6833            no_tools: true,
6834            ..Args::default()
6835        };
6836        assert!(filter_active_tool_names(names, &args).is_empty());
6837    }
6838
6839    #[test]
6840    fn select_ephemeral_when_no_session() {
6841        let args = Args {
6842            no_session: true,
6843            ..Args::default()
6844        };
6845        let cwd = Path::new("/tmp");
6846        assert!(matches!(
6847            select_session(&args, cwd),
6848            SessionSelection::Ephemeral
6849        ));
6850    }
6851
6852    #[test]
6853    fn project_resources_load_by_default_and_allow_explicit_opt_out() {
6854        let defaults = Args::default();
6855        assert!(resolve_project_trust(
6856            &defaults,
6857            Path::new("C:/definitely-not-a-project")
6858        ));
6859
6860        let denied = Args {
6861            trust_override: Some(false),
6862            ..Args::default()
6863        };
6864        assert!(!resolve_project_trust(
6865            &denied,
6866            Path::new("C:/definitely-not-a-project")
6867        ));
6868    }
6869
6870    #[tokio::test(flavor = "current_thread")]
6871    async fn build_preserves_the_supplied_startup_project_snapshot() {
6872        struct RestoreConfigDir(Option<std::ffi::OsString>);
6873
6874        impl Drop for RestoreConfigDir {
6875            fn drop(&mut self) {
6876                match self.0.take() {
6877                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6878                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6879                }
6880            }
6881        }
6882
6883        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6884        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6885        let tmp = tempfile::tempdir().unwrap();
6886        let agent = tmp.path().join("agent");
6887        let cwd = tmp.path().join("project");
6888        std::fs::create_dir_all(&agent).unwrap();
6889        std::fs::create_dir_all(&cwd).unwrap();
6890        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6891
6892        let resolved = crate::provider::resolve(
6893            &crate::config::AgentHome::process(),
6894            Some("anthropic"),
6895            Some(crate::provider::DEFAULT_MODEL_ID),
6896            None,
6897            Some("test-key"),
6898            None,
6899        )
6900        .unwrap();
6901        let args = Args {
6902            trust_override: Some(false),
6903            no_session: true,
6904            no_tools: true,
6905            no_extensions: true,
6906            no_skills: true,
6907            no_prompt_templates: true,
6908            no_context_files: true,
6909            system_prompt: Some("test prompt".into()),
6910            ..Args::default()
6911        };
6912
6913        let (_, _, context) = build(
6914            &crate::config::AgentHome::process(),
6915            &resolved,
6916            &args,
6917            &cwd,
6918            true,
6919        )
6920        .await
6921        .unwrap();
6922
6923        assert_eq!(context.cwd, cwd);
6924        assert!(context.project_trusted);
6925    }
6926
6927    #[tokio::test(flavor = "current_thread")]
6928    async fn build_applies_the_name_flag_to_the_session() {
6929        struct RestoreConfigDir(Option<std::ffi::OsString>);
6930
6931        impl Drop for RestoreConfigDir {
6932            fn drop(&mut self) {
6933                match self.0.take() {
6934                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
6935                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
6936                }
6937            }
6938        }
6939
6940        let _guard = crate::config::test_support::env_lock().lock().unwrap();
6941        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
6942        let tmp = tempfile::tempdir().unwrap();
6943        let agent = tmp.path().join("agent");
6944        let cwd = tmp.path().join("project");
6945        std::fs::create_dir_all(&agent).unwrap();
6946        std::fs::create_dir_all(&cwd).unwrap();
6947        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
6948
6949        let resolved = crate::provider::resolve(
6950            &crate::config::AgentHome::process(),
6951            Some("anthropic"),
6952            Some(crate::provider::DEFAULT_MODEL_ID),
6953            None,
6954            Some("test-key"),
6955            None,
6956        )
6957        .unwrap();
6958        let args = Args {
6959            trust_override: Some(false),
6960            no_tools: true,
6961            no_extensions: true,
6962            no_skills: true,
6963            no_prompt_templates: true,
6964            no_context_files: true,
6965            system_prompt: Some("test prompt".into()),
6966            name: Some("smoke name".into()),
6967            session_dir: Some(cwd.join("sessions")),
6968            ..Args::default()
6969        };
6970
6971        let (harness, _, _) = build(
6972            &crate::config::AgentHome::process(),
6973            &resolved,
6974            &args,
6975            &cwd,
6976            true,
6977        )
6978        .await
6979        .unwrap();
6980        assert_eq!(
6981            harness.get_name().await.unwrap().as_deref(),
6982            Some("smoke name")
6983        );
6984    }
6985
6986    #[test]
6987    fn select_latest_for_continue_and_resume() {
6988        let _env = crate::config::test_support::SessionDirEnv::new(None);
6989        let args = Args {
6990            continue_session: true,
6991            ..Args::default()
6992        };
6993        let cwd = Path::new("/tmp");
6994        assert!(matches!(
6995            select_session(&args, cwd),
6996            SessionSelection::Latest { .. }
6997        ));
6998
6999        let args = Args {
7000            resume: true,
7001            ..Args::default()
7002        };
7003        assert!(matches!(
7004            select_session(&args, cwd),
7005            SessionSelection::Latest { .. }
7006        ));
7007    }
7008
7009    #[test]
7010    fn select_by_id_for_session_flag() {
7011        let _env = crate::config::test_support::SessionDirEnv::new(None);
7012        let args = Args {
7013            session: Some("01a02ece".into()),
7014            ..Args::default()
7015        };
7016        let cwd = Path::new("/tmp");
7017        assert!(matches!(
7018            select_session(&args, cwd),
7019            SessionSelection::ById { id, .. } if id == "01a02ece"
7020        ));
7021    }
7022
7023    /// The cut flags have to survive selection: `select_session_in_dir` is the
7024    /// only place that copies them off `Args`, so a dropped field here would
7025    /// make `--fork-entry` silently fork at the lane leaf again.
7026    #[test]
7027    fn select_fork_carries_the_cut_flags() {
7028        use rpi_harness::session::types::ForkPosition;
7029
7030        let _env = crate::config::test_support::SessionDirEnv::new(None);
7031        let cwd = Path::new("/tmp");
7032
7033        // No cut: both stay absent so the build uses the harness defaults.
7034        let args = Args {
7035            fork: Some("parent".into()),
7036            ..Args::default()
7037        };
7038        match select_session(&args, cwd) {
7039            SessionSelection::Fork {
7040                source,
7041                entry_id,
7042                position,
7043                ..
7044            } => {
7045                assert_eq!(source, "parent");
7046                assert_eq!(entry_id, None);
7047                assert_eq!(position, None);
7048            }
7049            other => panic!("expected Fork, got {other:?}"),
7050        }
7051
7052        for (flag, expected) in [
7053            (None, None),
7054            (Some(ForkPosition::At), Some(ForkPosition::At)),
7055            (Some(ForkPosition::Before), Some(ForkPosition::Before)),
7056        ] {
7057            let args = Args {
7058                fork: Some("parent".into()),
7059                fork_entry: Some("message-2".into()),
7060                fork_position: flag,
7061                ..Args::default()
7062            };
7063            match select_session(&args, cwd) {
7064                SessionSelection::Fork {
7065                    entry_id, position, ..
7066                } => {
7067                    assert_eq!(entry_id.as_deref(), Some("message-2"));
7068                    assert_eq!(position, expected, "{flag:?}");
7069                }
7070                other => panic!("expected Fork, got {other:?}"),
7071            }
7072        }
7073    }
7074
7075    #[test]
7076    fn select_new_with_custom_dir() {
7077        let _env = crate::config::test_support::SessionDirEnv::new(None);
7078        let args = Args {
7079            session_dir: Some(PathBuf::from("/tmp/sess")),
7080            ..Args::default()
7081        };
7082        let cwd = Path::new("/tmp");
7083        match select_session(&args, cwd) {
7084            SessionSelection::New { dir, .. } => assert_eq!(dir, PathBuf::from("/tmp/sess")),
7085            other => panic!("expected New, got {other:?}"),
7086        }
7087    }
7088
7089    #[test]
7090    fn select_new_default_dir() {
7091        let _env = crate::config::test_support::SessionDirEnv::new(None);
7092        let args = Args::default();
7093        let cwd = Path::new("/proj");
7094        match select_session(&args, cwd) {
7095            SessionSelection::New { dir, .. } => {
7096                assert_eq!(dir, Path::new("/proj/.rpi/sessions"));
7097            }
7098            other => panic!("expected New, got {other:?}"),
7099        }
7100    }
7101
7102    #[test]
7103    fn default_session_dir_only_uses_rpi() {
7104        let _env = crate::config::test_support::SessionDirEnv::new(None);
7105        let tmp = tempfile::tempdir().unwrap();
7106        let cwd = tmp.path();
7107        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
7108        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
7109        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
7110        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
7111    }
7112
7113    #[test]
7114    fn default_session_dir_uses_env_var() {
7115        let tmp = tempfile::tempdir().unwrap();
7116        let cwd = tmp.path();
7117        let custom = tmp.path().join("custom_sessions");
7118        let _env = crate::config::test_support::SessionDirEnv::new(Some(&custom));
7119        assert_eq!(default_session_dir(cwd), custom);
7120    }
7121
7122    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7123    async fn ephemeral_session_builds_roundtrips() {
7124        // Sanity: the ephemeral path produces a usable Session facade (the
7125        // harness build itself needs a provider; tested via the integration
7126        // path in tests/build.rs instead).
7127        let s = ephemeral_session();
7128        let leaf = s.get_leaf_id().await;
7129        assert!(leaf.is_ok());
7130    }
7131
7132    // NOTE: `build_tools`/`active_tool_names` integration is exercised by the
7133    // `tests/build.rs` harness-build test (needs a provider + multi-thread rt).
7134
7135    /// The exclusion policy, checked against the constants rather than copies.
7136    ///
7137    /// `rpi-tools` builds its exclusion from `rpi-plugin-sdk`'s declarations, so
7138    /// within this repo a rename is a compile error — this test is not the link
7139    /// between those two crates any more. What it still guards is the part the
7140    /// compiler cannot see:
7141    ///
7142    /// - **The wire values.** `rpi-langfuse` lives in a different repository and
7143    ///   agrees on the *strings*, not the constant paths. Rewriting a constant's
7144    ///   value would compile here and silently stop matching there, so the exact
7145    ///   values are pinned below. Changing one is a deliberate, breaking change to
7146    ///   a cross-repo contract, and it should fail here first.
7147    /// - **Coverage.** Every name the SDK declares must actually be excluded.
7148    /// - **Narrowness.** The user's own configuration must still reach the shell.
7149    #[test]
7150    fn host_private_env_matches_the_declared_contract() {
7151        // 1. The wire values. Pinned literally on purpose: see the doc comment.
7152        assert_eq!(rpi_plugin_sdk::SESSION_ID_ENV, "RPI_SESSION_ID");
7153        assert_eq!(
7154            rpi_plugin_sdk::SUBAGENT_PARENT_ENV,
7155            [
7156                "LANGFUSE_PI_PARENT_TRACE_ID",
7157                "LANGFUSE_PI_PARENT_SPAN_ID",
7158                "LANGFUSE_PI_PARENT_SESSION_ID",
7159                "LANGFUSE_PI_PARENT_DEPTH",
7160            ],
7161            "these strings are what rpi-langfuse (a different repo) matches; a \
7162             change here is a breaking cross-repo change, not a refactor"
7163        );
7164
7165        // 2. Coverage — derived from the declarations, so a newly added family
7166        //    member is checked without anyone remembering to extend this test.
7167        for name in rpi_plugin_sdk::SUBAGENT_PARENT_ENV
7168            .iter()
7169            .chain(std::iter::once(&rpi_plugin_sdk::SESSION_ID_ENV))
7170        {
7171            assert!(
7172                rpi_tools::is_host_private_env(name),
7173                "`{name}` must not reach a spawned shell, but rpi-tools excludes only {:?}",
7174                rpi_tools::HOST_PRIVATE_ENV
7175            );
7176        }
7177
7178        // 3. Narrowness — these name how the *user* configured the run and are
7179        //    exactly what a command inside the shell should still see.
7180        for visible in [
7181            crate::args::RPI_OFFLINE_ENV,
7182            crate::config::CONFIG_DIR_ENV,
7183            "PATH",
7184        ] {
7185            assert!(
7186                !rpi_tools::is_host_private_env(visible),
7187                "{visible} describes the user's configuration and must still reach the shell"
7188            );
7189        }
7190    }
7191    #[tokio::test]
7192    async fn reload_shutdown_joins_all_handlers_even_after_veto() {
7193        use rpi_plugin_sdk::{EventTag, StablePluginEvent};
7194        use std::sync::atomic::AtomicUsize;
7195        static CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<AtomicUsize>> =
7196            rpi_plugin_sdk::handles::ToolHandles::new();
7197        struct ContextOwner(usize);
7198        impl Drop for ContextOwner {
7199            fn drop(&mut self) {
7200                drop(CONTEXTS.remove(self.0 as rpi_plugin_sdk::StepHandle));
7201            }
7202        }
7203        extern "C" fn stop(_: StablePluginEvent, data: *mut std::ffi::c_void) -> i32 {
7204            let context = CONTEXTS.get(data).expect("live test context");
7205            let calls = context.lock().clone();
7206            std::thread::sleep(std::time::Duration::from_millis(20));
7207            if calls.fetch_add(1, Ordering::SeqCst) == 0 {
7208                rpi_plugin_sdk::EVENT_HANDLER_ABORT
7209            } else {
7210                0
7211            }
7212        }
7213        let calls = Arc::new(AtomicUsize::new(0));
7214        let context = CONTEXTS.insert(calls.clone());
7215        let _owner = ContextOwner(context as usize);
7216        let mut registry = rpi_extensions::ExtensionRegistry::new();
7217        for name in ["first", "second"] {
7218            registry.register_event_handler(name.into(), EventTag::SessionShutdown, stop, context);
7219        }
7220        super::shutdown_extensions_for_reload(
7221            Some(Arc::new(registry.snapshot())),
7222            rpi_extensions::PluginKeepalive::empty(),
7223        )
7224        .await
7225        .unwrap();
7226        assert_eq!(calls.load(Ordering::SeqCst), 2);
7227    }
7228
7229    #[tokio::test(flavor = "multi_thread")]
7230    async fn host_restore_revalidates_history_after_the_previous_writer_settles() {
7231        use rpi_harness::session::jsonl::{
7232            JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
7233        };
7234        use rpi_harness::session::{SessionValueWriter, SessionValues};
7235
7236        for reject_binding in [false, true] {
7237            let project = tempfile::tempdir().unwrap();
7238            let cwd = project.path().canonicalize().unwrap();
7239            let dir = cwd.join("sessions");
7240            let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
7241                fs: Arc::new(OsExecutionEnv::with_cwd(cwd.clone())),
7242                sessions_root: dir.to_string_lossy().into_owned(),
7243                clock: Arc::new(SystemClock),
7244                ids: Arc::new(DefaultIdGenerator::new()),
7245            });
7246            let previous = Arc::new(
7247                repo.create_typed(&JsonlSessionCreateOptions {
7248                    id: None,
7249                    parent_session_id: None,
7250                    cwd: cwd.to_string_lossy().into_owned(),
7251                    metadata: None,
7252                })
7253                .await
7254                .unwrap(),
7255            );
7256            let meta = previous.jsonl_metadata();
7257            let previous = Session::new(previous, None);
7258            let writer = SessionValueWriter::new(previous.clone());
7259            let key = if reject_binding {
7260                "rpi.resource-selection.v1"
7261            } else {
7262                "test-handoff"
7263            };
7264            let mut checks = 0;
7265            let prepared = prepare_host_restore(&repo, &meta, |values| {
7266                checks += 1;
7267                if checks == 1 {
7268                    assert!(values.get(key).is_none());
7269                    tokio::task::block_in_place(|| {
7270                        tokio::runtime::Handle::current().block_on(async {
7271                            writer
7272                                .set(key, serde_json::json!("final write"))
7273                                .await
7274                                .unwrap();
7275                            previous.drain().await;
7276                        });
7277                    });
7278                    previous.storage().release_writer_lease();
7279                } else {
7280                    assert_eq!(values.get_as::<String>(key).as_deref(), Some("final write"));
7281                }
7282                crate::resource_selection::validate_session_binding(values, None)
7283            })
7284            .await;
7285            assert_eq!(checks, 2);
7286            if reject_binding {
7287                let Err(error) = prepared else {
7288                    panic!("Host accepted an invalid binding from the final write");
7289                };
7290                assert!(error
7291                    .to_string()
7292                    .contains("invalid persisted resource binding"));
7293                let lease_probe = repo.prepare_restore_by_jsonl_metadata(&meta).await.unwrap();
7294                assert!(lease_probe
7295                    .reserve_current_writer()
7296                    .await
7297                    .unwrap()
7298                    .is_some());
7299            } else {
7300                let selection = SessionSelection::ByExactId {
7301                    id: meta.id.clone(),
7302                    dir,
7303                };
7304                let restored = restore_session(&selection, &meta.cwd, Some(prepared.unwrap()))
7305                    .await
7306                    .unwrap();
7307                assert!(restored.storage().writer_lease_held());
7308                assert_eq!(restored.storage().metadata().id, meta.id);
7309                let values = SessionValues::load(&restored).await.unwrap();
7310                assert_eq!(values.get_as::<String>(key).as_deref(), Some("final write"));
7311            }
7312        }
7313    }
7314
7315    // ---- restored-session working directory ----
7316
7317    /// A restore peek must name the directory the session was created in —
7318    /// that is the whole point of recording it. Everything downstream (tool
7319    /// env, system prompt, context files, extensions) keys off the run's cwd,
7320    /// so a peek that falls back to the launch directory would leave the
7321    /// resumed agent editing files in whatever directory `rpi` happened to be
7322    /// started from.
7323    #[tokio::test]
7324    async fn a_restored_session_adopts_its_recorded_directory() {
7325        let tmp = tempfile::tempdir().unwrap();
7326        let project = tmp.path().join("project-a");
7327        let launch = tmp.path().join("launch-dir");
7328        let sessions = tmp.path().join("sessions");
7329        std::fs::create_dir_all(&project).unwrap();
7330        std::fs::create_dir_all(&launch).unwrap();
7331        std::fs::create_dir_all(&sessions).unwrap();
7332        create_jsonl_session_with_id(
7333            &sessions,
7334            &project.to_string_lossy(),
7335            Some("cwdadopt01".into()),
7336        )
7337        .await
7338        .unwrap();
7339
7340        let selection = SessionSelection::ById {
7341            id: "cwdadopt01".into(),
7342            dir: sessions.clone(),
7343        };
7344        let peeked = peek_restored_session_cwd(&selection, &launch)
7345            .await
7346            .expect("a resumable session with a recorded cwd");
7347        assert_eq!(peeked.recorded, project);
7348        assert_eq!(peeked.adopted, Some(project));
7349    }
7350
7351    /// A recorded directory that no longer exists must NOT be adopted: the run
7352    /// falls back to the launch cwd, and the peek hands back the record so the
7353    /// host can say so (instead of the old behaviour of eprintln-ing mid-TUI).
7354    #[tokio::test]
7355    async fn a_missing_recorded_directory_is_reported_not_adopted() {
7356        let tmp = tempfile::tempdir().unwrap();
7357        let gone = tmp.path().join("project-gone");
7358        let launch = tmp.path().join("launch-dir");
7359        let sessions = tmp.path().join("sessions");
7360        std::fs::create_dir_all(&launch).unwrap();
7361        std::fs::create_dir_all(&sessions).unwrap();
7362        create_jsonl_session_with_id(
7363            &sessions,
7364            &gone.to_string_lossy(),
7365            Some("cwdgone001".into()),
7366        )
7367        .await
7368        .unwrap();
7369
7370        let selection = SessionSelection::ById {
7371            id: "cwdgone001".into(),
7372            dir: sessions.clone(),
7373        };
7374        let peeked = peek_restored_session_cwd(&selection, &launch)
7375            .await
7376            .expect("the session itself is resumable");
7377        assert_eq!(peeked.recorded, gone);
7378        assert_eq!(peeked.adopted, None);
7379        let note = crate::session_cwd::missing_session_cwd_note(&peeked.recorded, &launch);
7380        assert!(note.contains("no longer exists"), "{note}");
7381        assert!(note.contains("launch-dir"), "{note}");
7382    }
7383
7384    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7385    async fn legacy_progress_upgrade_normal_open_runs_and_reopens() {
7386        use rpi_ai::providers::faux::{FauxProvider, FauxScript};
7387        use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
7388        use rpi_harness::session::jsonl::{
7389            encode_header, JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
7390            JsonlV4Header,
7391        };
7392        let tmp = tempfile::tempdir().unwrap();
7393        let sessions = tmp.path().join("sessions");
7394        std::fs::create_dir_all(&sessions).unwrap();
7395        let cwd = tmp.path().to_string_lossy().into_owned();
7396        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
7397            fs: Arc::new(OsExecutionEnv::with_cwd(tmp.path().into())),
7398            sessions_root: sessions.to_string_lossy().into_owned(),
7399            clock: Arc::new(SystemClock),
7400            ids: Arc::new(DefaultIdGenerator::new()),
7401        });
7402        let fixture = repo
7403            .create_typed(&JsonlSessionCreateOptions {
7404                id: Some("legacycli001".into()),
7405                parent_session_id: None,
7406                cwd: cwd.clone(),
7407                metadata: None,
7408            })
7409            .await
7410            .unwrap();
7411        let path = PathBuf::from(fixture.jsonl_metadata().path);
7412        drop(fixture);
7413        let sidecar = PathBuf::from(format!("{}.progress.jsonl", path.display()));
7414        std::fs::remove_file(&sidecar).unwrap();
7415        let header = JsonlV4Header::new("legacycli001".into(), 1, cwd.clone(), None, None, None);
7416        std::fs::write(&path, encode_header(&header)).unwrap();
7417        assert!(!sidecar.exists());
7418        for attempt in 0..2 {
7419            let restored = open_session_by_id_in_dir("legacycli001", &cwd, &sessions)
7420                .await
7421                .map_err(|e| e.to_string())
7422                .unwrap();
7423            // Hold the binding so the OS writer lease can be retired explicitly
7424            // below. Dropping the harness is NOT enough: any surviving `Arc` to
7425            // the storage keeps the lease alive until the last handle goes away,
7426            // so the next `open` of the SAME journal could still observe
7427            // "writer lease is already held". That ordering is not
7428            // deterministic, which is exactly how this test flaked under CI
7429            // concurrency.
7430            let storage = restored.session.storage();
7431            assert_eq!(storage.metadata().id, "legacycli001");
7432            assert!(
7433                storage.writer_lease_held(),
7434                "reopened binding must own the journal (attempt {attempt})"
7435            );
7436            let provider =
7437                FauxProvider::new(FauxScript::new().with_text("continued legacy session"));
7438            let harness = AgentHarness::create(AgentHarnessOptions {
7439                model: provider.default_model().clone(),
7440                models: vec![provider],
7441                session: restored.session,
7442                allow_existing_session: true,
7443                ..Default::default()
7444            })
7445            .await
7446            .unwrap();
7447            let run = harness.prompt_text("continue", vec![]).await.unwrap();
7448            assert!(matches!(run.outcome, HarnessRunOutcome::Completed { .. }));
7449            // Retire this binding before the next iteration reopens the journal.
7450            // `release_writer_lease` bumps the revocation flag and drops the OS
7451            // lease box, so ownership is released now rather than whenever the
7452            // last storage handle happens to be dropped.
7453            drop(run);
7454            drop(harness);
7455            storage.release_writer_lease();
7456            assert!(
7457                !storage.writer_lease_held(),
7458                "retired binding must not retain the writer lease"
7459            );
7460        }
7461        let content = std::fs::read_to_string(&path).unwrap();
7462        assert!(content.lines().next().unwrap().contains("progressFormat"));
7463        assert!(sidecar.exists());
7464    }
7465
7466    /// `open_session` hands back the recorded directory as data (for the
7467    /// `/session` hot-switch notes) while still opening the session normally.
7468    #[tokio::test]
7469    async fn open_session_reports_the_recorded_directory() {
7470        let tmp = tempfile::tempdir().unwrap();
7471        let project = tmp.path().join("project-open");
7472        let launch = tmp.path().join("launch-dir");
7473        let sessions = tmp.path().join("sessions");
7474        std::fs::create_dir_all(&project).unwrap();
7475        std::fs::create_dir_all(&launch).unwrap();
7476        std::fs::create_dir_all(&sessions).unwrap();
7477        create_jsonl_session_with_id(
7478            &sessions,
7479            &project.to_string_lossy(),
7480            Some("cwdopen001".into()),
7481        )
7482        .await
7483        .unwrap();
7484
7485        let restored =
7486            open_session_by_id_in_dir("cwdopen001", &launch.to_string_lossy(), &sessions)
7487                .await
7488                .map_err(|error| error.to_string())
7489                .unwrap();
7490        assert_eq!(restored.recorded_cwd, Some(project.clone()));
7491        assert_eq!(restored.session.storage().metadata().id, "cwdopen001");
7492    }
7493
7494    #[tokio::test]
7495    async fn the_peeked_session_is_the_one_the_build_opens() {
7496        let tmp = tempfile::tempdir().unwrap();
7497        let first_project = tmp.path().join("project-first");
7498        let second_project = tmp.path().join("project-second");
7499        let launch = tmp.path().join("launch-dir");
7500        let sessions = tmp.path().join("sessions");
7501        for dir in [&first_project, &second_project, &launch, &sessions] {
7502            std::fs::create_dir_all(dir).unwrap();
7503        }
7504        create_jsonl_session_with_id(
7505            &sessions,
7506            &first_project.to_string_lossy(),
7507            Some("cwdrace001".into()),
7508        )
7509        .await
7510        .unwrap();
7511
7512        let args = Args {
7513            continue_session: true,
7514            session_dir: Some(sessions.clone()),
7515            ..Default::default()
7516        };
7517        let selection = select_session_in_dir(&args, sessions.clone());
7518        let peeked = peek_restored_session_cwd(&selection, &launch)
7519            .await
7520            .expect("a resumable session");
7521        assert_eq!(peeked.adopted, Some(first_project.clone()));
7522
7523        // A newer file with the same ID appears in another workspace.
7524        let second_cwd = second_project.to_string_lossy();
7525        create_jsonl_session_with_id(&sessions, &second_cwd, Some(peeked.id.clone()))
7526            .await
7527            .unwrap();
7528        let newer =
7529            list_session_metadata_in_scope_in_dir(&second_cwd, &sessions, SessionScope::Project)
7530                .await
7531                .unwrap()
7532                .pop()
7533                .unwrap();
7534        let newer = PathBuf::from(newer.path);
7535        std::fs::File::options()
7536            .write(true)
7537            .open(&newer)
7538            .unwrap()
7539            .set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(2))
7540            .unwrap();
7541        let newer = newer.canonicalize().unwrap();
7542        let home = crate::config::AgentHome::from_option(Some(tmp.path().join("agent"))).unwrap();
7543        let cwd = first_project.to_string_lossy();
7544        let duplicate = find_session_metadata(&peeked.id, &cwd, &sessions)
7545            .await
7546            .unwrap_err();
7547        assert!(duplicate.to_string().contains("multiple saved sessions"));
7548        let (
7549            _,
7550            SessionPreflight {
7551                selection,
7552                prepared_restore: prepared,
7553                ..
7554            },
7555        ) = preflight_extension_startup_with_restore(
7556            &home,
7557            &args,
7558            &first_project,
7559            false,
7560            true,
7561            Some(&peeked),
7562        )
7563        .unwrap();
7564        assert_eq!(
7565            Path::new(&prepared.as_ref().unwrap().metadata().path),
7566            peeked.path
7567        );
7568        let reopened = restore_session(&selection, &cwd, prepared).await.unwrap();
7569        assert_eq!(reopened.storage().metadata().id, peeked.id);
7570        drop(reopened);
7571
7572        let (
7573            _,
7574            SessionPreflight {
7575                selection,
7576                prepared_restore: prepared,
7577                ..
7578            },
7579        ) = preflight_extension_startup_with_restore(
7580            &home,
7581            &args,
7582            &first_project,
7583            false,
7584            true,
7585            Some(&peeked),
7586        )
7587        .unwrap();
7588        std::fs::remove_file(&peeked.path).unwrap();
7589        let missing_before_preflight = preflight_extension_startup_with_restore(
7590            &home,
7591            &args,
7592            &first_project,
7593            false,
7594            true,
7595            Some(&peeked),
7596        );
7597        assert!(matches!(
7598            missing_before_preflight,
7599            Err(BuildError::SessionOpen(_))
7600        ));
7601        assert!(restore_session(&selection, &cwd, prepared).await.is_err());
7602        let remaining = list_session_metadata_in_dir(&cwd, &sessions).await.unwrap();
7603        assert_eq!(remaining.len(), 1);
7604        assert_eq!(remaining[0].id, peeked.id);
7605        assert_eq!(Path::new(&remaining[0].path).canonicalize().unwrap(), newer);
7606    }
7607
7608    /// Trust must be resolved against the directory it is asked about. A
7609    /// session recorded in another project must not inherit the launch
7610    /// directory's decision — that would run an untrusted project's settings,
7611    /// skills, and context files with trusted privileges.
7612    #[test]
7613    fn trust_is_resolved_per_directory() {
7614        struct RestoreConfigDir(Option<std::ffi::OsString>);
7615
7616        impl Drop for RestoreConfigDir {
7617            fn drop(&mut self) {
7618                match self.0.take() {
7619                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
7620                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
7621                }
7622            }
7623        }
7624
7625        let _guard = crate::config::test_support::env_lock().lock().unwrap();
7626        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
7627        let tmp = tempfile::tempdir().unwrap();
7628        let agent = tmp.path().join("agent");
7629        std::fs::create_dir_all(&agent).unwrap();
7630        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
7631
7632        let untrusted = tmp.path().join("project-untrusted");
7633        let launch = tmp.path().join("project-launch");
7634        std::fs::create_dir_all(&untrusted).unwrap();
7635        std::fs::create_dir_all(&launch).unwrap();
7636        crate::config::set_project_trust(&untrusted, Some(false)).unwrap();
7637
7638        let args = Args::default();
7639        assert!(!resolve_project_trust(&args, &untrusted));
7640        // A directory with no stored decision loads by default.
7641        assert!(resolve_project_trust(&args, &launch));
7642    }
7643}
7644
7645#[cfg(test)]
7646#[path = "session/experimental_dialog_continuity_tests.rs"]
7647mod experimental_dialog_continuity_tests;
7648#[cfg(test)]
7649#[path = "session/experimental_reload_continuity_tests.rs"]
7650mod experimental_reload_continuity_tests;