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(args, &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(args, &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). Extension after-tool/context adapters remain unwired.
1232        // Native durable observes the committed service per model request, using
1233        // the same weak binding as its tool, even when model tools are filtered.
1234        before_tool_call,
1235        after_tool_call: None,
1236        transform_context: args
1237            .native_durable
1238            .then(|| crate::native_durable::context_hook(Arc::clone(&durable_binding))),
1239        entry_transforms: Vec::new(),
1240        // Extension provider hooks (B4): plugins subscribing to the
1241        // BeforeProviderRequest / BeforeProviderHeaders / AfterProviderResponse
1242        // events observe every provider call (observer semantics — the handler
1243        // ABI has no patch channel in v1). A session without provider-hook
1244        // subscribers runs hook-free.
1245        provider_hooks: rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
1246            .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
1247    };
1248
1249    let harness = match experimental_policy {
1250        Some(policy) => AgentHarness::create_experimental(options, policy).await,
1251        None => AgentHarness::create(options).await,
1252    }
1253    .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
1254
1255    if args.native_durable {
1256        // Validate legacy/corrupt branch state before sealing resources or ready.
1257        rpi_harness::durable::DurableService::bind(
1258            &harness,
1259            rpi_harness::durable::DurableActor::owner("native-cli")
1260                .map_err(|e| BuildError::HarnessCreate(e.to_string()))?,
1261        )
1262        .snapshot()
1263        .await
1264        .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
1265        // Populate the weak tool binding before resource selection is published.
1266        let _ = durable_binding.set(harness.downgrade());
1267    }
1268
1269    // Retain read leases even for resource-only/--no-extensions hosts.
1270    let harness_leases = resource_leases.clone();
1271    harness
1272        .events()
1273        .on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |_| {
1274            let _ = &harness_leases;
1275        });
1276    install_extension_settlement_bridge(harness.events(), extension_session_cell.clone());
1277    if let Some(selected) = &resource_selection {
1278        harness
1279            .seal_resources(active)
1280            .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
1281        crate::resource_selection::attach(
1282            &harness,
1283            serde_json::json!({
1284                "version": 1,
1285                "hostId": uuid::Uuid::new_v4().to_string(),
1286                "host": {"name": crate::APP_NAME, "version": crate::VERSION, "pid": std::process::id()},
1287                "selection": selected.selection,
1288                "package": selected.package,
1289                "selectedSkills": selected.skills,
1290                "skillDiagnostics": [],
1291                "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<_>>(),
1292                "instructions": selected.provenance(),
1293                "baseSystemPrompt": "native-default",
1294                "projectContext": "disabled",
1295                "resourceDiscovery": "disabled",
1296                "changes": "restart-required"
1297            }),
1298        );
1299        crate::resource_selection::get_resource_state(&harness)
1300            .await
1301            .map_err(BuildError::HarnessCreate)?;
1302        if selected.transition.is_some() {
1303            // Re-read persisted facts at commit, not merely the startup mirror.
1304            // The canonical OS writer claim acquired before registration is
1305            // retained by the host for the entire session lifetime.
1306            let meta = resolve_restore_target(&selection, &cwd_str)
1307                .await?
1308                .ok_or_else(|| {
1309                    BuildError::SessionOpen("transition session disappeared before commit".into())
1310                })?;
1311            if !harness.session().storage().writer_lease_held() {
1312                return Err(BuildError::SessionOpen(
1313                    "resource transition lost storage-level writer ownership".into(),
1314                ));
1315            }
1316            let path = std::fs::canonicalize(&meta.path)
1317                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
1318            let facts =
1319                rpi_harness::session::jsonl::JsonlSessionStorage::read_resource_transition_facts(
1320                    Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())),
1321                    &path.to_string_lossy(),
1322                    Arc::new(SystemClock),
1323                    Arc::new(DefaultIdGenerator::new()),
1324                )
1325                .await
1326                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
1327            crate::resource_selection::validate_session_binding(&facts.values, Some(selected))
1328                .map_err(BuildError::SessionOpen)?;
1329            let mirror = rpi_harness::session::SessionValues::load(harness.session())
1330                .await
1331                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
1332            if crate::resource_selection::binding_state(&mirror)
1333                != crate::resource_selection::binding_state(&facts.values)
1334            {
1335                return Err(BuildError::SessionOpen(
1336                    "resource binding changed before commit".into(),
1337                ));
1338            }
1339        }
1340        crate::resource_selection::bind_inventory(&harness, selected)
1341            .await
1342            .map_err(BuildError::SessionOpen)?;
1343    }
1344    // Publish only after exact resources have been sealed and validated.
1345    crate::extensions_actions::HarnessActionHost::set_harness(
1346        &harness_cell,
1347        Arc::new(harness.clone()),
1348    );
1349    register_file_io_router(&harness, &file_io);
1350
1351    // ---- Durable operation recovery (runtime layer) ----
1352    // A previous process can die between `operation_started` and
1353    // `operation_finished`, leaving the lane with an orphaned operation. Sweep
1354    // every lane, surface what was found, and emit `run_start`/`run_end`
1355    // (aborted) pairs so a TUI that already attached sees the settle. This is
1356    // read-only: nothing is mutated here, so a failed sweep cannot corrupt the
1357    // log. A clean session (the common case) reports no findings.
1358    {
1359        let runtime = rpi_harness::runtime::SessionRuntime::new(harness.session().clone());
1360        match rpi_harness::runtime::recover_all_lanes(&runtime).await {
1361            Ok(reports) => {
1362                for (lane, report) in reports {
1363                    if report.is_clean() {
1364                        continue;
1365                    }
1366                    if report.is_corrupt() {
1367                        eprintln!(
1368                            "warning: session lane '{lane}' is corrupt ({} open operations); \
1369                             refusing to auto-repair — inspect the session file",
1370                            report.open_operations.len()
1371                        );
1372                        continue;
1373                    }
1374                    for decision in runtime.reconcile(&report) {
1375                        if let rpi_harness::runtime::RecoveryDecision::Abort { run_id } = decision {
1376                            if args.verbose {
1377                                eprintln!(
1378                                    "recovered interrupted run {run_id} on lane '{lane}' (aborted)"
1379                                );
1380                            }
1381                        }
1382                    }
1383                    runtime.emit_recovery_events(harness.events(), &report);
1384                }
1385            }
1386            Err(e) => {
1387                if args.verbose {
1388                    eprintln!("warning: session recovery sweep failed: {e}");
1389                }
1390            }
1391        }
1392    }
1393
1394    // ---- B5d: assemble the ReloadContext the TUI holds ----
1395    // Every field is cheap to clone (Arc / Vec / args Clone). The cells own the
1396    // live session + bridge so `/reload` can swap them; the harness itself is
1397    // NOT held here (the TUI already owns a `&AgentHarness` / clone at the call
1398    // site — passing it into `reload_extension_resources` keeps this structfree
1399    // of a harness back-reference so it can be `Clone` into the reload callback).
1400    // Retain the resolved root in the existing args snapshot so reload never
1401    // reselects it from mutable settings or environment variables.
1402    let mut reload_args = args.clone();
1403    reload_args.session_dir = Some(session_dir);
1404    let reload_context = ReloadContext {
1405        resource_leases,
1406        fresh_session_only,
1407        extension_session: extension_session_cell,
1408        action_bridge: Arc::new(Mutex::new(Some(Arc::clone(&action_bridge)))),
1409        tool_context,
1410        file_io,
1411        catalog: Arc::new(std::sync::RwLock::new(catalog)),
1412        providers: Arc::new(std::sync::RwLock::new(resolved.providers.clone())),
1413        runtime: runtime.clone(),
1414        cwd: cwd.to_path_buf(),
1415        project_trusted,
1416        discovered_theme_paths: Arc::new(std::sync::Mutex::new(discovered.theme_paths.clone())),
1417        args: reload_args,
1418        resolved_model: resolved.model.clone(),
1419        broadcast: broadcast_for_context,
1420        mailbox: reload_mailbox,
1421        ui_dialog: ui_dialog_mailbox,
1422        ext_status: ext_status_mailbox,
1423        editor_text: editor_text_mailbox,
1424        dev_extension: None,
1425        startup_notices: Vec::new(),
1426    };
1427
1428    Ok((harness, event_rx, reload_context))
1429}
1430
1431/// Project authoritative harness termination, not per-attempt AgentEnd, to
1432/// plugins. The bus owns this listener; its session cell follows reloads and
1433/// retains callback libraries, while the action host binds the harness weakly.
1434fn install_extension_settlement_bridge(
1435    events: &rpi_harness::events::HarnessEventBus,
1436    sessions: ExtensionSessionCell,
1437) {
1438    events.on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |event| {
1439        if event.lane != "main" {
1440            return;
1441        }
1442        let session = sessions.lock().unwrap().clone();
1443        if let Some(snapshot) = session.snapshot_arc() {
1444            rpi_extensions::dispatch_empty_event(&snapshot, rpi_plugin_sdk::EventTag::AgentSettled);
1445        }
1446    });
1447}
1448
1449/// Resolve the current plugin session for each call rather than keeping a
1450/// startup snapshot. A clone retains its libraries while approval is pending.
1451fn extension_tool_call_hook(
1452    sessions: ExtensionSessionCell,
1453    ui_dialog: rpi_extensions::UiDialogMailbox,
1454) -> rpi_agent::BeforeToolCall {
1455    Arc::new(move |ctx: rpi_agent::BeforeToolCallContext<'_>, signal| {
1456        let session = sessions
1457            .lock()
1458            .map(|session| session.clone())
1459            .map_err(|_| ());
1460        let ui_dialog = ui_dialog.clone();
1461        let tool_call_id = ctx.tool_call.id.clone();
1462        let tool_name = ctx.tool_call.name.clone();
1463        let params = ctx.args.clone();
1464        Box::pin(async move {
1465            let reason = match session {
1466                Ok(session) => {
1467                    rpi_extensions::dispatch_tool_call_event(
1468                        &session,
1469                        &tool_call_id,
1470                        &tool_name,
1471                        &params,
1472                        &signal,
1473                        &ui_dialog,
1474                    )
1475                    .await
1476                }
1477                Err(_) => Some("extension approval session is unavailable".to_string()),
1478            };
1479            reason.map(|reason| rpi_agent::BeforeToolCallResult {
1480                block: true,
1481                reason: Some(reason),
1482                terminate: false,
1483                args: None,
1484            })
1485        })
1486    })
1487}
1488
1489// ===========================================================================
1490// B5d — `/reload`: re-run extension + resource discovery into a LIVE harness
1491// ===========================================================================
1492//
1493// `/reload` (interactive TUI command, or a plugin's `runtime_action(Reload)`)
1494// re-runs everything `build` did around resources/extensions WITHOUT rebuilding
1495// the `AgentHarness` itself (rebuilding would tear down the session/lane/event
1496// wiring + the broadcast drain task the TUI owns). Instead it:
1497//
1498//  1. Builds a fresh `ExtensionSession` (re-load the cdylibs) over the same
1499//     dir set, with a FRESH `ActionBridge` (the old one is `invalidate`d so
1500//     in-flight plugin→host calls on the old bridge fail fast).
1501//  2. Fans `resources_discover(_, "reload")` over the fresh snapshot.
1502//  3. Re-runs the Part-A loaders (skills/prompts/context/SYSTEM.md/
1503//     APPEND_SYSTEM.md) with the discovered paths merged in — same precedence
1504//     + `--no-*` gates as startup.
1505//  4. Rebuilds the harness's live state via the B5d setters
1506//     (`set_system_prompt`/`set_resources`/`set_agent_emitter`/`set_models`/
1507//     `set_provider_hooks`/`set_tools`) so the NEXT run observes the reloaded
1508//     config (in-flight runs finish on the old `ConfigSnapshot`).
1509//  5. Swaps the cells (`ExtensionSession`, `ActionBridge`, harness action
1510//     host's harness cell stays — the harness is the same object) and drops
1511//     the old session + bridge (their keepalives unmap the old cdylibs; the
1512//     new session's keepalive holds the fresh mappings).
1513//
1514// The reload is a `rpi-cli` concern (NOT a harness op): `rpi-extensions`
1515// carries only the `ActionBridge` staleness flag + a `ReloadMailbox` `()` signal
1516// (no pi-cli `TuiMessage` type — leaf DAG preserved). The TUI owns the mailbox
1517// receiver + the actual reload routine; a plugin's
1518// `runtime_action(Reload)` signals the mailbox and returns `Ok(null)`
1519// immediately so the calling plugin's cdylib is NOT unmapped while its
1520// `runtime_action` frame is still on the stack (the self-unmapping race a
1521// synchronous plugin-initiated reload would have).
1522//
1523// `reload_extension_resources` is the shared routine both `/reload` (TUI) and
1524// a plugin's `runtime_action(Reload)` (via the mailbox) drive. It is `pub` so
1525// the TUI's main-loop handler + the mailbox-driven path call the same code.
1526
1527/// The cell that holds the live `ExtensionSession` across a `/reload`. Cloned
1528/// into every site that needs the current session (the TUI, the reload
1529/// callback). On reload the old session is `replace`d out (its `active` flag
1530/// flipped) and the fresh one stored atomically. In-flight callbacks retain
1531/// the old keepalive until they return; callers never observe an empty
1532/// placeholder during the swap.
1533pub type ExtensionSessionCell = Arc<Mutex<ExtensionSession>>;
1534
1535/// The cell that holds the live `ActionBridge` across a `/reload`. A plugin
1536/// stores the bridge's raw `user_data` pointer during `register`; on reload the
1537/// old bridge is `invalidate`d (in-flight calls fail fast) and the fresh one
1538/// `store`d. The fresh session's plugins are handed the fresh bridge pointer.
1539pub type ActionBridgeCell = Arc<Mutex<Option<Arc<rpi_extensions::ActionBridge>>>>;
1540
1541/// Everything `/reload` needs to rebuild extension + resource state into a live
1542/// harness. Built once in [`build`] (alongside the harness) and held by the TUI
1543/// (cloned into the reload callback the bridge carries + the `/reload` command
1544/// handler). The harness itself is NOT held here — the TUI already owns a
1545/// `&AgentHarness` / a clone; passing it at the call site keeps this struct
1546/// free of a harness back-reference (so it can be `Clone` and moved into the
1547/// reload callback without borrowing the harness).
1548#[derive(Clone)]
1549pub struct ReloadContext {
1550    resource_leases: Arc<Vec<crate::resource_management::Lease>>,
1551    /// Startup routing capability, retained independently of mutable args/settings.
1552    fresh_session_only: bool,
1553    /// One neutral router for all built-ins, including those reconstructed on reload.
1554    pub file_io: Arc<rpi_tools::file_io::FileIORouter>,
1555    /// The live extension-session cell (swapped on reload).
1556    pub extension_session: ExtensionSessionCell,
1557    /// The session's plugin-tool context (`cwd` + session id), reused — not
1558    /// rebuilt — on reload so the rebuilt adapters keep serving the SAME
1559    /// session. A reload that made a fresh context would leave every plugin
1560    /// tool without a session id until the next launch.
1561    pub tool_context: rpi_extensions::ToolCallContext,
1562    /// The live action-bridge cell (swapped + old invalidated on reload).
1563    pub action_bridge: ActionBridgeCell,
1564    /// The extension status registry the TUI renders in its footer (`SetStatus`).
1565    /// Lives in the context (not the cell) so it survives a bridge swap.
1566    pub ext_status: rpi_extensions::ExtensionStatusMailbox,
1567    /// The extension editor-text queue the TUI drains into the prompt editor
1568    /// (`SetEditorText`, runtime action 19). Lives in the context (not the cell)
1569    /// so it survives a bridge swap — exactly like `ext_status`. A voice plugin
1570    /// writes a transcription here as a *draft*; the TUI applies it, starts the
1571    /// optional auto-send countdown, and submits through the normal path so the
1572    /// user bubble renders as usual.
1573    pub editor_text: rpi_extensions::EditorTextMailbox,
1574    /// Shared authenticated model catalog for runtime actions and the TUI.
1575    /// Provider-package reloads replace it together with the runtime bindings.
1576    pub catalog: Arc<std::sync::RwLock<Vec<rpi_ai::Model>>>,
1577    /// Current configured provider runtimes. Replaced after package reload so
1578    /// subsequent reloads cannot recover stale plugin snapshots.
1579    pub providers: Arc<std::sync::RwLock<Vec<Arc<dyn Provider>>>>,
1580    /// The ambient runtime handle (captured in `build`) — `PluggableProvider`
1581    /// + the fresh `ActionBridge` need a captured `Handle` to spawn from any
1582    /// thread.
1583    pub runtime: tokio::runtime::Handle,
1584    /// The cwd (for static resource-dir resolution + context-file walk).
1585    pub cwd: PathBuf,
1586    /// The project-trust decision captured before provider and session setup.
1587    /// Startup consumers reuse this value so extension code cannot change the
1588    /// effective policy by mutating the process cwd while it is loading.
1589    pub project_trusted: bool,
1590    /// Theme file paths contributed by extensions via `resources_discover`,
1591    /// shared so the TUI theme registry can merge them. Filled at startup,
1592    /// replaced on every `/reload` (paths are unattributed — the v1 divergence
1593    /// documented in `rpi-extensions::resources`).
1594    pub discovered_theme_paths: Arc<std::sync::Mutex<Vec<String>>>,
1595    /// The parsed args (cloned) — `--no-*`/`--tools`/`--exclude-tools`/
1596    /// `--extensions-dir`/`--no-extensions`/`--system-prompt`/etc all apply on
1597    /// reload exactly as at startup (a reload re-reads the same flags; it does
1598    /// not pick up argv changes mid-session, which is the right contract — pi's
1599    /// `/reload` re-runs discovery with the same config). `session_dir` holds
1600    /// the resolved startup root, including saved settings/environment defaults.
1601    pub args: Args,
1602    /// The resolved model + thinking level (the harness's active model stays
1603    /// unless `set_model` changed it; reload does not touch the model).
1604    pub resolved_model: rpi_ai::Model,
1605    /// The broadcast emitter the harness was built with. Reload rebuilds the
1606    /// `TeeEmitter` over the fresh `ExtensionEmitter` (the old tee's extension
1607    /// child is dropped, unsubscribing from the old registry). The broadcast
1608    /// half stays live the whole session (the TUI's drain task holds the
1609    /// receiver), so we keep a handle to re-wrap.
1610    pub broadcast: Arc<dyn rpi_agent::AgentEmitter>,
1611    /// The session-long reload mailbox (B5d). Build creates one, installs it on
1612    /// the initial `ActionBridge` via [`reload_callback_from_mailbox`], and hands
1613    /// a clone to the TUI. The TUI installs its `TuiMessage` sender so a plugin's
1614    /// `runtime_action(Reload)` signals the main loop — the reload routine reuses
1615    /// THIS mailbox (not a fresh default) when building the fresh bridge, so the
1616    /// bridge always carries the mailbox the TUI installed across reloads.
1617    pub mailbox: rpi_extensions::ReloadMailbox,
1618    /// Session-long UI-dialog mailbox (runtime action 17). The initial bridge
1619    /// carries it; the TUI attaches itself and polls `take_pending` from its key
1620    /// loop, and `/reload` reuses THIS mailbox when it builds the fresh bridge.
1621    /// A detached mailbox makes `ask_user` fail with "requires an interactive
1622    /// UI" (headless contract).
1623    pub ui_dialog: rpi_extensions::UiDialogMailbox,
1624    /// Active `rpi dev` extension builder. `/reload` rebuilds it before
1625    /// swapping plugin sessions; its watcher signals `mailbox` after a
1626    /// successful background build.
1627    pub dev_extension: Option<Arc<crate::dev_extension::DevExtension>>,
1628    /// One-line notices the host should show at startup (a session directory
1629    /// that fell back, an untrusted adopted directory). Filled by the CLI after
1630    /// the build and rendered as transcript notes in the TUI; headless modes
1631    /// print them to stderr. Kept as data — never `eprintln!`d from here, which
1632    /// would corrupt the alternate screen (issue #115).
1633    pub startup_notices: Vec<String>,
1634}
1635
1636impl ReloadContext {
1637    pub(crate) fn session_dir(&self) -> PathBuf {
1638        // The fallback also supports contexts constructed by embedding hosts.
1639        self.args
1640            .session_dir
1641            .clone()
1642            .unwrap_or_else(|| configured_session_dir(&self.args, &self.cwd))
1643    }
1644}
1645
1646/// Dispatch a no-payload lifecycle event (e.g. `SessionStart`, `SessionShutdown`,
1647/// the rpi-specific `BeforeTuiStart`) to every extension handler subscribed to
1648/// that tag, with **veto** + **timeout** semantics (P1).
1649///
1650/// Resolves the **current** extension session from the reload cell so a
1651/// `/reload`-swapped session is honored. Each handler runs on a blocking thread
1652/// with a per-event timeout ([`rpi_extensions::lifecycle_timeout_for`]); a
1653/// handler returning [`rpi_plugin_sdk::EVENT_HANDLER_ABORT`] vetoes the phase
1654/// and this returns `Some(reason)`. No-op (`None`) when no plugins loaded, no
1655/// handler subscribes, or the registry is stale.
1656///
1657/// The caller decides what a veto means: a `BeforeTuiStart` veto aborts startup
1658/// (never enter the TUI); `SessionStart`/`SessionShutdown` vetoes are advisory
1659/// (the session is already up or already closing).
1660pub async fn dispatch_session_event_async(
1661    reload_context: &ReloadContext,
1662    tag: rpi_plugin_sdk::EventTag,
1663) -> Option<String> {
1664    // Take the snapshot Arc + keepalive, drop the session lock, then dispatch —
1665    // we must not hold the session cell's mutex across the await (a handler
1666    // could re-enter a reload path that locks it). Holding the keepalive across
1667    // the await keeps the cdylibs (owning the handler fn pointers) mapped even
1668    // if a concurrent `/reload` swaps the session cell out.
1669    let (snapshot, keepalive) = {
1670        let session = reload_context.extension_session.lock().unwrap();
1671        (session.snapshot_arc(), session.keepalive())
1672    };
1673    match snapshot {
1674        Some(snapshot) => rpi_extensions::dispatch_lifecycle_event(&snapshot, tag, keepalive).await,
1675        None => None,
1676    }
1677}
1678
1679/// Join plugin teardown before unloading modules. A detached timed-out handler
1680/// could still execute code in the old DLL, so it cannot safely permit a swap.
1681async fn shutdown_extensions_for_reload(
1682    snapshot: Option<Arc<rpi_extensions::RegistrySnapshot>>,
1683    keepalive: Arc<rpi_extensions::PluginKeepalive>,
1684) -> Result<(), String> {
1685    if let Some(snapshot) = snapshot {
1686        tokio::task::spawn_blocking(move || {
1687            let _keepalive = keepalive;
1688            rpi_extensions::dispatch_empty_event(
1689                &snapshot,
1690                rpi_plugin_sdk::EventTag::SessionShutdown,
1691            );
1692        })
1693        .await
1694        .map_err(|error| error.to_string())?;
1695    }
1696    Ok(())
1697}
1698
1699/// The outcome of a reload: a human-readable status line for the transcript
1700/// (counts of what reloaded), and whether any load diagnostics appeared.
1701pub struct ReloadOutcome {
1702    /// One-line summary for the transcript note (e.g. "Reloaded 2 plugin(s),
1703    /// 5 skill(s), 1 prompt(s).").
1704    pub summary: String,
1705    /// True iff at least one extension load warning fired (ABI mismatch / skip).
1706    pub had_warnings: bool,
1707    /// Formatted diagnostic lines (package / skill / prompt-template warnings)
1708    /// that the caller should surface in its UI. Kept out of `eprintln!`
1709    /// because the TUI owns the terminal: direct stderr writes during a run
1710    /// would corrupt the alternate-screen input row.
1711    pub details: Vec<String>,
1712    /// True iff the reload itself failed hard (e.g. the extension build or
1713    /// settings reload errored) and the previous resources were kept. Soft
1714    /// diagnostics (skill shadowing, name validation) do not set this.
1715    pub had_errors: bool,
1716    /// The project-trust policy this reload actually resolved and applied.
1717    /// `None` when the reload failed hard and kept the previous resources, so
1718    /// consumers (e.g. theme discovery) should stay on the snapshot they
1719    /// already match instead of re-reading a stale startup bool.
1720    pub project_trusted: Option<bool>,
1721}
1722
1723struct PreparedReloadInputs {
1724    extension_dirs: Vec<PathBuf>,
1725    skill_base_dirs: Vec<PathBuf>,
1726    prompt_base_dirs: Vec<PathBuf>,
1727}
1728
1729/// Append the resource sources that are specific to a reload after the
1730/// conventional project/global directories. Keep this order aligned with the
1731/// initial build: explicit CLI paths must remain available after `/reload`,
1732/// while discovered and package resources retain their lower precedence.
1733fn append_reload_resource_paths(
1734    mut paths: Vec<PathBuf>,
1735    explicit: &[PathBuf],
1736    discovered: &[String],
1737    js_paths: &[PathBuf],
1738    package_paths: &[PathBuf],
1739) -> Vec<PathBuf> {
1740    paths.extend(explicit.iter().cloned());
1741    paths.extend(discovered.iter().map(PathBuf::from));
1742    paths.extend(js_paths.iter().cloned());
1743    paths.extend(package_paths.iter().cloned());
1744    paths
1745}
1746
1747/// Re-run extension + resource discovery and push the rebuilt state into the
1748/// live `harness` via the B5d setters. The old `ExtensionSession` +
1749/// `ActionBridge` are invalidated + swapped in [`ReloadContext`]'s cells. This
1750/// is the single routine both `/reload` (TUI) and a plugin's
1751/// `runtime_action(Reload)` drive (the latter via the mailbox signal).
1752///
1753/// Returns a [`ReloadOutcome`] for the transcript. Best-effort: a failure in
1754/// one channel (e.g. a plugin that fails to reload) does not abort the others —
1755/// the reload completes with whatever loaded, mirroring pi's per-plugin
1756/// skip-on-error. A hard failure (e.g. the harness is closed) surfaces as an
1757/// error summary.
1758pub async fn reload_extension_resources(
1759    harness: &AgentHarness,
1760    ctx: &ReloadContext,
1761) -> ReloadOutcome {
1762    reload_extension_resources_inner(harness, ctx, || {}).await
1763}
1764
1765async fn reload_extension_resources_inner<F>(
1766    harness: &AgentHarness,
1767    ctx: &ReloadContext,
1768    after_prepare: F,
1769) -> ReloadOutcome
1770where
1771    F: FnOnce() + Send,
1772{
1773    if ctx.args.native_durable {
1774        return ReloadOutcome {
1775            summary:
1776                "Native durable prototype is restart-required; reload/dev hot apply unsupported"
1777                    .into(),
1778            had_warnings: true,
1779            details: Vec::new(),
1780            had_errors: true,
1781            project_trusted: None,
1782        };
1783    }
1784    if harness.has_exact_resources()
1785        || ctx.args.resource_config.is_some()
1786        || ctx.args.resource_transition.is_some()
1787    {
1788        return ReloadOutcome {
1789            summary:
1790                "Exact resource selection is restart-required; reload/dev hot apply unsupported"
1791                    .into(),
1792            had_warnings: true,
1793            details: Vec::new(),
1794            had_errors: true,
1795            project_trusted: None,
1796        };
1797    }
1798    // Resolve the arguments once for this reload. `rpi dev` may append its
1799    // freshly staged extension directory; every subsequent loader and policy
1800    // decision must observe that same effective set rather than falling back
1801    // to the pre-dev snapshot held in `ctx.args`.
1802    let mut effective_args = ctx.args.clone();
1803    if let Some(dev) = &ctx.dev_extension {
1804        if let Err(error) = dev
1805            .rebuild()
1806            .and_then(|_| dev.apply_to_args(&mut effective_args))
1807        {
1808            return ReloadOutcome {
1809                summary: format!(
1810                    "Extension build failed for {}: {error}. Keeping the currently loaded version.",
1811                    dev.package_name()
1812                ),
1813                had_warnings: true,
1814                details: Vec::new(),
1815                had_errors: true,
1816                project_trusted: None,
1817            };
1818        }
1819    }
1820    let cwd_str = ctx.cwd.to_string_lossy().to_string();
1821    let project_trusted = resolve_project_trust(&effective_args, &ctx.cwd);
1822    let prepared = match prepare_reload_inputs(&effective_args, &ctx.cwd, project_trusted) {
1823        Ok(prepared) => prepared,
1824        Err(error) => {
1825            return ReloadOutcome {
1826                summary: format!(
1827                    "Settings reload failed: {error}. Keeping the currently loaded resources."
1828                ),
1829                had_warnings: true,
1830                details: Vec::new(),
1831                had_errors: true,
1832                project_trusted: None,
1833            };
1834        }
1835    };
1836    after_prepare();
1837    let PreparedReloadInputs {
1838        extension_dirs,
1839        skill_base_dirs,
1840        prompt_base_dirs,
1841    } = prepared;
1842    let mut warnings = false;
1843
1844    // Shutdown callbacks must finish before a replacement can unload old DLLs.
1845    // Ordinary lifecycle dispatch can time out or stop on a veto; unload cleanup
1846    // instead joins every handler while keeping its module mapped.
1847    let (shutdown_snapshot, shutdown_keepalive) = {
1848        let session = ctx.extension_session.lock().unwrap();
1849        (session.snapshot_arc(), session.keepalive())
1850    };
1851    if let Err(reason) = shutdown_extensions_for_reload(shutdown_snapshot, shutdown_keepalive).await
1852    {
1853        return ReloadOutcome {
1854            summary: "Reload failed during extension shutdown".into(),
1855            had_warnings: true,
1856            details: vec![reason],
1857            had_errors: true,
1858            project_trusted: None,
1859        };
1860    }
1861
1862    // ---- 1. Build a fresh ActionBridge + ExtensionSession ----
1863    // The fresh bridge carries the SAME `HarnessActionHost` (the host's harness
1864    // cell already points at this harness; the host impl is reusable across
1865    // reloads — only the bridge's staleness flag + reload callback differ). We
1866    // re-use the host by reading it off the OLD bridge (it's the same
1867    // `Arc<dyn RuntimeActionHost>`).
1868    let old_bridge = ctx.action_bridge.lock().unwrap().clone();
1869    let host: Arc<dyn rpi_extensions::RuntimeActionHost> = match &old_bridge {
1870        Some(b) => b.clone_host(),
1871        None => {
1872            // No prior bridge (no extensions ever loaded). Build a fresh host so
1873            // a reload that newly discovers plugins can still drive actions.
1874            let (action_host, _cell) = crate::extensions_actions::HarnessActionHost::new_empty(
1875                ctx.catalog
1876                    .read()
1877                    .unwrap_or_else(|error| error.into_inner())
1878                    .clone(),
1879                ctx.cwd.clone(),
1880                ctx.runtime.clone(),
1881                ctx.args.unknown_flags.clone(),
1882                ctx.tool_context.clone(),
1883            );
1884            crate::extensions_actions::HarnessActionHost::set_harness(
1885                &_cell,
1886                Arc::new(harness.clone()),
1887            );
1888            Arc::new(
1889                action_host
1890                    .with_session_dir(ctx.session_dir())
1891                    .with_fresh_session_only(ctx.fresh_session_only)
1892                    .with_native_durable(ctx.args.native_durable),
1893            )
1894        }
1895    };
1896
1897    let reload_cb = rpi_extensions::reload_callback_from_mailbox(ctx.mailbox.clone());
1898    let publish_host = Arc::clone(&host);
1899    let fresh_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
1900        ctx.runtime.clone(),
1901        host,
1902        reload_cb,
1903        ctx.ui_dialog.clone(),
1904        ctx.ext_status.clone(),
1905        ctx.editor_text.clone(),
1906    );
1907
1908    let extension_session = if effective_args.no_extensions {
1909        rpi_extensions::ExtensionSession::none()
1910    } else {
1911        load_extensions_from_dirs(
1912            &effective_args,
1913            &extension_dirs,
1914            Some(Arc::clone(&fresh_bridge)),
1915            Some(ctx.resource_leases.clone()),
1916        )
1917    };
1918    if extension_session.is_empty() && !effective_args.no_extensions {
1919        // The fresh session may be empty if no cdylibs are present — not a
1920        // warning per se, but note it.
1921    }
1922    if effective_args.verbose {
1923        if let Some(s) = extension_session.summary() {
1924            eprintln!("reload: {s}");
1925        }
1926        report_deferred_renderers(&extension_session);
1927    }
1928
1929    let has_package_providers = |session: &ExtensionSession| {
1930        session.snapshot().is_some_and(|snapshot| {
1931            snapshot
1932                .providers()
1933                .iter()
1934                .any(|provider| snapshot.provider_manifest(&provider.provider_id).is_some())
1935        })
1936    };
1937    let packaged = has_package_providers(&extension_session)
1938        || has_package_providers(&ctx.extension_session.lock().unwrap());
1939    let refreshed = if packaged {
1940        let mut args = effective_args.clone();
1941        if let Ok(current) = harness.lane("main").get_model().await {
1942            let was_package = ctx
1943                .extension_session
1944                .lock()
1945                .unwrap()
1946                .snapshot()
1947                .is_some_and(|snapshot| snapshot.provider_manifest(&current.provider).is_some());
1948            let has_replacement = extension_session.snapshot().is_some_and(|snapshot| {
1949                snapshot
1950                    .providers()
1951                    .iter()
1952                    .any(|provider| provider.provider_id == current.provider)
1953            });
1954            if was_package && !has_replacement {
1955                return ReloadOutcome {
1956                    summary: "Reload failed while resolving provider packages".into(),
1957                    had_warnings: true,
1958                    details: vec![format!(
1959                        "active provider package '{}' is no longer loaded",
1960                        current.provider
1961                    )],
1962                    had_errors: true,
1963                    project_trusted: None,
1964                };
1965            }
1966            args.provider = Some(current.provider.clone());
1967            args.model = Some(current.id);
1968            if current.provider != ctx.resolved_model.provider {
1969                args.api_key = None;
1970                args.base_url = None;
1971            }
1972        }
1973        match crate::provider::resolve_with_extensions(
1974            &args,
1975            &ctx.cwd,
1976            ctx.project_trusted,
1977            &extension_session,
1978        ) {
1979            Ok(resolved) => Some(resolved),
1980            Err(error) => {
1981                return ReloadOutcome {
1982                    summary: "Reload failed while resolving provider packages".into(),
1983                    had_warnings: true,
1984                    details: vec![error.to_string()],
1985                    had_errors: true,
1986                    project_trusted: None,
1987                }
1988            }
1989        }
1990    } else {
1991        None
1992    };
1993
1994    // ---- 2. Invalidate the old session + bridge BEFORE the swap ----
1995    // The old registry's `active` flag flips false so any in-flight
1996    // `emit_resources_discover`/event dispatch on the old snapshot no-ops; the
1997    // old bridge's flag flips false so in-flight `runtime_action` calls parked
1998    // on the old `user_data` hit the staleness guard. Invalidate under the
1999    // session lock before exposing the replacement to approval callbacks.
2000    //
2001    // Swap directly to the fresh session under the same lock that approvals
2002    // use. A temporary empty session would let a concurrent call bypass its gate.
2003    // In-flight approvals retain their old session until their callback exits;
2004    // its staleness flag prevents them from authorizing after this swap.
2005    let old_session = {
2006        let mut session_guard = ctx.extension_session.lock().unwrap();
2007        let old_session = std::mem::replace(&mut *session_guard, extension_session.clone());
2008        if let Some(old_snap) = old_session.snapshot_arc() {
2009            // `invalidate` is on the registry, but the snapshot shares the flag —
2010            // flipping the snapshot's flag invalidates the registry too (same Arc).
2011            // `RegistrySnapshot` exposes `active_flag()` for this.
2012            old_snap.active_flag().store(false, Ordering::SeqCst);
2013        }
2014        old_session
2015    };
2016    if let Some(old_b) = old_bridge {
2017        old_b.invalidate();
2018    }
2019    // Shutdown callbacks see stale host actions and run outside session locks.
2020    old_session.begin_shutdown();
2021
2022    // The session was swapped atomically above; expose its matching bridge.
2023    *ctx.action_bridge.lock().unwrap() = Some(Arc::clone(&fresh_bridge));
2024    // Republish the registry so `ListCommands` reflects the commands the reload
2025    // just discovered — without this a remote UI keeps serving the startup set
2026    // until the host process restarts. Via the trait method because all we hold
2027    // here is `Arc<dyn RuntimeActionHost>`.
2028    // Publish even when the reload found nothing: a nonempty -> empty reload
2029    // returns `ExtensionSession::none()`, and skipping it would leave the old
2030    // snapshot advertised.
2031    publish_host.publish_registry_opt(extension_session.snapshot_arc());
2032
2033    // ---- 3. resources_discover ("reload") over the fresh snapshot ----
2034    let discovered = extension_session
2035        .snapshot_arc()
2036        .map(|snap| rpi_extensions::emit_resources_discover(&cwd_str, "reload", &snap))
2037        .unwrap_or_default();
2038    // Publish the fresh theme paths so the TUI registry rebuild sees the same
2039    // set the skill/prompt loaders just consumed.
2040    if let Ok(mut guard) = ctx.discovered_theme_paths.lock() {
2041        *guard = discovered.theme_paths.clone();
2042    }
2043
2044    // ---- 4. Re-run the Part-A loaders (same precedence + --no-* gates) ----
2045    let env = Arc::new(rpi_tools::OsExecutionEnv::with_cwd(ctx.cwd.clone()));
2046    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
2047
2048    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
2049    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
2050    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
2051    if !effective_args.no_skills {
2052        // JS discovery is backed by the session-long lazy Node host. Until
2053        // that host is swapped as part of a future full JS reload, preserve
2054        // the paths it contributed at startup across `/reload`.
2055        let js_paths: &[PathBuf] = &[];
2056        let package_paths: &[PathBuf] = &[];
2057        let dirs = append_reload_resource_paths(
2058            skill_base_dirs,
2059            &effective_args.skill,
2060            &discovered.skill_paths,
2061            js_paths,
2062            package_paths,
2063        );
2064        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
2065        skills = result.skills;
2066        skill_diags = result.diagnostics;
2067        resource_diags.extend(result.resource_diagnostics);
2068    }
2069
2070    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
2071    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
2072    if !effective_args.no_prompt_templates {
2073        let js_paths: &[PathBuf] = &[];
2074        let package_paths: &[PathBuf] = &[];
2075        let dirs = append_reload_resource_paths(
2076            prompt_base_dirs,
2077            &effective_args.prompt_template,
2078            &discovered.prompt_paths,
2079            js_paths,
2080            package_paths,
2081        );
2082        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
2083        prompt_templates = result.prompt_templates;
2084        prompt_diags = result.diagnostics;
2085        resource_diags.extend(result.resource_diagnostics);
2086    }
2087
2088    let context_files = if effective_args.no_context_files || !project_trusted {
2089        Vec::new()
2090    } else {
2091        let agent_dir = crate::config::agent_dir().ok();
2092        let agent_dir_path = agent_dir.unwrap_or_else(|| ctx.cwd.clone());
2093        load_project_context_files(&env_dyn, &ctx.cwd, &agent_dir_path).await
2094    };
2095    let context_block = format_project_context(&context_files);
2096
2097    let mut details: Vec<String> = Vec::new();
2098    if let Some(resolved) = &refreshed {
2099        warnings |= !resolved.compat_warnings.is_empty();
2100        details.extend(
2101            resolved
2102                .compat_warnings
2103                .iter()
2104                .map(|warning| format!("warning: models.json: {warning}")),
2105        );
2106    }
2107    if !skill_diags.is_empty() || !prompt_diags.is_empty() || !resource_diags.is_empty() {
2108        warnings = true;
2109        // Collect formatted diagnostics for the caller to surface in its UI
2110        // instead of writing to stderr directly: the TUI owns the terminal,
2111        // and a raw `eprintln!` during a run would scribble over the
2112        // alternate-screen input row.
2113        for d in &skill_diags {
2114            details.push(format!(
2115                "warning: skill {} ({}): {}",
2116                d.path,
2117                d.code.as_str(),
2118                d.message
2119            ));
2120        }
2121        for d in &prompt_diags {
2122            details.push(format!(
2123                "warning: prompt template {} ({}): {}",
2124                d.path,
2125                d.code.as_str(),
2126                d.message
2127            ));
2128        }
2129        // Structured collisions: winner (kept) · loser (shadowed).
2130        for d in &resource_diags {
2131            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
2132                details.push(format!(
2133                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
2134                    c.resource_type.as_str(),
2135                    c.name,
2136                    c.winner_path,
2137                    c.loser_path
2138                ));
2139            }
2140        }
2141    }
2142
2143    // ---- Re-compose the system prompt (same precedence as build) ----
2144    // Same working-state wording rule as `build`; a mid-session `/model` switch
2145    // re-composes the prompt on the next reload, which is the same staleness the
2146    // rest of this path already has (provider resolution is a startup concern).
2147    // Re-merge extension tools (a reloaded plugin may have added/removed a
2148    // tool). The built-in set is rebuilt from scratch + extension tools merged
2149    // on top, mirroring `build`. Built before the
2150    // prompt so the prompt lists exactly the active tools.
2151    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
2152    let tool_ctx = rpi_tools::ExecutionToolContext::new(env_dyn.clone(), Some(mut_env))
2153        .with_file_io(ctx.file_io.clone());
2154    // Native durable reload is rejected above; this binding cannot be used.
2155    let mut tools = build_tools_bound(
2156        &tool_ctx,
2157        &effective_args,
2158        Arc::new(std::sync::OnceLock::new()),
2159    );
2160    merge_extension_tools(
2161        &mut tools,
2162        &extension_session,
2163        &effective_args,
2164        &ctx.tool_context,
2165    );
2166    let mut active = active_tool_names(&tools, &effective_args);
2167    active = filter_active_tool_names(active, &effective_args);
2168    let prompt_tools = active.clone();
2169    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
2170    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&ctx.resolved_model);
2171    let default_prompt = || {
2172        default_system_prompt_with_tool_prompts(
2173            &cwd_str,
2174            prior_reasoning_replayed,
2175            &prompt_tools,
2176            &prompt_metadata,
2177        )
2178    };
2179    let mut context_paths = Vec::new();
2180    let base_prompt = match effective_args.system_prompt.as_deref() {
2181        Some(explicit) => explicit.to_string(),
2182        None if project_trusted => match discover_system_prompt_file(&ctx.cwd) {
2183            Some(path) => {
2184                read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
2185            }
2186            None => default_prompt(),
2187        },
2188        None => default_prompt(),
2189    };
2190    let mut append_texts: Vec<String> = Vec::new();
2191    for extra in &effective_args.append_system_prompt {
2192        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
2193        append_texts.push(text);
2194    }
2195    if effective_args.append_system_prompt.is_empty() {
2196        if let Some(path) = project_trusted
2197            .then(|| discover_append_system_prompt_file(&ctx.cwd))
2198            .flatten()
2199        {
2200            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
2201                append_texts.push(text);
2202            }
2203        }
2204    }
2205    context_paths.extend(
2206        context_files
2207            .iter()
2208            .map(|file| file.path.to_string_lossy().into_owned()),
2209    );
2210    let append_join = if append_texts.is_empty() {
2211        None
2212    } else {
2213        Some(append_texts.join("\n\n"))
2214    };
2215    let system_prompt = compose_system_prompt(
2216        Some(&base_prompt),
2217        &[],
2218        if context_block.is_empty() {
2219            None
2220        } else {
2221            Some(&context_block)
2222        },
2223        append_join.as_deref(),
2224    );
2225
2226    // ---- Rebuild the emitter (TeeEmitter over fresh ExtensionEmitter) ----
2227    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
2228        Some(snapshot) => {
2229            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
2230            Arc::new(TeeEmitter::new(vec![ctx.broadcast.clone(), Arc::new(ext)]))
2231        }
2232        None => ctx.broadcast.clone(),
2233    };
2234
2235    // ---- 5. Push the rebuilt state into the live harness via the B5d setters ----
2236    let resources = AgentHarnessResources {
2237        context_files: context_paths,
2238        skills: if skills.is_empty() {
2239            None
2240        } else {
2241            Some(skills.clone())
2242        },
2243        prompt_templates: if prompt_templates.is_empty() {
2244            None
2245        } else {
2246            Some(prompt_templates.clone())
2247        },
2248    };
2249    let _ = harness.set_system_prompt(Some(system_prompt)).await;
2250    let _ = harness.set_resources(resources).await;
2251    let _ = harness.set_agent_emitter(Some(emitter)).await;
2252    let _ = harness
2253        .set_models(build_models_with_extensions_for_reload(
2254            &refreshed
2255                .as_ref()
2256                .map(|resolved| resolved.providers.clone())
2257                .unwrap_or_else(|| {
2258                    ctx.providers
2259                        .read()
2260                        .unwrap_or_else(|error| error.into_inner())
2261                        .clone()
2262                }),
2263            &extension_session,
2264            ctx.runtime.clone(),
2265        ))
2266        .await;
2267    let _ = harness
2268        .set_provider_hooks(
2269            rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
2270                .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
2271        )
2272        .await;
2273
2274    if let Some(resolved) = &refreshed {
2275        *ctx.providers
2276            .write()
2277            .unwrap_or_else(|error| error.into_inner()) = resolved.providers.clone();
2278        let catalog = crate::provider::authenticated_catalog(resolved);
2279        fresh_bridge
2280            .clone_host()
2281            .replace_model_catalog(catalog.clone());
2282        *ctx.catalog
2283            .write()
2284            .unwrap_or_else(|error| error.into_inner()) = catalog;
2285        // Refresh the public descriptor. Credentials remain in the newly bound
2286        // provider instances installed above and never enter the lane model.
2287        let _ = harness.lane("main").set_model(resolved.model.clone()).await;
2288    }
2289
2290    let _ = harness.set_tools(tools, Some(active)).await;
2291
2292    let summary = format!(
2293        "Reloaded {} plugin(s), {} skill(s), {} prompt(s).",
2294        extension_session.loaded_paths().len(),
2295        skills.len(),
2296        prompt_templates.len(),
2297    );
2298    ReloadOutcome {
2299        summary,
2300        had_warnings: warnings,
2301        details,
2302        // Reload completed; any diagnostics here are soft (shadowing / name
2303        // validation / skipped optional resources), not hard failures.
2304        had_errors: false,
2305        project_trusted: Some(project_trusted),
2306    }
2307}
2308
2309#[derive(Clone, Debug, PartialEq, Eq)]
2310struct ReloadSettingsFields {
2311    skill_dirs: Option<Vec<String>>,
2312    prompt_dirs: Option<Vec<String>>,
2313    extension_dirs: Option<Vec<String>>,
2314}
2315
2316impl From<crate::settings::Settings> for ReloadSettingsFields {
2317    fn from(settings: crate::settings::Settings) -> Self {
2318        Self {
2319            skill_dirs: settings.skill_dirs,
2320            prompt_dirs: settings.prompt_dirs,
2321            extension_dirs: settings.extension_dirs,
2322        }
2323    }
2324}
2325
2326#[derive(Clone, Debug, PartialEq, Eq)]
2327struct ReloadSettingsSnapshot {
2328    global: ReloadSettingsFields,
2329    project: Option<ReloadSettingsFields>,
2330}
2331
2332fn reload_reads_settings(args: &Args) -> bool {
2333    !args.dev_local_only && (!args.no_extensions || !args.no_skills || !args.no_prompt_templates)
2334}
2335
2336/// Strictly read the settings fields consumed while preparing a reload. The
2337/// snapshot intentionally excludes UI/model fields that `/reload` does not
2338/// use, so an unrelated settings save does not invalidate the operation.
2339fn load_reload_settings_snapshot(
2340    args: &Args,
2341    cwd: &Path,
2342    project_trusted: bool,
2343) -> Result<Option<ReloadSettingsSnapshot>, String> {
2344    if !reload_reads_settings(args) {
2345        return Ok(None);
2346    }
2347    let global = crate::settings::load_settings()
2348        .map_err(|error| format!("could not load global settings: {error}"))?
2349        .into();
2350    let project = if project_trusted {
2351        crate::settings::load_active_project_settings(cwd)
2352            .map_err(|error| format!("could not load project settings: {error}"))?
2353            .map(|(_, settings)| settings.into())
2354    } else {
2355        None
2356    };
2357    Ok(Some(ReloadSettingsSnapshot { global, project }))
2358}
2359
2360/// Validate every settings document that this reload will consume before
2361/// replacing any live extension, bridge, or harness resource.
2362#[cfg(test)]
2363fn validate_settings_for_reload(
2364    args: &Args,
2365    cwd: &Path,
2366    project_trusted: bool,
2367) -> Result<(), String> {
2368    load_reload_settings_snapshot(args, cwd, project_trusted).map(|_| ())
2369}
2370
2371fn prepare_reload_inputs(
2372    args: &Args,
2373    cwd: &Path,
2374    project_trusted: bool,
2375) -> Result<PreparedReloadInputs, String> {
2376    prepare_reload_inputs_inner(args, cwd, project_trusted, || {})
2377}
2378
2379fn prepare_reload_inputs_inner<F>(
2380    args: &Args,
2381    cwd: &Path,
2382    project_trusted: bool,
2383    before_verify: F,
2384) -> Result<PreparedReloadInputs, String>
2385where
2386    F: FnOnce(),
2387{
2388    let settings_before = load_reload_settings_snapshot(args, cwd, project_trusted)?;
2389
2390    let mut extension_dirs = if args.no_extensions || args.dev_local_only {
2391        Vec::new()
2392    } else if args.project_only {
2393        project_extension_dirs(cwd)
2394    } else if project_trusted {
2395        extension_dirs(cwd)
2396    } else {
2397        global_extension_dirs()
2398    };
2399    if !args.no_extensions {
2400        extension_dirs.extend(args.extensions_dir.iter().cloned());
2401    }
2402
2403    let skill_base_dirs = if args.no_skills {
2404        Vec::new()
2405    } else if args.dev_local_only || args.project_only {
2406        project_skill_dirs(cwd)
2407    } else if project_trusted {
2408        skill_dirs(cwd)
2409    } else {
2410        global_skill_dirs()
2411    };
2412
2413    let prompt_base_dirs = if args.no_prompt_templates {
2414        Vec::new()
2415    } else if args.dev_local_only || args.project_only {
2416        project_prompt_template_dirs(cwd)
2417    } else if project_trusted {
2418        prompt_template_dirs(cwd)
2419    } else {
2420        global_prompt_template_dirs()
2421    };
2422
2423    before_verify();
2424    let settings_after = load_reload_settings_snapshot(args, cwd, project_trusted)?;
2425    if settings_before != settings_after {
2426        return Err(
2427            "settings changed while reload inputs were being prepared; retry /reload".to_string(),
2428        );
2429    }
2430
2431    Ok(PreparedReloadInputs {
2432        extension_dirs,
2433        skill_base_dirs,
2434        prompt_base_dirs,
2435    })
2436}
2437
2438/// `build_models_with_extensions` for the reload path: the resolved provider
2439/// runtimes (NOT `resolved` — the reload context carries the `Arc<dyn Provider>`
2440/// list directly, since provider/auth did not change) first, then one
2441/// `PluggableProvider` per registered extension provider in the fresh session.
2442fn build_models_with_extensions_for_reload(
2443    providers: &[Arc<dyn Provider>],
2444    extension_session: &ExtensionSession,
2445    runtime: tokio::runtime::Handle,
2446) -> Vec<Arc<dyn Provider>> {
2447    let mut models: Vec<Arc<dyn Provider>> = providers.to_vec();
2448    let pluggable = rpi_extensions::PluggableProvider::from_session(extension_session, runtime);
2449    for provider in pluggable {
2450        // Declared packages must enter through credential-bound factories.
2451        // Falling back to a raw adapter would reintroduce packages rejected by
2452        // auth filtering and would discard their configured model snapshot.
2453        if extension_session
2454            .snapshot()
2455            .is_some_and(|snapshot| snapshot.provider_manifest(provider.id()).is_some())
2456        {
2457            continue;
2458        }
2459        if !models.iter().any(|known| known.id() == provider.id()) {
2460            models.push(provider);
2461        }
2462    }
2463    models
2464}
2465
2466/// Diagnostic for registered TUI renderers. All three renderer kinds are
2467/// consumed by the interactive TUI's JSON component adapter; this line remains
2468/// useful under `--verbose` for extension authors.
2469fn report_deferred_renderers(session: &ExtensionSession) {
2470    let Some(snap) = session.snapshot_arc() else {
2471        return;
2472    };
2473    let all = snap.renderers();
2474    let markdown = all
2475        .iter()
2476        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Markdown)
2477        .count();
2478    let message = all
2479        .iter()
2480        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Message)
2481        .count();
2482    let entry = all
2483        .iter()
2484        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Entry)
2485        .count();
2486    if markdown + message + entry == 0 {
2487        return;
2488    }
2489    eprintln!(
2490        "renderers: {} markdown-transform, {} message-render, {} entry-render (active)",
2491        markdown, message, entry
2492    );
2493}
2494
2495/// A harness-build error.
2496#[derive(Debug, thiserror::Error)]
2497pub enum BuildError {
2498    #[error("Could not create the session directory: {0}")]
2499    SessionDir(String),
2500    #[error("Could not open the saved session: {0}")]
2501    SessionOpen(String),
2502    #[error("No session found for {requested} in {dir}. Start a fresh session instead (drop --continue/--resume/--session).")]
2503    SessionNotFound { requested: String, dir: String },
2504    #[error("Could not build the harness: {0}")]
2505    HarnessCreate(String),
2506}
2507
2508/// Keep configured factories (including package-specific auth and catalogs)
2509/// first, then append legacy plugin registrations that have no runtime yet.
2510fn build_models_with_extensions(
2511    resolved: &ResolvedModel,
2512    extension_session: &ExtensionSession,
2513    runtime: tokio::runtime::Handle,
2514) -> Vec<Arc<dyn Provider>> {
2515    build_models_with_extensions_for_reload(&resolved.providers, extension_session, runtime)
2516}
2517
2518/// Resolve project resource loading without prompting. Explicit CLI overrides
2519/// win, then a stored decision; projects with no decision load by default.
2520pub(crate) fn resolve_project_trust(args: &Args, cwd: &Path) -> bool {
2521    if let Some(override_value) = args.trust_override {
2522        return override_value;
2523    }
2524    crate::config::project_trust_decision(cwd)
2525        .ok()
2526        .flatten()
2527        .unwrap_or(true)
2528}
2529
2530/// Resolve the extension dirs to scan and load the cdylib plugins, returning
2531/// the loaded session guard (keeps the `Library` handles alive for the harness
2532/// lifetime). Scan order: configured project paths, project `.rpi/extensions`,
2533/// configured/global conventional paths, then any
2534/// `--extensions-dir` flags (scanned after the defaults — `args.rs`).
2535/// Diagnostics are a no-op sink for now; load skips/ABI mismatches surface via
2536/// the `--verbose` summary.
2537pub(crate) fn load_extensions(
2538    args: &Args,
2539    cwd: &Path,
2540    project_trusted: bool,
2541    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
2542) -> ExtensionSession {
2543    if args.no_extensions {
2544        return ExtensionSession::none();
2545    }
2546    let mut dirs = if args.dev_local_only {
2547        Vec::new()
2548    } else if args.project_only {
2549        project_extension_dirs(cwd)
2550    } else if project_trusted {
2551        extension_dirs(cwd)
2552    } else {
2553        global_extension_dirs()
2554    };
2555    dirs.extend(args.extensions_dir.iter().cloned());
2556    let leases = match crate::resource_management::host_leases(cwd) {
2557        Ok(leases) => leases,
2558        Err(error) => {
2559            eprintln!("warning: refusing extension loading: {error}");
2560            return ExtensionSession::none();
2561        }
2562    };
2563    load_extensions_from_dirs(args, &dirs, action_bridge, Some(leases))
2564}
2565
2566fn load_extensions_from_dirs(
2567    args: &Args,
2568    dirs: &[PathBuf],
2569    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
2570    host_guard: Option<Arc<dyn Send + Sync>>,
2571) -> ExtensionSession {
2572    let diagnostics: Arc<dyn PluginDiagnostics> = Arc::new(NullDiagnostics);
2573    // B5a: the action bridge is cloned into every loaded plugin's vtable
2574    // `user_data` so post-register `runtime_action` calls recover the harness
2575    // host from any thread. The call site already gates `load_extensions` behind
2576    // `!no_extensions` and threads `Some(bridge)`; `None` is only passed by the
2577    // `--no-extensions` branch (which calls `ExtensionSession::none()` directly)
2578    // and tests. Explicit `--extension`/`-e` files load after the dirs.
2579    rpi_extensions::load_session_mixed_guarded(
2580        dirs,
2581        &args.extension,
2582        diagnostics,
2583        action_bridge,
2584        host_guard,
2585    )
2586}
2587
2588/// The host permanently owns both durable public names.
2589/// Refuse rather than override, fall back to, or dual-write a legacy extension
2590/// implementation. The core native durable feature may still be disabled; that
2591/// does not make the reserved names available to extensions.
2592fn validate_durable_extensions(args: &Args, session: &ExtensionSession) -> Result<(), String> {
2593    if args.native_durable && session.owns_stdio() {
2594        return Err(
2595            "--native-durable requires the native host; stdio-owning extensions are unsupported"
2596                .into(),
2597        );
2598    }
2599    if let Some(snapshot) = session.snapshot() {
2600        if reserved_durable_name(
2601            snapshot.tools().iter().map(|tool| tool.tool.name.as_str()),
2602            snapshot
2603                .commands()
2604                .iter()
2605                .map(|command| command.name.as_str()),
2606        ) {
2607            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());
2608        }
2609    }
2610    Ok(())
2611}
2612
2613fn reserved_durable_name<'a>(
2614    mut tools: impl Iterator<Item = &'a str>,
2615    mut commands: impl Iterator<Item = &'a str>,
2616) -> bool {
2617    tools.any(|name| name == "durable")
2618        || commands.any(|name| name.trim_start_matches('/') == "durable")
2619}
2620
2621#[cfg(test)]
2622#[path = "native_durable/session_tests.rs"]
2623mod native_durable_session_tests;
2624
2625/// Merge extension tools into the built-ins. Ordinarily extensions override
2626/// same-named built-ins (first extension wins); host-reserved durable names
2627/// were already checked above. Both tool filters still apply to the merged set.
2628fn merge_extension_tools(
2629    tools: &mut Vec<HarnessTool>,
2630    session: &ExtensionSession,
2631    args: &Args,
2632    tool_context: &rpi_extensions::ToolCallContext,
2633) {
2634    let Some(snapshot) = session.snapshot() else {
2635        return;
2636    };
2637    for et in snapshot.tools() {
2638        let name = &et.tool.name;
2639        if !tool_name_allowed(name, args) {
2640            continue;
2641        }
2642        let adapter = PluginToolAdapter::new(et.tool.clone(), et.handle(), session.keepalive())
2643            .with_context(tool_context.clone());
2644        let harness_tool = HarnessTool::new(Arc::new(adapter));
2645        match tools.iter_mut().find(|t| t.tool.schema().name == *name) {
2646            Some(slot) => *slot = harness_tool,
2647            None => tools.push(harness_tool),
2648        }
2649    }
2650}
2651
2652/// Build the tool list per `--tools`/`--exclude-tools`/`--no-tools`/
2653/// `--no-builtin-tools`. Mirrors the TS `tools`/`excludeTools`/`noTools`
2654/// resolution in `createAgentSession`.
2655/// Default bash timeout: 120s when the model doesn't pass one (prevents a
2656/// forgotten `timeout` from hanging the run forever — the "卡住" report).
2657/// `RPI_BASH_TIMEOUT` overrides; a model-supplied timeout always wins.
2658pub fn bash_options() -> rpi_tools::tools::bash::BashToolOptions {
2659    use rpi_tools::tools::bash::BashToolOptions;
2660    let default = std::env::var("RPI_BASH_TIMEOUT")
2661        .ok()
2662        .and_then(|v| v.parse::<f64>().ok())
2663        .unwrap_or(rpi_tools::tools::bash::DEFAULT_BASH_TIMEOUT_SECONDS);
2664    // Saved user defaults, matching how `defaultTools` is read in `build_tools`.
2665    // `shellCommandPrefix` is prepended to every command (upstream's key for
2666    // alias/`shopt` setup). Native's `shellPath` is *not* wired: neither
2667    // `BashToolOptions` nor `ShellCaptureOptions` carries a shell binary today, so
2668    // honouring it means plumbing one through pi-tools first.
2669    let settings = crate::settings::load_settings().unwrap_or_default();
2670    BashToolOptions {
2671        command_prefix: settings.shell_command_prefix.clone(),
2672        default_timeout: Some(default),
2673        prepare: None,
2674    }
2675}
2676
2677#[cfg(test)]
2678fn build_tools(ctx: &ExecutionToolContext, args: &Args) -> Vec<HarnessTool> {
2679    build_tools_bound(ctx, args, Arc::new(std::sync::OnceLock::new()))
2680}
2681
2682fn build_tools_bound(
2683    ctx: &ExecutionToolContext,
2684    args: &Args,
2685    durable_binding: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
2686) -> Vec<HarnessTool> {
2687    if args.no_tools {
2688        return Vec::new();
2689    }
2690    // Keep the coding tools aligned with Pi and expose rpi's read-only docs
2691    // lookup as a default assistant capability.
2692    //
2693    // Replay policy (native `ToolDeclaration.replay`): only tools that are
2694    // genuinely free of side effects may be re-run when a crash leaves their
2695    // outcome unknown — everything else must stay `Never`, because replaying
2696    // `bash`/`write`/`edit` would duplicate a side effect. `HarnessTool::new`
2697    // already defaults to `Never`, so this is opt-in per read-only tool.
2698    let mut all: Vec<(&'static str, HarnessTool)> = vec![
2699        (
2700            "read",
2701            HarnessTool::new(create_read_tool(
2702                ctx,
2703                Some(rpi_tools::tools::read::ReadToolOptions {
2704                    image_processor: Some(Arc::new(
2705                        rpi_tools::image_processing::InlineImageProcessor,
2706                    )),
2707                    ..Default::default()
2708                }),
2709            ))
2710            .with_replay(ToolReplay::Safe),
2711        ),
2712        (
2713            "bash",
2714            HarnessTool::new(create_bash_tool(ctx, Some(bash_options()))),
2715        ),
2716        ("edit", HarnessTool::new(create_edit_tool(ctx))),
2717        ("write", HarnessTool::new(create_write_tool(ctx))),
2718        (
2719            "docs",
2720            HarnessTool::new(create_docs_tool()).with_replay(ToolReplay::Safe),
2721        ),
2722    ];
2723
2724    if args.native_durable {
2725        // Mixed read/write tool is NEVER safe for automatic replay.
2726        all.push((
2727            "durable",
2728            HarnessTool::new(Arc::new(crate::native_durable::NativeDurableTool::new(
2729                durable_binding,
2730            ))),
2731        ));
2732    }
2733
2734    // Add PowerShell tool on Windows
2735    #[cfg(target_os = "windows")]
2736    all.push(("powershell", HarnessTool::new(create_powershell_tool(ctx))));
2737
2738    // Apply default_tools from settings (if no CLI override)
2739    if args.tools.is_none() && args.resource_config.is_none() && args.resource_transition.is_none()
2740    {
2741        if let Ok(settings) = crate::settings::load_settings() {
2742            if let Some(default_tools) = &settings.default_tools {
2743                all.retain(|(name, _)| default_tools.iter().any(|t| t == name));
2744            }
2745        }
2746    }
2747
2748    // `--no-builtin-tools` disables the built-in set but would keep
2749    // extension/custom tools — v1 has none, so it's equivalent to `--no-tools`
2750    // here. We honor it by clearing the built-ins.
2751    if args.no_builtin_tools {
2752        all.clear();
2753    }
2754
2755    // Allowlist (`--tools`): keep only named built-ins.
2756    if let Some(allow) = &args.tools {
2757        all.retain(|(name, _)| allow.iter().any(|a| a == name));
2758    }
2759    // Denylist (`--exclude-tools`): drop named tools.
2760    if let Some(deny) = &args.exclude_tools {
2761        all.retain(|(name, _)| !deny.iter().any(|d| d == name));
2762    }
2763
2764    all.into_iter().map(|(_, t)| t).collect()
2765}
2766
2767/// Resolve the active tool names from the constructed tools when no explicit
2768/// `--tools` allowlist was given. Mirrors the TS default: all registered tools
2769/// active.
2770fn active_tool_names(tools: &[HarnessTool], args: &Args) -> Vec<String> {
2771    filter_active_tool_names(
2772        tools.iter().map(|tool| tool.tool.schema().name.clone()),
2773        args,
2774    )
2775}
2776
2777/// Whether a tool name survives the command-line tool policy. Keep this check
2778/// centralized so extension-provided tools honor the same policy as built-ins.
2779pub(crate) fn tool_name_allowed(name: &str, args: &Args) -> bool {
2780    if args.no_tools {
2781        return false;
2782    }
2783    if args
2784        .tools
2785        .as_ref()
2786        .is_some_and(|allow| !allow.iter().any(|value| value == name))
2787    {
2788        return false;
2789    }
2790    if args
2791        .exclude_tools
2792        .as_ref()
2793        .is_some_and(|deny| deny.iter().any(|value| value == name))
2794    {
2795        return false;
2796    }
2797    true
2798}
2799
2800pub(crate) fn filter_active_tool_names<I>(names: I, args: &Args) -> Vec<String>
2801where
2802    I: IntoIterator<Item = String>,
2803{
2804    names
2805        .into_iter()
2806        .filter(|name| tool_name_allowed(name, args))
2807        .collect()
2808}
2809
2810/// Build the `Session` facade for the chosen selection.
2811async fn build_session(
2812    selection: &SessionSelection,
2813    cwd: &str,
2814    selected: Option<&crate::resource_selection::ResolvedSelection>,
2815) -> Result<Session, BuildError> {
2816    match selection {
2817        SessionSelection::Ephemeral => Ok(ephemeral_session()),
2818        SessionSelection::New { dir, .. } => {
2819            // Ensure the sessions directory exists, then create a fresh JSONL
2820            // session file inside it.
2821            std::fs::create_dir_all(dir)
2822                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2823            let session = create_jsonl_session(dir, cwd)
2824                .await
2825                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2826            Ok(session)
2827        }
2828        SessionSelection::Latest { .. }
2829        | SessionSelection::ById { .. }
2830        | SessionSelection::ByExactId { .. } => restore_session(selection, cwd).await,
2831        SessionSelection::Fork { source, dir } => {
2832            fork_session_at_launch(source, dir, cwd, selected).await
2833        }
2834    }
2835}
2836
2837/// Open an existing JSONL session for `Latest` / `ById`. Mirrors the TS
2838/// `SessionManager.resume`/`open` flow: list the session dir (newest-first),
2839/// match the request, then open the matched file and wrap it in a `Session`
2840/// facade. The restored transcript renders into the TUI at startup and the
2841/// harness continues appending to the same file.
2842async fn restore_session(selection: &SessionSelection, cwd: &str) -> Result<Session, BuildError> {
2843    // `resolve_restore_target` is newest-first; `Latest` takes the head, `ById`
2844    // matches the id exactly or by file-name containment (so `--session 01a02…`
2845    // or a partial id works, mirroring the TS id/path matching).
2846    let Some(meta) = resolve_restore_target(selection, cwd).await? else {
2847        return match selection {
2848            // Exact id match only (pi `--session-id`): a missing session is
2849            // created fresh under the selected dir instead of an error.
2850            SessionSelection::ByExactId { id, dir } => {
2851                std::fs::create_dir_all(dir)
2852                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2853                create_jsonl_session_with_id(dir, cwd, Some(id.clone()))
2854                    .await
2855                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))
2856            }
2857            SessionSelection::Latest { dir } => Err(BuildError::SessionNotFound {
2858                requested: "the most recent session".to_string(),
2859                dir: dir.display().to_string(),
2860            }),
2861            SessionSelection::ById { id, dir } => Err(BuildError::SessionNotFound {
2862                requested: format!("session {id}"),
2863                dir: dir.display().to_string(),
2864            }),
2865            _ => unreachable!("resolve_restore_target only returns None for restore selections"),
2866        };
2867    };
2868    let sessions_root = selection_dir(selection);
2869    open_session(&meta, cwd, &sessions_root)
2870        .await
2871        .map(|restored| restored.session)
2872}
2873
2874/// The sessions root a selection was resolved against.
2875fn selection_dir(selection: &SessionSelection) -> PathBuf {
2876    match selection {
2877        SessionSelection::Ephemeral => PathBuf::new(),
2878        SessionSelection::New { dir, .. }
2879        | SessionSelection::Latest { dir }
2880        | SessionSelection::ById { dir, .. }
2881        | SessionSelection::ByExactId { dir, .. }
2882        | SessionSelection::Fork { dir, .. } => dir.clone(),
2883    }
2884}
2885
2886/// Resolve the metadata a restore selection names, without opening the file.
2887///
2888/// Shared by the startup build ([`restore_session`]) and the cwd peek
2889/// ([`peek_restored_session_cwd`]) so the two can never disagree about which
2890/// session a launch restores. Pure listing + matching: no session lock is
2891/// claimed and nothing is created.
2892async fn resolve_restore_target(
2893    selection: &SessionSelection,
2894    cwd: &str,
2895) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
2896    match selection {
2897        SessionSelection::Latest { dir } => {
2898            let metas = list_session_metadata_in_dir(cwd, dir).await?;
2899            Ok(first_resumable_session(&metas).cloned())
2900        }
2901        SessionSelection::ById { id, dir } => find_session_metadata(id, cwd, dir).await,
2902        SessionSelection::ByExactId { id, dir } => {
2903            let metas = list_session_metadata_in_dir(cwd, dir).await?;
2904            Ok(metas.into_iter().find(|m| m.id == *id))
2905        }
2906        SessionSelection::Fork { .. }
2907        | SessionSelection::New { .. }
2908        | SessionSelection::Ephemeral => Ok(None),
2909    }
2910}
2911
2912/// The metadata of the session whose id matches exactly or by file-name
2913/// containment (so `--session 01a02…` / a partial id / a full file name all
2914/// work), or `None` when nothing matches.
2915async fn find_session_metadata(
2916    id: &str,
2917    cwd: &str,
2918    dir: &Path,
2919) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
2920    let metas = list_session_metadata_in_dir(cwd, dir).await?;
2921    Ok(metas
2922        .into_iter()
2923        .find(|m| m.id == id || m.path.contains(id) || id.contains(&m.id)))
2924}
2925
2926/// What a launch that would restore a session says about the working directory.
2927pub(crate) struct RestoredSessionCwd {
2928    /// The id of the session this launch will restore. The host pins it into
2929    /// `args` so the later build opens exactly this session — a directory
2930    /// listing taken twice can disagree (another `rpi` may write a newer
2931    /// session in between), and adopting one session's directory while opening
2932    /// another is the very bug this restores.
2933    pub id: String,
2934    /// The directory recorded in the session header.
2935    pub recorded: PathBuf,
2936    /// `Some` when the recorded directory still exists and the run adopts it;
2937    /// `None` when the caller must fall back to the launch cwd and say so.
2938    pub adopted: Option<PathBuf>,
2939}
2940
2941/// The working directory the launch's restored session was created in, resolved
2942/// WITHOUT opening, locking, or creating anything.
2943///
2944/// Read-only by design: this runs before trust resolution and extension
2945/// preparation, where a failure must not take the run down — the real open
2946/// happens later and surfaces its own errors. Returns `None` when the selection
2947/// is not a restore (fresh/ephemeral/fork) or cannot be resolved.
2948pub(crate) async fn peek_restored_session_cwd(
2949    selection: &SessionSelection,
2950    launch_cwd: &Path,
2951) -> Option<RestoredSessionCwd> {
2952    let cwd_str = launch_cwd.to_string_lossy().into_owned();
2953    let meta = resolve_restore_target(selection, &cwd_str).await.ok()??;
2954    let recorded = PathBuf::from(&meta.cwd);
2955    if recorded.as_os_str().is_empty() {
2956        return None;
2957    }
2958    Some(RestoredSessionCwd {
2959        id: meta.id,
2960        adopted: crate::session_cwd::resolve_session_cwd(&recorded),
2961        recorded,
2962    })
2963}
2964
2965/// Pin a peeked restore target into `args` so the later build opens exactly the
2966/// session the peek inspected.
2967///
2968/// `Latest` (`-c`) re-lists the session directory when the build runs, and
2969/// another `rpi` may have written a newer session in between. Adopting one
2970/// session's working directory while opening a different conversation would put
2971/// the tools in a directory that conversation never used — the exact failure
2972/// this adoption exists to prevent. Pinning the resolved id turns the second
2973/// listing into an exact match instead of a fresh "newest" choice.
2974pub(crate) fn pin_restored_selection(args: &mut Args, restored: &RestoredSessionCwd) {
2975    args.continue_session = false;
2976    args.resume = false;
2977    args.session = Some(restored.id.clone());
2978}
2979
2980/// `--fork <path|id>`: open the source session, fork it into a new JSONL
2981/// session (records the parent id), and start in the fork.
2982async fn fork_session_at_launch(
2983    source: &str,
2984    dir: &Path,
2985    cwd: &str,
2986    selected: Option<&crate::resource_selection::ResolvedSelection>,
2987) -> Result<Session, BuildError> {
2988    use rpi_harness::session::jsonl::{
2989        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
2990    };
2991    use rpi_harness::session::types::{ForkOptions, SessionStorage};
2992    use rpi_tools::FileSystem;
2993
2994    let dir = dir.to_path_buf();
2995    std::fs::create_dir_all(&dir)
2996        .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2997    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
2998    let fs: Arc<dyn FileSystem> = env.clone();
2999    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3000        fs: fs.clone(),
3001        sessions_root: dir.to_string_lossy().into_owned(),
3002        clock: Arc::new(SystemClock),
3003        ids: Arc::new(DefaultIdGenerator::new()),
3004    });
3005    // A session file given by path forks from wherever it lives (pi parity:
3006    // `pi --fork <file>` takes any session file); an id or a name fragment is
3007    // looked up in the session directory.
3008    let source_meta = match session_metadata_at(Path::new(source)) {
3009        Some(meta) => meta,
3010        None => {
3011            let metas = repo
3012                .list_typed(&rpi_harness::session::jsonl::JsonlSessionListOptions::default())
3013                .await
3014                .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")))?;
3015            metas
3016                .into_iter()
3017                .find(|m| m.id == *source || m.path.contains(source) || source.contains(&m.id))
3018                .ok_or_else(|| BuildError::SessionNotFound {
3019                    requested: format!("--fork {source}"),
3020                    dir: dir.display().to_string(),
3021                })?
3022        }
3023    };
3024    let fork_storage = repo
3025        .fork_typed_with_value_initializer(
3026            &source_meta,
3027            &JsonlSessionCreateOptions {
3028                id: None,
3029                parent_session_id: Some(source_meta.id.clone()),
3030                cwd: cwd.to_string(),
3031                metadata: None,
3032            },
3033            &ForkOptions::default(),
3034            |values| crate::resource_selection::fork_initial_values_for_selection(values, selected),
3035        )
3036        .await
3037        .map_err(|e| BuildError::SessionDir(format!("fork {}: {e}", source_meta.path)))?;
3038    fork_storage
3039        .acquire_writer_lease()
3040        .await
3041        .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
3042    let storage_arc: Arc<dyn SessionStorage> = Arc::new(fork_storage);
3043    Ok(Session::new(storage_arc, None))
3044}
3045
3046/// The metadata of the JSONL session file at `path`, or `None` when `path` is
3047/// not a readable session file.
3048fn session_metadata_at(path: &Path) -> Option<rpi_harness::session::jsonl::JsonlSessionMetadata> {
3049    use rpi_harness::session::jsonl::codec::{metadata_from_header, parse_header};
3050    use std::io::BufRead;
3051
3052    let file = std::fs::File::open(path).ok()?;
3053    let modified_at = file
3054        .metadata()
3055        .ok()?
3056        .modified()
3057        .ok()?
3058        .duration_since(std::time::UNIX_EPOCH)
3059        .ok()?
3060        .as_millis() as i64;
3061    let mut first_line = String::new();
3062    std::io::BufReader::new(file)
3063        .read_line(&mut first_line)
3064        .ok()?;
3065    let header = parse_header(first_line.trim_end()).ok()?;
3066    let path = std::fs::canonicalize(path).ok()?;
3067    Some(metadata_from_header(
3068        &header,
3069        &path.to_string_lossy(),
3070        modified_at,
3071    ))
3072}
3073
3074/// Errors from [`open_session_by_id`], split so the CLI can map them to
3075/// [`BuildError`] while the TUI can surface a friendlier note.
3076pub enum OpenError {
3077    /// No session matched the request.
3078    NotFound { requested: String },
3079    /// The match existed but could not be opened/parsed.
3080    Other(String),
3081}
3082
3083impl std::fmt::Display for OpenError {
3084    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3085        match self {
3086            OpenError::NotFound { requested } => write!(f, "no session matches {requested}"),
3087            // `Other` carries the bare reason (see `open_session_by_id`); the
3088            // prefix lives here so the TUI and the CLI's
3089            // `BuildError::SessionOpen` wrapper each render it exactly once
3090            // (wrapping the already-prefixed `BuildError` string doubled it).
3091            OpenError::Other(msg) => write!(f, "Could not open the saved session: {msg}"),
3092        }
3093    }
3094}
3095
3096/// Which sessions a picker lists. The default is [`Self::Project`]: with a
3097/// shared `sessionDir`, a flat list over every cwd directory buries the current
3098/// project's history (fork issue DavidHinton-xcpc/pi-rust#13). `All` is an
3099/// explicit opt-in and rows carry their project so the list stays traceable.
3100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3101pub enum SessionScope {
3102    #[default]
3103    Project,
3104    All,
3105}
3106
3107impl SessionScope {
3108    pub fn toggled(self) -> Self {
3109        match self {
3110            Self::Project => Self::All,
3111            Self::All => Self::Project,
3112        }
3113    }
3114
3115    pub fn label(self) -> &'static str {
3116        match self {
3117            Self::Project => "this project",
3118            Self::All => "all projects",
3119        }
3120    }
3121}
3122
3123/// List the JSONL session metadata under the default session dir, newest
3124/// first. Shared by startup restore and the TUI `/session` hot-switch.
3125///
3126/// `list_session_metadata` intentionally stays unscoped: it resolves sessions
3127/// to *open* (including `--continue`/`-c`), where filtering by cwd would make
3128/// a session that the caller named by id unopenable. Only pickers apply a scope.
3129pub async fn list_session_metadata(
3130    cwd: &str,
3131) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3132    let dir = default_session_dir(Path::new(cwd));
3133    list_session_metadata_in_dir(cwd, &dir).await
3134}
3135
3136pub(crate) async fn list_session_metadata_in_dir(
3137    cwd: &str,
3138    dir: &Path,
3139) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3140    list_session_metadata_in_scope_in_dir(cwd, dir, SessionScope::All).await
3141}
3142
3143/// Scope-aware metadata listing for pickers. `Project` passes the cwd to the
3144/// repo's typed list API, so the enumeration and the open path agree on which
3145/// directory belongs to this project.
3146pub(crate) async fn list_session_metadata_in_scope_in_dir(
3147    cwd: &str,
3148    dir: &Path,
3149    scope: SessionScope,
3150) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3151    use rpi_harness::session::jsonl::{
3152        JsonlSessionListOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
3153    };
3154    use rpi_tools::FileSystem;
3155
3156    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3157    let fs: Arc<dyn FileSystem> = env.clone();
3158    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3159        fs: fs.clone(),
3160        sessions_root: dir.to_string_lossy().into_owned(),
3161        clock: Arc::new(SystemClock),
3162        ids: Arc::new(DefaultIdGenerator::new()),
3163    });
3164    let options = JsonlSessionListOptions {
3165        cwd: match scope {
3166            SessionScope::Project => Some(cwd.to_string()),
3167            SessionScope::All => None,
3168        },
3169    };
3170    let metadata_lookup = StartupSpan::start(Phase::MetadataLookup);
3171    let result = repo
3172        .list_typed(&options)
3173        .await
3174        .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")));
3175    if result.is_ok() {
3176        metadata_lookup.finish();
3177    }
3178    result
3179}
3180
3181/// A cheap, display-oriented summary of one JSONL session file.
3182///
3183/// The session pickers (`-r` and `/session`) need enough context to tell saved
3184/// sessions apart. The header-only [`JsonlSessionMetadata`] carries no name and
3185/// no transcript, so a list built from it renders as a wall of identical
3186/// `2026-09-25T15-05-15-847Z_…` file names — including the many header-only
3187/// sessions an abandoned launch leaves behind. This reads just the head (and a
3188/// small tail, for a late `--name`/`/name` fact) of the file to recover:
3189///
3190/// - the session display name, when one was recorded;
3191/// - the first user prompt, single-lined and truncated, for a readable label;
3192/// - whether the file is header-only (nothing to resume).
3193///
3194/// It intentionally does **not** parse the whole log: sessions can be tens of
3195/// megabytes, and the picker runs over every session at startup.
3196#[derive(Debug, Clone, Default, PartialEq, Eq)]
3197pub struct SessionSummary {
3198    /// The session display name (`--name` / `/name`), if one was recorded.
3199    pub name: Option<String>,
3200    /// The first user prompt, single-lined and trimmed to a label-sized length.
3201    pub preview: Option<String>,
3202    /// True when the file holds only its header (a session with no content).
3203    pub empty: bool,
3204    /// On-disk size in bytes (a rough content-volume hint for the picker).
3205    pub bytes: u64,
3206}
3207
3208/// Bytes read from the head of a session file to recover a name + first prompt.
3209const SUMMARY_HEAD_BYTES: u64 = 256 * 1024;
3210/// Bytes read from the tail of a session file to recover a late name fact.
3211const SUMMARY_TAIL_BYTES: u64 = 8 * 1024;
3212/// Longest preview retained (characters, not bytes).
3213const SUMMARY_PREVIEW_CHARS: usize = 80;
3214
3215/// Summarize one session file for the pickers. Best-effort: an unreadable or
3216/// malformed file yields a summary with `empty: false` and no label, so it is
3217/// still selectable rather than silently dropped.
3218pub fn summarize_session_file(path: &Path) -> SessionSummary {
3219    use std::io::{Read, Seek, SeekFrom};
3220
3221    let Ok(mut file) = std::fs::File::open(path) else {
3222        return SessionSummary::default();
3223    };
3224    let Ok(size) = file.metadata().map(|m| m.len()) else {
3225        return SessionSummary::default();
3226    };
3227    if size == 0 {
3228        return SessionSummary {
3229            name: None,
3230            preview: None,
3231            empty: true,
3232            bytes: 0,
3233        };
3234    }
3235
3236    // Head: the header line (for the empty check) + a name fact + the first user
3237    // prompt. The whole window is scanned; it is already in memory.
3238    let mut head = vec![0u8; SUMMARY_HEAD_BYTES.min(size) as usize];
3239    let head_len = file.read(&mut head).unwrap_or(0);
3240    head.truncate(head_len);
3241    let head = String::from_utf8_lossy(&head);
3242    let mut lines: Vec<&str> = head.lines().collect();
3243    let header_len = lines.first().map(|line| line.len()).unwrap_or(0);
3244    // A header-only file is exactly the header plus an optional trailing `\n`.
3245    let empty = (size as usize) <= header_len + 1;
3246    // When the window stopped short of the file end, its final line is partial:
3247    // drop it so a half-read message can never be mistaken for a complete one.
3248    if (head_len as u64) < size && !lines.is_empty() {
3249        lines.pop();
3250    }
3251
3252    let mut summary = SessionSummary {
3253        name: None,
3254        preview: None,
3255        empty,
3256        bytes: size,
3257    };
3258    for line in lines {
3259        apply_summary_line(line, &mut summary);
3260    }
3261
3262    // Tail: a name set late in the session lives after the head window. Read the
3263    // last window and scan only complete lines so a torn/partial first line is
3264    // ignored. Only do this when the file is larger than the head window.
3265    if size > SUMMARY_HEAD_BYTES
3266        && file
3267            .seek(SeekFrom::End(-(SUMMARY_TAIL_BYTES as i64)))
3268            .is_ok()
3269    {
3270        let mut tail = Vec::new();
3271        if file.read_to_end(&mut tail).is_ok() {
3272            let tail = String::from_utf8_lossy(&tail);
3273            let mut tail_lines = tail.lines();
3274            // Drop the possibly-partial first line of the window.
3275            tail_lines.next();
3276            for line in tail_lines {
3277                if let Some(name) = name_from_line(line) {
3278                    summary.name = name;
3279                }
3280            }
3281        }
3282    }
3283    summary
3284}
3285
3286/// Extract the name from a `{"kind":"fact","fact":"name","name":…}` line.
3287/// Returns `Some(None)` for an explicit `name: null` (the fact was cleared).
3288fn name_from_line(line: &str) -> Option<Option<String>> {
3289    let value: serde_json::Value = serde_json::from_str(line).ok()?;
3290    if value.get("kind").and_then(|v| v.as_str()) != Some("fact") {
3291        return None;
3292    }
3293    if value.get("fact").and_then(|v| v.as_str()) != Some("name") {
3294        return None;
3295    }
3296    Some(match value.get("name") {
3297        Some(serde_json::Value::String(name)) => Some(name.clone()),
3298        _ => None,
3299    })
3300}
3301
3302/// Fold one JSONL line into `summary`: record a name fact, or capture the first
3303/// user prompt as the preview.
3304fn apply_summary_line(line: &str, summary: &mut SessionSummary) {
3305    if let Some(name) = name_from_line(line) {
3306        summary.name = name;
3307        return;
3308    }
3309    if summary.preview.is_some() {
3310        return;
3311    }
3312    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
3313        return;
3314    };
3315    if value.get("kind").and_then(|v| v.as_str()) != Some("entry") {
3316        return;
3317    }
3318    if value.get("type").and_then(|v| v.as_str()) != Some("message") {
3319        return;
3320    }
3321    let Some(message) = value.get("message") else {
3322        return;
3323    };
3324    if message.get("role").and_then(|v| v.as_str()) != Some("user") {
3325        return;
3326    }
3327    let text = match message.get("content") {
3328        Some(serde_json::Value::String(text)) => Some(text.as_str()),
3329        Some(serde_json::Value::Array(blocks)) => blocks.iter().find_map(|block| {
3330            (block.get("type").and_then(|v| v.as_str()) == Some("text"))
3331                .then(|| block.get("text").and_then(|v| v.as_str()))
3332                .flatten()
3333        }),
3334        _ => None,
3335    };
3336    let Some(text) = text else { return };
3337    let collapsed = text
3338        .lines()
3339        .map(str::trim)
3340        .filter(|line| !line.is_empty())
3341        .collect::<Vec<_>>()
3342        .join(" ");
3343    if collapsed.is_empty() {
3344        return;
3345    }
3346    summary.preview = Some(collapsed.chars().take(SUMMARY_PREVIEW_CHARS).collect());
3347}
3348
3349/// The human label for a session row: its recorded name, else the first user
3350/// prompt, else a marker that says the file has no transcript to show. Shared
3351/// by the startup picker and the in-TUI `/session` selector.
3352pub fn session_display_label(summary: &SessionSummary) -> String {
3353    if let Some(name) = summary.name.as_deref().map(str::trim) {
3354        if !name.is_empty() {
3355            return name.to_string();
3356        }
3357    }
3358    match summary.preview.as_deref().map(str::trim) {
3359        Some(preview) if !preview.is_empty() => preview.to_string(),
3360        _ => "(no messages)".to_string(),
3361    }
3362}
3363
3364/// Compact byte count (1.2MB / 34KB / 512B), shared by the startup picker and
3365/// the in-TUI `/session` selector.
3366pub fn format_session_bytes(bytes: u64) -> String {
3367    if bytes >= 1_048_576 {
3368        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
3369    } else if bytes >= 1024 {
3370        format!("{}KB", bytes / 1024)
3371    } else {
3372        format!("{bytes}B")
3373    }
3374}
3375
3376/// The first 8 characters of a session id, enough to disambiguate two rows that
3377/// share a timestamp without shouting the whole UUID.
3378pub fn short_session_id(id: &str) -> &str {
3379    &id[..id.len().min(8)]
3380}
3381
3382/// One listed session file. `project` is the cwd-encoded directory name when
3383/// the row comes from a project subdirectory; `None` for legacy files that sit
3384/// directly under the sessions root. The All view renders it so a flat list is
3385/// still attributable to a project.
3386#[derive(Debug, Clone, PartialEq, Eq)]
3387pub struct SessionFileEntry {
3388    pub path: PathBuf,
3389    pub project: Option<String>,
3390}
3391
3392/// Synchronously list every JSONL session file under `dir`, newest-first by
3393/// modification time. Kept for callers that explicitly want the full set (e.g.
3394/// resolving a session by id); pickers use [`list_session_files_in_scope_sync`].
3395///
3396/// The repo's [`list_session_metadata`] is async and scans one cwd-encoded
3397/// subdirectory level; the in-TUI `/session` selector runs on the blocking key
3398/// thread and cannot await it, so this walks the same layout directly. Both
3399/// `.jsonl` files directly under `dir` and one level of subdirectories are
3400/// accepted.
3401pub fn list_session_files_sync(dir: &Path) -> Vec<PathBuf> {
3402    list_entries_sync(dir, None)
3403        .into_iter()
3404        .map(|entry| entry.path)
3405        .collect()
3406}
3407
3408/// Scope-aware synchronous listing for the `/session` selector.
3409///
3410/// `Project` resolves the current project's directory with the *same* encoding
3411/// the repo uses for create/open (`jsonl_session_directory_name`), rather than
3412/// re-deriving it: the old flat walk and the open path disagreed about which
3413/// files belong to this project (fork issue #13). `All` keeps the old layout but
3414/// tags each row with its project directory.
3415pub fn list_session_files_in_scope_sync(
3416    cwd: &Path,
3417    dir: &Path,
3418    scope: SessionScope,
3419) -> Vec<SessionFileEntry> {
3420    let project_dir = match scope {
3421        SessionScope::Project => {
3422            let resolved = normalize_cwd(cwd);
3423            Some(rpi_harness::session::jsonl::jsonl_session_directory_name(
3424                &resolved.to_string_lossy(),
3425            ))
3426        }
3427        SessionScope::All => None,
3428    };
3429    match project_dir {
3430        Some(name) => list_entries_sync(&dir.join(&name), None),
3431        None => list_entries_sync(dir, Some(true)),
3432    }
3433}
3434
3435/// Mirror the repo's `absolute_path` normalization for a cwd path: the picker
3436/// runs on the blocking key thread and cannot await the `FileSystem` trait, so
3437/// this is the synchronous equivalent of `OsExecutionEnv::absolute_path`.
3438fn normalize_cwd(cwd: &Path) -> PathBuf {
3439    let absolute = if cwd.is_absolute() {
3440        cwd.to_path_buf()
3441    } else {
3442        std::env::current_dir()
3443            .unwrap_or_else(|_| PathBuf::from("."))
3444            .join(cwd)
3445    };
3446    // Lexical normalization only (`.` / `..` components), no symlink or FS
3447    // access — the repo's normalize_absolute is likewise purely lexical.
3448    let mut out = PathBuf::new();
3449    for component in absolute.components() {
3450        match component {
3451            std::path::Component::CurDir => {}
3452            std::path::Component::ParentDir => {
3453                out.pop();
3454            }
3455            other => out.push(other.as_os_str()),
3456        }
3457    }
3458    out
3459}
3460
3461fn list_entries_sync(dir: &Path, tag_projects: Option<bool>) -> Vec<SessionFileEntry> {
3462    let tag_projects = tag_projects.unwrap_or(false);
3463    let mut files: Vec<(SessionFileEntry, std::time::SystemTime)> = Vec::new();
3464    let mut visit = |path: PathBuf, project: Option<String>| {
3465        if path.extension().and_then(|e| e.to_str()) != Some("jsonl")
3466            || path.to_string_lossy().ends_with(".progress.jsonl")
3467        {
3468            return;
3469        }
3470        let modified = std::fs::metadata(&path)
3471            .and_then(|m| m.modified())
3472            .unwrap_or(std::time::UNIX_EPOCH);
3473        files.push((SessionFileEntry { path, project }, modified));
3474    };
3475    if let Ok(entries) = std::fs::read_dir(dir) {
3476        for entry in entries.flatten() {
3477            let path = entry.path();
3478            if path.is_dir() {
3479                let project = if tag_projects {
3480                    path.file_name()
3481                        .and_then(|name| name.to_str())
3482                        .map(str::to_owned)
3483                } else {
3484                    None
3485                };
3486                if let Ok(inner) = std::fs::read_dir(&path) {
3487                    for child in inner.flatten() {
3488                        visit(child.path(), project.clone());
3489                    }
3490                }
3491            } else {
3492                visit(path, None);
3493            }
3494        }
3495    }
3496    files.sort_by(|a, b| b.1.cmp(&a.1));
3497    files.into_iter().map(|(entry, _)| entry).collect()
3498}
3499
3500/// Pick the session `--continue`/`-c` should open: the newest session that has
3501/// content (a header-only session resumes to an empty transcript). Falls back to
3502/// the newest overall when every session is empty, and `None` only when the
3503/// list is empty.
3504fn first_resumable_session(
3505    metas: &[rpi_harness::session::jsonl::JsonlSessionMetadata],
3506) -> Option<&rpi_harness::session::jsonl::JsonlSessionMetadata> {
3507    metas
3508        .iter()
3509        .find(|meta| !summarize_session_file(Path::new(&meta.path)).empty)
3510        .or_else(|| metas.first())
3511}
3512
3513/// Open a session whose id matches exactly or by file-name containment
3514/// (so `--session 01a02…` / a partial id / a full file name all work). The
3515/// TUI `/session` hot-switch calls this with the selector's item value.
3516pub async fn open_session_by_id(id: &str, cwd: &str) -> Result<Session, OpenError> {
3517    let dir = default_session_dir(Path::new(cwd));
3518    open_session_by_id_in_dir(id, cwd, &dir)
3519        .await
3520        .map(|restored| restored.session)
3521}
3522
3523pub(crate) async fn open_session_by_id_in_dir(
3524    id: &str,
3525    cwd: &str,
3526    dir: &Path,
3527) -> Result<RestoredSession, OpenError> {
3528    let meta = find_session_metadata(id, cwd, dir)
3529        .await
3530        .map_err(|e| OpenError::Other(e.to_string()))?;
3531    let Some(meta) = meta else {
3532        return Err(OpenError::NotFound {
3533            requested: format!("session {id}"),
3534        });
3535    };
3536    open_session(&meta, cwd, dir).await.map_err(|e| {
3537        OpenError::Other(match e {
3538            // `open_session` renders as "Could not open the saved session:
3539            // <reason>" via `BuildError`. Carry the bare reason so it is not
3540            // prefixed twice (once here, once by the CLI/TUI).
3541            BuildError::SessionOpen(reason) => reason,
3542            other => other.to_string(),
3543        })
3544    })
3545}
3546
3547/// Publish the active session's id to plugins, on both channels that carry it.
3548///
3549/// Called on **every** activation of a session — the startup build AND every
3550/// in-process swap (`switch_to_session`, `fork_session`, and the plugin
3551/// `NewSession`/`Fork`/`SwitchSession` runtime actions all route through
3552/// [`set_active_session`]). Two things must stay in step:
3553///
3554/// - `ToolCallContext` — read per plugin **tool** call, which is why a stale
3555///   value there made a plugin's `todo`-style state follow the wrong session.
3556/// - `RPI_SESSION_ID` — read per **turn** by the provider hooks, which is the
3557///   only channel an observer gets for a pure-chat run. Process-global, which is
3558///   exactly the scope of "the session this process is serving".
3559///
3560/// The write overwrites unconditionally, deliberately. An inherited value is not
3561/// an override: `rpi` spawning `rpi` would otherwise hand the child the parent's
3562/// session id, and the child — which is *serving its own* session — would report
3563/// it forever. (Children no longer inherit the variable at all; see
3564/// `rpi_tools::HOST_PRIVATE_ENV`. This overwrite is the second line of defence,
3565/// for any other way a value can arrive pre-set.)
3566///
3567/// An embedder that genuinely wants to pin the id can revert to the old
3568/// behaviour by setting the variable *after* this runs; there is no supported
3569/// way to pin it before, because a session that does not match its own id is
3570/// never what the caller wants.
3571fn publish_session_identity(tool_context: &rpi_extensions::ToolCallContext, id: &str) {
3572    std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, id);
3573    tool_context.set_session_id(id);
3574}
3575
3576/// Swap the session the harness serves, republishing the identity to plugins.
3577///
3578/// The single funnel for an in-process session change. Prefer this over calling
3579/// `AgentHarness::set_session` directly: the harness holds no reference to the
3580/// plugin channels, so a bare `set_session` would leave every plugin reporting
3581/// the session it had before the swap.
3582///
3583/// `tool_context` is optional because not every caller has one (the harness's own
3584/// tests, a headless embedder); the env channel is always published, since the
3585/// provider hooks depend on it.
3586pub(crate) async fn set_active_session(
3587    harness: &AgentHarness,
3588    session: Session,
3589    tool_context: Option<&rpi_extensions::ToolCallContext>,
3590) -> Result<(), String> {
3591    let metadata = session.get_metadata().await.ok();
3592    harness
3593        .set_session(session)
3594        .await
3595        .map_err(|e| e.to_string())?;
3596    if let Some(metadata) = metadata {
3597        std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, &metadata.id);
3598        if let Some(context) = tool_context {
3599            context.set_session_id(metadata.id);
3600        }
3601    }
3602    Ok(())
3603}
3604
3605/// Fork the harness's current session into a new JSONL session (new id, parent
3606/// set to the source) and wrap it in a `Session`. Mirrors the TUI's
3607/// `fork_session` flow (`interactive_tui.rs`) — hoisted here so both the TUI
3608/// and the plugin `runtime_action(Fork)` host share one implementation.
3609/// Returns the new `Session` (NOT yet swapped onto the harness — the caller
3610/// does `harness.set_session(...)`).
3611pub(crate) async fn fork_session_storage(
3612    harness: &AgentHarness,
3613    cwd: &str,
3614    dir: &Path,
3615) -> Result<Session, String> {
3616    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
3617    use rpi_tools::FileSystem;
3618
3619    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3620    let fs: Arc<dyn FileSystem> = env.clone();
3621    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3622        fs,
3623        sessions_root: dir.to_string_lossy().into_owned(),
3624        clock: Arc::new(SystemClock),
3625        ids: Arc::new(DefaultIdGenerator::new()),
3626    });
3627    // The fork needs the rich JSONL metadata (with the on-disk path); resolve
3628    // it from the session list by the current session's id.
3629    let id = harness.session().storage().metadata().id.clone();
3630    let metas = list_session_metadata_in_dir(cwd, dir)
3631        .await
3632        .map_err(|e| e.to_string())?;
3633    let Some(source) = metas.iter().find(|m| m.id == id) else {
3634        return Err(format!("current session {id} not found on disk"));
3635    };
3636    let fork_storage = repo
3637        .fork_typed_with_value_initializer(
3638            source,
3639            &rpi_harness::session::jsonl::JsonlSessionCreateOptions {
3640                id: None,
3641                parent_session_id: Some(source.id.clone()),
3642                cwd: cwd.to_string(),
3643                metadata: None,
3644            },
3645            &rpi_harness::session::types::ForkOptions::default(),
3646            crate::resource_selection::fork_initial_values,
3647        )
3648        .await
3649        .map_err(|e| e.to_string())?;
3650    fork_storage
3651        .acquire_writer_lease()
3652        .await
3653        .map_err(|e| e.to_string())?;
3654    Ok(Session::new(Arc::new(fork_storage), None))
3655}
3656
3657/// Validate a private copy before publishing it in the repo's normal cwd
3658/// directory. Keep the imported identity/history and never overwrite a saved
3659/// session (including when the source is already inside this repository).
3660pub(crate) async fn import_session_file(
3661    source: &Path,
3662    cwd: &str,
3663    dir: &Path,
3664) -> Result<Session, String> {
3665    use rpi_harness::session::jsonl::{
3666        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions, JsonlSessionStorage,
3667    };
3668    use rpi_harness::session::types::SessionStorage;
3669    use rpi_tools::FileSystem;
3670
3671    let dir = if dir.is_absolute() {
3672        dir.to_path_buf()
3673    } else {
3674        Path::new(cwd).join(dir)
3675    };
3676    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
3677    // External writers must be closed. This process deliberately retains locks
3678    // for previously opened sessions, so its own copies additionally verify a
3679    // stable history around the sidecar snapshot (bind/entry before retirement).
3680    let source_progress = PathBuf::from(format!("{}.progress.jsonl", source.display()));
3681    let _source_lock = if source_progress.try_exists().map_err(|e| e.to_string())? {
3682        let lock = std::fs::OpenOptions::new()
3683            .create(true)
3684            .write(true)
3685            .open(format!("{}.lock", source.display()))
3686            .map_err(|e| format!("lock import source: {e}"))?;
3687        fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| {
3688            "close the source session before importing its recovery pair".to_owned()
3689        })?;
3690        Some(lock)
3691    } else {
3692        None
3693    };
3694    let staging = tempfile::tempdir_in(&dir).map_err(|e| e.to_string())?;
3695    let staged = staging.path().join("history.stage");
3696    let staged_progress = PathBuf::from(format!("{}.progress.jsonl", staged.display()));
3697    let mut attempts = 0;
3698    let has_progress = loop {
3699        std::fs::copy(source, &staged).map_err(|e| format!("copy import: {e}"))?;
3700        let copied_history = std::fs::read(&staged).map_err(|e| e.to_string())?;
3701        let has_progress = match std::fs::copy(&source_progress, &staged_progress) {
3702            Ok(_) => true,
3703            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
3704                let _ = std::fs::remove_file(&staged_progress);
3705                false
3706            }
3707            Err(error) => return Err(format!("copy progress import: {error}")),
3708        };
3709        if copied_history == std::fs::read(source).map_err(|e| e.to_string())? {
3710            break has_progress;
3711        }
3712        attempts += 1;
3713        if attempts >= 4 {
3714            return Err(
3715                "source history changed during import; retry when the session is idle".into(),
3716            );
3717        }
3718        tokio::task::yield_now().await;
3719    };
3720    let fs: Arc<dyn FileSystem> = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3721    let validated = JsonlSessionStorage::load(
3722        fs.clone(),
3723        &staged.to_string_lossy(),
3724        Arc::new(SystemClock),
3725        Arc::new(DefaultIdGenerator::new()),
3726    )
3727    .await
3728    .map_err(|e| format!("invalid session import: {e}"))?;
3729    validated
3730        .read_progress("")
3731        .await
3732        .map_err(|e| format!("invalid recovery import: {e}"))?;
3733    let mut metadata = validated.jsonl_metadata().clone();
3734    drop(validated);
3735    let text = std::fs::read_to_string(&staged).map_err(|e| e.to_string())?;
3736    let (first, rest) = text
3737        .split_once('\n')
3738        .ok_or_else(|| "import has no complete header".to_owned())?;
3739    let mut header =
3740        rpi_harness::session::jsonl::codec::parse_header(first).map_err(|e| e.to_string())?;
3741    if has_progress && header.progress_format.is_none() {
3742        return Err("history-only artifact has an undeclared recovery companion".into());
3743    }
3744    // An imported history-only artifact receives the destination's empty store.
3745    // Imports of live-format sessions retain their validated companion instead.
3746    header.progress_format = Some("assistant-progress-v1".into());
3747    std::fs::write(
3748        &staged,
3749        format!(
3750            "{}{}",
3751            rpi_harness::session::jsonl::codec::encode_header(&header),
3752            rest
3753        ),
3754    )
3755    .map_err(|e| e.to_string())?;
3756    if list_session_metadata_in_dir(cwd, &dir)
3757        .await
3758        .map_err(|e| e.to_string())?
3759        .iter()
3760        .any(|saved| saved.id == metadata.id)
3761    {
3762        return Err(format!(
3763            "session {} already exists in {}",
3764            metadata.id,
3765            dir.display()
3766        ));
3767    }
3768    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3769        fs,
3770        sessions_root: dir.to_string_lossy().into_owned(),
3771        clock: Arc::new(SystemClock),
3772        ids: Arc::new(DefaultIdGenerator::new()),
3773    });
3774    // Let the repository validate the id and choose its canonical destination.
3775    let destination = repo
3776        .create_typed(&JsonlSessionCreateOptions {
3777            id: Some(metadata.id.clone()),
3778            parent_session_id: metadata.parent_session_id.clone(),
3779            cwd: cwd.to_string(),
3780            metadata: metadata.metadata.clone(),
3781        })
3782        .await
3783        .map_err(|e| e.to_string())?;
3784    let path = destination.jsonl_metadata().path.clone();
3785    drop(destination);
3786    // Do not claim the session-level `.lock` here. The destination storage
3787    // opened below owns the same OS lease; claiming it first would make this
3788    // process conflict with itself. The JSONL storage lease is the
3789    // authoritative writer fence for the imported session.
3790    let destination_progress = format!("{path}.progress.jsonl");
3791    let publish = (|| -> std::io::Result<()> {
3792        if has_progress {
3793            std::fs::rename(&staged_progress, &destination_progress)?;
3794        }
3795        std::fs::rename(&staged, &path)
3796    })();
3797    if let Err(error) = publish {
3798        let _ = std::fs::remove_file(&path);
3799        let _ = std::fs::remove_file(&destination_progress);
3800        return Err(format!("publish import: {error}"));
3801    }
3802    metadata.path = path;
3803    let storage = repo
3804        .open_by_jsonl_metadata(&metadata)
3805        .await
3806        .map_err(|e| e.to_string())?;
3807    Ok(Session::new(Arc::new(storage), None))
3808}
3809
3810/// A restored session together with the working directory it was created in.
3811///
3812/// The recorded cwd is data for the host's notices, never a silent adoption:
3813/// the launch path adopts the directory in [`app`](crate::app) before any
3814/// resource loads (tools, extensions, system prompt, and trust all key off it),
3815/// and the `/session` hot-switch does not move the running tools at all. Either
3816/// way the user hears about the directory instead of the process quietly
3817/// working somewhere unexpected.
3818pub(crate) struct RestoredSession {
3819    pub session: Session,
3820    /// The directory recorded in the session header, when it still exists.
3821    /// `None` when the record is empty or the path is gone (or is a file).
3822    pub recorded_cwd: Option<PathBuf>,
3823}
3824
3825/// Wrap an opened [`JsonlSessionStorage`] in the `Session` facade (shared by
3826/// startup restore + TUI hot-switch).
3827///
3828/// `sessions_root` is passed in rather than re-derived from `cwd`: after a
3829/// restore adopts the session's directory, `default_session_dir(cwd)` would
3830/// name the ADOPTED project's tree, which is not where this session was found.
3831async fn open_session(
3832    meta: &rpi_harness::session::jsonl::JsonlSessionMetadata,
3833    cwd: &str,
3834    sessions_root: &Path,
3835) -> Result<RestoredSession, BuildError> {
3836    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
3837    use rpi_harness::session::types::SessionStorage;
3838    use rpi_tools::FileSystem;
3839
3840    let dir = sessions_root;
3841    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3842    let fs: Arc<dyn FileSystem> = env.clone();
3843    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3844        fs: fs.clone(),
3845        sessions_root: dir.to_string_lossy().into_owned(),
3846        clock: Arc::new(SystemClock),
3847        ids: Arc::new(DefaultIdGenerator::new()),
3848    });
3849    let storage = repo
3850        .open_by_jsonl_metadata(meta)
3851        .await
3852        .map_err(|e| BuildError::SessionOpen(format!("open {}: {e}", meta.path)))?;
3853    storage
3854        .acquire_writer_lease()
3855        .await
3856        .map_err(|e| BuildError::SessionOpen(format!("lock {}: {e}", meta.path)))?;
3857    // Native saved sessions predating progressFormat remain read-only to plain
3858    // storage loaders. Only this locked, not-yet-shared restore opts into writes.
3859    let storage = storage
3860        .enable_progress_under_exclusive_lock()
3861        .await
3862        .map_err(|e| BuildError::SessionOpen(format!("upgrade {}: {e}", meta.path)))?;
3863    let storage_arc: Arc<dyn SessionStorage> = Arc::new(storage);
3864    Ok(RestoredSession {
3865        session: Session::new(storage_arc, None),
3866        recorded_cwd: crate::session_cwd::resolve_session_cwd(Path::new(&meta.cwd)),
3867    })
3868}
3869
3870/// A fresh ephemeral in-memory session (no persistence). Used for `--no-session`
3871/// and for `/new` inside such a run — an ephemeral launch keeps swapping in
3872/// in-memory sessions, never a JSONL file.
3873pub(crate) fn ephemeral_session() -> Session {
3874    let storage = Arc::new(InMemorySessionStorage::new(
3875        SessionMetadata {
3876            id: "ephemeral".into(),
3877            created_at: 0,
3878            parent_session_id: None,
3879        },
3880        Arc::new(SystemClock),
3881        Arc::new(DefaultIdGenerator::new()),
3882    ));
3883    Session::new(storage, None).with_volatile_progress()
3884}
3885
3886/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
3887///
3888/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
3889/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
3890/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
3891/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
3892///
3893/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
3894/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
3895/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
3896pub(crate) async fn create_jsonl_session(dir: &Path, cwd: &str) -> Result<Session, String> {
3897    create_jsonl_session_with_id(dir, cwd, None).await
3898}
3899
3900/// `create_jsonl_session` with an explicit id (the `--session-id` fixed-id
3901/// contract: the file is named with the given id so later `--session-id`
3902/// launches restore the same session).
3903pub(crate) async fn create_jsonl_session_with_id(
3904    dir: &Path,
3905    cwd: &str,
3906    id: Option<String>,
3907) -> Result<Session, String> {
3908    use rpi_harness::session::jsonl::{
3909        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
3910    };
3911    use rpi_tools::FileSystem;
3912
3913    // A dedicated OS env for session-file I/O, rooted at the cwd so the repo's
3914    // relative-path resolution matches the tool env.
3915    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3916    let fs: Arc<dyn FileSystem> = env.clone();
3917
3918    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3919        fs: fs.clone(),
3920        sessions_root: dir.to_string_lossy().into_owned(),
3921        clock: Arc::new(SystemClock),
3922        ids: Arc::new(DefaultIdGenerator::new()),
3923    });
3924
3925    let opts = JsonlSessionCreateOptions {
3926        id, // fresh uuidv7 when None (--session-id passes the fixed id)
3927        parent_session_id: None,
3928        cwd: cwd.to_string(),
3929        metadata: None,
3930    };
3931    let storage = repo
3932        .create_typed(&opts)
3933        .await
3934        .map_err(|e| format!("create session: {e}"))?;
3935    // `JsonlSessionStorage` acquires the storage-level lease during create;
3936    // wrap it in the facade without a second CLI-owned lock table.
3937    let storage_arc: Arc<dyn rpi_harness::session::types::SessionStorage> = Arc::new(storage);
3938    Ok(Session::new(storage_arc, None))
3939}
3940
3941/// Read an `--append-system-prompt` target: if it's a readable file path, return
3942/// its contents; otherwise return `None` and let the caller use the literal.
3943fn read_append_target(target: &str, sources: &mut Vec<String>) -> Option<String> {
3944    let path = Path::new(target);
3945    if path.is_file() {
3946        read_prompt_source(path, sources)
3947    } else {
3948        None
3949    }
3950}
3951
3952/// Record provenance at the successful read, rather than rediscovering files
3953/// during rendering (which could report a shadowed or unreadable file).
3954fn read_prompt_source(path: &Path, sources: &mut Vec<String>) -> Option<String> {
3955    let text = std::fs::read_to_string(path).ok()?;
3956    let absolute = if path.is_absolute() {
3957        path.to_path_buf()
3958    } else {
3959        std::env::current_dir()
3960            .map(|cwd| cwd.join(path))
3961            .unwrap_or_else(|_| path.to_path_buf())
3962    };
3963    let source = absolute.to_string_lossy().into_owned();
3964    if !sources.contains(&source) {
3965        sources.push(source);
3966    }
3967    Some(text)
3968}
3969
3970#[cfg(test)]
3971mod goal_outbox_smoke_tests;
3972#[cfg(test)]
3973mod runtime_session_tests;
3974
3975#[cfg(test)]
3976mod tests {
3977    use super::*;
3978
3979    #[test]
3980    fn settlement_bridge_follows_reload_and_releases_its_session_with_the_bus() {
3981        use rpi_harness::events::{HarnessEvent, HarnessEventBus, RunEndEvent, RunEndOutcome};
3982        use std::sync::atomic::{AtomicUsize, Ordering};
3983        static OLD: AtomicUsize = AtomicUsize::new(0);
3984        static NEW: AtomicUsize = AtomicUsize::new(0);
3985        extern "C" fn old(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
3986            OLD.fetch_add(1, Ordering::SeqCst);
3987            0
3988        }
3989        extern "C" fn new(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
3990            NEW.fetch_add(1, Ordering::SeqCst);
3991            0
3992        }
3993        let make = |handler: rpi_plugin_sdk::EventHandlerFn| {
3994            let mut registry = rpi_extensions::ExtensionRegistry::new();
3995            registry.register_event_handler(
3996                "settlement".into(),
3997                rpi_plugin_sdk::EventTag::AgentSettled,
3998                handler,
3999                std::ptr::null_mut(),
4000            );
4001            ExtensionSession::from_parts(
4002                Arc::new(registry.snapshot()),
4003                rpi_extensions::PluginKeepalive::empty(),
4004                vec![],
4005                None,
4006            )
4007        };
4008        let sessions = Arc::new(Mutex::new(make(old)));
4009        let weak = Arc::downgrade(&sessions);
4010        let bus = HarnessEventBus::new();
4011        install_extension_settlement_bridge(&bus, sessions.clone());
4012        let ended = |outcome| {
4013            HarnessEvent::RunEnd(RunEndEvent {
4014                lane: "main".into(),
4015                run_id: "run".into(),
4016                outcome,
4017                leaf_id: "leaf".into(),
4018            })
4019        };
4020        bus.emit(&ended(RunEndOutcome::Completed));
4021        assert_eq!(OLD.load(Ordering::SeqCst), 1);
4022        *sessions.lock().unwrap() = make(new);
4023        for outcome in [RunEndOutcome::Aborted, RunEndOutcome::Failed] {
4024            bus.emit(&ended(outcome));
4025        }
4026        assert_eq!(OLD.load(Ordering::SeqCst), 1);
4027        assert_eq!(NEW.load(Ordering::SeqCst), 2);
4028        drop(sessions);
4029        assert!(weak.upgrade().is_some());
4030        drop(bus);
4031        assert!(
4032            weak.upgrade().is_none(),
4033            "settlement observer must not create an ownership cycle"
4034        );
4035    }
4036
4037    #[tokio::test]
4038    async fn unauthenticated_packages_are_not_reintroduced_as_legacy_adapters() {
4039        extern "C" fn request(
4040            _: rpi_plugin_sdk::StbStringRef,
4041            _: *mut rpi_plugin_sdk::StbString,
4042            _: *mut std::ffi::c_void,
4043        ) -> i32 {
4044            1
4045        }
4046        let mut registry = rpi_extensions::ExtensionRegistry::new();
4047        for id in ["package", "legacy"] {
4048            registry.register_provider(rpi_extensions::RegisteredProvider {
4049                provider_id: id.into(),
4050                base_url: "http://localhost".into(),
4051                api_style: "openai-completions".into(),
4052                request_fn: request,
4053                stream_fn: None,
4054                plugin_free_string: rpi_plugin_sdk::callbacks::free_string,
4055                user_data: std::ptr::null_mut(),
4056            });
4057        }
4058        assert!(registry.apply_declaration_json(&serde_json::json!({"providers":[{
4059            "id":"package", "requiresAuth":true,
4060            "models":[rpi_ai::Model::new("model", "Model", rpi_ai::Api::OpenaiCompletions, "package", "http://localhost")]
4061        }]}).to_string()));
4062        let session = ExtensionSession::from_parts(
4063            Arc::new(registry.snapshot()),
4064            rpi_extensions::PluginKeepalive::empty(),
4065            vec![],
4066            None,
4067        );
4068        let providers = build_models_with_extensions_for_reload(
4069            &[],
4070            &session,
4071            tokio::runtime::Handle::current(),
4072        );
4073        assert_eq!(
4074            providers
4075                .iter()
4076                .map(|provider| provider.id())
4077                .collect::<Vec<_>>(),
4078            ["legacy"]
4079        );
4080    }
4081    use crate::args::Args;
4082
4083    #[test]
4084    fn loaded_context_paths_track_precedence_and_reload() {
4085        const CHILD: &str = "RPI_CONTEXT_PATHS_REGRESSION_CHILD";
4086        if std::env::var_os(CHILD).is_none() {
4087            let dir = tempfile::tempdir().unwrap();
4088            let output = std::process::Command::new(std::env::current_exe().unwrap())
4089                .args([
4090                    "--exact",
4091                    "session::tests::loaded_context_paths_track_precedence_and_reload",
4092                    "--nocapture",
4093                ])
4094                .env(CHILD, "1")
4095                .env(crate::config::CONFIG_DIR_ENV, dir.path())
4096                .output()
4097                .unwrap();
4098            assert!(
4099                output.status.success(),
4100                "{}\n{}",
4101                String::from_utf8_lossy(&output.stdout),
4102                String::from_utf8_lossy(&output.stderr)
4103            );
4104            return;
4105        }
4106        tokio::runtime::Builder::new_current_thread()
4107            .enable_all()
4108            .build()
4109            .unwrap()
4110            .block_on(async {
4111                let agent = crate::config::agent_dir().unwrap();
4112                let cwd = agent.join("project");
4113                let project_config = cwd.join(".rpi");
4114                std::fs::create_dir_all(&project_config).unwrap();
4115                for (path, content) in [
4116                    (agent.join("SYSTEM.md"), "GLOBAL_BASE"),
4117                    (agent.join("APPEND_SYSTEM.md"), "GLOBAL_APPEND"),
4118                    (agent.join("AGENTS.md"), "GLOBAL_INSTRUCTIONS"),
4119                    (project_config.join("SYSTEM.md"), "PROJECT_BASE"),
4120                    (project_config.join("APPEND_SYSTEM.md"), "PROJECT_APPEND"),
4121                    (cwd.join("AGENTS.md"), "PROJECT_INSTRUCTIONS"),
4122                    (cwd.join("CLAUDE.md"), "SHADOWED_CLAUDE"),
4123                ] {
4124                    std::fs::write(path, content).unwrap();
4125                }
4126                let resolved = crate::provider::resolve(
4127                    Some("anthropic"),
4128                    Some(crate::provider::DEFAULT_MODEL_ID),
4129                    None,
4130                    Some("test-key"),
4131                    None,
4132                )
4133                .unwrap();
4134                let args = Args {
4135                    no_session: true,
4136                    no_extensions: true,
4137                    no_skills: true,
4138                    no_prompt_templates: true,
4139                    trust_override: Some(true),
4140                    ..Default::default()
4141                };
4142                let (harness, _events, mut context) =
4143                    build(&resolved, &args, &cwd, true).await.unwrap();
4144                let resources = harness.get_resources().await.unwrap();
4145                let path = |p: PathBuf| p.to_string_lossy().into_owned();
4146                assert_eq!(
4147                    &resources.context_files[..2],
4148                    &[
4149                        path(project_config.join("SYSTEM.md")),
4150                        path(project_config.join("APPEND_SYSTEM.md")),
4151                    ]
4152                );
4153                assert!(resources
4154                    .context_files
4155                    .contains(&path(agent.join("AGENTS.md"))));
4156                assert!(resources
4157                    .context_files
4158                    .contains(&path(cwd.join("AGENTS.md"))));
4159                assert!(!resources
4160                    .context_files
4161                    .contains(&path(cwd.join("CLAUDE.md"))));
4162                assert!(!resources
4163                    .context_files
4164                    .contains(&path(agent.join("SYSTEM.md"))));
4165                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
4166                assert!(prompt.contains("PROJECT_BASE") && prompt.contains("PROJECT_APPEND"));
4167                assert!(!prompt.contains("GLOBAL_BASE") && !prompt.contains("SHADOWED_CLAUDE"));
4168
4169                // Removing the selected project files makes reload fall back to
4170                // globals; removed instruction paths must disappear as well.
4171                std::fs::remove_file(project_config.join("SYSTEM.md")).unwrap();
4172                std::fs::remove_file(project_config.join("APPEND_SYSTEM.md")).unwrap();
4173                std::fs::remove_file(cwd.join("AGENTS.md")).unwrap();
4174                assert!(
4175                    !reload_extension_resources(&harness, &context)
4176                        .await
4177                        .had_errors
4178                );
4179                let resources = harness.get_resources().await.unwrap();
4180                assert_eq!(
4181                    &resources.context_files[..2],
4182                    &[
4183                        path(agent.join("SYSTEM.md")),
4184                        path(agent.join("APPEND_SYSTEM.md")),
4185                    ]
4186                );
4187                assert!(resources
4188                    .context_files
4189                    .contains(&path(cwd.join("CLAUDE.md"))));
4190                assert!(!resources
4191                    .context_files
4192                    .contains(&path(project_config.join("SYSTEM.md"))));
4193
4194                // Explicit append files are listed; literal text and overridden
4195                // discovered base/append files are not invented as file sources.
4196                let explicit = agent.join("custom-append.md");
4197                std::fs::write(&explicit, "EXPLICIT_APPEND").unwrap();
4198                context.args.system_prompt = Some("EXPLICIT_BASE".into());
4199                context.args.append_system_prompt =
4200                    vec![path(explicit.clone()), "literal append".into()];
4201                context.args.no_context_files = true;
4202                assert!(
4203                    !reload_extension_resources(&harness, &context)
4204                        .await
4205                        .had_errors
4206                );
4207                assert_eq!(
4208                    harness.get_resources().await.unwrap().context_files,
4209                    vec![path(explicit)]
4210                );
4211
4212                // The reload must honor the startup opt-out from project context.
4213                context.args.system_prompt = None;
4214                context.args.append_system_prompt.clear();
4215                context.args.no_context_files = false;
4216                context.args.trust_override = Some(false);
4217                assert!(
4218                    !reload_extension_resources(&harness, &context)
4219                        .await
4220                        .had_errors
4221                );
4222                assert!(harness
4223                    .get_resources()
4224                    .await
4225                    .unwrap()
4226                    .context_files
4227                    .is_empty());
4228                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
4229                assert!(
4230                    !prompt.contains("SHADOWED_CLAUDE") && !prompt.contains("GLOBAL_INSTRUCTIONS")
4231                );
4232            });
4233    }
4234
4235    #[test]
4236    fn prompt_source_read_failures_and_literals_do_not_create_file_provenance() {
4237        let dir = tempfile::tempdir().unwrap();
4238        let file = dir.path().join("SYSTEM.md");
4239        let mut sources = Vec::new();
4240        assert!(read_prompt_source(&file, &mut sources).is_none());
4241        std::fs::write(&file, [0xff, 0xfe]).unwrap();
4242        assert!(read_prompt_source(&file, &mut sources).is_none());
4243        assert!(read_append_target("literal instructions", &mut sources).is_none());
4244        assert!(sources.is_empty());
4245        std::fs::write(&file, "loaded instructions").unwrap();
4246        assert_eq!(
4247            read_prompt_source(&file, &mut sources).as_deref(),
4248            Some("loaded instructions")
4249        );
4250        assert!(read_prompt_source(&file, &mut sources).is_some());
4251        assert_eq!(sources, vec![file.to_string_lossy().into_owned()]);
4252    }
4253
4254    extern "C" fn deny_test_tool_call(
4255        _event: rpi_plugin_sdk::StablePluginEvent,
4256        _data: *mut std::ffi::c_void,
4257    ) -> i32 {
4258        rpi_plugin_sdk::EVENT_HANDLER_ABORT
4259    }
4260
4261    async fn invoke_test_tool_hook(
4262        hook: &rpi_agent::BeforeToolCall,
4263    ) -> Option<rpi_agent::BeforeToolCallResult> {
4264        let message = rpi_ai::providers::faux::faux_assistant_message(
4265            "approval",
4266            rpi_ai::types::StopReason::ToolUse,
4267        );
4268        let rpi_ai::types::Content::ToolCall(call) =
4269            rpi_ai::types::Content::tool_call("call", "read", serde_json::json!({"path":"x"}))
4270        else {
4271            unreachable!()
4272        };
4273        hook(
4274            rpi_agent::BeforeToolCallContext {
4275                assistant_message: &message,
4276                tool_call: &call,
4277                args: &call.arguments,
4278                context: &rpi_agent::AgentContext::default(),
4279            },
4280            tokio_util::sync::CancellationToken::new(),
4281        )
4282        .await
4283    }
4284
4285    #[tokio::test]
4286    async fn tool_call_hook_uses_reloaded_session_and_newly_discovered_gate() {
4287        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
4288        let hook =
4289            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
4290        assert!(invoke_test_tool_hook(&hook).await.is_none());
4291        for name in ["first-gate", "reloaded-gate"] {
4292            let mut registry = rpi_extensions::ExtensionRegistry::new();
4293            registry.register_event_handler(
4294                name.into(),
4295                rpi_plugin_sdk::EventTag::ToolCall,
4296                deny_test_tool_call,
4297                std::ptr::null_mut(),
4298            );
4299            let fresh = ExtensionSession::from_parts(
4300                Arc::new(registry.snapshot()),
4301                rpi_extensions::PluginKeepalive::empty(),
4302                Vec::new(),
4303                None,
4304            );
4305            {
4306                let mut current = sessions.lock().unwrap();
4307                if let Some(snapshot) = current.snapshot() {
4308                    snapshot.active_flag().store(false, Ordering::SeqCst);
4309                }
4310                *current = fresh;
4311            }
4312            let result = invoke_test_tool_hook(&hook).await.unwrap();
4313            assert!(result.block);
4314            assert!(result.reason.unwrap().contains(name));
4315        }
4316        *sessions.lock().unwrap() = ExtensionSession::none();
4317        assert!(invoke_test_tool_hook(&hook).await.is_none());
4318    }
4319
4320    /// A unique scratch file for one summary test.
4321    fn scratch(name: &str) -> PathBuf {
4322        let nanos = std::time::SystemTime::now()
4323            .duration_since(std::time::UNIX_EPOCH)
4324            .unwrap()
4325            .as_nanos();
4326        let path = std::env::temp_dir().join(format!(
4327            "rpi-summary-{}-{nanos}-{name}.jsonl",
4328            std::process::id()
4329        ));
4330        path
4331    }
4332
4333    #[test]
4334    fn summary_marks_a_header_only_session_empty() {
4335        let path = scratch("empty");
4336        std::fs::write(
4337            &path,
4338            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4339        )
4340        .unwrap();
4341        let summary = summarize_session_file(&path);
4342        assert!(summary.empty, "a header-only file has nothing to resume");
4343        assert!(summary.preview.is_none());
4344        assert_eq!(summary.bytes, std::fs::metadata(&path).unwrap().len());
4345        std::fs::remove_file(&path).ok();
4346    }
4347
4348    #[test]
4349    fn summary_reads_the_first_user_prompt_and_name() {
4350        let path = scratch("content");
4351        let body = concat!(
4352            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4353            "{\"kind\":\"fact\",\"seq\":1,\"fact\":\"name\",\"name\":\"fix resume picker\"}\n",
4354            "{\"kind\":\"record\",\"type\":\"operation_started\",\"id\":\"r1\"}\n",
4355            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"kind\":\"user\",\"role\":\"user\",\"content\":\"read the rpi -r picker\"}}\n",
4356            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e2\",\"message\":{\"kind\":\"assistant\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
4357        );
4358        std::fs::write(&path, body).unwrap();
4359        let summary = summarize_session_file(&path);
4360        assert!(!summary.empty);
4361        assert_eq!(summary.name.as_deref(), Some("fix resume picker"));
4362        assert_eq!(summary.preview.as_deref(), Some("read the rpi -r picker"));
4363        std::fs::remove_file(&path).ok();
4364    }
4365
4366    #[test]
4367    fn summary_extracts_a_block_style_user_prompt() {
4368        let path = scratch("blocks");
4369        let body = concat!(
4370            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4371            "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"line one\\nline two\"}]}}\n",
4372        );
4373        std::fs::write(&path, body).unwrap();
4374        let summary = summarize_session_file(&path);
4375        assert_eq!(summary.preview.as_deref(), Some("line one line two"));
4376        assert_eq!(session_display_label(&summary), "line one line two");
4377        std::fs::remove_file(&path).ok();
4378    }
4379
4380    fn meta_for(path: &Path, id: &str) -> rpi_harness::session::jsonl::JsonlSessionMetadata {
4381        rpi_harness::session::jsonl::JsonlSessionMetadata {
4382            id: id.to_string(),
4383            created_at: 0,
4384            cwd: ".".to_string(),
4385            path: path.to_string_lossy().into_owned(),
4386            modified_at: 0,
4387            source_format: rpi_harness::session::jsonl::JsonlSourceFormat::V4,
4388            parent_session_id: None,
4389            legacy_parent_session_path: None,
4390            metadata: None,
4391        }
4392    }
4393
4394    #[test]
4395    fn continue_skips_newer_empty_sessions() {
4396        let empty = scratch("newest-empty");
4397        std::fs::write(
4398            &empty,
4399            "{\"kind\":\"header\",\"version\":4,\"id\":\"empty\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4400        )
4401        .unwrap();
4402        let content = scratch("older-content");
4403        std::fs::write(
4404            &content,
4405            concat!(
4406                "{\"kind\":\"header\",\"version\":4,\"id\":\"old\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4407                "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n",
4408            ),
4409        )
4410        .unwrap();
4411
4412        let metas = vec![meta_for(&empty, "empty"), meta_for(&content, "old")];
4413        let picked = first_resumable_session(&metas).expect("a resumable session");
4414        assert_eq!(picked.id, "old");
4415
4416        // When every session is empty, fall back to the newest rather than
4417        // erroring.
4418        let all_empty = vec![meta_for(&empty, "empty")];
4419        assert_eq!(first_resumable_session(&all_empty).unwrap().id, "empty");
4420
4421        std::fs::remove_file(&empty).ok();
4422        std::fs::remove_file(&content).ok();
4423    }
4424
4425    #[tokio::test]
4426    async fn import_preserves_validates_and_locks_the_recovery_pair() {
4427        use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
4428        use rpi_harness::session::types::{
4429            AssistantFrameOp, AssistantFrameRecord, RecordBase, SessionStorage,
4430        };
4431        let tmp = tempfile::tempdir().unwrap();
4432        let source = tmp.path().join("source.jsonl");
4433        let progress = tmp.path().join("source.jsonl.progress.jsonl");
4434        let fs: Arc<dyn rpi_tools::FileSystem> =
4435            Arc::new(OsExecutionEnv::with_cwd(tmp.path().into()));
4436        let storage = JsonlSessionStorage::create(
4437            fs,
4438            &source.to_string_lossy(),
4439            JsonlV4Header::new("import-pair".into(), 1, "/".into(), None, None, None),
4440            Arc::new(SystemClock),
4441            Arc::new(DefaultIdGenerator::new()),
4442        )
4443        .await
4444        .unwrap();
4445        storage
4446            .append_progress(vec![AssistantFrameRecord {
4447                base: RecordBase {
4448                    id: "accepted-prefix".into(),
4449                    seq: 0,
4450                    lane: "main".into(),
4451                    timestamp: 0,
4452                },
4453                run_id: "run".into(),
4454                stream_index: 0,
4455                op: AssistantFrameOp::Append,
4456                frame: Some(serde_json::json!({"payload":"keep"})),
4457            }])
4458            .await
4459            .unwrap();
4460        drop(storage);
4461        let original = std::fs::read(&progress).unwrap();
4462        let destination = tmp.path().join("imported");
4463        let imported = import_session_file(&source, &tmp.path().to_string_lossy(), &destination)
4464            .await
4465            .unwrap();
4466        assert_eq!(
4467            imported.read_progress("run").await.unwrap()[0].base.id,
4468            "accepted-prefix"
4469        );
4470        assert_eq!(
4471            std::fs::read(&progress).unwrap(),
4472            original,
4473            "import must not repair or mutate its source"
4474        );
4475        let lock = std::fs::OpenOptions::new()
4476            .create(true)
4477            .write(true)
4478            .open(tmp.path().join("source.jsonl.lock"))
4479            .unwrap();
4480        fs2::FileExt::try_lock_exclusive(&lock).unwrap();
4481        assert!(import_session_file(
4482            &source,
4483            &tmp.path().to_string_lossy(),
4484            &tmp.path().join("busy")
4485        )
4486        .await
4487        .is_err());
4488        drop(lock);
4489        let mut corrupt = String::from_utf8(original.clone()).unwrap();
4490        corrupt = corrupt.replace(
4491            "\"session_id\":\"import-pair\"",
4492            "\"session_id\":\"foreign\"",
4493        );
4494        assert_ne!(corrupt.as_bytes(), original.as_slice());
4495        std::fs::write(&progress, corrupt).unwrap();
4496        assert!(import_session_file(
4497            &source,
4498            &tmp.path().to_string_lossy(),
4499            &tmp.path().join("foreign")
4500        )
4501        .await
4502        .is_err());
4503        std::fs::remove_file(&progress).unwrap();
4504        assert!(import_session_file(
4505            &source,
4506            &tmp.path().to_string_lossy(),
4507            &tmp.path().join("missing")
4508        )
4509        .await
4510        .is_err());
4511    }
4512
4513    #[test]
4514    fn list_session_files_sync_walks_the_cwd_subdirectory() {
4515        let root = std::env::temp_dir().join(format!("rpi-summary-{}-dir", std::process::id()));
4516        let nested = root.join("--proj--");
4517        std::fs::create_dir_all(&nested).unwrap();
4518        let file = nested.join("2026-01-01_a.jsonl");
4519        std::fs::write(&file, "{}\n").unwrap();
4520        let sidecar = nested.join("2026-01-01_a.jsonl.progress.jsonl");
4521        std::fs::write(&sidecar, "{}\n").unwrap();
4522        let found = list_session_files_sync(&root);
4523        assert!(found.iter().any(|p| p == &file));
4524        assert!(!found.contains(&sidecar));
4525        std::fs::remove_dir_all(&root).ok();
4526    }
4527
4528    /// Regression for fork issue #13: with a shared session root, the default
4529    /// picker scope must show only this project's sessions, and All must show
4530    /// every project with its directory tag so a flat list stays traceable.
4531    #[test]
4532    fn review_issue13_default_scope_is_this_project_and_all_is_tagged() {
4533        let tmp = tempfile::tempdir().unwrap();
4534        let root = tmp.path().join("sessions");
4535        let cwd = tmp.path().join("project");
4536        let own = root.join(rpi_harness::session::jsonl::jsonl_session_directory_name(
4537            &cwd.to_string_lossy(),
4538        ));
4539        let foreign = root.join("--some-other-project--");
4540        std::fs::create_dir_all(&own).unwrap();
4541        std::fs::create_dir_all(&foreign).unwrap();
4542        let own_file = own.join("2026-01-01_own.jsonl");
4543        let foreign_file = foreign.join("2026-01-02_foreign.jsonl");
4544        std::fs::write(&own_file, "{}\n").unwrap();
4545        std::fs::write(&foreign_file, "{}\n").unwrap();
4546        // A legacy file directly under the root is not a project subdirectory.
4547        let legacy = root.join("2026-01-03_legacy.jsonl");
4548        std::fs::write(&legacy, "{}\n").unwrap();
4549
4550        let project = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
4551        assert_eq!(project.len(), 1, "default scope must not flatten projects");
4552        assert_eq!(project[0].path, own_file);
4553        assert_eq!(project[0].project, None);
4554
4555        let all = list_session_files_in_scope_sync(&cwd, &root, SessionScope::All);
4556        assert_eq!(all.len(), 3);
4557        let own_project = own.file_name().unwrap().to_str().unwrap();
4558        assert!(all
4559            .iter()
4560            .any(|e| e.path == own_file && e.project.as_deref() == Some(own_project)));
4561        assert!(all
4562            .iter()
4563            .any(|e| e.path == foreign_file
4564                && e.project.as_deref() == Some("--some-other-project--")));
4565        assert!(all.iter().any(|e| e.path == legacy && e.project.is_none()));
4566
4567        assert_eq!(SessionScope::Project.toggled(), SessionScope::All);
4568        assert_eq!(SessionScope::All.toggled(), SessionScope::Project);
4569        assert_eq!(SessionScope::default(), SessionScope::Project);
4570    }
4571
4572    /// The project directory name must be the repo's own encoding, not a
4573    /// re-derivation that drifts from create/open. A relative cwd resolves
4574    /// against the process cwd the same way `OsExecutionEnv::absolute_path` does.
4575    #[test]
4576    fn review_issue13_project_scope_uses_the_repo_directory_encoding() {
4577        let tmp = tempfile::tempdir().unwrap();
4578        let root = tmp.path().join("sessions");
4579        let cwd = tmp.path().join("project");
4580        let name =
4581            rpi_harness::session::jsonl::jsonl_session_directory_name(&cwd.to_string_lossy());
4582        std::fs::create_dir_all(root.join(&name)).unwrap();
4583        let file = root.join(&name).join("a.jsonl");
4584        std::fs::write(&file, "{}\n").unwrap();
4585        // A look-alike directory that a naive "last path component" derivation
4586        // would pick instead. The repo encodes the *full* cwd, so this must not
4587        // be listed by the Project scope.
4588        let lookalike = root.join("--project--");
4589        std::fs::create_dir_all(&lookalike).unwrap();
4590        let other_file = lookalike.join("b.jsonl");
4591        std::fs::write(&other_file, "{}\n").unwrap();
4592        let found = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
4593        assert_eq!(
4594            found,
4595            vec![SessionFileEntry {
4596                path: file,
4597                project: None
4598            }]
4599        );
4600    }
4601
4602    /// Fork issue #13, async path: the `-r` picker's default scope must use the
4603    /// repo's typed list API with an explicit cwd, and the open path must stay
4604    /// unscoped so a row chosen from All still resolves by id.
4605    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4606    async fn review_issue13_resume_scope_and_open_path_agree() {
4607        let tmp = tempfile::tempdir().unwrap();
4608        let root = tmp.path().join("sessions");
4609        let cwd = tmp.path().join("project");
4610        std::fs::create_dir_all(&cwd).unwrap();
4611        let foreign_cwd = tmp.path().join("other");
4612        std::fs::create_dir_all(&foreign_cwd).unwrap();
4613        let cwd_text = cwd.to_string_lossy().into_owned();
4614        let own = create_jsonl_session(&root, &cwd_text).await.unwrap();
4615        let own_id = own.storage().metadata().id.clone();
4616        drop(own);
4617        let foreign = create_jsonl_session(&root, &foreign_cwd.to_string_lossy())
4618            .await
4619            .unwrap();
4620        let foreign_id = foreign.storage().metadata().id.clone();
4621        drop(foreign);
4622
4623        let project =
4624            list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::Project)
4625                .await
4626                .unwrap();
4627        assert_eq!(project.len(), 1, "-r default must not flatten projects");
4628        assert_eq!(project[0].id, own_id);
4629        let all = list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::All)
4630            .await
4631            .unwrap();
4632        assert_eq!(all.len(), 2);
4633        assert!(all.iter().any(|m| m.cwd == foreign_cwd.to_string_lossy()));
4634        // `list_session_metadata_in_dir` (the open path) must remain unscoped.
4635        let open = list_session_metadata_in_dir(&cwd_text, &root)
4636            .await
4637            .unwrap();
4638        assert_eq!(open.len(), 2);
4639        let found = find_session_metadata(&foreign_id, &cwd_text, &root)
4640            .await
4641            .unwrap();
4642        assert_eq!(found.unwrap().id, foreign_id);
4643    }
4644
4645    /// The default CLI tool set plus the `todo` tool its bundled plugins add.
4646    fn default_prompt_tools() -> Vec<String> {
4647        BUILTIN_TOOL_NAMES
4648            .iter()
4649            .copied()
4650            .chain(["todo"])
4651            .map(str::to_owned)
4652            .collect()
4653    }
4654
4655    #[test]
4656    fn default_prompt_lists_only_the_active_tools() {
4657        let tools = ["read", "grep", "find", "ls"].map(str::to_owned);
4658        let p = default_system_prompt_with_tools("/tmp/proj", true, &tools);
4659        assert!(p.contains("- read  — Read file contents"));
4660        assert!(p.contains("- grep  — Search file contents"));
4661        for absent in ["- edit", "- write", "- bash", "- docs", "todo", "Windows"] {
4662            assert!(
4663                !p.contains(absent),
4664                "{absent} must not appear for a read-only run: {p}"
4665            );
4666        }
4667        assert!(p.contains("Re-stating the same plan without acting on it is a bug"));
4668        let none = default_system_prompt_with_tools("/tmp/proj", false, &[]);
4669        assert!(none.contains("Available tools:\n(none)"));
4670    }
4671
4672    #[test]
4673    fn default_prompt_mentions_cwd_and_tools() {
4674        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
4675        assert!(p.contains("/tmp/proj"));
4676        assert!(p.contains("read"));
4677        assert!(p.contains("bash"));
4678        assert!(p.contains("edit"));
4679        assert!(p.contains("write"));
4680        assert!(p.contains("docs"));
4681        assert!(!p.contains("- grep"));
4682        assert!(!p.contains("- find"));
4683        assert!(!p.contains("- ls"));
4684        assert!(!p.contains("- powershell"));
4685        assert!(p.contains("Bash/POSIX syntax, also on Windows"));
4686    }
4687
4688    #[test]
4689    fn default_prompt_instructs_language_matching() {
4690        // A Chinese (or any non-English) user gets a same-language reply
4691        // without having to ask every turn.
4692        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
4693        assert!(
4694            p.contains("same language as the user's latest message"),
4695            "the prompt must tell the model to mirror the user's language: {p}"
4696        );
4697    }
4698
4699    #[test]
4700    fn default_prompt_keeps_working_state_in_the_visible_channel() {
4701        // Regression guard for the re-plan loop: on openai-compatible providers
4702        // the assistant's `thinking` blocks are dropped when the next request is
4703        // built (`providers/openai_completions.rs`: `Content::text_only`), so a
4704        // plan that lives only in reasoning is re-derived every turn. One
4705        // observed session paid for that 112 times in a single run, and twice
4706        // hallucinated the user's input ("The user is greeting me with hello",
4707        // with no such message). See `docs/llm-repetition-forensics.md` §八.
4708        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
4709        let lower = p.to_lowercase();
4710        // The rule must state the mechanism, not just "be clear".
4711        assert!(
4712            lower.contains("reasoning is not") && lower.contains("carried into your next turn"),
4713            "the prompt must explain that reasoning does not survive the turn: {p}"
4714        );
4715        // Working state stays visible; extension-specific rules require opt-in.
4716        assert!(
4717            lower.contains("visible") && !lower.contains("todo tool"),
4718            "the prompt must keep state visible without inventing extension rules: {p}"
4719        );
4720        // …plus the anti-repetition rule itself.
4721        assert!(
4722            lower.contains("re-stating the same plan"),
4723            "the prompt must call out plan re-statement as a bug: {p}"
4724        );
4725        // And the guidance must not instruct re-reading what is already shown.
4726        assert!(
4727            lower.contains("already shown earlier"),
4728            "the prompt must discourage re-fetching known content: {p}"
4729        );
4730    }
4731
4732    #[test]
4733    fn default_prompt_does_not_claim_reasoning_is_lost_when_it_is_replayed() {
4734        // `compat.requiresThinkingAsText` (and the native thinking channels of
4735        // anthropic-messages / openai-responses) DO carry the model's reasoning
4736        // back on the next request. Telling such a model "reasoning is not
4737        // carried into your next turn" is false, and the instruction to restate
4738        // the plan every turn is exactly the busy-work the re-plan analysis
4739        // measured. The wording must flip with the mechanism.
4740        let p = default_system_prompt_with_tools("/tmp/proj", true, &default_prompt_tools());
4741        let lower = p.to_lowercase();
4742        assert!(
4743            lower.contains("carried back"),
4744            "a replaying model must be told its reasoning survives: {p}"
4745        );
4746        assert!(
4747            !lower.contains("reasoning is not"),
4748            "the replayed variant must not claim reasoning is dropped: {p}"
4749        );
4750        assert!(
4751            lower.contains("do not re-derive"),
4752            "the replayed variant must forbid re-deriving the plan: {p}"
4753        );
4754        assert!(
4755            lower.contains("do not re-derive") && lower.contains("re-stating the same plan"),
4756            "the anti-repetition rule must survive the flip: {p}"
4757        );
4758        assert!(
4759            lower.contains("already shown earlier"),
4760            "the re-read rule must survive the flip: {p}"
4761        );
4762    }
4763
4764    #[test]
4765    fn default_prompt_states_each_rule_once() {
4766        // The plan rule, the todo tool and the anti-repetition line used to be
4767        // spread over two guidelines that repeated each other.
4768        for replayed in [false, true] {
4769            let p =
4770                default_system_prompt_with_tools("/tmp/proj", replayed, &default_prompt_tools());
4771            for phrase in ["the same plan", "Windows", "guessing"] {
4772                assert_eq!(p.matches(phrase).count(), 1, "{phrase:?} repeated: {p}");
4773            }
4774            assert!(
4775                !p.contains("todo tool"),
4776                "extension rules require explicit metadata"
4777            );
4778        }
4779    }
4780
4781    /// Only side-effect-free tools may be replayed after a crash.
4782    ///
4783    /// Regression guard for an inverted default: `ToolReplay` used to default to
4784    /// `Safe` and the CLI then marked *every* tool `Safe`, so the first time
4785    /// recovery acted on the flag it would have re-run `bash`/`write`/`edit` and
4786    /// duplicated their side effects. upstream defaults to `"never"`
4787    /// (`drive/tools.ts: tool.replay ?? "never"`).
4788    #[test]
4789    fn only_read_only_tools_are_replayable() {
4790        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
4791        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
4792        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
4793        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
4794        let tools = build_tools(&context, &Args::default());
4795
4796        let replay_of = |name: &str| {
4797            tools
4798                .iter()
4799                .find(|tool| tool.tool.schema().name == name)
4800                .map(|tool| tool.replay)
4801        };
4802
4803        for read_only in ["read", "docs"] {
4804            assert_eq!(
4805                replay_of(read_only),
4806                Some(ToolReplay::Safe),
4807                "{read_only} is side-effect free, so recovery may re-run it"
4808            );
4809        }
4810        for mutating in ["bash", "edit", "write", "powershell"] {
4811            if let Some(replay) = replay_of(mutating) {
4812                assert_eq!(
4813                    replay,
4814                    ToolReplay::Never,
4815                    "{mutating} must never be replayed: re-running it would duplicate its effect"
4816                );
4817            }
4818        }
4819    }
4820
4821    #[test]
4822    fn default_tools_include_docs_lookup() {
4823        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
4824        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
4825        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
4826        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
4827        let names: Vec<String> = build_tools(&context, &Args::default())
4828            .iter()
4829            .map(|tool| tool.tool.schema().name.clone())
4830            .collect();
4831
4832        // `docs` is a default capability; the legacy rpi-only lookup tools stay
4833        // unregistered. Asserted by membership (not exact equality) because
4834        // `powershell` is Windows-only and `settings.json#defaultTools` may
4835        // narrow the set in a developer's environment.
4836        assert!(names.contains(&"docs".to_string()));
4837        for legacy in ["grep", "find", "ls"] {
4838            assert!(
4839                !names.contains(&legacy.to_string()),
4840                "legacy tool {legacy} should not be registered by default"
4841            );
4842        }
4843    }
4844
4845    #[test]
4846    fn reload_settings_preflight_respects_trust() {
4847        struct RestoreConfigDir(Option<std::ffi::OsString>);
4848
4849        impl Drop for RestoreConfigDir {
4850            fn drop(&mut self) {
4851                match self.0.take() {
4852                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
4853                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
4854                }
4855            }
4856        }
4857
4858        let _guard = crate::config::test_support::env_lock().lock().unwrap();
4859        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4860        let tmp = tempfile::tempdir().unwrap();
4861        let agent = tmp.path().join("agent");
4862        let cwd = tmp.path().join("project");
4863        std::fs::create_dir_all(&agent).unwrap();
4864        std::fs::create_dir_all(cwd.join(".rpi")).unwrap();
4865        std::fs::write(agent.join("settings.json"), "{}").unwrap();
4866        std::fs::write(cwd.join(".rpi/settings.json"), "{ malformed").unwrap();
4867        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
4868        let args = Args::default();
4869
4870        let trusted = validate_settings_for_reload(&args, &cwd, true);
4871        let untrusted = validate_settings_for_reload(&args, &cwd, false);
4872        assert!(trusted
4873            .unwrap_err()
4874            .contains("could not load project settings"));
4875        assert!(untrusted.is_ok());
4876
4877        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
4878        assert!(validate_settings_for_reload(&args, &cwd, false)
4879            .unwrap_err()
4880            .contains("could not load global settings"));
4881
4882        let local_only = Args {
4883            dev_local_only: true,
4884            ..Args::default()
4885        };
4886        assert!(validate_settings_for_reload(&local_only, &cwd, true).is_ok());
4887    }
4888
4889    #[tokio::test(flavor = "current_thread")]
4890    async fn reload_preserves_live_resources_when_settings_break() {
4891        struct RestoreConfigDir(Option<std::ffi::OsString>);
4892
4893        impl Drop for RestoreConfigDir {
4894            fn drop(&mut self) {
4895                match self.0.take() {
4896                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
4897                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
4898                }
4899            }
4900        }
4901
4902        let _guard = crate::config::test_support::env_lock().lock().unwrap();
4903        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4904        let tmp = tempfile::tempdir().unwrap();
4905        let agent = tmp.path().join("agent");
4906        let cwd = tmp.path().join("project");
4907        let skill_dir = tmp.path().join("configured-skills");
4908        std::fs::create_dir_all(&agent).unwrap();
4909        std::fs::create_dir_all(&cwd).unwrap();
4910        std::fs::create_dir_all(&skill_dir).unwrap();
4911        std::fs::write(
4912            skill_dir.join("SKILL.md"),
4913            "---\nname: keep-me\ndescription: Reload sentinel\n---\nKeep this skill loaded.",
4914        )
4915        .unwrap();
4916        std::fs::write(
4917            agent.join("settings.json"),
4918            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
4919        )
4920        .unwrap();
4921        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
4922
4923        let resolved = crate::provider::resolve(
4924            Some("anthropic"),
4925            Some(crate::provider::DEFAULT_MODEL_ID),
4926            None,
4927            Some("test-key"),
4928            None,
4929        )
4930        .unwrap();
4931        let args = Args {
4932            trust_override: Some(false),
4933            no_session: true,
4934            no_extensions: true,
4935            no_prompt_templates: true,
4936            no_context_files: true,
4937            system_prompt: Some("stable system prompt".into()),
4938            ..Args::default()
4939        };
4940        let (harness, _events, context) = build(&resolved, &args, &cwd, false).await.unwrap();
4941        let before_resources = harness.get_resources().await.unwrap();
4942        assert_eq!(before_resources.skills.as_ref().unwrap().len(), 1);
4943        assert_eq!(before_resources.skills.as_ref().unwrap()[0].name, "keep-me");
4944        let before_prompt = harness.get_system_prompt().await.unwrap();
4945        let before_tools: Vec<String> = harness
4946            .get_tools()
4947            .await
4948            .unwrap()
4949            .iter()
4950            .map(|tool| tool.tool.schema().name.clone())
4951            .collect();
4952        let before_bridge = context
4953            .action_bridge
4954            .lock()
4955            .unwrap()
4956            .as_ref()
4957            .unwrap()
4958            .clone();
4959
4960        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
4961        let outcome = reload_extension_resources(&harness, &context).await;
4962
4963        assert!(outcome.had_warnings);
4964        assert!(outcome.summary.contains("Settings reload failed"));
4965        assert!(outcome.summary.contains("could not load global settings"));
4966        // Hard failure keeps the previous resources; the outcome must not
4967        // advertise a fresh trust policy either (theme discovery keeps the
4968        // registry it already matches).
4969        assert_eq!(outcome.project_trusted, None);
4970        assert_eq!(harness.get_resources().await.unwrap(), before_resources);
4971        assert_eq!(harness.get_system_prompt().await.unwrap(), before_prompt);
4972        let after_tools: Vec<String> = harness
4973            .get_tools()
4974            .await
4975            .unwrap()
4976            .iter()
4977            .map(|tool| tool.tool.schema().name.clone())
4978            .collect();
4979        assert_eq!(after_tools, before_tools);
4980        let after_bridge = context
4981            .action_bridge
4982            .lock()
4983            .unwrap()
4984            .as_ref()
4985            .unwrap()
4986            .clone();
4987        assert!(Arc::ptr_eq(&after_bridge, &before_bridge));
4988    }
4989
4990    #[tokio::test(flavor = "current_thread")]
4991    async fn reload_outcome_carries_the_current_project_trust() {
4992        struct RestoreConfigDir(Option<std::ffi::OsString>);
4993
4994        impl Drop for RestoreConfigDir {
4995            fn drop(&mut self) {
4996                match self.0.take() {
4997                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
4998                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
4999                }
5000            }
5001        }
5002
5003        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5004        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5005        let tmp = tempfile::tempdir().unwrap();
5006        let agent = tmp.path().join("agent");
5007        let cwd = tmp.path().join("project");
5008        std::fs::create_dir_all(&agent).unwrap();
5009        std::fs::create_dir_all(&cwd).unwrap();
5010        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5011
5012        // Startup snapshot: trusted.
5013        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
5014        let resolved = crate::provider::resolve(
5015            Some("anthropic"),
5016            Some(crate::provider::DEFAULT_MODEL_ID),
5017            None,
5018            Some("test-key"),
5019            None,
5020        )
5021        .unwrap();
5022        let args = Args {
5023            no_session: true,
5024            no_extensions: true,
5025            no_prompt_templates: true,
5026            no_context_files: true,
5027            system_prompt: Some("stable system prompt".into()),
5028            ..Args::default()
5029        };
5030        let (harness, _events, context) = build(&resolved, &args, &cwd, true).await.unwrap();
5031        assert!(context.project_trusted, "startup snapshot is trusted");
5032
5033        // /trust no, then /reload: the outcome must report the CURRENT
5034        // decision, not the immutable startup snapshot.
5035        crate::config::set_project_trust(&cwd, Some(false)).unwrap();
5036        let outcome = reload_extension_resources(&harness, &context).await;
5037        assert!(!outcome.had_errors, "{}", outcome.summary);
5038        assert_eq!(outcome.project_trusted, Some(false));
5039
5040        // And the opposite transition back to trusted.
5041        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
5042        let outcome = reload_extension_resources(&harness, &context).await;
5043        assert!(!outcome.had_errors, "{}", outcome.summary);
5044        assert_eq!(outcome.project_trusted, Some(true));
5045    }
5046
5047    #[test]
5048    fn reload_preparation_rejects_settings_changed_during_derivation() {
5049        struct RestoreConfigDir(Option<std::ffi::OsString>);
5050
5051        impl Drop for RestoreConfigDir {
5052            fn drop(&mut self) {
5053                match self.0.take() {
5054                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5055                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5056                }
5057            }
5058        }
5059
5060        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5061        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5062        let tmp = tempfile::tempdir().unwrap();
5063        let agent = tmp.path().join("agent");
5064        let cwd = tmp.path().join("project");
5065        let first_skill_dir = tmp.path().join("first-skills");
5066        let second_skill_dir = tmp.path().join("second-skills");
5067        std::fs::create_dir_all(&agent).unwrap();
5068        std::fs::create_dir_all(&cwd).unwrap();
5069        std::fs::write(
5070            agent.join("settings.json"),
5071            serde_json::json!({"skillDirs": [first_skill_dir]}).to_string(),
5072        )
5073        .unwrap();
5074        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5075        let args = Args {
5076            trust_override: Some(false),
5077            no_extensions: true,
5078            no_prompt_templates: true,
5079            ..Args::default()
5080        };
5081
5082        let result = prepare_reload_inputs_inner(&args, &cwd, false, || {
5083            std::fs::write(
5084                agent.join("settings.json"),
5085                serde_json::json!({"skillDirs": [second_skill_dir]}).to_string(),
5086            )
5087            .unwrap();
5088        });
5089
5090        let error = result
5091            .err()
5092            .expect("settings mutation must fail preparation");
5093        assert!(error.contains("settings changed while reload inputs were being prepared"));
5094    }
5095
5096    #[tokio::test(flavor = "current_thread")]
5097    async fn reload_uses_frozen_settings_inputs_after_preparation() {
5098        struct RestoreConfigDir(Option<std::ffi::OsString>);
5099
5100        impl Drop for RestoreConfigDir {
5101            fn drop(&mut self) {
5102                match self.0.take() {
5103                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5104                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5105                }
5106            }
5107        }
5108
5109        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5110        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5111        let tmp = tempfile::tempdir().unwrap();
5112        let agent = tmp.path().join("agent");
5113        let cwd = tmp.path().join("project");
5114        let skill_dir = tmp.path().join("configured-skills");
5115        std::fs::create_dir_all(&agent).unwrap();
5116        std::fs::create_dir_all(&cwd).unwrap();
5117        std::fs::create_dir_all(&skill_dir).unwrap();
5118        std::fs::write(
5119            skill_dir.join("SKILL.md"),
5120            "---\nname: frozen-skill\ndescription: Reload sentinel\n---\nFrozen input.",
5121        )
5122        .unwrap();
5123        std::fs::write(
5124            agent.join("settings.json"),
5125            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
5126        )
5127        .unwrap();
5128        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5129
5130        let resolved = crate::provider::resolve(
5131            Some("anthropic"),
5132            Some(crate::provider::DEFAULT_MODEL_ID),
5133            None,
5134            Some("test-key"),
5135            None,
5136        )
5137        .unwrap();
5138        let args = Args {
5139            trust_override: Some(false),
5140            no_session: true,
5141            no_extensions: true,
5142            no_prompt_templates: true,
5143            no_context_files: true,
5144            system_prompt: Some("stable system prompt".into()),
5145            ..Args::default()
5146        };
5147        let (harness, _events, context) = build(&resolved, &args, &cwd, false).await.unwrap();
5148
5149        let outcome = reload_extension_resources_inner(&harness, &context, || {
5150            std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
5151        })
5152        .await;
5153
5154        assert!(!outcome.summary.contains("Settings reload failed"));
5155        assert_eq!(
5156            outcome.summary,
5157            "Reloaded 0 plugin(s), 1 skill(s), 0 prompt(s)."
5158        );
5159        let resources = harness.get_resources().await.unwrap();
5160        let skills = resources.skills.as_ref().unwrap();
5161        assert_eq!(skills.len(), 1);
5162        assert_eq!(skills[0].name, "frozen-skill");
5163    }
5164
5165    #[tokio::test]
5166    async fn reload_resource_paths_include_explicit_skill_and_prompt_files() {
5167        let tmp = tempfile::tempdir().unwrap();
5168        let skill_path = tmp.path().join("explicit-skill.md");
5169        std::fs::write(
5170            &skill_path,
5171            "---\nname: explicit-skill\ndescription: Explicit skill\n---\nSkill body",
5172        )
5173        .unwrap();
5174        let prompt_path = tmp.path().join("explicit-prompt.md");
5175        std::fs::write(
5176            &prompt_path,
5177            "---\ndescription: Explicit prompt\n---\nPrompt body",
5178        )
5179        .unwrap();
5180
5181        let args = Args {
5182            skill: vec![skill_path.clone()],
5183            prompt_template: vec![prompt_path.clone()],
5184            ..Args::default()
5185        };
5186        let skill_paths = append_reload_resource_paths(Vec::new(), &args.skill, &[], &[], &[]);
5187        let prompt_paths =
5188            append_reload_resource_paths(Vec::new(), &args.prompt_template, &[], &[], &[]);
5189        let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
5190        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env;
5191
5192        let skills = load_skills_with_precedence(&env_dyn, &skill_paths).await;
5193        assert_eq!(skills.skills.len(), 1, "{:?}", skills.diagnostics);
5194        assert_eq!(skills.skills[0].name, "explicit-skill");
5195
5196        let prompts = load_prompt_templates_with_precedence(&env_dyn, &prompt_paths).await;
5197        assert_eq!(
5198            prompts.prompt_templates.len(),
5199            1,
5200            "{:?}",
5201            prompts.diagnostics
5202        );
5203        assert_eq!(prompts.prompt_templates[0].name, "explicit-prompt");
5204    }
5205
5206    #[test]
5207    fn tool_policy_applies_to_rust_and_js_active_names() {
5208        let names = vec![
5209            "read".to_string(),
5210            "ask_user_question".to_string(),
5211            "write".to_string(),
5212        ];
5213
5214        let args = Args {
5215            tools: Some(vec!["read".into(), "ask_user_question".into()]),
5216            ..Args::default()
5217        };
5218        assert_eq!(
5219            filter_active_tool_names(names.clone(), &args),
5220            vec!["read", "ask_user_question"]
5221        );
5222
5223        let args = Args {
5224            exclude_tools: Some(vec!["ask_user_question".into()]),
5225            ..Args::default()
5226        };
5227        assert_eq!(
5228            filter_active_tool_names(names.clone(), &args),
5229            vec!["read", "write"]
5230        );
5231
5232        let args = Args {
5233            no_tools: true,
5234            ..Args::default()
5235        };
5236        assert!(filter_active_tool_names(names, &args).is_empty());
5237    }
5238
5239    #[test]
5240    fn select_ephemeral_when_no_session() {
5241        let args = Args {
5242            no_session: true,
5243            ..Args::default()
5244        };
5245        let cwd = Path::new("/tmp");
5246        assert!(matches!(
5247            select_session(&args, cwd),
5248            SessionSelection::Ephemeral
5249        ));
5250    }
5251
5252    #[test]
5253    fn project_resources_load_by_default_and_allow_explicit_opt_out() {
5254        let defaults = Args::default();
5255        assert!(resolve_project_trust(
5256            &defaults,
5257            Path::new("C:/definitely-not-a-project")
5258        ));
5259
5260        let denied = Args {
5261            trust_override: Some(false),
5262            ..Args::default()
5263        };
5264        assert!(!resolve_project_trust(
5265            &denied,
5266            Path::new("C:/definitely-not-a-project")
5267        ));
5268    }
5269
5270    #[tokio::test(flavor = "current_thread")]
5271    async fn build_preserves_the_supplied_startup_project_snapshot() {
5272        struct RestoreConfigDir(Option<std::ffi::OsString>);
5273
5274        impl Drop for RestoreConfigDir {
5275            fn drop(&mut self) {
5276                match self.0.take() {
5277                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5278                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5279                }
5280            }
5281        }
5282
5283        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5284        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5285        let tmp = tempfile::tempdir().unwrap();
5286        let agent = tmp.path().join("agent");
5287        let cwd = tmp.path().join("project");
5288        std::fs::create_dir_all(&agent).unwrap();
5289        std::fs::create_dir_all(&cwd).unwrap();
5290        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5291
5292        let resolved = crate::provider::resolve(
5293            Some("anthropic"),
5294            Some(crate::provider::DEFAULT_MODEL_ID),
5295            None,
5296            Some("test-key"),
5297            None,
5298        )
5299        .unwrap();
5300        let args = Args {
5301            trust_override: Some(false),
5302            no_session: true,
5303            no_tools: true,
5304            no_extensions: true,
5305            no_skills: true,
5306            no_prompt_templates: true,
5307            no_context_files: true,
5308            system_prompt: Some("test prompt".into()),
5309            ..Args::default()
5310        };
5311
5312        let (_, _, context) = build(&resolved, &args, &cwd, true).await.unwrap();
5313
5314        assert_eq!(context.cwd, cwd);
5315        assert!(context.project_trusted);
5316    }
5317
5318    #[tokio::test(flavor = "current_thread")]
5319    async fn build_applies_the_name_flag_to_the_session() {
5320        struct RestoreConfigDir(Option<std::ffi::OsString>);
5321
5322        impl Drop for RestoreConfigDir {
5323            fn drop(&mut self) {
5324                match self.0.take() {
5325                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5326                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5327                }
5328            }
5329        }
5330
5331        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5332        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5333        let tmp = tempfile::tempdir().unwrap();
5334        let agent = tmp.path().join("agent");
5335        let cwd = tmp.path().join("project");
5336        std::fs::create_dir_all(&agent).unwrap();
5337        std::fs::create_dir_all(&cwd).unwrap();
5338        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5339
5340        let resolved = crate::provider::resolve(
5341            Some("anthropic"),
5342            Some(crate::provider::DEFAULT_MODEL_ID),
5343            None,
5344            Some("test-key"),
5345            None,
5346        )
5347        .unwrap();
5348        let args = Args {
5349            trust_override: Some(false),
5350            no_tools: true,
5351            no_extensions: true,
5352            no_skills: true,
5353            no_prompt_templates: true,
5354            no_context_files: true,
5355            system_prompt: Some("test prompt".into()),
5356            name: Some("smoke name".into()),
5357            session_dir: Some(cwd.join("sessions")),
5358            ..Args::default()
5359        };
5360
5361        let (harness, _, _) = build(&resolved, &args, &cwd, true).await.unwrap();
5362        assert_eq!(
5363            harness.get_name().await.unwrap().as_deref(),
5364            Some("smoke name")
5365        );
5366    }
5367
5368    #[test]
5369    fn select_latest_for_continue_and_resume() {
5370        let _env = crate::config::test_support::SessionDirEnv::new(None);
5371        let args = Args {
5372            continue_session: true,
5373            ..Args::default()
5374        };
5375        let cwd = Path::new("/tmp");
5376        assert!(matches!(
5377            select_session(&args, cwd),
5378            SessionSelection::Latest { .. }
5379        ));
5380
5381        let args = Args {
5382            resume: true,
5383            ..Args::default()
5384        };
5385        assert!(matches!(
5386            select_session(&args, cwd),
5387            SessionSelection::Latest { .. }
5388        ));
5389    }
5390
5391    #[test]
5392    fn select_by_id_for_session_flag() {
5393        let _env = crate::config::test_support::SessionDirEnv::new(None);
5394        let args = Args {
5395            session: Some("01a02ece".into()),
5396            ..Args::default()
5397        };
5398        let cwd = Path::new("/tmp");
5399        assert!(matches!(
5400            select_session(&args, cwd),
5401            SessionSelection::ById { id, .. } if id == "01a02ece"
5402        ));
5403    }
5404
5405    #[test]
5406    fn select_new_with_custom_dir() {
5407        let _env = crate::config::test_support::SessionDirEnv::new(None);
5408        let args = Args {
5409            session_dir: Some(PathBuf::from("/tmp/sess")),
5410            ..Args::default()
5411        };
5412        let cwd = Path::new("/tmp");
5413        match select_session(&args, cwd) {
5414            SessionSelection::New { dir, .. } => assert_eq!(dir, PathBuf::from("/tmp/sess")),
5415            other => panic!("expected New, got {other:?}"),
5416        }
5417    }
5418
5419    #[test]
5420    fn select_new_default_dir() {
5421        let _env = crate::config::test_support::SessionDirEnv::new(None);
5422        let args = Args::default();
5423        let cwd = Path::new("/proj");
5424        match select_session(&args, cwd) {
5425            SessionSelection::New { dir, .. } => {
5426                assert_eq!(dir, Path::new("/proj/.rpi/sessions"));
5427            }
5428            other => panic!("expected New, got {other:?}"),
5429        }
5430    }
5431
5432    #[test]
5433    fn default_session_dir_only_uses_rpi() {
5434        let _env = crate::config::test_support::SessionDirEnv::new(None);
5435        let tmp = tempfile::tempdir().unwrap();
5436        let cwd = tmp.path();
5437        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
5438        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
5439        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
5440        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
5441    }
5442
5443    #[test]
5444    fn default_session_dir_uses_env_var() {
5445        let tmp = tempfile::tempdir().unwrap();
5446        let cwd = tmp.path();
5447        let custom = tmp.path().join("custom_sessions");
5448        let _env = crate::config::test_support::SessionDirEnv::new(Some(&custom));
5449        assert_eq!(default_session_dir(cwd), custom);
5450    }
5451
5452    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5453    async fn ephemeral_session_builds_roundtrips() {
5454        // Sanity: the ephemeral path produces a usable Session facade (the
5455        // harness build itself needs a provider; tested via the integration
5456        // path in tests/build.rs instead).
5457        let s = ephemeral_session();
5458        let leaf = s.get_leaf_id().await;
5459        assert!(leaf.is_ok());
5460    }
5461
5462    // NOTE: `build_tools`/`active_tool_names` integration is exercised by the
5463    // `tests/build.rs` harness-build test (needs a provider + multi-thread rt).
5464
5465    /// The exclusion policy, checked against the constants rather than copies.
5466    ///
5467    /// `rpi-tools` builds its exclusion from `rpi-plugin-sdk`'s declarations, so
5468    /// within this repo a rename is a compile error — this test is not the link
5469    /// between those two crates any more. What it still guards is the part the
5470    /// compiler cannot see:
5471    ///
5472    /// - **The wire values.** `rpi-langfuse` lives in a different repository and
5473    ///   agrees on the *strings*, not the constant paths. Rewriting a constant's
5474    ///   value would compile here and silently stop matching there, so the exact
5475    ///   values are pinned below. Changing one is a deliberate, breaking change to
5476    ///   a cross-repo contract, and it should fail here first.
5477    /// - **Coverage.** Every name the SDK declares must actually be excluded.
5478    /// - **Narrowness.** The user's own configuration must still reach the shell.
5479    #[test]
5480    fn host_private_env_matches_the_declared_contract() {
5481        // 1. The wire values. Pinned literally on purpose: see the doc comment.
5482        assert_eq!(rpi_plugin_sdk::SESSION_ID_ENV, "RPI_SESSION_ID");
5483        assert_eq!(
5484            rpi_plugin_sdk::SUBAGENT_PARENT_ENV,
5485            [
5486                "LANGFUSE_PI_PARENT_TRACE_ID",
5487                "LANGFUSE_PI_PARENT_SPAN_ID",
5488                "LANGFUSE_PI_PARENT_SESSION_ID",
5489                "LANGFUSE_PI_PARENT_DEPTH",
5490            ],
5491            "these strings are what rpi-langfuse (a different repo) matches; a \
5492             change here is a breaking cross-repo change, not a refactor"
5493        );
5494
5495        // 2. Coverage — derived from the declarations, so a newly added family
5496        //    member is checked without anyone remembering to extend this test.
5497        for name in rpi_plugin_sdk::SUBAGENT_PARENT_ENV
5498            .iter()
5499            .chain(std::iter::once(&rpi_plugin_sdk::SESSION_ID_ENV))
5500        {
5501            assert!(
5502                rpi_tools::is_host_private_env(name),
5503                "`{name}` must not reach a spawned shell, but rpi-tools excludes only {:?}",
5504                rpi_tools::HOST_PRIVATE_ENV
5505            );
5506        }
5507
5508        // 3. Narrowness — these name how the *user* configured the run and are
5509        //    exactly what a command inside the shell should still see.
5510        for visible in [
5511            crate::args::RPI_OFFLINE_ENV,
5512            crate::config::CONFIG_DIR_ENV,
5513            "PATH",
5514        ] {
5515            assert!(
5516                !rpi_tools::is_host_private_env(visible),
5517                "{visible} describes the user's configuration and must still reach the shell"
5518            );
5519        }
5520    }
5521    #[tokio::test]
5522    async fn reload_shutdown_joins_all_handlers_even_after_veto() {
5523        use rpi_plugin_sdk::{EventTag, StablePluginEvent};
5524        use std::sync::atomic::AtomicUsize;
5525        static CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<AtomicUsize>> =
5526            rpi_plugin_sdk::handles::ToolHandles::new();
5527        struct ContextOwner(usize);
5528        impl Drop for ContextOwner {
5529            fn drop(&mut self) {
5530                drop(CONTEXTS.remove(self.0 as rpi_plugin_sdk::StepHandle));
5531            }
5532        }
5533        extern "C" fn stop(_: StablePluginEvent, data: *mut std::ffi::c_void) -> i32 {
5534            let context = CONTEXTS.get(data).expect("live test context");
5535            let calls = context.lock().clone();
5536            std::thread::sleep(std::time::Duration::from_millis(20));
5537            if calls.fetch_add(1, Ordering::SeqCst) == 0 {
5538                rpi_plugin_sdk::EVENT_HANDLER_ABORT
5539            } else {
5540                0
5541            }
5542        }
5543        let calls = Arc::new(AtomicUsize::new(0));
5544        let context = CONTEXTS.insert(calls.clone());
5545        let _owner = ContextOwner(context as usize);
5546        let mut registry = rpi_extensions::ExtensionRegistry::new();
5547        for name in ["first", "second"] {
5548            registry.register_event_handler(name.into(), EventTag::SessionShutdown, stop, context);
5549        }
5550        super::shutdown_extensions_for_reload(
5551            Some(Arc::new(registry.snapshot())),
5552            rpi_extensions::PluginKeepalive::empty(),
5553        )
5554        .await
5555        .unwrap();
5556        assert_eq!(calls.load(Ordering::SeqCst), 2);
5557    }
5558
5559    // ---- restored-session working directory ----
5560
5561    /// A restore peek must name the directory the session was created in —
5562    /// that is the whole point of recording it. Everything downstream (tool
5563    /// env, system prompt, context files, extensions) keys off the run's cwd,
5564    /// so a peek that falls back to the launch directory would leave the
5565    /// resumed agent editing files in whatever directory `rpi` happened to be
5566    /// started from.
5567    #[tokio::test]
5568    async fn a_restored_session_adopts_its_recorded_directory() {
5569        let tmp = tempfile::tempdir().unwrap();
5570        let project = tmp.path().join("project-a");
5571        let launch = tmp.path().join("launch-dir");
5572        let sessions = tmp.path().join("sessions");
5573        std::fs::create_dir_all(&project).unwrap();
5574        std::fs::create_dir_all(&launch).unwrap();
5575        std::fs::create_dir_all(&sessions).unwrap();
5576        create_jsonl_session_with_id(
5577            &sessions,
5578            &project.to_string_lossy(),
5579            Some("cwdadopt01".into()),
5580        )
5581        .await
5582        .unwrap();
5583
5584        let selection = SessionSelection::ById {
5585            id: "cwdadopt01".into(),
5586            dir: sessions.clone(),
5587        };
5588        let peeked = peek_restored_session_cwd(&selection, &launch)
5589            .await
5590            .expect("a resumable session with a recorded cwd");
5591        assert_eq!(peeked.recorded, project);
5592        assert_eq!(peeked.adopted, Some(project));
5593    }
5594
5595    /// A recorded directory that no longer exists must NOT be adopted: the run
5596    /// falls back to the launch cwd, and the peek hands back the record so the
5597    /// host can say so (instead of the old behaviour of eprintln-ing mid-TUI).
5598    #[tokio::test]
5599    async fn a_missing_recorded_directory_is_reported_not_adopted() {
5600        let tmp = tempfile::tempdir().unwrap();
5601        let gone = tmp.path().join("project-gone");
5602        let launch = tmp.path().join("launch-dir");
5603        let sessions = tmp.path().join("sessions");
5604        std::fs::create_dir_all(&launch).unwrap();
5605        std::fs::create_dir_all(&sessions).unwrap();
5606        create_jsonl_session_with_id(
5607            &sessions,
5608            &gone.to_string_lossy(),
5609            Some("cwdgone001".into()),
5610        )
5611        .await
5612        .unwrap();
5613
5614        let selection = SessionSelection::ById {
5615            id: "cwdgone001".into(),
5616            dir: sessions.clone(),
5617        };
5618        let peeked = peek_restored_session_cwd(&selection, &launch)
5619            .await
5620            .expect("the session itself is resumable");
5621        assert_eq!(peeked.recorded, gone);
5622        assert_eq!(peeked.adopted, None);
5623        let note = crate::session_cwd::missing_session_cwd_note(&peeked.recorded, &launch);
5624        assert!(note.contains("no longer exists"), "{note}");
5625        assert!(note.contains("launch-dir"), "{note}");
5626    }
5627
5628    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5629    async fn legacy_progress_upgrade_normal_open_runs_and_reopens() {
5630        use rpi_ai::providers::faux::{FauxProvider, FauxScript};
5631        use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
5632        use rpi_harness::session::jsonl::{
5633            encode_header, JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
5634            JsonlV4Header,
5635        };
5636        let tmp = tempfile::tempdir().unwrap();
5637        let sessions = tmp.path().join("sessions");
5638        std::fs::create_dir_all(&sessions).unwrap();
5639        let cwd = tmp.path().to_string_lossy().into_owned();
5640        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
5641            fs: Arc::new(OsExecutionEnv::with_cwd(tmp.path().into())),
5642            sessions_root: sessions.to_string_lossy().into_owned(),
5643            clock: Arc::new(SystemClock),
5644            ids: Arc::new(DefaultIdGenerator::new()),
5645        });
5646        let fixture = repo
5647            .create_typed(&JsonlSessionCreateOptions {
5648                id: Some("legacycli001".into()),
5649                parent_session_id: None,
5650                cwd: cwd.clone(),
5651                metadata: None,
5652            })
5653            .await
5654            .unwrap();
5655        let path = PathBuf::from(fixture.jsonl_metadata().path);
5656        drop(fixture);
5657        let sidecar = PathBuf::from(format!("{}.progress.jsonl", path.display()));
5658        std::fs::remove_file(&sidecar).unwrap();
5659        let header = JsonlV4Header::new("legacycli001".into(), 1, cwd.clone(), None, None, None);
5660        std::fs::write(&path, encode_header(&header)).unwrap();
5661        assert!(!sidecar.exists());
5662        for _ in 0..2 {
5663            let restored = open_session_by_id_in_dir("legacycli001", &cwd, &sessions)
5664                .await
5665                .map_err(|e| e.to_string())
5666                .unwrap();
5667            assert_eq!(restored.session.storage().metadata().id, "legacycli001");
5668            let provider =
5669                FauxProvider::new(FauxScript::new().with_text("continued legacy session"));
5670            let harness = AgentHarness::create(AgentHarnessOptions {
5671                model: provider.default_model().clone(),
5672                models: vec![provider],
5673                session: restored.session,
5674                allow_existing_session: true,
5675                ..Default::default()
5676            })
5677            .await
5678            .unwrap();
5679            let run = harness.prompt_text("continue", vec![]).await.unwrap();
5680            assert!(matches!(run.outcome, HarnessRunOutcome::Completed { .. }));
5681        }
5682        let content = std::fs::read_to_string(&path).unwrap();
5683        assert!(content.lines().next().unwrap().contains("progressFormat"));
5684        assert!(sidecar.exists());
5685    }
5686
5687    /// `open_session` hands back the recorded directory as data (for the
5688    /// `/session` hot-switch notes) while still opening the session normally.
5689    #[tokio::test]
5690    async fn open_session_reports_the_recorded_directory() {
5691        let tmp = tempfile::tempdir().unwrap();
5692        let project = tmp.path().join("project-open");
5693        let launch = tmp.path().join("launch-dir");
5694        let sessions = tmp.path().join("sessions");
5695        std::fs::create_dir_all(&project).unwrap();
5696        std::fs::create_dir_all(&launch).unwrap();
5697        std::fs::create_dir_all(&sessions).unwrap();
5698        create_jsonl_session_with_id(
5699            &sessions,
5700            &project.to_string_lossy(),
5701            Some("cwdopen001".into()),
5702        )
5703        .await
5704        .unwrap();
5705
5706        let restored =
5707            open_session_by_id_in_dir("cwdopen001", &launch.to_string_lossy(), &sessions)
5708                .await
5709                .map_err(|error| error.to_string())
5710                .unwrap();
5711        assert_eq!(restored.recorded_cwd, Some(project.clone()));
5712        assert_eq!(restored.session.storage().metadata().id, "cwdopen001");
5713    }
5714
5715    /// The session the peek inspected must be the session the build opens.
5716    ///
5717    /// `-c` means "the most recent session", and the build lists the directory
5718    /// again. Another `rpi` (or a `/session` new-session) can write a newer one
5719    /// between the peek and the build; adopting the peeked session's directory
5720    /// while opening the newer conversation would run the tools in a directory
5721    /// that conversation never used. Pinning the resolved id makes the second
5722    /// listing an exact match instead of a fresh newest-first choice.
5723    #[tokio::test]
5724    async fn the_peeked_session_is_the_one_the_build_opens() {
5725        let tmp = tempfile::tempdir().unwrap();
5726        let first_project = tmp.path().join("project-first");
5727        let second_project = tmp.path().join("project-second");
5728        let launch = tmp.path().join("launch-dir");
5729        let sessions = tmp.path().join("sessions");
5730        for dir in [&first_project, &second_project, &launch, &sessions] {
5731            std::fs::create_dir_all(dir).unwrap();
5732        }
5733        create_jsonl_session_with_id(
5734            &sessions,
5735            &first_project.to_string_lossy(),
5736            Some("cwdrace001".into()),
5737        )
5738        .await
5739        .unwrap();
5740
5741        let mut args = Args {
5742            continue_session: true,
5743            session_dir: Some(sessions.clone()),
5744            ..Default::default()
5745        };
5746        let selection = select_session_in_dir(&args, sessions.clone());
5747        let peeked = peek_restored_session_cwd(&selection, &launch)
5748            .await
5749            .expect("a resumable session");
5750        assert_eq!(peeked.adopted, Some(first_project.clone()));
5751
5752        // A newer session appears in another project before the build runs.
5753        create_jsonl_session_with_id(
5754            &sessions,
5755            &second_project.to_string_lossy(),
5756            Some("cwdrace002".into()),
5757        )
5758        .await
5759        .unwrap();
5760
5761        pin_restored_selection(&mut args, &peeked);
5762        let pinned = select_session_in_dir(&args, sessions.clone());
5763        let reopened = resolve_restore_target(&pinned, &launch.to_string_lossy())
5764            .await
5765            .unwrap()
5766            .expect("the pinned session still exists");
5767        assert_eq!(
5768            reopened.id, peeked.id,
5769            "the build must open the session the peek adopted the directory of"
5770        );
5771        assert_eq!(reopened.cwd, first_project.to_string_lossy());
5772    }
5773
5774    /// Trust must be resolved against the directory it is asked about. A
5775    /// session recorded in another project must not inherit the launch
5776    /// directory's decision — that would run an untrusted project's settings,
5777    /// skills, and context files with trusted privileges.
5778    #[test]
5779    fn trust_is_resolved_per_directory() {
5780        struct RestoreConfigDir(Option<std::ffi::OsString>);
5781
5782        impl Drop for RestoreConfigDir {
5783            fn drop(&mut self) {
5784                match self.0.take() {
5785                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5786                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5787                }
5788            }
5789        }
5790
5791        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5792        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5793        let tmp = tempfile::tempdir().unwrap();
5794        let agent = tmp.path().join("agent");
5795        std::fs::create_dir_all(&agent).unwrap();
5796        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5797
5798        let untrusted = tmp.path().join("project-untrusted");
5799        let launch = tmp.path().join("project-launch");
5800        std::fs::create_dir_all(&untrusted).unwrap();
5801        std::fs::create_dir_all(&launch).unwrap();
5802        crate::config::set_project_trust(&untrusted, Some(false)).unwrap();
5803
5804        let args = Args::default();
5805        assert!(!resolve_project_trust(&args, &untrusted));
5806        // A directory with no stored decision loads by default.
5807        assert!(resolve_project_trust(&args, &launch));
5808    }
5809}
5810
5811#[cfg(test)]
5812#[path = "session/experimental_dialog_continuity_tests.rs"]
5813mod experimental_dialog_continuity_tests;
5814#[cfg(test)]
5815#[path = "session/experimental_reload_continuity_tests.rs"]
5816mod experimental_reload_continuity_tests;