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