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