Skip to main content

rpi_cli/
session.rs

1//! Harness construction + session-storage wiring. Mirrors the Rust-side
2//! equivalent of the TS `packages/coding-agent/src/core/sdk.ts`
3//! (`createAgentSession`) — build the env, tools, durable session storage, and
4//! `AgentHarnessOptions`, then `AgentHarness::create`.
5//!
6//! v1 scope cuts vs the TS SDK (tracked in `docs/m6-cli-open-questions.md`):
7//! - **Skill / prompt-template / context-file discovery IS wired**
8//!   (`--no-skills`/`-ns`, `--no-prompt-templates`/`-np`, `--no-context-files`/
9//!   `-nc` each suppress one channel; project `.rpi/<sub>` + legacy
10//!   `.rpi/<sub>` + global
11//!   `agent_dir()<sub>` discovery with project-wins dedupe via
12//!   [`crate::resource_dirs`]; SYSTEM.md/APPEND_SYSTEM.md project-wins
13//!   precedence). **Extension `resources_discover` (B5b) feeds the SAME loaders:
14//!   a plugin's discovered skill/prompt paths merge with the static dirs and
15//!   re-run through `load_skills`/`load_prompt_templates` (individual `.md` files
16//!   load too — `load_skills` accepts both dirs and files). Package themes are
17//!   parsed by the TUI when selected via settings or `--theme`.**
18//!   Project resources load by default without a prompt. `--no-approve` or a
19//!   stored negative `trust.json` decision disables them explicitly.
20//! - **No `ModelRuntime`/multi-provider registry.** The resolver supports the
21//!   built-in Anthropic/OpenAI-compatible providers and `models.json`, but
22//!   runtime catalog mutation remains outside this layer.
23//! - **Built-in tools**: `read`, `bash`, `edit`, `write`, and the read-only
24//!   `docs` lookup tool. The former rpi-only `grep`, `find`, `ls`, and
25//!   `powershell` tools remain library modules but are not registered by the
26//!   CLI.
27//! - **Session restore (`-c`/`-r`/`--session`)** is *partially* supported: a
28//!   fresh session is always created. The harness's `create` rejects sessions
29//!   that already have records unless `allow_existing_session` is enabled.
30//!   The interactive `-c`/`-r`/`--session` paths enable that mode and replay
31//!   the existing branch before appending new messages. See [`SessionSelection`].
32
33use std::collections::{BTreeMap, HashSet};
34use std::path::{Path, PathBuf};
35use std::sync::atomic::Ordering;
36use std::sync::{Arc, Mutex};
37
38use rpi_ai::Provider;
39use rpi_harness::agent_harness::AgentHarness;
40use rpi_harness::context_files::{format_project_context, load_project_context_files};
41use rpi_harness::session::memory::{InMemorySessionStorage, SystemClock};
42use rpi_harness::session::session::DefaultIdGenerator;
43use rpi_harness::session::types::SessionMetadata;
44use rpi_harness::session::Session;
45use rpi_harness::system_prompt::compose_system_prompt;
46use rpi_harness::types::{
47    AgentHarnessOptions, AgentHarnessResources, AgentHarnessStreamOptions, DrivingMode,
48    HarnessTool, HarnessToolExecution, ToolReplay,
49};
50#[cfg(windows)]
51use rpi_tools::create_powershell_tool;
52use rpi_tools::{
53    create_bash_tool, create_edit_tool, create_read_tool, create_write_tool, ExecutionToolContext,
54    MutationQueueRegistry, OsExecutionEnv,
55};
56
57use crate::args::Args;
58use crate::docs_tool::create_docs_tool;
59use crate::provider::ResolvedModel;
60use crate::resource_dirs::{
61    discover_append_system_prompt_file, discover_system_prompt_file, extension_dirs,
62    global_extension_dirs, global_prompt_template_dirs, global_skill_dirs,
63    load_prompt_templates_with_precedence, load_skills_with_precedence, project_extension_dirs,
64    project_prompt_template_dirs, project_skill_dirs, prompt_template_dirs, skill_dirs,
65};
66use crate::startup_diagnostics::{Phase, StartupSpan};
67use rpi_extensions::{
68    emit_resources_discover, ExtensionEmitter, ExtensionSession, NullDiagnostics,
69    PluginDiagnostics, PluginToolAdapter, TeeEmitter, ToolPromptMetadata,
70};
71
72// Preserve the existing public modes::rpc signature. This CLI-only attachment
73// table holds no session/router alive and keys by storage allocation identity,
74// NOT by a durable ID (two independent restored hosts must never share routing).
75// The session/tools/ReloadContext own the actual router. RPC owns its client.
76// Reload MUST reuse ReloadContext::file_io, including a disconnected selected
77// client backend; rebuilding a default router would silently restore host file
78// authority. Missing attachments reject configuration (never infer a router or
79// install host-backed replacements). This compatibility bridge can be replaced
80// by an explicit neutral harness attachment when its public API is revised.
81type FileIOAttachment = (
82    std::sync::Weak<dyn rpi_harness::session::types::SessionStorage>,
83    std::sync::Weak<rpi_tools::file_io::FileIORouter>,
84);
85fn file_io_attachments() -> &'static Mutex<Vec<FileIOAttachment>> {
86    static ATTACHMENTS: std::sync::OnceLock<Mutex<Vec<FileIOAttachment>>> =
87        std::sync::OnceLock::new();
88    ATTACHMENTS.get_or_init(|| Mutex::new(Vec::new()))
89}
90pub(crate) fn register_file_io_router(
91    harness: &AgentHarness,
92    router: &Arc<rpi_tools::file_io::FileIORouter>,
93) {
94    let storage = harness.session().storage();
95    let mut attachments = file_io_attachments()
96        .lock()
97        .expect("file I/O attachments poisoned");
98    attachments.retain(|(s, r)| {
99        s.strong_count() > 0
100            && r.strong_count() > 0
101            && !s
102                .upgrade()
103                .is_some_and(|known| Arc::ptr_eq(&known, &storage))
104    });
105    attachments.push((Arc::downgrade(&storage), Arc::downgrade(router)));
106}
107pub(crate) fn file_io_router(
108    harness: &AgentHarness,
109) -> Option<Arc<rpi_tools::file_io::FileIORouter>> {
110    let storage = harness.session().storage();
111    let mut attachments = file_io_attachments()
112        .lock()
113        .expect("file I/O attachments poisoned");
114    attachments.retain(|(s, r)| s.strong_count() > 0 && r.strong_count() > 0);
115    attachments.iter().find_map(|(s, r)| {
116        s.upgrade()
117            .filter(|known| Arc::ptr_eq(known, &storage))
118            .and_then(|_| r.upgrade())
119    })
120}
121
122/// The coding tools registered by the CLI by default.
123pub const BUILTIN_TOOL_NAMES: &[&str] = &["read", "bash", "edit", "write", "docs"];
124
125/// The default coding system prompt for the CLI's built-in tools.
126///
127/// This retains the two-argument API for library callers. Session startup and
128/// reload use [`default_system_prompt_with_tool_prompts`] with the actual active
129/// tools and their winning extension metadata.
130pub fn default_system_prompt(cwd: &str, prior_reasoning_replayed: bool) -> String {
131    let tools = BUILTIN_TOOL_NAMES
132        .iter()
133        .map(|name| (*name).to_owned())
134        .collect::<Vec<_>>();
135    default_system_prompt_with_tools(cwd, prior_reasoning_replayed, &tools)
136}
137
138/// A coding system prompt for the selected tools. A condensed port of the TS
139/// `packages/coding-agent/src/core/system-prompt.ts` base prompt.
140///
141/// `tools` is the active tool set after `--tools`/`--exclude-tools` and
142/// extension merging. Like pi, the text list includes only tools with an
143/// explicit prompt snippet; other active tools remain available through their
144/// provider-facing schemas. Tool-specific guidelines still follow the full
145/// active set, so restricted runs get no guidance for unavailable tools.
146pub fn default_system_prompt_with_tools(
147    cwd: &str,
148    prior_reasoning_replayed: bool,
149    tools: &[String],
150) -> String {
151    default_system_prompt_with_tool_prompts(cwd, prior_reasoning_replayed, tools, &BTreeMap::new())
152}
153
154/// Render pi-style explicit prompt contributions for the active tool set.
155/// Entries override built-in metadata, including an empty entry for an
156/// extension that replaces a built-in without contributing a prompt snippet.
157/// Inactive metadata is ignored. Schemas and callable tools are not modified.
158pub fn default_system_prompt_with_tool_prompts(
159    cwd: &str,
160    prior_reasoning_replayed: bool,
161    tools: &[String],
162    overrides: &BTreeMap<String, ToolPromptMetadata>,
163) -> String {
164    let metadata: BTreeMap<_, _> = tools
165        .iter()
166        .map(|name| {
167            let prompt = overrides
168                .get(name)
169                .cloned()
170                .unwrap_or_else(|| ToolPromptMetadata {
171                    prompt_snippet: builtin_tool_snippet(name).map(str::to_owned),
172                    prompt_guidelines: Vec::new(),
173                })
174                .normalized();
175            (name.as_str(), prompt)
176        })
177        .collect();
178    // The working-state rule must match what actually comes back on the next
179    // request. With `compat.requiresThinkingAsText` (or the native thinking
180    // channels of anthropic/responses) the model *does* see its own reasoning
181    // again, and claiming otherwise makes it re-derive and restate the plan
182    // every turn — the re-plan symptom in `docs/llm-repetition-forensics.md`.
183    let working_state_rule = if prior_reasoning_replayed {
184        "- Your reasoning is carried back to you on the next turn: do not re-derive it or restate
185  the plan. Continue from the last unfinished step, and when a step lands, say which one.
186  Re-stating the same plan without acting on it is a bug, not progress."
187    } else {
188        "- Your reasoning is not carried into your next turn; only your visible replies and tool
189  output come back. Before each batch of tool calls, write one short line naming the step you
190  are on and what remains, and say which step is done when it lands.
191  Re-stating the same plan without acting on it is a bug, not progress."
192    };
193
194    // The text list is a selective summary, not the tool registry. In
195    // particular, do not repeat extension tool names without a prompt snippet.
196    let tool_lines = tools
197        .iter()
198        .filter_map(|name| {
199            metadata
200                .get(name.as_str())?
201                .prompt_snippet
202                .as_ref()
203                .map(|snippet| format!("- {name:<5} — {snippet}"))
204        })
205        .collect::<Vec<_>>()
206        .join("\n");
207    let tool_lines = if tool_lines.is_empty() {
208        "(none)".to_string()
209    } else {
210        tool_lines
211    };
212
213    // Tool-specific rules (Bash on Windows, docs before guessing) live in the
214    // tool's own line or description, not here a second time.
215    let guidelines = [
216        "- Reply in the same language as the user's latest message (the conversation's language when
217  that message is too short to tell), unless the user asks for another.",
218        "- Be concise in your responses",
219        "- Show file paths clearly when working with files",
220        "- Prefer the smallest change that solves the problem",
221        working_state_rule,
222        "- Read only what you need. If a file or search result was already shown earlier in this
223  conversation, use it instead of fetching it again.",
224    ];
225    // Tools contribute rules even without snippets. Like pi, trim and dedupe
226    // across the full active set and the core rules, preserving first occurrence.
227    let mut seen = HashSet::new();
228    let tool_rules = tools
229        .iter()
230        .flat_map(|name| &metadata[name.as_str()].prompt_guidelines)
231        .map(String::as_str);
232    let core_rules = guidelines
233        .iter()
234        .map(|rule| rule.strip_prefix("- ").unwrap_or(rule));
235    let guidelines = tool_rules
236        .chain(core_rules)
237        .map(str::trim)
238        .filter(|rule| !rule.is_empty() && seen.insert(*rule))
239        .map(|rule| format!("- {rule}"))
240        .collect::<Vec<_>>()
241        .join("\n");
242
243    format!(
244        "You are an expert coding assistant operating inside rpi, a coding agent harness. \
245You help users by reading files, executing commands, editing code, and writing new files.
246
247Available tools:
248{tool_lines}
249
250In addition to the tools above, you may have access to other custom tools depending on the project.
251
252Guidelines:
253{guidelines}
254
255Current working directory: {cwd}"
256    )
257}
258
259/// Take metadata from the same winning extension definitions used for tool
260/// merging, including empty metadata for overrides. Called on startup/reload.
261fn extension_tool_prompt_metadata(
262    session: &ExtensionSession,
263) -> BTreeMap<String, ToolPromptMetadata> {
264    session
265        .snapshot()
266        .map(|snapshot| {
267            snapshot
268                .tools()
269                .iter()
270                .map(|tool| (tool.tool.name.clone(), tool.prompt.clone()))
271                .collect()
272        })
273        .unwrap_or_default()
274}
275
276/// One-line prompt descriptions of the tools rpi itself registers.
277fn builtin_tool_snippet(name: &str) -> Option<&'static str> {
278    Some(match name {
279        "read" => "Read file contents",
280        "bash" => "Execute Bash commands (Bash/POSIX syntax, also on Windows)",
281        "edit" => "Find/replace edits to existing files",
282        "write" => "Create or overwrite files",
283        "docs" => "Look up rpi commands, extensions, Pi package compatibility and .rpi configuration instead of guessing",
284        "grep" => "Search file contents for a pattern",
285        "find" => "Find files by glob pattern",
286        "ls" => "List directory contents",
287        "powershell" => "Execute PowerShell commands on Windows",
288        _ => return None,
289    })
290}
291
292/// How the user asked to select a session. v1 honors `NoSession` (ephemeral
293/// `InMemorySessionStorage`), `New` (a fresh JSONL file), and — new this pass —
294/// `Latest` / `ById`, which **restore** an existing JSONL session on launch
295/// (`--continue`/`-c`, `--resume`/`-r`, `--session <id|path>`). The restored
296/// transcript renders into the TUI on startup and the run continues appending
297/// to the same file.
298#[derive(Debug, Clone)]
299pub enum SessionSelection {
300    /// `--no-session`: ephemeral, in-memory, nothing persisted.
301    Ephemeral,
302    /// Fresh durable JSONL session under `--session-dir` (or the default dir).
303    New { dir: PathBuf, name: Option<String> },
304    /// `-c` / `-r`: restore the most recent session in the default dir.
305    Latest { dir: PathBuf },
306    /// `--session <id|path>`: restore the session whose id matches, or whose
307    /// file name contains the id.
308    ById { id: String, dir: PathBuf },
309    /// `--session-id <id>`: use the EXACT session id, creating it if missing.
310    ByExactId { id: String, dir: PathBuf },
311    /// `--fork <path|id>`: fork the given session into a new one and start in
312    /// the fork.
313    Fork { source: String, dir: PathBuf },
314}
315
316/// Decide the session selection from parsed args + the resolved cwd.
317pub fn select_session(args: &Args, cwd: &Path) -> SessionSelection {
318    select_session_in_dir(args, configured_session_dir(args, cwd))
319}
320
321/// Resolve the root once at startup; runtime actions retain this selection.
322pub(crate) fn configured_session_dir(args: &Args, cwd: &Path) -> PathBuf {
323    let dir = args
324        .session_dir
325        .clone()
326        .or_else(|| {
327            crate::settings::load_settings()
328                .ok()
329                .and_then(|settings| settings.session_dir)
330        })
331        .unwrap_or_else(|| default_session_dir(cwd));
332    // Relative roots belong to the launch project, even if an extension later
333    // changes the process working directory.
334    if dir.is_relative() && !dir.has_root() {
335        cwd.join(dir)
336    } else {
337        dir
338    }
339}
340
341pub(crate) fn select_session_in_dir(args: &Args, dir: PathBuf) -> SessionSelection {
342    if args.no_session {
343        return SessionSelection::Ephemeral;
344    }
345    // `--session-dir` wins; then the saved `sessionDir` (upstream's key, same
346    // format as the flag); then the built-in default. Keep this directory on
347    // restore selections too, not only on fresh sessions.
348    if args.continue_session || args.resume {
349        return SessionSelection::Latest { dir };
350    }
351    if let Some(s) = &args.fork {
352        return SessionSelection::Fork {
353            source: s.clone(),
354            dir,
355        };
356    }
357    if let Some(s) = &args.session_id {
358        return SessionSelection::ByExactId { id: s.clone(), dir };
359    }
360    if let Some(s) = &args.session {
361        return SessionSelection::ById { id: s.clone(), dir };
362    }
363    SessionSelection::New {
364        dir,
365        name: args.name.clone(),
366    }
367}
368
369/// The default session directory is `<cwd>/.rpi/sessions`, unless
370/// `RPI_CODING_AGENT_SESSION_DIR` is set (in which case its value is used).
371pub fn default_session_dir(cwd: &Path) -> PathBuf {
372    std::env::var("RPI_CODING_AGENT_SESSION_DIR")
373        .ok()
374        .map(PathBuf::from)
375        .unwrap_or_else(|| cwd.join(".rpi").join("sessions"))
376}
377
378/// Extensions are loaded exactly once before model resolution. Their action
379/// host remains unbound until the harness and authenticated catalog exist.
380pub struct PreparedExtensions {
381    resource_leases: Arc<Vec<crate::resource_management::Lease>>,
382    resource_selection: Option<crate::resource_selection::ResolvedSelection>,
383    session_selection: SessionSelection,
384    transition_session: Option<Session>,
385    pub extension_session: ExtensionSession,
386    session_dir: PathBuf,
387    runtime: tokio::runtime::Handle,
388    tool_context: rpi_extensions::ToolCallContext,
389    action_host: Arc<crate::extensions_actions::HarnessActionHost>,
390    harness_cell: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
391    reload_mailbox: rpi_extensions::ReloadMailbox,
392    ui_dialog_mailbox: rpi_extensions::UiDialogMailbox,
393    ext_status_mailbox: rpi_extensions::ExtensionStatusMailbox,
394    editor_text_mailbox: rpi_extensions::EditorTextMailbox,
395    action_bridge: Arc<rpi_extensions::ActionBridge>,
396}
397
398/// Validate native durable resource ownership BEFORE loading any executable code.
399/// The synchronous public prepare_extensions API is retained: a scoped reader
400/// thread uses its own runtime so this also works inside current-thread Tokio.
401/// It does no registration, provider callbacks, session creation, or lock claiming.
402pub(crate) fn preflight_extension_startup(
403    args: &Args,
404    cwd: &Path,
405    trusted: bool,
406) -> Result<
407    (
408        Option<crate::resource_selection::ResolvedSelection>,
409        SessionSelection,
410    ),
411    BuildError,
412> {
413    let mut resources = crate::resource_selection::ResolvedSelection::load(args, cwd, trusted)
414        .map_err(BuildError::HarnessCreate)?;
415    let selection = select_session(args, cwd);
416    let pinned = std::thread::scope(|scope| {
417        scope
418            .spawn(|| {
419                tokio::runtime::Builder::new_current_thread()
420                    .enable_all()
421                    .build()
422                    .map_err(|e| BuildError::SessionOpen(e.to_string()))?
423                    .block_on(async {
424                        if let Some(selected) = &mut resources {
425                            let env: Arc<dyn rpi_tools::ExecutionEnv> =
426                                Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf()));
427                            selected
428                                .validate_skills(&env)
429                                .await
430                                .map_err(BuildError::HarnessCreate)?;
431                        }
432                        let cwd_str = cwd.to_string_lossy();
433                        let target = match &selection {
434                            SessionSelection::Fork { source, dir } => {
435                                match session_metadata_at(Path::new(source)) {
436                                    Some(meta) => Some(meta),
437                                    None => find_session_metadata(source, &cwd_str, dir).await?,
438                                }
439                            }
440                            _ => resolve_restore_target(&selection, &cwd_str).await?,
441                        };
442                        let Some(meta) = target else {
443                            if resources.as_ref().is_some_and(|r| r.transition.is_some()) {
444                                return Err(BuildError::SessionOpen("resource transition requires an existing native session".into()));
445                            }
446                            return Ok(selection.clone());
447                        };
448                        if resources.as_ref().is_some_and(|r| r.transition.is_some()) && matches!(selection, SessionSelection::Fork { .. }) {
449                            return Err(BuildError::SessionOpen("resource transition cannot fork".into()));
450                        }
451                        use rpi_harness::session::jsonl::{
452                            JsonlSessionRepo, JsonlSessionRepoOptions,
453                        };
454                        let dir = selection_dir(&selection);
455                        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
456                            fs: Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())),
457                            sessions_root: dir.to_string_lossy().into_owned(),
458                            clock: Arc::new(SystemClock),
459                            ids: Arc::new(DefaultIdGenerator::new()),
460                        });
461                        let facts = if resources.as_ref().is_some_and(|r| r.transition.is_some()) {
462                            rpi_harness::session::jsonl::JsonlSessionStorage::read_resource_transition_facts(
463                                Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())), &meta.path,
464                                Arc::new(SystemClock), Arc::new(DefaultIdGenerator::new()),
465                            ).await
466                        } else { repo.read_facts_by_jsonl_metadata(&meta).await }
467                            .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
468                        crate::resource_selection::validate_session_binding(
469                            &facts.values,
470                            resources.as_ref(),
471                        )
472                        .map_err(BuildError::SessionOpen)?;
473                        Ok(match selection {
474                            SessionSelection::Fork { .. } => SessionSelection::Fork {
475                                source: meta.path,
476                                dir,
477                            },
478                            _ => SessionSelection::ByExactId { id: meta.id, dir },
479                        })
480                    })
481            })
482            .join()
483            .map_err(|_| BuildError::SessionOpen("resource preflight reader panicked".into()))?
484    })?;
485    Ok((resources, pinned))
486}
487
488pub fn prepare_extensions(
489    args: &Args,
490    cwd: &Path,
491    project_trusted: bool,
492) -> Result<PreparedExtensions, BuildError> {
493    crate::native_durable::experimental_epoch::policy(args).map_err(BuildError::HarnessCreate)?;
494    let resource_leases =
495        crate::resource_management::host_leases(cwd).map_err(BuildError::HarnessCreate)?;
496    let (resource_selection, session_selection) =
497        preflight_extension_startup(args, cwd, project_trusted)?;
498    // Transition hosts own the writer before any DLL registration. The strict
499    // loader cannot repair history/progress or migrate metadata on rejection.
500    let transition_session = if resource_selection
501        .as_ref()
502        .is_some_and(|r| r.transition.is_some())
503    {
504        Some(std::thread::scope(|scope| {
505            scope.spawn(|| {
506            tokio::runtime::Builder::new_current_thread().enable_all().build()
507                .map_err(|e| BuildError::SessionOpen(e.to_string()))?.block_on(async {
508                    let meta = resolve_restore_target(&session_selection, &cwd.to_string_lossy()).await?
509                        .ok_or_else(|| BuildError::SessionOpen("transition session disappeared".into()))?;
510                    let path = std::fs::canonicalize(&meta.path).map_err(|e| BuildError::SessionOpen(e.to_string()))?;
511                    let storage = rpi_harness::session::jsonl::JsonlSessionStorage::load_for_resource_transition(
512                        Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())), &path.to_string_lossy(),
513                        Arc::new(SystemClock), Arc::new(DefaultIdGenerator::new()),
514                    ).await.map_err(|e| BuildError::SessionOpen(e.to_string()))?;
515                    storage.acquire_writer_lease().await.map_err(|e| BuildError::SessionOpen(e.to_string()))?;
516                    let session = Session::new(Arc::new(storage), None);
517                    crate::resource_selection::bind_session(&session, resource_selection.as_ref()).await.map_err(BuildError::SessionOpen)?;
518                    Ok::<_, BuildError>(session)
519                })
520        }).join().map_err(|_| BuildError::SessionOpen("transition writer preparation panicked".into()))?
521        })?)
522    } else {
523        None
524    };
525    let session_dir = if matches!(session_selection, SessionSelection::Ephemeral) {
526        configured_session_dir(args, cwd)
527    } else {
528        selection_dir(&session_selection)
529    };
530    let cwd_str = cwd.to_string_lossy().to_string();
531    let tool_context = rpi_extensions::ToolCallContext::new(cwd_str.clone());
532    if !project_trusted && args.verbose {
533        eprintln!(
534            "warning: current-project settings, resources, and discovered extensions are explicitly disabled (use --approve or /trust yes to re-enable)"
535        );
536    }
537    // Pi packages are explicitly opt-in because discovery can start Node and
538    // execute package code. An explicit project opt-out limits discovery to
539    // global settings.
540
541    // ---- B5a: build the action bridge BEFORE extension load ----
542    // Extensions load before `AgentHarness::create` (extensions provide tools the
543    // harness is built with), but a plugin stores the `ActionBridge`'s raw
544    // `user_data` pointer during `register` and it must remain valid + the host
545    // must be ready for the whole session. So:
546    //  1. Capture the current tokio `Handle` (the async main-thread runtime) —
547    //     the bridge spawns dispatch from any thread via `Handle::spawn`.
548    //  2. Build an *empty* `HarnessActionHost` (its harness cell is unset; no
549    //     plugin can call a runtime action before the harness runs).
550    //  3. Wrap it as `Arc<dyn RuntimeActionHost>` + `ActionBridge`, thread
551    //     `Some(bridge)` into `load_extensions` so every plugin's `user_data`
552    //     points at this bridge.
553    //  4. After `AgentHarness::create` succeeds, call `set_harness(&cell, …)` to
554    //     fill the host cell the bridge recovers on the first action call.
555    let runtime = tokio::runtime::Handle::try_current().map_err(|e| {
556        BuildError::HarnessCreate(format!("no tokio runtime for action bridge: {e}"))
557    })?;
558    let catalog = Vec::new();
559    let (action_host, harness_cell) = crate::extensions_actions::HarnessActionHost::new_empty(
560        catalog.clone(),
561        cwd.to_path_buf(),
562        runtime.clone(),
563        args.unknown_flags.clone(),
564        tool_context.clone(),
565    );
566    let action_host = Arc::new(
567        action_host
568            .with_session_dir(session_dir.clone())
569            .with_fresh_session_only(false)
570            .with_native_durable(args.native_durable),
571    );
572    let host_arc: Arc<dyn rpi_extensions::RuntimeActionHost> = action_host.clone();
573    // `runtime` is reused below (B5c: `PluggableProvider` needs a captured
574    // `Handle` to `spawn_blocking` the sync `ProviderRequestFn`), so clone here.
575    //
576    // B5d: build the initial bridge WITH a reload callback backed by a session-
577    // long `ReloadMailbox` (cloned into `ReloadContext` + handed to the TUI). A
578    // plugin's `runtime_action(Reload)` then signals the TUI's main loop instead
579    // of hitting the "not configured" fallback. The same mailbox is reused on
580    // `/reload` (the fresh bridge carries `ctx.mailbox`), so the bridge always
581    // points at the one TUI-installed sender across reloads.
582    let reload_mailbox = rpi_extensions::ReloadMailbox::new();
583    // Session-scoped UI-dialog mailbox (runtime action 17 / `ask_user`). The
584    // initial bridge carries it and the TUI attaches itself once it starts
585    // polling; a headless run leaves it detached so `ask_user` fails loudly
586    // instead of fabricating a user answer. The SAME mailbox is reused across
587    // `/reload` so in-flight prompts + TUI attachment survive a plugin swap.
588    let ui_dialog_mailbox = rpi_extensions::UiDialogMailbox::new();
589    // Session-scoped extension status registry (runtime action 18 / `SetStatus`).
590    // The bridge lets plugins write; the TUI polls the revision and repaints its
591    // footer. Reused across `/reload` so a plugin's status survives the swap.
592    let ext_status_mailbox = rpi_extensions::ExtensionStatusMailbox::new();
593    // Session-scoped editor-text queue (runtime action 19 / `SetEditorText`).
594    // The bridge lets a plugin drop a draft into the prompt editor; the TUI
595    // drains it each tick. Reused across `/reload` so a pending transcription
596    // survives a plugin swap.
597    let editor_text_mailbox = rpi_extensions::EditorTextMailbox::new();
598    let action_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
599        runtime.clone(),
600        host_arc,
601        rpi_extensions::reload_callback_from_mailbox(reload_mailbox.clone()),
602        ui_dialog_mailbox.clone(),
603        ext_status_mailbox.clone(),
604        editor_text_mailbox.clone(),
605    );
606
607    let extension_session = if let Some(selected) = &resource_selection {
608        let session = rpi_extensions::load_session_mixed_guarded(
609            &[],
610            &selected.extensions,
611            Arc::new(NullDiagnostics),
612            Some(Arc::clone(&action_bridge)),
613            Some(resource_leases.clone()),
614        );
615        if session.loaded_paths() != selected.extensions.as_slice() {
616            return Err(BuildError::HarnessCreate(
617                "selected native extension failed to load/register".into(),
618            ));
619        }
620        if session.owns_stdio() {
621            return Err(BuildError::HarnessCreate(
622                "stdio-owning extensions are unsupported with --resource-config".into(),
623            ));
624        }
625        session
626    } else if args.no_extensions {
627        ExtensionSession::none()
628    } else {
629        load_extensions(args, cwd, project_trusted, Some(Arc::clone(&action_bridge)))
630    };
631    if args.verbose {
632        if let Some(s) = extension_session.summary() {
633            eprintln!("extensions: {s}");
634        }
635        report_deferred_renderers(&extension_session);
636    }
637    validate_durable_extensions(&extension_session).map_err(BuildError::HarnessCreate)?;
638    // Publish the extension registry so `ListCommands` can enumerate slash
639    // commands. Done here rather than at host construction because the registry
640    // only exists after extensions load; `/reload` republishes the new snapshot
641    // via `RuntimeActionHost::publish_registry`.
642    action_host.publish_registry_impl(extension_session.snapshot_arc());
643    Ok(PreparedExtensions {
644        resource_leases,
645        resource_selection,
646        session_selection,
647        transition_session,
648        session_dir,
649        runtime,
650        tool_context,
651        action_host,
652        harness_cell,
653        reload_mailbox,
654        ui_dialog_mailbox,
655        ext_status_mailbox,
656        editor_text_mailbox,
657        action_bridge,
658        extension_session,
659    })
660}
661
662/// Build the `AgentHarness` from the resolved model + parsed args + cwd.
663///
664/// This is the v1 equivalent of TS `createAgentSession`. It:
665/// 1. Builds the `OsExecutionEnv` rooted at `cwd`.
666/// 2. Constructs the built-in tools (optionally filtered by `--tools`/
667///    `--exclude-tools`/`--no-tools`/`--no-builtin-tools`).
668/// 3. Resolves the session storage (ephemeral vs fresh JSONL vs restore-error).
669/// 4. Assembles `AgentHarnessOptions` and calls `AgentHarness::create`.
670///
671/// Returns the harness plus a `broadcast::Receiver<AgentEvent>` carrying the
672/// live `AgentEvent` stream from every run (backed by a `BroadcastEmitter`
673/// installed on the harness). Interactive mode drains this to render streaming
674/// responses; the non-interactive modes simply drop it.
675/// Returns the harness, the live `AgentEvent` broadcast receiver, and a
676/// [`ReloadContext`] the interactive TUI holds to drive `/reload` (and a
677/// plugin's `runtime_action(Reload)` via the mailbox). Non-interactive modes
678/// drop the context (no `/reload` surface in print/json mode).
679pub async fn build(
680    resolved: &ResolvedModel,
681    args: &Args,
682    cwd: &Path,
683    project_trusted: bool,
684) -> Result<
685    (
686        AgentHarness,
687        tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>,
688        ReloadContext,
689    ),
690    BuildError,
691> {
692    let prepared = prepare_extensions(args, cwd, project_trusted)?;
693    build_prepared(resolved, args, cwd, project_trusted, prepared).await
694}
695
696pub async fn build_prepared(
697    resolved: &ResolvedModel,
698    args: &Args,
699    cwd: &Path,
700    project_trusted: bool,
701    prepared: PreparedExtensions,
702) -> Result<
703    (
704        AgentHarness,
705        tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>,
706        ReloadContext,
707    ),
708    BuildError,
709> {
710    let experimental_policy = crate::native_durable::experimental_epoch::policy(args)
711        .map_err(BuildError::HarnessCreate)?;
712    let fresh_session_only = false;
713    let cwd_str = cwd.to_string_lossy().to_string();
714    // Plugin tools get the session's identity injected into every call's
715    // arguments (see `rpi_extensions::ToolCallContext`). It is created here,
716    // before the tools are built, and completed with the session id below once
717    // the session exists — the tool set has to exist before the harness does.
718    let PreparedExtensions {
719        resource_leases,
720        resource_selection,
721        session_selection: selection,
722        transition_session,
723        session_dir,
724        runtime,
725        tool_context,
726        action_host,
727        harness_cell,
728        reload_mailbox,
729        ui_dialog_mailbox,
730        ext_status_mailbox,
731        editor_text_mailbox,
732        action_bridge,
733        extension_session,
734    } = prepared;
735    let catalog = crate::provider::authenticated_catalog(resolved);
736    action_host.set_catalog(catalog.clone());
737
738    // ---- Execution env + tools ----
739    let env = Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf()));
740    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
741    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
742    let _registry = Arc::new(MutationQueueRegistry::new());
743    // `env_dyn` is shared between the tool context (moved in) and the resource
744    // loaders below (borrowed); clone one branch so both hold a reference.
745    let file_io = Arc::new(rpi_tools::file_io::FileIORouter::new());
746    let ctx =
747        ExecutionToolContext::new(env_dyn.clone(), Some(mut_env)).with_file_io(file_io.clone());
748
749    validate_durable_extensions(&extension_session).map_err(BuildError::HarnessCreate)?;
750    let durable_binding = Arc::new(std::sync::OnceLock::new());
751    let mut tools = build_tools_bound(&ctx, args, durable_binding.clone());
752
753    // ---- Extensions (Part B2) ----
754    // Load cdylib plugins from the resolved extension dirs, merge their tools
755    // into the built-in set (extension overrides same-named built-in; first-
756    // extension-wins across plugins; explicit `--tools`/`--exclude-tools` still
757    // apply to the merged set), and keep the loaded `Library` handles alive for
758    // the harness lifetime via the returned session guard. `--no-extensions`
759    // skips discovery entirely (no dirs scanned, no plugins loaded).
760    merge_extension_tools(&mut tools, &extension_session, args, &tool_context);
761    let active = if let Some(selected) = &resource_selection {
762        selected
763            .active_tools(
764                &tools
765                    .iter()
766                    .map(|t| t.tool.schema().name.clone())
767                    .collect::<Vec<_>>(),
768            )
769            .map_err(BuildError::HarnessCreate)?
770    } else {
771        filter_active_tool_names(active_tool_names(&tools, args), args)
772    };
773
774    // ---- Session storage ----
775    // The root is the one `prepare_extensions` froze at startup, never a fresh
776    // `configured_session_dir(args, cwd)`: settings and `RPI_CODING_AGENT_SESSION_DIR`
777    // can change while extensions load, and an adopted session cwd would point
778    // at another project's tree. Both the cwd peek and this build must read the
779    // same root, so the caller pins it into `args` before either runs.
780    let session = match transition_session {
781        Some(session) => session,
782        None => build_session(&selection, &cwd_str, resource_selection.as_ref()).await?,
783    };
784    crate::resource_selection::bind_session(&session, resource_selection.as_ref())
785        .await
786        .map_err(BuildError::SessionOpen)?;
787    // Plugin tools now know which session they serve: `todo` and friends key
788    // their per-session state off it. A session without an id (ephemeral) leaves
789    // the field unset and a plugin is expected to fall back to project scope.
790    if let Ok(metadata) = session.get_metadata().await {
791        publish_session_identity(&tool_context, &metadata.id);
792    }
793    // `--name`/`-n` sets the session display name durably (a `name` fact in the
794    // log). It applies to whichever session this launch works in — a fresh one
795    // or a restored one — and an empty value clears a previous name. This is the
796    // only place the flag is applied: `SessionSelection::New` carries it, but
797    // builds that do not create a session (restore/fork) must still honor it.
798    if let Some(requested) = args.name.as_deref() {
799        let name = requested.trim();
800        let name = if name.is_empty() { None } else { Some(name) };
801        if let Err(error) = session.set_name(name).await {
802            if fresh_session_only {
803                return Err(BuildError::SessionOpen(format!(
804                    "native session name persistence failed: {error}"
805                )));
806            }
807            if args.verbose {
808                eprintln!("warning: could not set session name: {error}");
809            }
810        }
811    }
812    // ---- System prompt base (precedence: --system-prompt > SYSTEM.md > default) ----
813    // Mirrors pi `discoverSystemPromptFile` (`resource-loader.ts:1022-1034`):
814    // an explicit `--system-prompt` flag wins; otherwise a discovered
815    // `<cwd>/.rpi/SYSTEM.md` wins, then
816    // `<agent_dir>/SYSTEM.md`.
817    // (global); otherwise the built-in default. **Project-wins** — the same
818    // direction as skills/prompts precedence.
819    // Whether this model sees its own prior reasoning again decides how the
820    // working-state rule is worded (see `default_system_prompt`).
821    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&resolved.model);
822    let prompt_tools = active.clone();
823    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
824    let default_prompt = || {
825        default_system_prompt_with_tool_prompts(
826            &cwd_str,
827            prior_reasoning_replayed,
828            &prompt_tools,
829            &prompt_metadata,
830        )
831    };
832    let mut context_paths = Vec::new();
833    let base_prompt = match args.system_prompt.as_deref() {
834        Some(explicit) => explicit.to_string(),
835        None if project_trusted && resource_selection.is_none() => {
836            match discover_system_prompt_file(cwd) {
837                Some(path) => {
838                    read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
839                }
840                None => default_prompt(),
841            }
842        }
843        None => default_prompt(),
844    };
845
846    // ---- Append-text sources (precedence: --append-system-prompt > APPEND_SYSTEM.md) ----
847    // Mirrors pi `appendSystemPrompt` (`resource-loader.ts:525-542`). Explicit
848    // `--append-system-prompt` flags are joined together; when none are given, a
849    // discovered `APPEND_SYSTEM.md` (project-wins over global) provides the
850    // append text. `--append-system-prompt` takes a value that may be a literal
851    // string OR a readable file path (mirrors TS `resolvePromptInput`).
852    let mut append_texts: Vec<String> = Vec::new();
853    for extra in &args.append_system_prompt {
854        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
855        append_texts.push(text);
856    }
857    if let Some(selected) = &resource_selection {
858        append_texts.extend(
859            selected
860                .instructions
861                .iter()
862                .map(|(_, _, text)| text.clone()),
863        );
864    }
865    if args.append_system_prompt.is_empty() && resource_selection.is_none() {
866        if let Some(path) = project_trusted
867            .then(|| discover_append_system_prompt_file(cwd))
868            .flatten()
869        {
870            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
871                append_texts.push(text);
872            }
873        }
874    }
875    let append_join = if append_texts.is_empty() {
876        None
877    } else {
878        Some(append_texts.join("\n\n"))
879    };
880
881    // ---- Resource discovery (skills + prompt-templates + context-files) ----
882    // The env is OS-backed, rooted at cwd. Each `--no-*` flag suppresses its
883    // channel independently (pi parity). Skills/prompts load project→global,
884    // explicit/plugin paths, then static packages; dedupe first-wins-by-name
885    // keeps project and user resources ahead of packages. Context files walk
886    // global→ancestor(cwd→root), deepest-last (pi parity).
887    //
888    // **Trust gate (v1 divergence):** pi gates project config discovery on
889    // `isProjectTrusted()` (global resources are unconditional). rpi v1 has no
890    // trust prompt — project resources are discovered unconditionally (a copied
891    // `.rpi/` dir drops in and works). Full trust gating is deferred.
892    let agent_dir = crate::config::agent_dir().ok();
893
894    // ---- B5b: extension resources_discover ----
895    // If any plugin registered a `resources_discover` handler, fan the event out
896    // (reason "startup") and collect skill/prompt/theme paths. These plugin-
897    // contributed paths merge WITH the static Part-A dirs (project
898    // `.rpi/skills` +
899    // `agent_dir/skills`, etc.) and the loaders re-run over the union — the
900    // coherence point: a plugin's discovered skills land through the SAME loaders
901    // as static skills. Static dirs load FIRST so project skills keep winning name
902    // collisions (a plugin must not shadow a project skill of the same name —
903    // mirrors pi `extendResources` running AFTER the default load's first-wins
904    // map). `load_skills` now accepts both dirs and individual `.md` files, so a
905    // plugin returning bare `SKILL.md` paths loads them (the gap this closes).
906    // Theme paths are available to the TUI through the package resource list;
907    // skill/prompt loaders are the only resources needed by the harness here.
908    // A `--no-*` flag suppresses its channel for BOTH static and discovered paths.
909    let discovered = extension_session
910        .snapshot_arc()
911        .filter(|_| resource_selection.is_none())
912        .map(|snap| emit_resources_discover(&cwd_str, "startup", &snap))
913        .unwrap_or_default();
914
915    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
916    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
917    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
918    if let Some(selected) = &resource_selection {
919        // Consume the preflight's parsed resources, never rediscover or reread
920        // selected Skills after executable registration / writer opening.
921        skills = selected
922            .validated_skills()
923            .map_err(BuildError::HarnessCreate)?
924            .skills
925            .clone();
926    } else if !args.no_skills {
927        let mut dirs = if args.dev_local_only || args.project_only {
928            project_skill_dirs(cwd)
929        } else if project_trusted {
930            skill_dirs(cwd)
931        } else {
932            global_skill_dirs()
933        };
934        dirs.extend(args.skill.iter().cloned());
935        dirs.extend(discovered.skill_paths.iter().map(PathBuf::from));
936        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
937        skills = result.skills;
938        skill_diags = result.diagnostics;
939        resource_diags.extend(result.resource_diagnostics);
940    }
941
942    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
943    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
944    if !args.no_prompt_templates && resource_selection.is_none() {
945        let mut dirs = if args.dev_local_only || args.project_only {
946            project_prompt_template_dirs(cwd)
947        } else if project_trusted {
948            prompt_template_dirs(cwd)
949        } else {
950            global_prompt_template_dirs()
951        };
952        dirs.extend(args.prompt_template.iter().cloned());
953        dirs.extend(discovered.prompt_paths.iter().map(PathBuf::from));
954        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
955        prompt_templates = result.prompt_templates;
956        prompt_diags = result.diagnostics;
957        resource_diags.extend(result.resource_diagnostics);
958    }
959
960    let context_block = if args.no_context_files || !project_trusted || resource_selection.is_some()
961    {
962        String::new()
963    } else {
964        // `load_project_context_files` walks the global agentDir first then
965        // ancestor-walks cwd→root (deepest last). It needs a real agent_dir; if
966        // none is resolvable, pass the cwd dir so only the ancestor-walk runs
967        // (the global step returns None anyway).
968        let agent_dir_path = agent_dir.clone().unwrap_or_else(|| cwd.to_path_buf());
969        let files = load_project_context_files(&env_dyn, cwd, &agent_dir_path).await;
970        context_paths.extend(
971            files
972                .iter()
973                .map(|file| file.path.to_string_lossy().into_owned()),
974        );
975        format_project_context(&files)
976    };
977
978    // Surface resource-discovery diagnostics as startup warnings (verbose-only).
979    if args.verbose {
980        for d in &skill_diags {
981            eprintln!(
982                "warning: skill {} ({}): {}",
983                d.path,
984                d.code.as_str(),
985                d.message
986            );
987        }
988        for d in &prompt_diags {
989            eprintln!(
990                "warning: prompt template {} ({}): {}",
991                d.path,
992                d.code.as_str(),
993                d.message
994            );
995        }
996        // Structured collisions: make the winner/loser explicit.
997        for d in &resource_diags {
998            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
999                eprintln!(
1000                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
1001                    c.resource_type.as_str(),
1002                    c.name,
1003                    c.winner_path,
1004                    c.loser_path
1005                );
1006            }
1007        }
1008    }
1009
1010    // ---- Compose the full system prompt ----
1011    // Order mirrors pi `buildSystemPrompt` (`system-prompt.ts:28-72`):
1012    // base → append → context → skills. The skills listing is the harness's own
1013    // section: `AgentHarness::compose_prompt` appends `<available_skills>` (gated
1014    // on the `read` tool + `disable_model_invocation`, applied inside
1015    // `format_skills_for_system_prompt`). So we pass None for skills here (the
1016    // harness adds the listing itself) and fold only base+append+context into
1017    // the prompt we hand the harness.
1018    let system_prompt = compose_system_prompt(
1019        Some(&base_prompt),
1020        &[], // skills: harness appends the listing itself
1021        if context_block.is_empty() {
1022            None
1023        } else {
1024            Some(&context_block)
1025        },
1026        append_join.as_deref(),
1027    );
1028
1029    // ---- Debug: dump the resolved system-prompt sections (verification) ----
1030    // A verification affordance for Part-A resource discovery: prints the
1031    // composed sections + resource counts to stderr so a smoke can confirm
1032    // `<available_skills>` + `<project_context>` + appended text reached the
1033    // prompt without parsing a provider round-trip. The harness composes the
1034    // final prompt (base → append → context → skills); here we print the
1035    // pre-harness sections (the harness adds the skills listing itself, gated
1036    // on `read` + `disable_model_invocation`).
1037    if args.debug_system_prompt {
1038        eprintln!("=== --debug-system-prompt ===");
1039        let base_src = if args.system_prompt.is_some() {
1040            "--system-prompt"
1041        } else if discover_system_prompt_file(cwd).is_some() {
1042            "SYSTEM.md"
1043        } else {
1044            "default"
1045        };
1046        eprintln!("[base source: {base_src}]");
1047        eprintln!("--- base ---\n{base_prompt}");
1048        if let Some(append) = append_join.as_deref() {
1049            eprintln!("--- append ---\n{append}");
1050        } else {
1051            eprintln!("--- append: (none) ---");
1052        }
1053        if context_block.is_empty() {
1054            eprintln!("--- context: (none) ---");
1055        } else {
1056            eprintln!("--- context ---{context_block}");
1057        }
1058        let visible_skills = skills
1059            .iter()
1060            .filter(|s| s.disable_model_invocation != Some(true))
1061            .count();
1062        eprintln!(
1063            "--- skills: {} loaded ({} model-visible, {} hidden) ---",
1064            skills.len(),
1065            visible_skills,
1066            skills.len() - visible_skills
1067        );
1068        for s in &skills {
1069            let hidden = if s.disable_model_invocation == Some(true) {
1070                " [hidden]"
1071            } else {
1072                ""
1073            };
1074            eprintln!("    {}{hidden} — {}", s.name, s.description);
1075        }
1076        eprintln!("--- prompt templates: {} ---", prompt_templates.len());
1077        for t in &prompt_templates {
1078            eprintln!("    /{}", t.name);
1079        }
1080        // B5b: surface plugin-contributed discovery paths so a smoke can confirm
1081        // the resources_discover round-trip fed the loaders; package themes are
1082        // selected by the TUI rather than injected into the harness prompt.
1083        eprintln!(
1084            "--- discovered via resources_discover: {} skill(s), {} prompt(s), {} theme(s) ---",
1085            discovered.skill_paths.len(),
1086            discovered.prompt_paths.len(),
1087            discovered.theme_paths.len(),
1088        );
1089        for p in &discovered.skill_paths {
1090            eprintln!("    skill: {p}");
1091        }
1092        for p in &discovered.prompt_paths {
1093            eprintln!("    prompt: {p}");
1094        }
1095        eprintln!(
1096            "--- final composed base+append+context (skills listing added by harness) ---\n{system_prompt}"
1097        );
1098        eprintln!("=== end --debug-system-prompt ===");
1099    }
1100
1101    // ---- Options ----
1102    // Install a BroadcastEmitter so the caller (the interactive TUI) can drain
1103    // AgentEvents live as a run unfolds. The corresponding broadcast::Receiver
1104    // is returned alongside the harness; non-interactive modes simply drop it.
1105    let (broadcast, event_rx) = rpi_agent::events::BroadcastEmitter::new(256);
1106    let broadcast_emitter: Arc<dyn rpi_agent::AgentEmitter> = Arc::new(broadcast);
1107    // The broadcast half stays live for the whole session (the TUI's drain task
1108    // holds the receiver); reload re-wraps it in a fresh `TeeEmitter`, so keep
1109    // a clone for the `ReloadContext` before the tee match consumes the original.
1110    let broadcast_for_context: Arc<dyn rpi_agent::AgentEmitter> = Arc::clone(&broadcast_emitter);
1111
1112    // ---- Extensions emitter (Part B3a) ----
1113    // If extensions loaded + registered any `on()` handlers, wrap the
1114    // broadcast emitter in a `TeeEmitter` so every `AgentEvent` flows to BOTH
1115    // the TUI (via the broadcast receiver above) AND the plugin handlers (via
1116    // the `ExtensionEmitter`, which translates each `AgentEvent` →
1117    // `StablePluginEvent` and fans out to the handlers registered for its tag).
1118    // With no extensions the tee degrades to the bare broadcast emitter (a
1119    // one-child passthrough), so the TUI path is unchanged.
1120    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
1121        Some(snapshot) => {
1122            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
1123            Arc::new(TeeEmitter::new(vec![broadcast_emitter, Arc::new(ext)]))
1124        }
1125        None => broadcast_emitter,
1126    };
1127
1128    // Saved user defaults. Best-effort: a missing or malformed file must not stop
1129    // a session from starting, and every accessor falls back to the harness
1130    // default when its key is absent.
1131    let saved_settings = crate::settings::load_settings().unwrap_or_default();
1132
1133    // `httpProxy` applies to rpi's own HTTP clients. Setting the environment is how
1134    // they are configured (`pi-ai/src/http.rs`), and upstream does the same thing
1135    // with this key — an explicit environment variable still wins, so a shell-level
1136    // proxy override is not silently replaced by the setting.
1137    if let Some(proxy) = &saved_settings.http_proxy {
1138        for key in ["HTTP_PROXY", "HTTPS_PROXY"] {
1139            if std::env::var_os(key).is_none() {
1140                std::env::set_var(key, proxy);
1141            }
1142        }
1143    }
1144
1145    // Share the live session cell with both /reload and the approval hook.
1146    // The hook is installed only when the current snapshot has a tool-call
1147    // handler; a later reload rebuilds the hook state together with the
1148    // extension session.
1149    let extension_session_cell = Arc::new(Mutex::new(extension_session.clone()));
1150    // Only install the approval hook when a plugin actually registered a
1151    // tool-call handler. An extension session may contain flags/resources but
1152    // no handler; dispatching through that empty session needlessly crosses
1153    // the plugin bridge and can leave a headless RPC tool call waiting.
1154    let before_tool_call = extension_session
1155        .snapshot()
1156        .filter(|snapshot| {
1157            !snapshot
1158                .handlers_for(rpi_plugin_sdk::EventTag::ToolCall)
1159                .is_empty()
1160        })
1161        .map(|_| {
1162            extension_tool_call_hook(
1163                Arc::clone(&extension_session_cell),
1164                ui_dialog_mailbox.clone(),
1165            )
1166        });
1167
1168    let options = AgentHarnessOptions {
1169        model: resolved.model.clone(),
1170        thinking_level: resolved.thinking_level,
1171        active_tool_names: active.clone(),
1172        tools,
1173        system_prompt: Some(system_prompt),
1174        resources: AgentHarnessResources {
1175            context_files: context_paths,
1176            skills: if skills.is_empty() {
1177                None
1178            } else {
1179                Some(skills)
1180            },
1181            prompt_templates: if prompt_templates.is_empty() {
1182                None
1183            } else {
1184                Some(prompt_templates)
1185            },
1186        },
1187        // A restored session (--continue/--resume/--session) already has
1188        // records — let the harness load it and keep appending.
1189        allow_existing_session: matches!(
1190            selection,
1191            SessionSelection::Latest { .. }
1192                | SessionSelection::ById { .. }
1193                | SessionSelection::ByExactId { .. }
1194                | SessionSelection::Fork { .. }
1195        ),
1196        require_native_durable: args.native_durable,
1197        stream_options: AgentHarnessStreamOptions {
1198            timeout: args.timeout,
1199            stream_idle_timeout: args.stream_idle_timeout.or_else(|| {
1200                saved_settings
1201                    .stream_idle_timeout
1202                    .map(std::time::Duration::from_secs)
1203            }),
1204            thinking_budgets: saved_settings.thinking_budgets,
1205            ..Default::default()
1206        },
1207        // Settings-backed harness options: upstream lets users tune retry,
1208        // compaction and queue drain modes from settings.json. Global only,
1209        // matching how `defaultTools` and the other settings-backed options in
1210        // this file are read.
1211        retry: saved_settings.retry_policy(),
1212        compaction: saved_settings.compaction_settings(),
1213        steering_mode: saved_settings.steering_mode(),
1214        follow_up_mode: saved_settings.follow_up_mode(),
1215        tool_execution: HarnessToolExecution::default(),
1216        drive: DrivingMode::default(),
1217        session,
1218        // B5c: inject the resolved gateway provider PLUS one `Arc<dyn Provider>`
1219        // per registered extension provider (`PluggableProvider` wraps a plugin's
1220        // sync `ProviderRequestFn`). The harness's `build_stream_fn` resolves a
1221        // provider lazily per call by `models.iter().find(|p| p.id() == model.provider)`,
1222        // so a catalog model whose `provider` matches an extension provider's id
1223        // routes to it. Extension providers land AFTER the gateway so the gateway
1224        // stays first-match for its own ids (first-wins on a `.find`).
1225        models: build_models_with_extensions(resolved, &extension_session, runtime.clone()),
1226        to_provider_messages: None,
1227        entry_projectors: Default::default(),
1228        agent_emitter: Some(emitter),
1229        // B3b loop hooks. `before_tool_call` dispatches the pi `on("tool_call")`
1230        // extension event and honors a veto (a permission gate can block a tool
1231        // before it runs). 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. Stdio ownership is independent: adapters such as ACP and
2591/// Web use it only to keep their protocol/server lifecycle alive while the
2592/// native host still owns session durability.
2593fn validate_durable_extensions(session: &ExtensionSession) -> Result<(), String> {
2594    if let Some(snapshot) = session.snapshot() {
2595        if reserved_durable_name(
2596            snapshot.tools().iter().map(|tool| tool.tool.name.as_str()),
2597            snapshot
2598                .commands()
2599                .iter()
2600                .map(|command| command.name.as_str()),
2601        ) {
2602            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());
2603        }
2604    }
2605    Ok(())
2606}
2607
2608fn reserved_durable_name<'a>(
2609    mut tools: impl Iterator<Item = &'a str>,
2610    mut commands: impl Iterator<Item = &'a str>,
2611) -> bool {
2612    tools.any(|name| name == "durable")
2613        || commands.any(|name| name.trim_start_matches('/') == "durable")
2614}
2615
2616#[cfg(test)]
2617#[path = "native_durable/session_tests.rs"]
2618mod native_durable_session_tests;
2619
2620/// Merge extension tools into the built-ins. Ordinarily extensions override
2621/// same-named built-ins (first extension wins); host-reserved durable names
2622/// were already checked above. Both tool filters still apply to the merged set.
2623fn merge_extension_tools(
2624    tools: &mut Vec<HarnessTool>,
2625    session: &ExtensionSession,
2626    args: &Args,
2627    tool_context: &rpi_extensions::ToolCallContext,
2628) {
2629    let Some(snapshot) = session.snapshot() else {
2630        return;
2631    };
2632    for et in snapshot.tools() {
2633        let name = &et.tool.name;
2634        if !tool_name_allowed(name, args) {
2635            continue;
2636        }
2637        let adapter = PluginToolAdapter::new(et.tool.clone(), et.handle(), session.keepalive())
2638            .with_context(tool_context.clone());
2639        let harness_tool = HarnessTool::new(Arc::new(adapter));
2640        match tools.iter_mut().find(|t| t.tool.schema().name == *name) {
2641            Some(slot) => *slot = harness_tool,
2642            None => tools.push(harness_tool),
2643        }
2644    }
2645}
2646
2647/// Build the tool list per `--tools`/`--exclude-tools`/`--no-tools`/
2648/// `--no-builtin-tools`. Mirrors the TS `tools`/`excludeTools`/`noTools`
2649/// resolution in `createAgentSession`.
2650/// Default bash timeout: 120s when the model doesn't pass one (prevents a
2651/// forgotten `timeout` from hanging the run forever — the "卡住" report).
2652/// `RPI_BASH_TIMEOUT` overrides; a model-supplied timeout always wins.
2653pub fn bash_options() -> rpi_tools::tools::bash::BashToolOptions {
2654    use rpi_tools::tools::bash::BashToolOptions;
2655    let default = std::env::var("RPI_BASH_TIMEOUT")
2656        .ok()
2657        .and_then(|v| v.parse::<f64>().ok())
2658        .unwrap_or(rpi_tools::tools::bash::DEFAULT_BASH_TIMEOUT_SECONDS);
2659    // Saved user defaults, matching how `defaultTools` is read in `build_tools`.
2660    // `shellCommandPrefix` is prepended to every command (upstream's key for
2661    // alias/`shopt` setup). Native's `shellPath` is *not* wired: neither
2662    // `BashToolOptions` nor `ShellCaptureOptions` carries a shell binary today, so
2663    // honouring it means plumbing one through pi-tools first.
2664    let settings = crate::settings::load_settings().unwrap_or_default();
2665    BashToolOptions {
2666        command_prefix: settings.shell_command_prefix.clone(),
2667        default_timeout: Some(default),
2668        prepare: None,
2669    }
2670}
2671
2672#[cfg(test)]
2673fn build_tools(ctx: &ExecutionToolContext, args: &Args) -> Vec<HarnessTool> {
2674    build_tools_bound(ctx, args, Arc::new(std::sync::OnceLock::new()))
2675}
2676
2677fn build_tools_bound(
2678    ctx: &ExecutionToolContext,
2679    args: &Args,
2680    durable_binding: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
2681) -> Vec<HarnessTool> {
2682    if args.no_tools {
2683        return Vec::new();
2684    }
2685    // Keep the coding tools aligned with Pi and expose rpi's read-only docs
2686    // lookup as a default assistant capability.
2687    //
2688    // Replay policy (native `ToolDeclaration.replay`): only tools that are
2689    // genuinely free of side effects may be re-run when a crash leaves their
2690    // outcome unknown — everything else must stay `Never`, because replaying
2691    // `bash`/`write`/`edit` would duplicate a side effect. `HarnessTool::new`
2692    // already defaults to `Never`, so this is opt-in per read-only tool.
2693    let mut all: Vec<(&'static str, HarnessTool)> = vec![
2694        (
2695            "read",
2696            HarnessTool::new(create_read_tool(
2697                ctx,
2698                Some(rpi_tools::tools::read::ReadToolOptions {
2699                    image_processor: Some(Arc::new(
2700                        rpi_tools::image_processing::InlineImageProcessor,
2701                    )),
2702                    ..Default::default()
2703                }),
2704            ))
2705            .with_replay(ToolReplay::Safe),
2706        ),
2707        (
2708            "bash",
2709            HarnessTool::new(create_bash_tool(ctx, Some(bash_options()))),
2710        ),
2711        ("edit", HarnessTool::new(create_edit_tool(ctx))),
2712        ("write", HarnessTool::new(create_write_tool(ctx))),
2713        (
2714            "docs",
2715            HarnessTool::new(create_docs_tool()).with_replay(ToolReplay::Safe),
2716        ),
2717    ];
2718
2719    if args.native_durable {
2720        // Mixed read/write tool is NEVER safe for automatic replay.
2721        all.push((
2722            "durable",
2723            HarnessTool::new(Arc::new(crate::native_durable::NativeDurableTool::new(
2724                durable_binding,
2725            ))),
2726        ));
2727    }
2728
2729    // Add PowerShell tool on Windows
2730    #[cfg(target_os = "windows")]
2731    all.push(("powershell", HarnessTool::new(create_powershell_tool(ctx))));
2732
2733    // Apply default_tools from settings (if no CLI override)
2734    if args.tools.is_none() && args.resource_config.is_none() && args.resource_transition.is_none()
2735    {
2736        if let Ok(settings) = crate::settings::load_settings() {
2737            if let Some(default_tools) = &settings.default_tools {
2738                all.retain(|(name, _)| default_tools.iter().any(|t| t == name));
2739            }
2740        }
2741    }
2742
2743    // `--no-builtin-tools` disables the built-in set but would keep
2744    // extension/custom tools — v1 has none, so it's equivalent to `--no-tools`
2745    // here. We honor it by clearing the built-ins.
2746    if args.no_builtin_tools {
2747        all.clear();
2748    }
2749
2750    // Allowlist (`--tools`): keep only named built-ins.
2751    if let Some(allow) = &args.tools {
2752        all.retain(|(name, _)| allow.iter().any(|a| a == name));
2753    }
2754    // Denylist (`--exclude-tools`): drop named tools.
2755    if let Some(deny) = &args.exclude_tools {
2756        all.retain(|(name, _)| !deny.iter().any(|d| d == name));
2757    }
2758
2759    all.into_iter().map(|(_, t)| t).collect()
2760}
2761
2762/// Resolve the active tool names from the constructed tools when no explicit
2763/// `--tools` allowlist was given. Mirrors the TS default: all registered tools
2764/// active.
2765fn active_tool_names(tools: &[HarnessTool], args: &Args) -> Vec<String> {
2766    filter_active_tool_names(
2767        tools.iter().map(|tool| tool.tool.schema().name.clone()),
2768        args,
2769    )
2770}
2771
2772/// Whether a tool name survives the command-line tool policy. Keep this check
2773/// centralized so extension-provided tools honor the same policy as built-ins.
2774pub(crate) fn tool_name_allowed(name: &str, args: &Args) -> bool {
2775    if args.no_tools {
2776        return false;
2777    }
2778    if args
2779        .tools
2780        .as_ref()
2781        .is_some_and(|allow| !allow.iter().any(|value| value == name))
2782    {
2783        return false;
2784    }
2785    if args
2786        .exclude_tools
2787        .as_ref()
2788        .is_some_and(|deny| deny.iter().any(|value| value == name))
2789    {
2790        return false;
2791    }
2792    true
2793}
2794
2795pub(crate) fn filter_active_tool_names<I>(names: I, args: &Args) -> Vec<String>
2796where
2797    I: IntoIterator<Item = String>,
2798{
2799    names
2800        .into_iter()
2801        .filter(|name| tool_name_allowed(name, args))
2802        .collect()
2803}
2804
2805/// Build the `Session` facade for the chosen selection.
2806async fn build_session(
2807    selection: &SessionSelection,
2808    cwd: &str,
2809    selected: Option<&crate::resource_selection::ResolvedSelection>,
2810) -> Result<Session, BuildError> {
2811    match selection {
2812        SessionSelection::Ephemeral => Ok(ephemeral_session()),
2813        SessionSelection::New { dir, .. } => {
2814            // Ensure the sessions directory exists, then create a fresh JSONL
2815            // session file inside it.
2816            std::fs::create_dir_all(dir)
2817                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2818            let session = create_jsonl_session(dir, cwd)
2819                .await
2820                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2821            Ok(session)
2822        }
2823        SessionSelection::Latest { .. }
2824        | SessionSelection::ById { .. }
2825        | SessionSelection::ByExactId { .. } => restore_session(selection, cwd).await,
2826        SessionSelection::Fork { source, dir } => {
2827            fork_session_at_launch(source, dir, cwd, selected).await
2828        }
2829    }
2830}
2831
2832/// Open an existing JSONL session for `Latest` / `ById`. Mirrors the TS
2833/// `SessionManager.resume`/`open` flow: list the session dir (newest-first),
2834/// match the request, then open the matched file and wrap it in a `Session`
2835/// facade. The restored transcript renders into the TUI at startup and the
2836/// harness continues appending to the same file.
2837async fn restore_session(selection: &SessionSelection, cwd: &str) -> Result<Session, BuildError> {
2838    // `resolve_restore_target` is newest-first; `Latest` takes the head, `ById`
2839    // matches the id exactly or by file-name containment (so `--session 01a02…`
2840    // or a partial id works, mirroring the TS id/path matching).
2841    let Some(meta) = resolve_restore_target(selection, cwd).await? else {
2842        return match selection {
2843            // Exact id match only (pi `--session-id`): a missing session is
2844            // created fresh under the selected dir instead of an error.
2845            SessionSelection::ByExactId { id, dir } => {
2846                std::fs::create_dir_all(dir)
2847                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2848                create_jsonl_session_with_id(dir, cwd, Some(id.clone()))
2849                    .await
2850                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))
2851            }
2852            SessionSelection::Latest { dir } => Err(BuildError::SessionNotFound {
2853                requested: "the most recent session".to_string(),
2854                dir: dir.display().to_string(),
2855            }),
2856            SessionSelection::ById { id, dir } => Err(BuildError::SessionNotFound {
2857                requested: format!("session {id}"),
2858                dir: dir.display().to_string(),
2859            }),
2860            _ => unreachable!("resolve_restore_target only returns None for restore selections"),
2861        };
2862    };
2863    let sessions_root = selection_dir(selection);
2864    open_session(&meta, cwd, &sessions_root)
2865        .await
2866        .map(|restored| restored.session)
2867}
2868
2869/// The sessions root a selection was resolved against.
2870fn selection_dir(selection: &SessionSelection) -> PathBuf {
2871    match selection {
2872        SessionSelection::Ephemeral => PathBuf::new(),
2873        SessionSelection::New { dir, .. }
2874        | SessionSelection::Latest { dir }
2875        | SessionSelection::ById { dir, .. }
2876        | SessionSelection::ByExactId { dir, .. }
2877        | SessionSelection::Fork { dir, .. } => dir.clone(),
2878    }
2879}
2880
2881/// Resolve the metadata a restore selection names, without opening the file.
2882///
2883/// Shared by the startup build ([`restore_session`]) and the cwd peek
2884/// ([`peek_restored_session_cwd`]) so the two can never disagree about which
2885/// session a launch restores. Pure listing + matching: no session lock is
2886/// claimed and nothing is created.
2887async fn resolve_restore_target(
2888    selection: &SessionSelection,
2889    cwd: &str,
2890) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
2891    match selection {
2892        SessionSelection::Latest { dir } => {
2893            let metas = list_session_metadata_in_dir(cwd, dir).await?;
2894            Ok(first_resumable_session(&metas).cloned())
2895        }
2896        SessionSelection::ById { id, dir } => find_session_metadata(id, cwd, dir).await,
2897        SessionSelection::ByExactId { id, dir } => {
2898            let metas = list_session_metadata_in_dir(cwd, dir).await?;
2899            Ok(metas.into_iter().find(|m| m.id == *id))
2900        }
2901        SessionSelection::Fork { .. }
2902        | SessionSelection::New { .. }
2903        | SessionSelection::Ephemeral => Ok(None),
2904    }
2905}
2906
2907/// The metadata of the session whose id matches exactly or by file-name
2908/// containment (so `--session 01a02…` / a partial id / a full file name all
2909/// work), or `None` when nothing matches.
2910async fn find_session_metadata(
2911    id: &str,
2912    cwd: &str,
2913    dir: &Path,
2914) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
2915    let metas = list_session_metadata_in_dir(cwd, dir).await?;
2916    Ok(metas
2917        .into_iter()
2918        .find(|m| m.id == id || m.path.contains(id) || id.contains(&m.id)))
2919}
2920
2921/// What a launch that would restore a session says about the working directory.
2922pub(crate) struct RestoredSessionCwd {
2923    /// The id of the session this launch will restore. The host pins it into
2924    /// `args` so the later build opens exactly this session — a directory
2925    /// listing taken twice can disagree (another `rpi` may write a newer
2926    /// session in between), and adopting one session's directory while opening
2927    /// another is the very bug this restores.
2928    pub id: String,
2929    /// The directory recorded in the session header.
2930    pub recorded: PathBuf,
2931    /// `Some` when the recorded directory still exists and the run adopts it;
2932    /// `None` when the caller must fall back to the launch cwd and say so.
2933    pub adopted: Option<PathBuf>,
2934}
2935
2936/// The working directory the launch's restored session was created in, resolved
2937/// WITHOUT opening, locking, or creating anything.
2938///
2939/// Read-only by design: this runs before trust resolution and extension
2940/// preparation, where a failure must not take the run down — the real open
2941/// happens later and surfaces its own errors. Returns `None` when the selection
2942/// is not a restore (fresh/ephemeral/fork) or cannot be resolved.
2943pub(crate) async fn peek_restored_session_cwd(
2944    selection: &SessionSelection,
2945    launch_cwd: &Path,
2946) -> Option<RestoredSessionCwd> {
2947    let cwd_str = launch_cwd.to_string_lossy().into_owned();
2948    let meta = resolve_restore_target(selection, &cwd_str).await.ok()??;
2949    let recorded = PathBuf::from(&meta.cwd);
2950    if recorded.as_os_str().is_empty() {
2951        return None;
2952    }
2953    Some(RestoredSessionCwd {
2954        id: meta.id,
2955        adopted: crate::session_cwd::resolve_session_cwd(&recorded),
2956        recorded,
2957    })
2958}
2959
2960/// Pin a peeked restore target into `args` so the later build opens exactly the
2961/// session the peek inspected.
2962///
2963/// `Latest` (`-c`) re-lists the session directory when the build runs, and
2964/// another `rpi` may have written a newer session in between. Adopting one
2965/// session's working directory while opening a different conversation would put
2966/// the tools in a directory that conversation never used — the exact failure
2967/// this adoption exists to prevent. Pinning the resolved id turns the second
2968/// listing into an exact match instead of a fresh "newest" choice.
2969pub(crate) fn pin_restored_selection(args: &mut Args, restored: &RestoredSessionCwd) {
2970    args.continue_session = false;
2971    args.resume = false;
2972    args.session = Some(restored.id.clone());
2973}
2974
2975/// `--fork <path|id>`: open the source session, fork it into a new JSONL
2976/// session (records the parent id), and start in the fork.
2977async fn fork_session_at_launch(
2978    source: &str,
2979    dir: &Path,
2980    cwd: &str,
2981    selected: Option<&crate::resource_selection::ResolvedSelection>,
2982) -> Result<Session, BuildError> {
2983    use rpi_harness::session::jsonl::{
2984        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
2985    };
2986    use rpi_harness::session::types::{ForkOptions, SessionStorage};
2987    use rpi_tools::FileSystem;
2988
2989    let dir = dir.to_path_buf();
2990    std::fs::create_dir_all(&dir)
2991        .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
2992    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
2993    let fs: Arc<dyn FileSystem> = env.clone();
2994    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
2995        fs: fs.clone(),
2996        sessions_root: dir.to_string_lossy().into_owned(),
2997        clock: Arc::new(SystemClock),
2998        ids: Arc::new(DefaultIdGenerator::new()),
2999    });
3000    // A session file given by path forks from wherever it lives (pi parity:
3001    // `pi --fork <file>` takes any session file); an id or a name fragment is
3002    // looked up in the session directory.
3003    let source_meta = match session_metadata_at(Path::new(source)) {
3004        Some(meta) => meta,
3005        None => {
3006            let metas = repo
3007                .list_typed(&rpi_harness::session::jsonl::JsonlSessionListOptions::default())
3008                .await
3009                .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")))?;
3010            metas
3011                .into_iter()
3012                .find(|m| m.id == *source || m.path.contains(source) || source.contains(&m.id))
3013                .ok_or_else(|| BuildError::SessionNotFound {
3014                    requested: format!("--fork {source}"),
3015                    dir: dir.display().to_string(),
3016                })?
3017        }
3018    };
3019    let fork_storage = repo
3020        .fork_typed_with_value_initializer(
3021            &source_meta,
3022            &JsonlSessionCreateOptions {
3023                id: None,
3024                parent_session_id: Some(source_meta.id.clone()),
3025                cwd: cwd.to_string(),
3026                metadata: None,
3027            },
3028            &ForkOptions::default(),
3029            |values| crate::resource_selection::fork_initial_values_for_selection(values, selected),
3030        )
3031        .await
3032        .map_err(|e| BuildError::SessionDir(format!("fork {}: {e}", source_meta.path)))?;
3033    fork_storage
3034        .acquire_writer_lease()
3035        .await
3036        .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
3037    let storage_arc: Arc<dyn SessionStorage> = Arc::new(fork_storage);
3038    Ok(Session::new(storage_arc, None))
3039}
3040
3041/// The metadata of the JSONL session file at `path`, or `None` when `path` is
3042/// not a readable session file.
3043fn session_metadata_at(path: &Path) -> Option<rpi_harness::session::jsonl::JsonlSessionMetadata> {
3044    use rpi_harness::session::jsonl::codec::{metadata_from_header, parse_header};
3045    use std::io::BufRead;
3046
3047    let file = std::fs::File::open(path).ok()?;
3048    let modified_at = file
3049        .metadata()
3050        .ok()?
3051        .modified()
3052        .ok()?
3053        .duration_since(std::time::UNIX_EPOCH)
3054        .ok()?
3055        .as_millis() as i64;
3056    let mut first_line = String::new();
3057    std::io::BufReader::new(file)
3058        .read_line(&mut first_line)
3059        .ok()?;
3060    let header = parse_header(first_line.trim_end()).ok()?;
3061    let path = std::fs::canonicalize(path).ok()?;
3062    Some(metadata_from_header(
3063        &header,
3064        &path.to_string_lossy(),
3065        modified_at,
3066    ))
3067}
3068
3069/// Errors from [`open_session_by_id`], split so the CLI can map them to
3070/// [`BuildError`] while the TUI can surface a friendlier note.
3071pub enum OpenError {
3072    /// No session matched the request.
3073    NotFound { requested: String },
3074    /// The match existed but could not be opened/parsed.
3075    Other(String),
3076}
3077
3078impl std::fmt::Display for OpenError {
3079    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3080        match self {
3081            OpenError::NotFound { requested } => write!(f, "no session matches {requested}"),
3082            // `Other` carries the bare reason (see `open_session_by_id`); the
3083            // prefix lives here so the TUI and the CLI's
3084            // `BuildError::SessionOpen` wrapper each render it exactly once
3085            // (wrapping the already-prefixed `BuildError` string doubled it).
3086            OpenError::Other(msg) => write!(f, "Could not open the saved session: {msg}"),
3087        }
3088    }
3089}
3090
3091/// Which sessions a picker lists. The default is [`Self::Project`]: with a
3092/// shared `sessionDir`, a flat list over every cwd directory buries the current
3093/// project's history (fork issue DavidHinton-xcpc/pi-rust#13). `All` is an
3094/// explicit opt-in and rows carry their project so the list stays traceable.
3095#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3096pub enum SessionScope {
3097    #[default]
3098    Project,
3099    All,
3100}
3101
3102impl SessionScope {
3103    pub fn toggled(self) -> Self {
3104        match self {
3105            Self::Project => Self::All,
3106            Self::All => Self::Project,
3107        }
3108    }
3109
3110    pub fn label(self) -> &'static str {
3111        match self {
3112            Self::Project => "this project",
3113            Self::All => "all projects",
3114        }
3115    }
3116}
3117
3118/// List the JSONL session metadata under the default session dir, newest
3119/// first. Shared by startup restore and the TUI `/session` hot-switch.
3120///
3121/// `list_session_metadata` intentionally stays unscoped: it resolves sessions
3122/// to *open* (including `--continue`/`-c`), where filtering by cwd would make
3123/// a session that the caller named by id unopenable. Only pickers apply a scope.
3124pub async fn list_session_metadata(
3125    cwd: &str,
3126) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3127    let dir = default_session_dir(Path::new(cwd));
3128    list_session_metadata_in_dir(cwd, &dir).await
3129}
3130
3131pub(crate) async fn list_session_metadata_in_dir(
3132    cwd: &str,
3133    dir: &Path,
3134) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3135    list_session_metadata_in_scope_in_dir(cwd, dir, SessionScope::All).await
3136}
3137
3138/// Scope-aware metadata listing for pickers. `Project` passes the cwd to the
3139/// repo's typed list API, so the enumeration and the open path agree on which
3140/// directory belongs to this project.
3141pub(crate) async fn list_session_metadata_in_scope_in_dir(
3142    cwd: &str,
3143    dir: &Path,
3144    scope: SessionScope,
3145) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
3146    use rpi_harness::session::jsonl::{
3147        JsonlSessionListOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
3148    };
3149    use rpi_tools::FileSystem;
3150
3151    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3152    let fs: Arc<dyn FileSystem> = env.clone();
3153    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3154        fs: fs.clone(),
3155        sessions_root: dir.to_string_lossy().into_owned(),
3156        clock: Arc::new(SystemClock),
3157        ids: Arc::new(DefaultIdGenerator::new()),
3158    });
3159    let options = JsonlSessionListOptions {
3160        cwd: match scope {
3161            SessionScope::Project => Some(cwd.to_string()),
3162            SessionScope::All => None,
3163        },
3164    };
3165    let metadata_lookup = StartupSpan::start(Phase::MetadataLookup);
3166    let result = repo
3167        .list_typed(&options)
3168        .await
3169        .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")));
3170    if result.is_ok() {
3171        metadata_lookup.finish();
3172    }
3173    result
3174}
3175
3176/// A cheap, display-oriented summary of one JSONL session file.
3177///
3178/// The session pickers (`-r` and `/session`) need enough context to tell saved
3179/// sessions apart. The header-only [`JsonlSessionMetadata`] carries no name and
3180/// no transcript, so a list built from it renders as a wall of identical
3181/// `2026-09-25T15-05-15-847Z_…` file names — including the many header-only
3182/// sessions an abandoned launch leaves behind. This reads just the head (and a
3183/// small tail, for a late `--name`/`/name` fact) of the file to recover:
3184///
3185/// - the session display name, when one was recorded;
3186/// - the first user prompt, single-lined and truncated, for a readable label;
3187/// - whether the file is header-only (nothing to resume).
3188///
3189/// It intentionally does **not** parse the whole log: sessions can be tens of
3190/// megabytes, and the picker runs over every session at startup.
3191#[derive(Debug, Clone, Default, PartialEq, Eq)]
3192pub struct SessionSummary {
3193    /// The session display name (`--name` / `/name`), if one was recorded.
3194    pub name: Option<String>,
3195    /// The first user prompt, single-lined and trimmed to a label-sized length.
3196    pub preview: Option<String>,
3197    /// True when the file holds only its header (a session with no content).
3198    pub empty: bool,
3199    /// On-disk size in bytes (a rough content-volume hint for the picker).
3200    pub bytes: u64,
3201}
3202
3203/// Bytes read from the head of a session file to recover a name + first prompt.
3204const SUMMARY_HEAD_BYTES: u64 = 256 * 1024;
3205/// Bytes read from the tail of a session file to recover a late name fact.
3206const SUMMARY_TAIL_BYTES: u64 = 8 * 1024;
3207/// Longest preview retained (characters, not bytes).
3208const SUMMARY_PREVIEW_CHARS: usize = 80;
3209
3210/// Summarize one session file for the pickers. Best-effort: an unreadable or
3211/// malformed file yields a summary with `empty: false` and no label, so it is
3212/// still selectable rather than silently dropped.
3213pub fn summarize_session_file(path: &Path) -> SessionSummary {
3214    use std::io::{Read, Seek, SeekFrom};
3215
3216    let Ok(mut file) = std::fs::File::open(path) else {
3217        return SessionSummary::default();
3218    };
3219    let Ok(size) = file.metadata().map(|m| m.len()) else {
3220        return SessionSummary::default();
3221    };
3222    if size == 0 {
3223        return SessionSummary {
3224            name: None,
3225            preview: None,
3226            empty: true,
3227            bytes: 0,
3228        };
3229    }
3230
3231    // Head: the header line (for the empty check) + a name fact + the first user
3232    // prompt. The whole window is scanned; it is already in memory.
3233    let mut head = vec![0u8; SUMMARY_HEAD_BYTES.min(size) as usize];
3234    let head_len = file.read(&mut head).unwrap_or(0);
3235    head.truncate(head_len);
3236    let head = String::from_utf8_lossy(&head);
3237    let mut lines: Vec<&str> = head.lines().collect();
3238    let header_len = lines.first().map(|line| line.len()).unwrap_or(0);
3239    // A header-only file is exactly the header plus an optional trailing `\n`.
3240    let empty = (size as usize) <= header_len + 1;
3241    // When the window stopped short of the file end, its final line is partial:
3242    // drop it so a half-read message can never be mistaken for a complete one.
3243    if (head_len as u64) < size && !lines.is_empty() {
3244        lines.pop();
3245    }
3246
3247    let mut summary = SessionSummary {
3248        name: None,
3249        preview: None,
3250        empty,
3251        bytes: size,
3252    };
3253    for line in lines {
3254        apply_summary_line(line, &mut summary);
3255    }
3256
3257    // Tail: a name set late in the session lives after the head window. Read the
3258    // last window and scan only complete lines so a torn/partial first line is
3259    // ignored. Only do this when the file is larger than the head window.
3260    if size > SUMMARY_HEAD_BYTES
3261        && file
3262            .seek(SeekFrom::End(-(SUMMARY_TAIL_BYTES as i64)))
3263            .is_ok()
3264    {
3265        let mut tail = Vec::new();
3266        if file.read_to_end(&mut tail).is_ok() {
3267            let tail = String::from_utf8_lossy(&tail);
3268            let mut tail_lines = tail.lines();
3269            // Drop the possibly-partial first line of the window.
3270            tail_lines.next();
3271            for line in tail_lines {
3272                if let Some(name) = name_from_line(line) {
3273                    summary.name = name;
3274                }
3275            }
3276        }
3277    }
3278    summary
3279}
3280
3281/// Extract the name from a `{"kind":"fact","fact":"name","name":…}` line.
3282/// Returns `Some(None)` for an explicit `name: null` (the fact was cleared).
3283fn name_from_line(line: &str) -> Option<Option<String>> {
3284    let value: serde_json::Value = serde_json::from_str(line).ok()?;
3285    if value.get("kind").and_then(|v| v.as_str()) != Some("fact") {
3286        return None;
3287    }
3288    if value.get("fact").and_then(|v| v.as_str()) != Some("name") {
3289        return None;
3290    }
3291    Some(match value.get("name") {
3292        Some(serde_json::Value::String(name)) => Some(name.clone()),
3293        _ => None,
3294    })
3295}
3296
3297/// Fold one JSONL line into `summary`: record a name fact, or capture the first
3298/// user prompt as the preview.
3299fn apply_summary_line(line: &str, summary: &mut SessionSummary) {
3300    if let Some(name) = name_from_line(line) {
3301        summary.name = name;
3302        return;
3303    }
3304    if summary.preview.is_some() {
3305        return;
3306    }
3307    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
3308        return;
3309    };
3310    if value.get("kind").and_then(|v| v.as_str()) != Some("entry") {
3311        return;
3312    }
3313    if value.get("type").and_then(|v| v.as_str()) != Some("message") {
3314        return;
3315    }
3316    let Some(message) = value.get("message") else {
3317        return;
3318    };
3319    if message.get("role").and_then(|v| v.as_str()) != Some("user") {
3320        return;
3321    }
3322    let text = match message.get("content") {
3323        Some(serde_json::Value::String(text)) => Some(text.as_str()),
3324        Some(serde_json::Value::Array(blocks)) => blocks.iter().find_map(|block| {
3325            (block.get("type").and_then(|v| v.as_str()) == Some("text"))
3326                .then(|| block.get("text").and_then(|v| v.as_str()))
3327                .flatten()
3328        }),
3329        _ => None,
3330    };
3331    let Some(text) = text else { return };
3332    let collapsed = text
3333        .lines()
3334        .map(str::trim)
3335        .filter(|line| !line.is_empty())
3336        .collect::<Vec<_>>()
3337        .join(" ");
3338    if collapsed.is_empty() {
3339        return;
3340    }
3341    summary.preview = Some(collapsed.chars().take(SUMMARY_PREVIEW_CHARS).collect());
3342}
3343
3344/// The human label for a session row: its recorded name, else the first user
3345/// prompt, else a marker that says the file has no transcript to show. Shared
3346/// by the startup picker and the in-TUI `/session` selector.
3347pub fn session_display_label(summary: &SessionSummary) -> String {
3348    if let Some(name) = summary.name.as_deref().map(str::trim) {
3349        if !name.is_empty() {
3350            return name.to_string();
3351        }
3352    }
3353    match summary.preview.as_deref().map(str::trim) {
3354        Some(preview) if !preview.is_empty() => preview.to_string(),
3355        _ => "(no messages)".to_string(),
3356    }
3357}
3358
3359/// Compact byte count (1.2MB / 34KB / 512B), shared by the startup picker and
3360/// the in-TUI `/session` selector.
3361pub fn format_session_bytes(bytes: u64) -> String {
3362    if bytes >= 1_048_576 {
3363        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
3364    } else if bytes >= 1024 {
3365        format!("{}KB", bytes / 1024)
3366    } else {
3367        format!("{bytes}B")
3368    }
3369}
3370
3371/// The first 8 characters of a session id, enough to disambiguate two rows that
3372/// share a timestamp without shouting the whole UUID.
3373pub fn short_session_id(id: &str) -> &str {
3374    &id[..id.len().min(8)]
3375}
3376
3377/// One listed session file. `project` is the cwd-encoded directory name when
3378/// the row comes from a project subdirectory; `None` for legacy files that sit
3379/// directly under the sessions root. The All view renders it so a flat list is
3380/// still attributable to a project.
3381#[derive(Debug, Clone, PartialEq, Eq)]
3382pub struct SessionFileEntry {
3383    pub path: PathBuf,
3384    pub project: Option<String>,
3385}
3386
3387/// Synchronously list every JSONL session file under `dir`, newest-first by
3388/// modification time. Kept for callers that explicitly want the full set (e.g.
3389/// resolving a session by id); pickers use [`list_session_files_in_scope_sync`].
3390///
3391/// The repo's [`list_session_metadata`] is async and scans one cwd-encoded
3392/// subdirectory level; the in-TUI `/session` selector runs on the blocking key
3393/// thread and cannot await it, so this walks the same layout directly. Both
3394/// `.jsonl` files directly under `dir` and one level of subdirectories are
3395/// accepted.
3396pub fn list_session_files_sync(dir: &Path) -> Vec<PathBuf> {
3397    list_entries_sync(dir, None)
3398        .into_iter()
3399        .map(|entry| entry.path)
3400        .collect()
3401}
3402
3403/// Scope-aware synchronous listing for the `/session` selector.
3404///
3405/// `Project` resolves the current project's directory with the *same* encoding
3406/// the repo uses for create/open (`jsonl_session_directory_name`), rather than
3407/// re-deriving it: the old flat walk and the open path disagreed about which
3408/// files belong to this project (fork issue #13). `All` keeps the old layout but
3409/// tags each row with its project directory.
3410pub fn list_session_files_in_scope_sync(
3411    cwd: &Path,
3412    dir: &Path,
3413    scope: SessionScope,
3414) -> Vec<SessionFileEntry> {
3415    let project_dir = match scope {
3416        SessionScope::Project => {
3417            let resolved = normalize_cwd(cwd);
3418            Some(rpi_harness::session::jsonl::jsonl_session_directory_name(
3419                &resolved.to_string_lossy(),
3420            ))
3421        }
3422        SessionScope::All => None,
3423    };
3424    match project_dir {
3425        Some(name) => list_entries_sync(&dir.join(&name), None),
3426        None => list_entries_sync(dir, Some(true)),
3427    }
3428}
3429
3430/// Mirror the repo's `absolute_path` normalization for a cwd path: the picker
3431/// runs on the blocking key thread and cannot await the `FileSystem` trait, so
3432/// this is the synchronous equivalent of `OsExecutionEnv::absolute_path`.
3433fn normalize_cwd(cwd: &Path) -> PathBuf {
3434    let absolute = if cwd.is_absolute() {
3435        cwd.to_path_buf()
3436    } else {
3437        std::env::current_dir()
3438            .unwrap_or_else(|_| PathBuf::from("."))
3439            .join(cwd)
3440    };
3441    // Lexical normalization only (`.` / `..` components), no symlink or FS
3442    // access — the repo's normalize_absolute is likewise purely lexical.
3443    let mut out = PathBuf::new();
3444    for component in absolute.components() {
3445        match component {
3446            std::path::Component::CurDir => {}
3447            std::path::Component::ParentDir => {
3448                out.pop();
3449            }
3450            other => out.push(other.as_os_str()),
3451        }
3452    }
3453    out
3454}
3455
3456fn list_entries_sync(dir: &Path, tag_projects: Option<bool>) -> Vec<SessionFileEntry> {
3457    let tag_projects = tag_projects.unwrap_or(false);
3458    let mut files: Vec<(SessionFileEntry, std::time::SystemTime)> = Vec::new();
3459    let mut visit = |path: PathBuf, project: Option<String>| {
3460        if path.extension().and_then(|e| e.to_str()) != Some("jsonl")
3461            || path.to_string_lossy().ends_with(".progress.jsonl")
3462        {
3463            return;
3464        }
3465        let modified = std::fs::metadata(&path)
3466            .and_then(|m| m.modified())
3467            .unwrap_or(std::time::UNIX_EPOCH);
3468        files.push((SessionFileEntry { path, project }, modified));
3469    };
3470    if let Ok(entries) = std::fs::read_dir(dir) {
3471        for entry in entries.flatten() {
3472            let path = entry.path();
3473            if path.is_dir() {
3474                let project = if tag_projects {
3475                    path.file_name()
3476                        .and_then(|name| name.to_str())
3477                        .map(str::to_owned)
3478                } else {
3479                    None
3480                };
3481                if let Ok(inner) = std::fs::read_dir(&path) {
3482                    for child in inner.flatten() {
3483                        visit(child.path(), project.clone());
3484                    }
3485                }
3486            } else {
3487                visit(path, None);
3488            }
3489        }
3490    }
3491    files.sort_by(|a, b| b.1.cmp(&a.1));
3492    files.into_iter().map(|(entry, _)| entry).collect()
3493}
3494
3495/// Pick the session `--continue`/`-c` should open: the newest session that has
3496/// content (a header-only session resumes to an empty transcript). Falls back to
3497/// the newest overall when every session is empty, and `None` only when the
3498/// list is empty.
3499fn first_resumable_session(
3500    metas: &[rpi_harness::session::jsonl::JsonlSessionMetadata],
3501) -> Option<&rpi_harness::session::jsonl::JsonlSessionMetadata> {
3502    metas
3503        .iter()
3504        .find(|meta| !summarize_session_file(Path::new(&meta.path)).empty)
3505        .or_else(|| metas.first())
3506}
3507
3508/// Open a session whose id matches exactly or by file-name containment
3509/// (so `--session 01a02…` / a partial id / a full file name all work). The
3510/// TUI `/session` hot-switch calls this with the selector's item value.
3511pub async fn open_session_by_id(id: &str, cwd: &str) -> Result<Session, OpenError> {
3512    let dir = default_session_dir(Path::new(cwd));
3513    open_session_by_id_in_dir(id, cwd, &dir)
3514        .await
3515        .map(|restored| restored.session)
3516}
3517
3518pub(crate) async fn open_session_by_id_in_dir(
3519    id: &str,
3520    cwd: &str,
3521    dir: &Path,
3522) -> Result<RestoredSession, OpenError> {
3523    let meta = find_session_metadata(id, cwd, dir)
3524        .await
3525        .map_err(|e| OpenError::Other(e.to_string()))?;
3526    let Some(meta) = meta else {
3527        return Err(OpenError::NotFound {
3528            requested: format!("session {id}"),
3529        });
3530    };
3531    open_session(&meta, cwd, dir).await.map_err(|e| {
3532        OpenError::Other(match e {
3533            // `open_session` renders as "Could not open the saved session:
3534            // <reason>" via `BuildError`. Carry the bare reason so it is not
3535            // prefixed twice (once here, once by the CLI/TUI).
3536            BuildError::SessionOpen(reason) => reason,
3537            other => other.to_string(),
3538        })
3539    })
3540}
3541
3542/// Publish the active session's id to plugins, on both channels that carry it.
3543///
3544/// Called on **every** activation of a session — the startup build AND every
3545/// in-process swap (`switch_to_session`, `fork_session`, and the plugin
3546/// `NewSession`/`Fork`/`SwitchSession` runtime actions all route through
3547/// [`set_active_session`]). Two things must stay in step:
3548///
3549/// - `ToolCallContext` — read per plugin **tool** call, which is why a stale
3550///   value there made a plugin's `todo`-style state follow the wrong session.
3551/// - `RPI_SESSION_ID` — read per **turn** by the provider hooks, which is the
3552///   only channel an observer gets for a pure-chat run. Process-global, which is
3553///   exactly the scope of "the session this process is serving".
3554///
3555/// The write overwrites unconditionally, deliberately. An inherited value is not
3556/// an override: `rpi` spawning `rpi` would otherwise hand the child the parent's
3557/// session id, and the child — which is *serving its own* session — would report
3558/// it forever. (Children no longer inherit the variable at all; see
3559/// `rpi_tools::HOST_PRIVATE_ENV`. This overwrite is the second line of defence,
3560/// for any other way a value can arrive pre-set.)
3561///
3562/// An embedder that genuinely wants to pin the id can revert to the old
3563/// behaviour by setting the variable *after* this runs; there is no supported
3564/// way to pin it before, because a session that does not match its own id is
3565/// never what the caller wants.
3566fn publish_session_identity(tool_context: &rpi_extensions::ToolCallContext, id: &str) {
3567    std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, id);
3568    tool_context.set_session_id(id);
3569}
3570
3571/// Swap the session the harness serves, republishing the identity to plugins.
3572///
3573/// The single funnel for an in-process session change. Prefer this over calling
3574/// `AgentHarness::set_session` directly: the harness holds no reference to the
3575/// plugin channels, so a bare `set_session` would leave every plugin reporting
3576/// the session it had before the swap.
3577///
3578/// `tool_context` is optional because not every caller has one (the harness's own
3579/// tests, a headless embedder); the env channel is always published, since the
3580/// provider hooks depend on it.
3581pub(crate) async fn set_active_session(
3582    harness: &AgentHarness,
3583    session: Session,
3584    tool_context: Option<&rpi_extensions::ToolCallContext>,
3585) -> Result<(), String> {
3586    let metadata = session.get_metadata().await.ok();
3587    harness
3588        .set_session(session)
3589        .await
3590        .map_err(|e| e.to_string())?;
3591    if let Some(metadata) = metadata {
3592        std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, &metadata.id);
3593        if let Some(context) = tool_context {
3594            context.set_session_id(metadata.id);
3595        }
3596    }
3597    Ok(())
3598}
3599
3600/// Fork the harness's current session into a new JSONL session (new id, parent
3601/// set to the source) and wrap it in a `Session`. Mirrors the TUI's
3602/// `fork_session` flow (`interactive_tui.rs`) — hoisted here so both the TUI
3603/// and the plugin `runtime_action(Fork)` host share one implementation.
3604/// Returns the new `Session` (NOT yet swapped onto the harness — the caller
3605/// does `harness.set_session(...)`).
3606pub(crate) async fn fork_session_storage(
3607    harness: &AgentHarness,
3608    cwd: &str,
3609    dir: &Path,
3610) -> Result<Session, String> {
3611    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
3612    use rpi_tools::FileSystem;
3613
3614    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3615    let fs: Arc<dyn FileSystem> = env.clone();
3616    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3617        fs,
3618        sessions_root: dir.to_string_lossy().into_owned(),
3619        clock: Arc::new(SystemClock),
3620        ids: Arc::new(DefaultIdGenerator::new()),
3621    });
3622    // The fork needs the rich JSONL metadata (with the on-disk path); resolve
3623    // it from the session list by the current session's id.
3624    let id = harness.session().storage().metadata().id.clone();
3625    let metas = list_session_metadata_in_dir(cwd, dir)
3626        .await
3627        .map_err(|e| e.to_string())?;
3628    let Some(source) = metas.iter().find(|m| m.id == id) else {
3629        return Err(format!("current session {id} not found on disk"));
3630    };
3631    let fork_storage = repo
3632        .fork_typed_with_value_initializer(
3633            source,
3634            &rpi_harness::session::jsonl::JsonlSessionCreateOptions {
3635                id: None,
3636                parent_session_id: Some(source.id.clone()),
3637                cwd: cwd.to_string(),
3638                metadata: None,
3639            },
3640            &rpi_harness::session::types::ForkOptions::default(),
3641            crate::resource_selection::fork_initial_values,
3642        )
3643        .await
3644        .map_err(|e| e.to_string())?;
3645    fork_storage
3646        .acquire_writer_lease()
3647        .await
3648        .map_err(|e| e.to_string())?;
3649    Ok(Session::new(Arc::new(fork_storage), None))
3650}
3651
3652/// Validate a private copy before publishing it in the repo's normal cwd
3653/// directory. Keep the imported identity/history and never overwrite a saved
3654/// session (including when the source is already inside this repository).
3655pub(crate) async fn import_session_file(
3656    source: &Path,
3657    cwd: &str,
3658    dir: &Path,
3659) -> Result<Session, String> {
3660    use rpi_harness::session::jsonl::{
3661        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions, JsonlSessionStorage,
3662    };
3663    use rpi_harness::session::types::SessionStorage;
3664    use rpi_tools::FileSystem;
3665
3666    let dir = if dir.is_absolute() {
3667        dir.to_path_buf()
3668    } else {
3669        Path::new(cwd).join(dir)
3670    };
3671    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
3672    // External writers must be closed. This process deliberately retains locks
3673    // for previously opened sessions, so its own copies additionally verify a
3674    // stable history around the sidecar snapshot (bind/entry before retirement).
3675    let source_progress = PathBuf::from(format!("{}.progress.jsonl", source.display()));
3676    let _source_lock = if source_progress.try_exists().map_err(|e| e.to_string())? {
3677        let lock = std::fs::OpenOptions::new()
3678            .create(true)
3679            .write(true)
3680            .open(format!("{}.lock", source.display()))
3681            .map_err(|e| format!("lock import source: {e}"))?;
3682        fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| {
3683            "close the source session before importing its recovery pair".to_owned()
3684        })?;
3685        Some(lock)
3686    } else {
3687        None
3688    };
3689    let staging = tempfile::tempdir_in(&dir).map_err(|e| e.to_string())?;
3690    let staged = staging.path().join("history.stage");
3691    let staged_progress = PathBuf::from(format!("{}.progress.jsonl", staged.display()));
3692    let mut attempts = 0;
3693    let has_progress = loop {
3694        std::fs::copy(source, &staged).map_err(|e| format!("copy import: {e}"))?;
3695        let copied_history = std::fs::read(&staged).map_err(|e| e.to_string())?;
3696        let has_progress = match std::fs::copy(&source_progress, &staged_progress) {
3697            Ok(_) => true,
3698            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
3699                let _ = std::fs::remove_file(&staged_progress);
3700                false
3701            }
3702            Err(error) => return Err(format!("copy progress import: {error}")),
3703        };
3704        if copied_history == std::fs::read(source).map_err(|e| e.to_string())? {
3705            break has_progress;
3706        }
3707        attempts += 1;
3708        if attempts >= 4 {
3709            return Err(
3710                "source history changed during import; retry when the session is idle".into(),
3711            );
3712        }
3713        tokio::task::yield_now().await;
3714    };
3715    let fs: Arc<dyn FileSystem> = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3716    let validated = JsonlSessionStorage::load(
3717        fs.clone(),
3718        &staged.to_string_lossy(),
3719        Arc::new(SystemClock),
3720        Arc::new(DefaultIdGenerator::new()),
3721    )
3722    .await
3723    .map_err(|e| format!("invalid session import: {e}"))?;
3724    validated
3725        .read_progress("")
3726        .await
3727        .map_err(|e| format!("invalid recovery import: {e}"))?;
3728    let mut metadata = validated.jsonl_metadata().clone();
3729    drop(validated);
3730    let text = std::fs::read_to_string(&staged).map_err(|e| e.to_string())?;
3731    let (first, rest) = text
3732        .split_once('\n')
3733        .ok_or_else(|| "import has no complete header".to_owned())?;
3734    let mut header =
3735        rpi_harness::session::jsonl::codec::parse_header(first).map_err(|e| e.to_string())?;
3736    if has_progress && header.progress_format.is_none() {
3737        return Err("history-only artifact has an undeclared recovery companion".into());
3738    }
3739    // An imported history-only artifact receives the destination's empty store.
3740    // Imports of live-format sessions retain their validated companion instead.
3741    header.progress_format = Some("assistant-progress-v1".into());
3742    std::fs::write(
3743        &staged,
3744        format!(
3745            "{}{}",
3746            rpi_harness::session::jsonl::codec::encode_header(&header),
3747            rest
3748        ),
3749    )
3750    .map_err(|e| e.to_string())?;
3751    if list_session_metadata_in_dir(cwd, &dir)
3752        .await
3753        .map_err(|e| e.to_string())?
3754        .iter()
3755        .any(|saved| saved.id == metadata.id)
3756    {
3757        return Err(format!(
3758            "session {} already exists in {}",
3759            metadata.id,
3760            dir.display()
3761        ));
3762    }
3763    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3764        fs,
3765        sessions_root: dir.to_string_lossy().into_owned(),
3766        clock: Arc::new(SystemClock),
3767        ids: Arc::new(DefaultIdGenerator::new()),
3768    });
3769    // Let the repository validate the id and choose its canonical destination.
3770    let destination = repo
3771        .create_typed(&JsonlSessionCreateOptions {
3772            id: Some(metadata.id.clone()),
3773            parent_session_id: metadata.parent_session_id.clone(),
3774            cwd: cwd.to_string(),
3775            metadata: metadata.metadata.clone(),
3776        })
3777        .await
3778        .map_err(|e| e.to_string())?;
3779    let path = destination.jsonl_metadata().path.clone();
3780    drop(destination);
3781    // Do not claim the session-level `.lock` here. The destination storage
3782    // opened below owns the same OS lease; claiming it first would make this
3783    // process conflict with itself. The JSONL storage lease is the
3784    // authoritative writer fence for the imported session.
3785    let destination_progress = format!("{path}.progress.jsonl");
3786    let publish = (|| -> std::io::Result<()> {
3787        if has_progress {
3788            std::fs::rename(&staged_progress, &destination_progress)?;
3789        }
3790        std::fs::rename(&staged, &path)
3791    })();
3792    if let Err(error) = publish {
3793        let _ = std::fs::remove_file(&path);
3794        let _ = std::fs::remove_file(&destination_progress);
3795        return Err(format!("publish import: {error}"));
3796    }
3797    metadata.path = path;
3798    let storage = repo
3799        .open_by_jsonl_metadata(&metadata)
3800        .await
3801        .map_err(|e| e.to_string())?;
3802    Ok(Session::new(Arc::new(storage), None))
3803}
3804
3805/// A restored session together with the working directory it was created in.
3806///
3807/// The recorded cwd is data for the host's notices, never a silent adoption:
3808/// the launch path adopts the directory in [`app`](crate::app) before any
3809/// resource loads (tools, extensions, system prompt, and trust all key off it),
3810/// and the `/session` hot-switch does not move the running tools at all. Either
3811/// way the user hears about the directory instead of the process quietly
3812/// working somewhere unexpected.
3813pub(crate) struct RestoredSession {
3814    pub session: Session,
3815    /// The directory recorded in the session header, when it still exists.
3816    /// `None` when the record is empty or the path is gone (or is a file).
3817    pub recorded_cwd: Option<PathBuf>,
3818}
3819
3820/// Wrap an opened [`JsonlSessionStorage`] in the `Session` facade (shared by
3821/// startup restore + TUI hot-switch).
3822///
3823/// `sessions_root` is passed in rather than re-derived from `cwd`: after a
3824/// restore adopts the session's directory, `default_session_dir(cwd)` would
3825/// name the ADOPTED project's tree, which is not where this session was found.
3826async fn open_session(
3827    meta: &rpi_harness::session::jsonl::JsonlSessionMetadata,
3828    cwd: &str,
3829    sessions_root: &Path,
3830) -> Result<RestoredSession, BuildError> {
3831    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
3832    use rpi_harness::session::types::SessionStorage;
3833    use rpi_tools::FileSystem;
3834
3835    let dir = sessions_root;
3836    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3837    let fs: Arc<dyn FileSystem> = env.clone();
3838    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3839        fs: fs.clone(),
3840        sessions_root: dir.to_string_lossy().into_owned(),
3841        clock: Arc::new(SystemClock),
3842        ids: Arc::new(DefaultIdGenerator::new()),
3843    });
3844    let storage = repo
3845        .open_by_jsonl_metadata(meta)
3846        .await
3847        .map_err(|e| BuildError::SessionOpen(format!("open {}: {e}", meta.path)))?;
3848    storage
3849        .acquire_writer_lease()
3850        .await
3851        .map_err(|e| BuildError::SessionOpen(format!("lock {}: {e}", meta.path)))?;
3852    // Native saved sessions predating progressFormat remain read-only to plain
3853    // storage loaders. Only this locked, not-yet-shared restore opts into writes.
3854    let storage = storage
3855        .enable_progress_under_exclusive_lock()
3856        .await
3857        .map_err(|e| BuildError::SessionOpen(format!("upgrade {}: {e}", meta.path)))?;
3858    let storage_arc: Arc<dyn SessionStorage> = Arc::new(storage);
3859    Ok(RestoredSession {
3860        session: Session::new(storage_arc, None),
3861        recorded_cwd: crate::session_cwd::resolve_session_cwd(Path::new(&meta.cwd)),
3862    })
3863}
3864
3865/// A fresh ephemeral in-memory session (no persistence). Used for `--no-session`
3866/// and for `/new` inside such a run — an ephemeral launch keeps swapping in
3867/// in-memory sessions, never a JSONL file.
3868pub(crate) fn ephemeral_session() -> Session {
3869    let storage = Arc::new(InMemorySessionStorage::new(
3870        SessionMetadata {
3871            id: "ephemeral".into(),
3872            created_at: 0,
3873            parent_session_id: None,
3874        },
3875        Arc::new(SystemClock),
3876        Arc::new(DefaultIdGenerator::new()),
3877    ));
3878    Session::new(storage, None).with_volatile_progress()
3879}
3880
3881/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
3882///
3883/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
3884/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
3885/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
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).
3891pub(crate) async fn create_jsonl_session(dir: &Path, cwd: &str) -> Result<Session, String> {
3892    create_jsonl_session_with_id(dir, cwd, None).await
3893}
3894
3895/// `create_jsonl_session` with an explicit id (the `--session-id` fixed-id
3896/// contract: the file is named with the given id so later `--session-id`
3897/// launches restore the same session).
3898pub(crate) async fn create_jsonl_session_with_id(
3899    dir: &Path,
3900    cwd: &str,
3901    id: Option<String>,
3902) -> Result<Session, String> {
3903    use rpi_harness::session::jsonl::{
3904        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
3905    };
3906    use rpi_tools::FileSystem;
3907
3908    // A dedicated OS env for session-file I/O, rooted at the cwd so the repo's
3909    // relative-path resolution matches the tool env.
3910    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
3911    let fs: Arc<dyn FileSystem> = env.clone();
3912
3913    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
3914        fs: fs.clone(),
3915        sessions_root: dir.to_string_lossy().into_owned(),
3916        clock: Arc::new(SystemClock),
3917        ids: Arc::new(DefaultIdGenerator::new()),
3918    });
3919
3920    let opts = JsonlSessionCreateOptions {
3921        id, // fresh uuidv7 when None (--session-id passes the fixed id)
3922        parent_session_id: None,
3923        cwd: cwd.to_string(),
3924        metadata: None,
3925    };
3926    let storage = repo
3927        .create_typed(&opts)
3928        .await
3929        .map_err(|e| format!("create session: {e}"))?;
3930    // `JsonlSessionStorage` acquires the storage-level lease during create;
3931    // wrap it in the facade without a second CLI-owned lock table.
3932    let storage_arc: Arc<dyn rpi_harness::session::types::SessionStorage> = Arc::new(storage);
3933    Ok(Session::new(storage_arc, None))
3934}
3935
3936/// Read an `--append-system-prompt` target: if it's a readable file path, return
3937/// its contents; otherwise return `None` and let the caller use the literal.
3938fn read_append_target(target: &str, sources: &mut Vec<String>) -> Option<String> {
3939    let path = Path::new(target);
3940    if path.is_file() {
3941        read_prompt_source(path, sources)
3942    } else {
3943        None
3944    }
3945}
3946
3947/// Record provenance at the successful read, rather than rediscovering files
3948/// during rendering (which could report a shadowed or unreadable file).
3949fn read_prompt_source(path: &Path, sources: &mut Vec<String>) -> Option<String> {
3950    let text = std::fs::read_to_string(path).ok()?;
3951    let absolute = if path.is_absolute() {
3952        path.to_path_buf()
3953    } else {
3954        std::env::current_dir()
3955            .map(|cwd| cwd.join(path))
3956            .unwrap_or_else(|_| path.to_path_buf())
3957    };
3958    let source = absolute.to_string_lossy().into_owned();
3959    if !sources.contains(&source) {
3960        sources.push(source);
3961    }
3962    Some(text)
3963}
3964
3965#[cfg(test)]
3966mod goal_outbox_smoke_tests;
3967#[cfg(test)]
3968mod runtime_session_tests;
3969
3970#[cfg(test)]
3971mod tests {
3972    use super::*;
3973
3974    #[test]
3975    fn settlement_bridge_follows_reload_and_releases_its_session_with_the_bus() {
3976        use rpi_harness::events::{HarnessEvent, HarnessEventBus, RunEndEvent, RunEndOutcome};
3977        use std::sync::atomic::{AtomicUsize, Ordering};
3978        static OLD: AtomicUsize = AtomicUsize::new(0);
3979        static NEW: AtomicUsize = AtomicUsize::new(0);
3980        extern "C" fn old(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
3981            OLD.fetch_add(1, Ordering::SeqCst);
3982            0
3983        }
3984        extern "C" fn new(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
3985            NEW.fetch_add(1, Ordering::SeqCst);
3986            0
3987        }
3988        let make = |handler: rpi_plugin_sdk::EventHandlerFn| {
3989            let mut registry = rpi_extensions::ExtensionRegistry::new();
3990            registry.register_event_handler(
3991                "settlement".into(),
3992                rpi_plugin_sdk::EventTag::AgentSettled,
3993                handler,
3994                std::ptr::null_mut(),
3995            );
3996            ExtensionSession::from_parts(
3997                Arc::new(registry.snapshot()),
3998                rpi_extensions::PluginKeepalive::empty(),
3999                vec![],
4000                None,
4001            )
4002        };
4003        let sessions = Arc::new(Mutex::new(make(old)));
4004        let weak = Arc::downgrade(&sessions);
4005        let bus = HarnessEventBus::new();
4006        install_extension_settlement_bridge(&bus, sessions.clone());
4007        let ended = |outcome| {
4008            HarnessEvent::RunEnd(RunEndEvent {
4009                lane: "main".into(),
4010                run_id: "run".into(),
4011                outcome,
4012                leaf_id: "leaf".into(),
4013            })
4014        };
4015        bus.emit(&ended(RunEndOutcome::Completed));
4016        assert_eq!(OLD.load(Ordering::SeqCst), 1);
4017        *sessions.lock().unwrap() = make(new);
4018        for outcome in [RunEndOutcome::Aborted, RunEndOutcome::Failed] {
4019            bus.emit(&ended(outcome));
4020        }
4021        assert_eq!(OLD.load(Ordering::SeqCst), 1);
4022        assert_eq!(NEW.load(Ordering::SeqCst), 2);
4023        drop(sessions);
4024        assert!(weak.upgrade().is_some());
4025        drop(bus);
4026        assert!(
4027            weak.upgrade().is_none(),
4028            "settlement observer must not create an ownership cycle"
4029        );
4030    }
4031
4032    #[tokio::test]
4033    async fn unauthenticated_packages_are_not_reintroduced_as_legacy_adapters() {
4034        extern "C" fn request(
4035            _: rpi_plugin_sdk::StbStringRef,
4036            _: *mut rpi_plugin_sdk::StbString,
4037            _: *mut std::ffi::c_void,
4038        ) -> i32 {
4039            1
4040        }
4041        let mut registry = rpi_extensions::ExtensionRegistry::new();
4042        for id in ["package", "legacy"] {
4043            registry.register_provider(rpi_extensions::RegisteredProvider {
4044                provider_id: id.into(),
4045                base_url: "http://localhost".into(),
4046                api_style: "openai-completions".into(),
4047                request_fn: request,
4048                stream_fn: None,
4049                plugin_free_string: rpi_plugin_sdk::callbacks::free_string,
4050                user_data: std::ptr::null_mut(),
4051            });
4052        }
4053        assert!(registry.apply_declaration_json(&serde_json::json!({"providers":[{
4054            "id":"package", "requiresAuth":true,
4055            "models":[rpi_ai::Model::new("model", "Model", rpi_ai::Api::OpenaiCompletions, "package", "http://localhost")]
4056        }]}).to_string()));
4057        let session = ExtensionSession::from_parts(
4058            Arc::new(registry.snapshot()),
4059            rpi_extensions::PluginKeepalive::empty(),
4060            vec![],
4061            None,
4062        );
4063        let providers = build_models_with_extensions_for_reload(
4064            &[],
4065            &session,
4066            tokio::runtime::Handle::current(),
4067        );
4068        assert_eq!(
4069            providers
4070                .iter()
4071                .map(|provider| provider.id())
4072                .collect::<Vec<_>>(),
4073            ["legacy"]
4074        );
4075    }
4076    use crate::args::Args;
4077
4078    #[test]
4079    fn loaded_context_paths_track_precedence_and_reload() {
4080        const CHILD: &str = "RPI_CONTEXT_PATHS_REGRESSION_CHILD";
4081        if std::env::var_os(CHILD).is_none() {
4082            let dir = tempfile::tempdir().unwrap();
4083            let output = std::process::Command::new(std::env::current_exe().unwrap())
4084                .args([
4085                    "--exact",
4086                    "session::tests::loaded_context_paths_track_precedence_and_reload",
4087                    "--nocapture",
4088                ])
4089                .env(CHILD, "1")
4090                .env(crate::config::CONFIG_DIR_ENV, dir.path())
4091                .output()
4092                .unwrap();
4093            assert!(
4094                output.status.success(),
4095                "{}\n{}",
4096                String::from_utf8_lossy(&output.stdout),
4097                String::from_utf8_lossy(&output.stderr)
4098            );
4099            return;
4100        }
4101        tokio::runtime::Builder::new_current_thread()
4102            .enable_all()
4103            .build()
4104            .unwrap()
4105            .block_on(async {
4106                let agent = crate::config::agent_dir().unwrap();
4107                let cwd = agent.join("project");
4108                let project_config = cwd.join(".rpi");
4109                std::fs::create_dir_all(&project_config).unwrap();
4110                for (path, content) in [
4111                    (agent.join("SYSTEM.md"), "GLOBAL_BASE"),
4112                    (agent.join("APPEND_SYSTEM.md"), "GLOBAL_APPEND"),
4113                    (agent.join("AGENTS.md"), "GLOBAL_INSTRUCTIONS"),
4114                    (project_config.join("SYSTEM.md"), "PROJECT_BASE"),
4115                    (project_config.join("APPEND_SYSTEM.md"), "PROJECT_APPEND"),
4116                    (cwd.join("AGENTS.md"), "PROJECT_INSTRUCTIONS"),
4117                    (cwd.join("CLAUDE.md"), "SHADOWED_CLAUDE"),
4118                ] {
4119                    std::fs::write(path, content).unwrap();
4120                }
4121                let resolved = crate::provider::resolve(
4122                    Some("anthropic"),
4123                    Some(crate::provider::DEFAULT_MODEL_ID),
4124                    None,
4125                    Some("test-key"),
4126                    None,
4127                )
4128                .unwrap();
4129                let args = Args {
4130                    no_session: true,
4131                    no_extensions: true,
4132                    no_skills: true,
4133                    no_prompt_templates: true,
4134                    trust_override: Some(true),
4135                    ..Default::default()
4136                };
4137                let (harness, _events, mut context) =
4138                    build(&resolved, &args, &cwd, true).await.unwrap();
4139                let resources = harness.get_resources().await.unwrap();
4140                let path = |p: PathBuf| p.to_string_lossy().into_owned();
4141                assert_eq!(
4142                    &resources.context_files[..2],
4143                    &[
4144                        path(project_config.join("SYSTEM.md")),
4145                        path(project_config.join("APPEND_SYSTEM.md")),
4146                    ]
4147                );
4148                assert!(resources
4149                    .context_files
4150                    .contains(&path(agent.join("AGENTS.md"))));
4151                assert!(resources
4152                    .context_files
4153                    .contains(&path(cwd.join("AGENTS.md"))));
4154                assert!(!resources
4155                    .context_files
4156                    .contains(&path(cwd.join("CLAUDE.md"))));
4157                assert!(!resources
4158                    .context_files
4159                    .contains(&path(agent.join("SYSTEM.md"))));
4160                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
4161                assert!(prompt.contains("PROJECT_BASE") && prompt.contains("PROJECT_APPEND"));
4162                assert!(!prompt.contains("GLOBAL_BASE") && !prompt.contains("SHADOWED_CLAUDE"));
4163
4164                // Removing the selected project files makes reload fall back to
4165                // globals; removed instruction paths must disappear as well.
4166                std::fs::remove_file(project_config.join("SYSTEM.md")).unwrap();
4167                std::fs::remove_file(project_config.join("APPEND_SYSTEM.md")).unwrap();
4168                std::fs::remove_file(cwd.join("AGENTS.md")).unwrap();
4169                assert!(
4170                    !reload_extension_resources(&harness, &context)
4171                        .await
4172                        .had_errors
4173                );
4174                let resources = harness.get_resources().await.unwrap();
4175                assert_eq!(
4176                    &resources.context_files[..2],
4177                    &[
4178                        path(agent.join("SYSTEM.md")),
4179                        path(agent.join("APPEND_SYSTEM.md")),
4180                    ]
4181                );
4182                assert!(resources
4183                    .context_files
4184                    .contains(&path(cwd.join("CLAUDE.md"))));
4185                assert!(!resources
4186                    .context_files
4187                    .contains(&path(project_config.join("SYSTEM.md"))));
4188
4189                // Explicit append files are listed; literal text and overridden
4190                // discovered base/append files are not invented as file sources.
4191                let explicit = agent.join("custom-append.md");
4192                std::fs::write(&explicit, "EXPLICIT_APPEND").unwrap();
4193                context.args.system_prompt = Some("EXPLICIT_BASE".into());
4194                context.args.append_system_prompt =
4195                    vec![path(explicit.clone()), "literal append".into()];
4196                context.args.no_context_files = true;
4197                assert!(
4198                    !reload_extension_resources(&harness, &context)
4199                        .await
4200                        .had_errors
4201                );
4202                assert_eq!(
4203                    harness.get_resources().await.unwrap().context_files,
4204                    vec![path(explicit)]
4205                );
4206
4207                // The reload must honor the startup opt-out from project context.
4208                context.args.system_prompt = None;
4209                context.args.append_system_prompt.clear();
4210                context.args.no_context_files = false;
4211                context.args.trust_override = Some(false);
4212                assert!(
4213                    !reload_extension_resources(&harness, &context)
4214                        .await
4215                        .had_errors
4216                );
4217                assert!(harness
4218                    .get_resources()
4219                    .await
4220                    .unwrap()
4221                    .context_files
4222                    .is_empty());
4223                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
4224                assert!(
4225                    !prompt.contains("SHADOWED_CLAUDE") && !prompt.contains("GLOBAL_INSTRUCTIONS")
4226                );
4227            });
4228    }
4229
4230    #[test]
4231    fn prompt_source_read_failures_and_literals_do_not_create_file_provenance() {
4232        let dir = tempfile::tempdir().unwrap();
4233        let file = dir.path().join("SYSTEM.md");
4234        let mut sources = Vec::new();
4235        assert!(read_prompt_source(&file, &mut sources).is_none());
4236        std::fs::write(&file, [0xff, 0xfe]).unwrap();
4237        assert!(read_prompt_source(&file, &mut sources).is_none());
4238        assert!(read_append_target("literal instructions", &mut sources).is_none());
4239        assert!(sources.is_empty());
4240        std::fs::write(&file, "loaded instructions").unwrap();
4241        assert_eq!(
4242            read_prompt_source(&file, &mut sources).as_deref(),
4243            Some("loaded instructions")
4244        );
4245        assert!(read_prompt_source(&file, &mut sources).is_some());
4246        assert_eq!(sources, vec![file.to_string_lossy().into_owned()]);
4247    }
4248
4249    extern "C" fn deny_test_tool_call(
4250        _event: rpi_plugin_sdk::StablePluginEvent,
4251        _data: *mut std::ffi::c_void,
4252    ) -> i32 {
4253        rpi_plugin_sdk::EVENT_HANDLER_ABORT
4254    }
4255
4256    async fn invoke_test_tool_hook(
4257        hook: &rpi_agent::BeforeToolCall,
4258    ) -> Option<rpi_agent::BeforeToolCallResult> {
4259        let message = rpi_ai::providers::faux::faux_assistant_message(
4260            "approval",
4261            rpi_ai::types::StopReason::ToolUse,
4262        );
4263        let rpi_ai::types::Content::ToolCall(call) =
4264            rpi_ai::types::Content::tool_call("call", "read", serde_json::json!({"path":"x"}))
4265        else {
4266            unreachable!()
4267        };
4268        hook(
4269            rpi_agent::BeforeToolCallContext {
4270                assistant_message: &message,
4271                tool_call: &call,
4272                args: &call.arguments,
4273                context: &rpi_agent::AgentContext::default(),
4274            },
4275            tokio_util::sync::CancellationToken::new(),
4276        )
4277        .await
4278    }
4279
4280    #[tokio::test]
4281    async fn tool_call_hook_uses_reloaded_session_and_newly_discovered_gate() {
4282        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
4283        let hook =
4284            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
4285        assert!(invoke_test_tool_hook(&hook).await.is_none());
4286        for name in ["first-gate", "reloaded-gate"] {
4287            let mut registry = rpi_extensions::ExtensionRegistry::new();
4288            registry.register_event_handler(
4289                name.into(),
4290                rpi_plugin_sdk::EventTag::ToolCall,
4291                deny_test_tool_call,
4292                std::ptr::null_mut(),
4293            );
4294            let fresh = ExtensionSession::from_parts(
4295                Arc::new(registry.snapshot()),
4296                rpi_extensions::PluginKeepalive::empty(),
4297                Vec::new(),
4298                None,
4299            );
4300            {
4301                let mut current = sessions.lock().unwrap();
4302                if let Some(snapshot) = current.snapshot() {
4303                    snapshot.active_flag().store(false, Ordering::SeqCst);
4304                }
4305                *current = fresh;
4306            }
4307            let result = invoke_test_tool_hook(&hook).await.unwrap();
4308            assert!(result.block);
4309            assert!(result.reason.unwrap().contains(name));
4310        }
4311        *sessions.lock().unwrap() = ExtensionSession::none();
4312        assert!(invoke_test_tool_hook(&hook).await.is_none());
4313    }
4314
4315    /// A unique scratch file for one summary test.
4316    fn scratch(name: &str) -> PathBuf {
4317        let nanos = std::time::SystemTime::now()
4318            .duration_since(std::time::UNIX_EPOCH)
4319            .unwrap()
4320            .as_nanos();
4321        let path = std::env::temp_dir().join(format!(
4322            "rpi-summary-{}-{nanos}-{name}.jsonl",
4323            std::process::id()
4324        ));
4325        path
4326    }
4327
4328    #[test]
4329    fn summary_marks_a_header_only_session_empty() {
4330        let path = scratch("empty");
4331        std::fs::write(
4332            &path,
4333            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4334        )
4335        .unwrap();
4336        let summary = summarize_session_file(&path);
4337        assert!(summary.empty, "a header-only file has nothing to resume");
4338        assert!(summary.preview.is_none());
4339        assert_eq!(summary.bytes, std::fs::metadata(&path).unwrap().len());
4340        std::fs::remove_file(&path).ok();
4341    }
4342
4343    #[test]
4344    fn summary_reads_the_first_user_prompt_and_name() {
4345        let path = scratch("content");
4346        let body = concat!(
4347            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4348            "{\"kind\":\"fact\",\"seq\":1,\"fact\":\"name\",\"name\":\"fix resume picker\"}\n",
4349            "{\"kind\":\"record\",\"type\":\"operation_started\",\"id\":\"r1\"}\n",
4350            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"kind\":\"user\",\"role\":\"user\",\"content\":\"read the rpi -r picker\"}}\n",
4351            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e2\",\"message\":{\"kind\":\"assistant\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
4352        );
4353        std::fs::write(&path, body).unwrap();
4354        let summary = summarize_session_file(&path);
4355        assert!(!summary.empty);
4356        assert_eq!(summary.name.as_deref(), Some("fix resume picker"));
4357        assert_eq!(summary.preview.as_deref(), Some("read the rpi -r picker"));
4358        std::fs::remove_file(&path).ok();
4359    }
4360
4361    #[test]
4362    fn summary_extracts_a_block_style_user_prompt() {
4363        let path = scratch("blocks");
4364        let body = concat!(
4365            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4366            "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"line one\\nline two\"}]}}\n",
4367        );
4368        std::fs::write(&path, body).unwrap();
4369        let summary = summarize_session_file(&path);
4370        assert_eq!(summary.preview.as_deref(), Some("line one line two"));
4371        assert_eq!(session_display_label(&summary), "line one line two");
4372        std::fs::remove_file(&path).ok();
4373    }
4374
4375    fn meta_for(path: &Path, id: &str) -> rpi_harness::session::jsonl::JsonlSessionMetadata {
4376        rpi_harness::session::jsonl::JsonlSessionMetadata {
4377            id: id.to_string(),
4378            created_at: 0,
4379            cwd: ".".to_string(),
4380            path: path.to_string_lossy().into_owned(),
4381            modified_at: 0,
4382            source_format: rpi_harness::session::jsonl::JsonlSourceFormat::V4,
4383            parent_session_id: None,
4384            legacy_parent_session_path: None,
4385            metadata: None,
4386        }
4387    }
4388
4389    #[test]
4390    fn continue_skips_newer_empty_sessions() {
4391        let empty = scratch("newest-empty");
4392        std::fs::write(
4393            &empty,
4394            "{\"kind\":\"header\",\"version\":4,\"id\":\"empty\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4395        )
4396        .unwrap();
4397        let content = scratch("older-content");
4398        std::fs::write(
4399            &content,
4400            concat!(
4401                "{\"kind\":\"header\",\"version\":4,\"id\":\"old\",\"createdAt\":1,\"cwd\":\"x\"}\n",
4402                "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n",
4403            ),
4404        )
4405        .unwrap();
4406
4407        let metas = vec![meta_for(&empty, "empty"), meta_for(&content, "old")];
4408        let picked = first_resumable_session(&metas).expect("a resumable session");
4409        assert_eq!(picked.id, "old");
4410
4411        // When every session is empty, fall back to the newest rather than
4412        // erroring.
4413        let all_empty = vec![meta_for(&empty, "empty")];
4414        assert_eq!(first_resumable_session(&all_empty).unwrap().id, "empty");
4415
4416        std::fs::remove_file(&empty).ok();
4417        std::fs::remove_file(&content).ok();
4418    }
4419
4420    #[tokio::test]
4421    async fn import_preserves_validates_and_locks_the_recovery_pair() {
4422        use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
4423        use rpi_harness::session::types::{
4424            AssistantFrameOp, AssistantFrameRecord, RecordBase, SessionStorage,
4425        };
4426        let tmp = tempfile::tempdir().unwrap();
4427        let source = tmp.path().join("source.jsonl");
4428        let progress = tmp.path().join("source.jsonl.progress.jsonl");
4429        let fs: Arc<dyn rpi_tools::FileSystem> =
4430            Arc::new(OsExecutionEnv::with_cwd(tmp.path().into()));
4431        let storage = JsonlSessionStorage::create(
4432            fs,
4433            &source.to_string_lossy(),
4434            JsonlV4Header::new("import-pair".into(), 1, "/".into(), None, None, None),
4435            Arc::new(SystemClock),
4436            Arc::new(DefaultIdGenerator::new()),
4437        )
4438        .await
4439        .unwrap();
4440        storage
4441            .append_progress(vec![AssistantFrameRecord {
4442                base: RecordBase {
4443                    id: "accepted-prefix".into(),
4444                    seq: 0,
4445                    lane: "main".into(),
4446                    timestamp: 0,
4447                },
4448                run_id: "run".into(),
4449                stream_index: 0,
4450                op: AssistantFrameOp::Append,
4451                frame: Some(serde_json::json!({"payload":"keep"})),
4452            }])
4453            .await
4454            .unwrap();
4455        drop(storage);
4456        let original = std::fs::read(&progress).unwrap();
4457        let destination = tmp.path().join("imported");
4458        let imported = import_session_file(&source, &tmp.path().to_string_lossy(), &destination)
4459            .await
4460            .unwrap();
4461        assert_eq!(
4462            imported.read_progress("run").await.unwrap()[0].base.id,
4463            "accepted-prefix"
4464        );
4465        assert_eq!(
4466            std::fs::read(&progress).unwrap(),
4467            original,
4468            "import must not repair or mutate its source"
4469        );
4470        let lock = std::fs::OpenOptions::new()
4471            .create(true)
4472            .write(true)
4473            .open(tmp.path().join("source.jsonl.lock"))
4474            .unwrap();
4475        fs2::FileExt::try_lock_exclusive(&lock).unwrap();
4476        assert!(import_session_file(
4477            &source,
4478            &tmp.path().to_string_lossy(),
4479            &tmp.path().join("busy")
4480        )
4481        .await
4482        .is_err());
4483        drop(lock);
4484        let mut corrupt = String::from_utf8(original.clone()).unwrap();
4485        corrupt = corrupt.replace(
4486            "\"session_id\":\"import-pair\"",
4487            "\"session_id\":\"foreign\"",
4488        );
4489        assert_ne!(corrupt.as_bytes(), original.as_slice());
4490        std::fs::write(&progress, corrupt).unwrap();
4491        assert!(import_session_file(
4492            &source,
4493            &tmp.path().to_string_lossy(),
4494            &tmp.path().join("foreign")
4495        )
4496        .await
4497        .is_err());
4498        std::fs::remove_file(&progress).unwrap();
4499        assert!(import_session_file(
4500            &source,
4501            &tmp.path().to_string_lossy(),
4502            &tmp.path().join("missing")
4503        )
4504        .await
4505        .is_err());
4506    }
4507
4508    #[test]
4509    fn list_session_files_sync_walks_the_cwd_subdirectory() {
4510        let root = std::env::temp_dir().join(format!("rpi-summary-{}-dir", std::process::id()));
4511        let nested = root.join("--proj--");
4512        std::fs::create_dir_all(&nested).unwrap();
4513        let file = nested.join("2026-01-01_a.jsonl");
4514        std::fs::write(&file, "{}\n").unwrap();
4515        let sidecar = nested.join("2026-01-01_a.jsonl.progress.jsonl");
4516        std::fs::write(&sidecar, "{}\n").unwrap();
4517        let found = list_session_files_sync(&root);
4518        assert!(found.iter().any(|p| p == &file));
4519        assert!(!found.contains(&sidecar));
4520        std::fs::remove_dir_all(&root).ok();
4521    }
4522
4523    /// Regression for fork issue #13: with a shared session root, the default
4524    /// picker scope must show only this project's sessions, and All must show
4525    /// every project with its directory tag so a flat list stays traceable.
4526    #[test]
4527    fn review_issue13_default_scope_is_this_project_and_all_is_tagged() {
4528        let tmp = tempfile::tempdir().unwrap();
4529        let root = tmp.path().join("sessions");
4530        let cwd = tmp.path().join("project");
4531        let own = root.join(rpi_harness::session::jsonl::jsonl_session_directory_name(
4532            &cwd.to_string_lossy(),
4533        ));
4534        let foreign = root.join("--some-other-project--");
4535        std::fs::create_dir_all(&own).unwrap();
4536        std::fs::create_dir_all(&foreign).unwrap();
4537        let own_file = own.join("2026-01-01_own.jsonl");
4538        let foreign_file = foreign.join("2026-01-02_foreign.jsonl");
4539        std::fs::write(&own_file, "{}\n").unwrap();
4540        std::fs::write(&foreign_file, "{}\n").unwrap();
4541        // A legacy file directly under the root is not a project subdirectory.
4542        let legacy = root.join("2026-01-03_legacy.jsonl");
4543        std::fs::write(&legacy, "{}\n").unwrap();
4544
4545        let project = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
4546        assert_eq!(project.len(), 1, "default scope must not flatten projects");
4547        assert_eq!(project[0].path, own_file);
4548        assert_eq!(project[0].project, None);
4549
4550        let all = list_session_files_in_scope_sync(&cwd, &root, SessionScope::All);
4551        assert_eq!(all.len(), 3);
4552        let own_project = own.file_name().unwrap().to_str().unwrap();
4553        assert!(all
4554            .iter()
4555            .any(|e| e.path == own_file && e.project.as_deref() == Some(own_project)));
4556        assert!(all
4557            .iter()
4558            .any(|e| e.path == foreign_file
4559                && e.project.as_deref() == Some("--some-other-project--")));
4560        assert!(all.iter().any(|e| e.path == legacy && e.project.is_none()));
4561
4562        assert_eq!(SessionScope::Project.toggled(), SessionScope::All);
4563        assert_eq!(SessionScope::All.toggled(), SessionScope::Project);
4564        assert_eq!(SessionScope::default(), SessionScope::Project);
4565    }
4566
4567    /// The project directory name must be the repo's own encoding, not a
4568    /// re-derivation that drifts from create/open. A relative cwd resolves
4569    /// against the process cwd the same way `OsExecutionEnv::absolute_path` does.
4570    #[test]
4571    fn review_issue13_project_scope_uses_the_repo_directory_encoding() {
4572        let tmp = tempfile::tempdir().unwrap();
4573        let root = tmp.path().join("sessions");
4574        let cwd = tmp.path().join("project");
4575        let name =
4576            rpi_harness::session::jsonl::jsonl_session_directory_name(&cwd.to_string_lossy());
4577        std::fs::create_dir_all(root.join(&name)).unwrap();
4578        let file = root.join(&name).join("a.jsonl");
4579        std::fs::write(&file, "{}\n").unwrap();
4580        // A look-alike directory that a naive "last path component" derivation
4581        // would pick instead. The repo encodes the *full* cwd, so this must not
4582        // be listed by the Project scope.
4583        let lookalike = root.join("--project--");
4584        std::fs::create_dir_all(&lookalike).unwrap();
4585        let other_file = lookalike.join("b.jsonl");
4586        std::fs::write(&other_file, "{}\n").unwrap();
4587        let found = list_session_files_in_scope_sync(&cwd, &root, SessionScope::Project);
4588        assert_eq!(
4589            found,
4590            vec![SessionFileEntry {
4591                path: file,
4592                project: None
4593            }]
4594        );
4595    }
4596
4597    /// Fork issue #13, async path: the `-r` picker's default scope must use the
4598    /// repo's typed list API with an explicit cwd, and the open path must stay
4599    /// unscoped so a row chosen from All still resolves by id.
4600    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4601    async fn review_issue13_resume_scope_and_open_path_agree() {
4602        let tmp = tempfile::tempdir().unwrap();
4603        let root = tmp.path().join("sessions");
4604        let cwd = tmp.path().join("project");
4605        std::fs::create_dir_all(&cwd).unwrap();
4606        let foreign_cwd = tmp.path().join("other");
4607        std::fs::create_dir_all(&foreign_cwd).unwrap();
4608        let cwd_text = cwd.to_string_lossy().into_owned();
4609        let own = create_jsonl_session(&root, &cwd_text).await.unwrap();
4610        let own_id = own.storage().metadata().id.clone();
4611        drop(own);
4612        let foreign = create_jsonl_session(&root, &foreign_cwd.to_string_lossy())
4613            .await
4614            .unwrap();
4615        let foreign_id = foreign.storage().metadata().id.clone();
4616        drop(foreign);
4617
4618        let project =
4619            list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::Project)
4620                .await
4621                .unwrap();
4622        assert_eq!(project.len(), 1, "-r default must not flatten projects");
4623        assert_eq!(project[0].id, own_id);
4624        let all = list_session_metadata_in_scope_in_dir(&cwd_text, &root, SessionScope::All)
4625            .await
4626            .unwrap();
4627        assert_eq!(all.len(), 2);
4628        assert!(all.iter().any(|m| m.cwd == foreign_cwd.to_string_lossy()));
4629        // `list_session_metadata_in_dir` (the open path) must remain unscoped.
4630        let open = list_session_metadata_in_dir(&cwd_text, &root)
4631            .await
4632            .unwrap();
4633        assert_eq!(open.len(), 2);
4634        let found = find_session_metadata(&foreign_id, &cwd_text, &root)
4635            .await
4636            .unwrap();
4637        assert_eq!(found.unwrap().id, foreign_id);
4638    }
4639
4640    /// The default CLI tool set plus the `todo` tool its bundled plugins add.
4641    fn default_prompt_tools() -> Vec<String> {
4642        BUILTIN_TOOL_NAMES
4643            .iter()
4644            .copied()
4645            .chain(["todo"])
4646            .map(str::to_owned)
4647            .collect()
4648    }
4649
4650    #[test]
4651    fn default_prompt_lists_only_the_active_tools() {
4652        let tools = ["read", "grep", "find", "ls"].map(str::to_owned);
4653        let p = default_system_prompt_with_tools("/tmp/proj", true, &tools);
4654        assert!(p.contains("- read  — Read file contents"));
4655        assert!(p.contains("- grep  — Search file contents"));
4656        for absent in ["- edit", "- write", "- bash", "- docs", "todo", "Windows"] {
4657            assert!(
4658                !p.contains(absent),
4659                "{absent} must not appear for a read-only run: {p}"
4660            );
4661        }
4662        assert!(p.contains("Re-stating the same plan without acting on it is a bug"));
4663        let none = default_system_prompt_with_tools("/tmp/proj", false, &[]);
4664        assert!(none.contains("Available tools:\n(none)"));
4665    }
4666
4667    #[test]
4668    fn default_prompt_mentions_cwd_and_tools() {
4669        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
4670        assert!(p.contains("/tmp/proj"));
4671        assert!(p.contains("read"));
4672        assert!(p.contains("bash"));
4673        assert!(p.contains("edit"));
4674        assert!(p.contains("write"));
4675        assert!(p.contains("docs"));
4676        assert!(!p.contains("- grep"));
4677        assert!(!p.contains("- find"));
4678        assert!(!p.contains("- ls"));
4679        assert!(!p.contains("- powershell"));
4680        assert!(p.contains("Bash/POSIX syntax, also on Windows"));
4681    }
4682
4683    #[test]
4684    fn default_prompt_instructs_language_matching() {
4685        // A Chinese (or any non-English) user gets a same-language reply
4686        // without having to ask every turn.
4687        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
4688        assert!(
4689            p.contains("same language as the user's latest message"),
4690            "the prompt must tell the model to mirror the user's language: {p}"
4691        );
4692    }
4693
4694    #[test]
4695    fn default_prompt_keeps_working_state_in_the_visible_channel() {
4696        // Regression guard for the re-plan loop: on openai-compatible providers
4697        // the assistant's `thinking` blocks are dropped when the next request is
4698        // built (`providers/openai_completions.rs`: `Content::text_only`), so a
4699        // plan that lives only in reasoning is re-derived every turn. One
4700        // observed session paid for that 112 times in a single run, and twice
4701        // hallucinated the user's input ("The user is greeting me with hello",
4702        // with no such message). See `docs/llm-repetition-forensics.md` §八.
4703        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
4704        let lower = p.to_lowercase();
4705        // The rule must state the mechanism, not just "be clear".
4706        assert!(
4707            lower.contains("reasoning is not") && lower.contains("carried into your next turn"),
4708            "the prompt must explain that reasoning does not survive the turn: {p}"
4709        );
4710        // Working state stays visible; extension-specific rules require opt-in.
4711        assert!(
4712            lower.contains("visible") && !lower.contains("todo tool"),
4713            "the prompt must keep state visible without inventing extension rules: {p}"
4714        );
4715        // …plus the anti-repetition rule itself.
4716        assert!(
4717            lower.contains("re-stating the same plan"),
4718            "the prompt must call out plan re-statement as a bug: {p}"
4719        );
4720        // And the guidance must not instruct re-reading what is already shown.
4721        assert!(
4722            lower.contains("already shown earlier"),
4723            "the prompt must discourage re-fetching known content: {p}"
4724        );
4725    }
4726
4727    #[test]
4728    fn default_prompt_does_not_claim_reasoning_is_lost_when_it_is_replayed() {
4729        // `compat.requiresThinkingAsText` (and the native thinking channels of
4730        // anthropic-messages / openai-responses) DO carry the model's reasoning
4731        // back on the next request. Telling such a model "reasoning is not
4732        // carried into your next turn" is false, and the instruction to restate
4733        // the plan every turn is exactly the busy-work the re-plan analysis
4734        // measured. The wording must flip with the mechanism.
4735        let p = default_system_prompt_with_tools("/tmp/proj", true, &default_prompt_tools());
4736        let lower = p.to_lowercase();
4737        assert!(
4738            lower.contains("carried back"),
4739            "a replaying model must be told its reasoning survives: {p}"
4740        );
4741        assert!(
4742            !lower.contains("reasoning is not"),
4743            "the replayed variant must not claim reasoning is dropped: {p}"
4744        );
4745        assert!(
4746            lower.contains("do not re-derive"),
4747            "the replayed variant must forbid re-deriving the plan: {p}"
4748        );
4749        assert!(
4750            lower.contains("do not re-derive") && lower.contains("re-stating the same plan"),
4751            "the anti-repetition rule must survive the flip: {p}"
4752        );
4753        assert!(
4754            lower.contains("already shown earlier"),
4755            "the re-read rule must survive the flip: {p}"
4756        );
4757    }
4758
4759    #[test]
4760    fn default_prompt_states_each_rule_once() {
4761        // The plan rule, the todo tool and the anti-repetition line used to be
4762        // spread over two guidelines that repeated each other.
4763        for replayed in [false, true] {
4764            let p =
4765                default_system_prompt_with_tools("/tmp/proj", replayed, &default_prompt_tools());
4766            for phrase in ["the same plan", "Windows", "guessing"] {
4767                assert_eq!(p.matches(phrase).count(), 1, "{phrase:?} repeated: {p}");
4768            }
4769            assert!(
4770                !p.contains("todo tool"),
4771                "extension rules require explicit metadata"
4772            );
4773        }
4774    }
4775
4776    /// Only side-effect-free tools may be replayed after a crash.
4777    ///
4778    /// Regression guard for an inverted default: `ToolReplay` used to default to
4779    /// `Safe` and the CLI then marked *every* tool `Safe`, so the first time
4780    /// recovery acted on the flag it would have re-run `bash`/`write`/`edit` and
4781    /// duplicated their side effects. upstream defaults to `"never"`
4782    /// (`drive/tools.ts: tool.replay ?? "never"`).
4783    #[test]
4784    fn only_read_only_tools_are_replayable() {
4785        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
4786        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
4787        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
4788        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
4789        let tools = build_tools(&context, &Args::default());
4790
4791        let replay_of = |name: &str| {
4792            tools
4793                .iter()
4794                .find(|tool| tool.tool.schema().name == name)
4795                .map(|tool| tool.replay)
4796        };
4797
4798        for read_only in ["read", "docs"] {
4799            assert_eq!(
4800                replay_of(read_only),
4801                Some(ToolReplay::Safe),
4802                "{read_only} is side-effect free, so recovery may re-run it"
4803            );
4804        }
4805        for mutating in ["bash", "edit", "write", "powershell"] {
4806            if let Some(replay) = replay_of(mutating) {
4807                assert_eq!(
4808                    replay,
4809                    ToolReplay::Never,
4810                    "{mutating} must never be replayed: re-running it would duplicate its effect"
4811                );
4812            }
4813        }
4814    }
4815
4816    #[test]
4817    fn default_tools_include_docs_lookup() {
4818        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
4819        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
4820        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
4821        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
4822        let names: Vec<String> = build_tools(&context, &Args::default())
4823            .iter()
4824            .map(|tool| tool.tool.schema().name.clone())
4825            .collect();
4826
4827        // `docs` is a default capability; the legacy rpi-only lookup tools stay
4828        // unregistered. Asserted by membership (not exact equality) because
4829        // `powershell` is Windows-only and `settings.json#defaultTools` may
4830        // narrow the set in a developer's environment.
4831        assert!(names.contains(&"docs".to_string()));
4832        for legacy in ["grep", "find", "ls"] {
4833            assert!(
4834                !names.contains(&legacy.to_string()),
4835                "legacy tool {legacy} should not be registered by default"
4836            );
4837        }
4838    }
4839
4840    #[test]
4841    fn reload_settings_preflight_respects_trust() {
4842        struct RestoreConfigDir(Option<std::ffi::OsString>);
4843
4844        impl Drop for RestoreConfigDir {
4845            fn drop(&mut self) {
4846                match self.0.take() {
4847                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
4848                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
4849                }
4850            }
4851        }
4852
4853        let _guard = crate::config::test_support::env_lock().lock().unwrap();
4854        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4855        let tmp = tempfile::tempdir().unwrap();
4856        let agent = tmp.path().join("agent");
4857        let cwd = tmp.path().join("project");
4858        std::fs::create_dir_all(&agent).unwrap();
4859        std::fs::create_dir_all(cwd.join(".rpi")).unwrap();
4860        std::fs::write(agent.join("settings.json"), "{}").unwrap();
4861        std::fs::write(cwd.join(".rpi/settings.json"), "{ malformed").unwrap();
4862        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
4863        let args = Args::default();
4864
4865        let trusted = validate_settings_for_reload(&args, &cwd, true);
4866        let untrusted = validate_settings_for_reload(&args, &cwd, false);
4867        assert!(trusted
4868            .unwrap_err()
4869            .contains("could not load project settings"));
4870        assert!(untrusted.is_ok());
4871
4872        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
4873        assert!(validate_settings_for_reload(&args, &cwd, false)
4874            .unwrap_err()
4875            .contains("could not load global settings"));
4876
4877        let local_only = Args {
4878            dev_local_only: true,
4879            ..Args::default()
4880        };
4881        assert!(validate_settings_for_reload(&local_only, &cwd, true).is_ok());
4882    }
4883
4884    #[tokio::test(flavor = "current_thread")]
4885    async fn reload_preserves_live_resources_when_settings_break() {
4886        struct RestoreConfigDir(Option<std::ffi::OsString>);
4887
4888        impl Drop for RestoreConfigDir {
4889            fn drop(&mut self) {
4890                match self.0.take() {
4891                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
4892                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
4893                }
4894            }
4895        }
4896
4897        let _guard = crate::config::test_support::env_lock().lock().unwrap();
4898        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
4899        let tmp = tempfile::tempdir().unwrap();
4900        let agent = tmp.path().join("agent");
4901        let cwd = tmp.path().join("project");
4902        let skill_dir = tmp.path().join("configured-skills");
4903        std::fs::create_dir_all(&agent).unwrap();
4904        std::fs::create_dir_all(&cwd).unwrap();
4905        std::fs::create_dir_all(&skill_dir).unwrap();
4906        std::fs::write(
4907            skill_dir.join("SKILL.md"),
4908            "---\nname: keep-me\ndescription: Reload sentinel\n---\nKeep this skill loaded.",
4909        )
4910        .unwrap();
4911        std::fs::write(
4912            agent.join("settings.json"),
4913            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
4914        )
4915        .unwrap();
4916        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
4917
4918        let resolved = crate::provider::resolve(
4919            Some("anthropic"),
4920            Some(crate::provider::DEFAULT_MODEL_ID),
4921            None,
4922            Some("test-key"),
4923            None,
4924        )
4925        .unwrap();
4926        let args = Args {
4927            trust_override: Some(false),
4928            no_session: true,
4929            no_extensions: true,
4930            no_prompt_templates: true,
4931            no_context_files: true,
4932            system_prompt: Some("stable system prompt".into()),
4933            ..Args::default()
4934        };
4935        let (harness, _events, context) = build(&resolved, &args, &cwd, false).await.unwrap();
4936        let before_resources = harness.get_resources().await.unwrap();
4937        assert_eq!(before_resources.skills.as_ref().unwrap().len(), 1);
4938        assert_eq!(before_resources.skills.as_ref().unwrap()[0].name, "keep-me");
4939        let before_prompt = harness.get_system_prompt().await.unwrap();
4940        let before_tools: Vec<String> = harness
4941            .get_tools()
4942            .await
4943            .unwrap()
4944            .iter()
4945            .map(|tool| tool.tool.schema().name.clone())
4946            .collect();
4947        let before_bridge = context
4948            .action_bridge
4949            .lock()
4950            .unwrap()
4951            .as_ref()
4952            .unwrap()
4953            .clone();
4954
4955        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
4956        let outcome = reload_extension_resources(&harness, &context).await;
4957
4958        assert!(outcome.had_warnings);
4959        assert!(outcome.summary.contains("Settings reload failed"));
4960        assert!(outcome.summary.contains("could not load global settings"));
4961        // Hard failure keeps the previous resources; the outcome must not
4962        // advertise a fresh trust policy either (theme discovery keeps the
4963        // registry it already matches).
4964        assert_eq!(outcome.project_trusted, None);
4965        assert_eq!(harness.get_resources().await.unwrap(), before_resources);
4966        assert_eq!(harness.get_system_prompt().await.unwrap(), before_prompt);
4967        let after_tools: Vec<String> = harness
4968            .get_tools()
4969            .await
4970            .unwrap()
4971            .iter()
4972            .map(|tool| tool.tool.schema().name.clone())
4973            .collect();
4974        assert_eq!(after_tools, before_tools);
4975        let after_bridge = context
4976            .action_bridge
4977            .lock()
4978            .unwrap()
4979            .as_ref()
4980            .unwrap()
4981            .clone();
4982        assert!(Arc::ptr_eq(&after_bridge, &before_bridge));
4983    }
4984
4985    #[tokio::test(flavor = "current_thread")]
4986    async fn reload_outcome_carries_the_current_project_trust() {
4987        struct RestoreConfigDir(Option<std::ffi::OsString>);
4988
4989        impl Drop for RestoreConfigDir {
4990            fn drop(&mut self) {
4991                match self.0.take() {
4992                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
4993                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
4994                }
4995            }
4996        }
4997
4998        let _guard = crate::config::test_support::env_lock().lock().unwrap();
4999        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5000        let tmp = tempfile::tempdir().unwrap();
5001        let agent = tmp.path().join("agent");
5002        let cwd = tmp.path().join("project");
5003        std::fs::create_dir_all(&agent).unwrap();
5004        std::fs::create_dir_all(&cwd).unwrap();
5005        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5006
5007        // Startup snapshot: trusted.
5008        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
5009        let resolved = crate::provider::resolve(
5010            Some("anthropic"),
5011            Some(crate::provider::DEFAULT_MODEL_ID),
5012            None,
5013            Some("test-key"),
5014            None,
5015        )
5016        .unwrap();
5017        let args = Args {
5018            no_session: true,
5019            no_extensions: true,
5020            no_prompt_templates: true,
5021            no_context_files: true,
5022            system_prompt: Some("stable system prompt".into()),
5023            ..Args::default()
5024        };
5025        let (harness, _events, context) = build(&resolved, &args, &cwd, true).await.unwrap();
5026        assert!(context.project_trusted, "startup snapshot is trusted");
5027
5028        // /trust no, then /reload: the outcome must report the CURRENT
5029        // decision, not the immutable startup snapshot.
5030        crate::config::set_project_trust(&cwd, Some(false)).unwrap();
5031        let outcome = reload_extension_resources(&harness, &context).await;
5032        assert!(!outcome.had_errors, "{}", outcome.summary);
5033        assert_eq!(outcome.project_trusted, Some(false));
5034
5035        // And the opposite transition back to trusted.
5036        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
5037        let outcome = reload_extension_resources(&harness, &context).await;
5038        assert!(!outcome.had_errors, "{}", outcome.summary);
5039        assert_eq!(outcome.project_trusted, Some(true));
5040    }
5041
5042    #[test]
5043    fn reload_preparation_rejects_settings_changed_during_derivation() {
5044        struct RestoreConfigDir(Option<std::ffi::OsString>);
5045
5046        impl Drop for RestoreConfigDir {
5047            fn drop(&mut self) {
5048                match self.0.take() {
5049                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5050                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5051                }
5052            }
5053        }
5054
5055        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5056        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5057        let tmp = tempfile::tempdir().unwrap();
5058        let agent = tmp.path().join("agent");
5059        let cwd = tmp.path().join("project");
5060        let first_skill_dir = tmp.path().join("first-skills");
5061        let second_skill_dir = tmp.path().join("second-skills");
5062        std::fs::create_dir_all(&agent).unwrap();
5063        std::fs::create_dir_all(&cwd).unwrap();
5064        std::fs::write(
5065            agent.join("settings.json"),
5066            serde_json::json!({"skillDirs": [first_skill_dir]}).to_string(),
5067        )
5068        .unwrap();
5069        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5070        let args = Args {
5071            trust_override: Some(false),
5072            no_extensions: true,
5073            no_prompt_templates: true,
5074            ..Args::default()
5075        };
5076
5077        let result = prepare_reload_inputs_inner(&args, &cwd, false, || {
5078            std::fs::write(
5079                agent.join("settings.json"),
5080                serde_json::json!({"skillDirs": [second_skill_dir]}).to_string(),
5081            )
5082            .unwrap();
5083        });
5084
5085        let error = result
5086            .err()
5087            .expect("settings mutation must fail preparation");
5088        assert!(error.contains("settings changed while reload inputs were being prepared"));
5089    }
5090
5091    #[tokio::test(flavor = "current_thread")]
5092    async fn reload_uses_frozen_settings_inputs_after_preparation() {
5093        struct RestoreConfigDir(Option<std::ffi::OsString>);
5094
5095        impl Drop for RestoreConfigDir {
5096            fn drop(&mut self) {
5097                match self.0.take() {
5098                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5099                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5100                }
5101            }
5102        }
5103
5104        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5105        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5106        let tmp = tempfile::tempdir().unwrap();
5107        let agent = tmp.path().join("agent");
5108        let cwd = tmp.path().join("project");
5109        let skill_dir = tmp.path().join("configured-skills");
5110        std::fs::create_dir_all(&agent).unwrap();
5111        std::fs::create_dir_all(&cwd).unwrap();
5112        std::fs::create_dir_all(&skill_dir).unwrap();
5113        std::fs::write(
5114            skill_dir.join("SKILL.md"),
5115            "---\nname: frozen-skill\ndescription: Reload sentinel\n---\nFrozen input.",
5116        )
5117        .unwrap();
5118        std::fs::write(
5119            agent.join("settings.json"),
5120            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
5121        )
5122        .unwrap();
5123        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5124
5125        let resolved = crate::provider::resolve(
5126            Some("anthropic"),
5127            Some(crate::provider::DEFAULT_MODEL_ID),
5128            None,
5129            Some("test-key"),
5130            None,
5131        )
5132        .unwrap();
5133        let args = Args {
5134            trust_override: Some(false),
5135            no_session: true,
5136            no_extensions: true,
5137            no_prompt_templates: true,
5138            no_context_files: true,
5139            system_prompt: Some("stable system prompt".into()),
5140            ..Args::default()
5141        };
5142        let (harness, _events, context) = build(&resolved, &args, &cwd, false).await.unwrap();
5143
5144        let outcome = reload_extension_resources_inner(&harness, &context, || {
5145            std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
5146        })
5147        .await;
5148
5149        assert!(!outcome.summary.contains("Settings reload failed"));
5150        assert_eq!(
5151            outcome.summary,
5152            "Reloaded 0 plugin(s), 1 skill(s), 0 prompt(s)."
5153        );
5154        let resources = harness.get_resources().await.unwrap();
5155        let skills = resources.skills.as_ref().unwrap();
5156        assert_eq!(skills.len(), 1);
5157        assert_eq!(skills[0].name, "frozen-skill");
5158    }
5159
5160    #[tokio::test]
5161    async fn reload_resource_paths_include_explicit_skill_and_prompt_files() {
5162        let tmp = tempfile::tempdir().unwrap();
5163        let skill_path = tmp.path().join("explicit-skill.md");
5164        std::fs::write(
5165            &skill_path,
5166            "---\nname: explicit-skill\ndescription: Explicit skill\n---\nSkill body",
5167        )
5168        .unwrap();
5169        let prompt_path = tmp.path().join("explicit-prompt.md");
5170        std::fs::write(
5171            &prompt_path,
5172            "---\ndescription: Explicit prompt\n---\nPrompt body",
5173        )
5174        .unwrap();
5175
5176        let args = Args {
5177            skill: vec![skill_path.clone()],
5178            prompt_template: vec![prompt_path.clone()],
5179            ..Args::default()
5180        };
5181        let skill_paths = append_reload_resource_paths(Vec::new(), &args.skill, &[], &[], &[]);
5182        let prompt_paths =
5183            append_reload_resource_paths(Vec::new(), &args.prompt_template, &[], &[], &[]);
5184        let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
5185        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env;
5186
5187        let skills = load_skills_with_precedence(&env_dyn, &skill_paths).await;
5188        assert_eq!(skills.skills.len(), 1, "{:?}", skills.diagnostics);
5189        assert_eq!(skills.skills[0].name, "explicit-skill");
5190
5191        let prompts = load_prompt_templates_with_precedence(&env_dyn, &prompt_paths).await;
5192        assert_eq!(
5193            prompts.prompt_templates.len(),
5194            1,
5195            "{:?}",
5196            prompts.diagnostics
5197        );
5198        assert_eq!(prompts.prompt_templates[0].name, "explicit-prompt");
5199    }
5200
5201    #[test]
5202    fn tool_policy_applies_to_rust_and_js_active_names() {
5203        let names = vec![
5204            "read".to_string(),
5205            "ask_user_question".to_string(),
5206            "write".to_string(),
5207        ];
5208
5209        let args = Args {
5210            tools: Some(vec!["read".into(), "ask_user_question".into()]),
5211            ..Args::default()
5212        };
5213        assert_eq!(
5214            filter_active_tool_names(names.clone(), &args),
5215            vec!["read", "ask_user_question"]
5216        );
5217
5218        let args = Args {
5219            exclude_tools: Some(vec!["ask_user_question".into()]),
5220            ..Args::default()
5221        };
5222        assert_eq!(
5223            filter_active_tool_names(names.clone(), &args),
5224            vec!["read", "write"]
5225        );
5226
5227        let args = Args {
5228            no_tools: true,
5229            ..Args::default()
5230        };
5231        assert!(filter_active_tool_names(names, &args).is_empty());
5232    }
5233
5234    #[test]
5235    fn select_ephemeral_when_no_session() {
5236        let args = Args {
5237            no_session: true,
5238            ..Args::default()
5239        };
5240        let cwd = Path::new("/tmp");
5241        assert!(matches!(
5242            select_session(&args, cwd),
5243            SessionSelection::Ephemeral
5244        ));
5245    }
5246
5247    #[test]
5248    fn project_resources_load_by_default_and_allow_explicit_opt_out() {
5249        let defaults = Args::default();
5250        assert!(resolve_project_trust(
5251            &defaults,
5252            Path::new("C:/definitely-not-a-project")
5253        ));
5254
5255        let denied = Args {
5256            trust_override: Some(false),
5257            ..Args::default()
5258        };
5259        assert!(!resolve_project_trust(
5260            &denied,
5261            Path::new("C:/definitely-not-a-project")
5262        ));
5263    }
5264
5265    #[tokio::test(flavor = "current_thread")]
5266    async fn build_preserves_the_supplied_startup_project_snapshot() {
5267        struct RestoreConfigDir(Option<std::ffi::OsString>);
5268
5269        impl Drop for RestoreConfigDir {
5270            fn drop(&mut self) {
5271                match self.0.take() {
5272                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5273                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5274                }
5275            }
5276        }
5277
5278        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5279        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5280        let tmp = tempfile::tempdir().unwrap();
5281        let agent = tmp.path().join("agent");
5282        let cwd = tmp.path().join("project");
5283        std::fs::create_dir_all(&agent).unwrap();
5284        std::fs::create_dir_all(&cwd).unwrap();
5285        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5286
5287        let resolved = crate::provider::resolve(
5288            Some("anthropic"),
5289            Some(crate::provider::DEFAULT_MODEL_ID),
5290            None,
5291            Some("test-key"),
5292            None,
5293        )
5294        .unwrap();
5295        let args = Args {
5296            trust_override: Some(false),
5297            no_session: true,
5298            no_tools: true,
5299            no_extensions: true,
5300            no_skills: true,
5301            no_prompt_templates: true,
5302            no_context_files: true,
5303            system_prompt: Some("test prompt".into()),
5304            ..Args::default()
5305        };
5306
5307        let (_, _, context) = build(&resolved, &args, &cwd, true).await.unwrap();
5308
5309        assert_eq!(context.cwd, cwd);
5310        assert!(context.project_trusted);
5311    }
5312
5313    #[tokio::test(flavor = "current_thread")]
5314    async fn build_applies_the_name_flag_to_the_session() {
5315        struct RestoreConfigDir(Option<std::ffi::OsString>);
5316
5317        impl Drop for RestoreConfigDir {
5318            fn drop(&mut self) {
5319                match self.0.take() {
5320                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5321                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5322                }
5323            }
5324        }
5325
5326        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5327        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5328        let tmp = tempfile::tempdir().unwrap();
5329        let agent = tmp.path().join("agent");
5330        let cwd = tmp.path().join("project");
5331        std::fs::create_dir_all(&agent).unwrap();
5332        std::fs::create_dir_all(&cwd).unwrap();
5333        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5334
5335        let resolved = crate::provider::resolve(
5336            Some("anthropic"),
5337            Some(crate::provider::DEFAULT_MODEL_ID),
5338            None,
5339            Some("test-key"),
5340            None,
5341        )
5342        .unwrap();
5343        let args = Args {
5344            trust_override: Some(false),
5345            no_tools: true,
5346            no_extensions: true,
5347            no_skills: true,
5348            no_prompt_templates: true,
5349            no_context_files: true,
5350            system_prompt: Some("test prompt".into()),
5351            name: Some("smoke name".into()),
5352            session_dir: Some(cwd.join("sessions")),
5353            ..Args::default()
5354        };
5355
5356        let (harness, _, _) = build(&resolved, &args, &cwd, true).await.unwrap();
5357        assert_eq!(
5358            harness.get_name().await.unwrap().as_deref(),
5359            Some("smoke name")
5360        );
5361    }
5362
5363    #[test]
5364    fn select_latest_for_continue_and_resume() {
5365        let _env = crate::config::test_support::SessionDirEnv::new(None);
5366        let args = Args {
5367            continue_session: true,
5368            ..Args::default()
5369        };
5370        let cwd = Path::new("/tmp");
5371        assert!(matches!(
5372            select_session(&args, cwd),
5373            SessionSelection::Latest { .. }
5374        ));
5375
5376        let args = Args {
5377            resume: true,
5378            ..Args::default()
5379        };
5380        assert!(matches!(
5381            select_session(&args, cwd),
5382            SessionSelection::Latest { .. }
5383        ));
5384    }
5385
5386    #[test]
5387    fn select_by_id_for_session_flag() {
5388        let _env = crate::config::test_support::SessionDirEnv::new(None);
5389        let args = Args {
5390            session: Some("01a02ece".into()),
5391            ..Args::default()
5392        };
5393        let cwd = Path::new("/tmp");
5394        assert!(matches!(
5395            select_session(&args, cwd),
5396            SessionSelection::ById { id, .. } if id == "01a02ece"
5397        ));
5398    }
5399
5400    #[test]
5401    fn select_new_with_custom_dir() {
5402        let _env = crate::config::test_support::SessionDirEnv::new(None);
5403        let args = Args {
5404            session_dir: Some(PathBuf::from("/tmp/sess")),
5405            ..Args::default()
5406        };
5407        let cwd = Path::new("/tmp");
5408        match select_session(&args, cwd) {
5409            SessionSelection::New { dir, .. } => assert_eq!(dir, PathBuf::from("/tmp/sess")),
5410            other => panic!("expected New, got {other:?}"),
5411        }
5412    }
5413
5414    #[test]
5415    fn select_new_default_dir() {
5416        let _env = crate::config::test_support::SessionDirEnv::new(None);
5417        let args = Args::default();
5418        let cwd = Path::new("/proj");
5419        match select_session(&args, cwd) {
5420            SessionSelection::New { dir, .. } => {
5421                assert_eq!(dir, Path::new("/proj/.rpi/sessions"));
5422            }
5423            other => panic!("expected New, got {other:?}"),
5424        }
5425    }
5426
5427    #[test]
5428    fn default_session_dir_only_uses_rpi() {
5429        let _env = crate::config::test_support::SessionDirEnv::new(None);
5430        let tmp = tempfile::tempdir().unwrap();
5431        let cwd = tmp.path();
5432        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
5433        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
5434        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
5435        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
5436    }
5437
5438    #[test]
5439    fn default_session_dir_uses_env_var() {
5440        let tmp = tempfile::tempdir().unwrap();
5441        let cwd = tmp.path();
5442        let custom = tmp.path().join("custom_sessions");
5443        let _env = crate::config::test_support::SessionDirEnv::new(Some(&custom));
5444        assert_eq!(default_session_dir(cwd), custom);
5445    }
5446
5447    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5448    async fn ephemeral_session_builds_roundtrips() {
5449        // Sanity: the ephemeral path produces a usable Session facade (the
5450        // harness build itself needs a provider; tested via the integration
5451        // path in tests/build.rs instead).
5452        let s = ephemeral_session();
5453        let leaf = s.get_leaf_id().await;
5454        assert!(leaf.is_ok());
5455    }
5456
5457    // NOTE: `build_tools`/`active_tool_names` integration is exercised by the
5458    // `tests/build.rs` harness-build test (needs a provider + multi-thread rt).
5459
5460    /// The exclusion policy, checked against the constants rather than copies.
5461    ///
5462    /// `rpi-tools` builds its exclusion from `rpi-plugin-sdk`'s declarations, so
5463    /// within this repo a rename is a compile error — this test is not the link
5464    /// between those two crates any more. What it still guards is the part the
5465    /// compiler cannot see:
5466    ///
5467    /// - **The wire values.** `rpi-langfuse` lives in a different repository and
5468    ///   agrees on the *strings*, not the constant paths. Rewriting a constant's
5469    ///   value would compile here and silently stop matching there, so the exact
5470    ///   values are pinned below. Changing one is a deliberate, breaking change to
5471    ///   a cross-repo contract, and it should fail here first.
5472    /// - **Coverage.** Every name the SDK declares must actually be excluded.
5473    /// - **Narrowness.** The user's own configuration must still reach the shell.
5474    #[test]
5475    fn host_private_env_matches_the_declared_contract() {
5476        // 1. The wire values. Pinned literally on purpose: see the doc comment.
5477        assert_eq!(rpi_plugin_sdk::SESSION_ID_ENV, "RPI_SESSION_ID");
5478        assert_eq!(
5479            rpi_plugin_sdk::SUBAGENT_PARENT_ENV,
5480            [
5481                "LANGFUSE_PI_PARENT_TRACE_ID",
5482                "LANGFUSE_PI_PARENT_SPAN_ID",
5483                "LANGFUSE_PI_PARENT_SESSION_ID",
5484                "LANGFUSE_PI_PARENT_DEPTH",
5485            ],
5486            "these strings are what rpi-langfuse (a different repo) matches; a \
5487             change here is a breaking cross-repo change, not a refactor"
5488        );
5489
5490        // 2. Coverage — derived from the declarations, so a newly added family
5491        //    member is checked without anyone remembering to extend this test.
5492        for name in rpi_plugin_sdk::SUBAGENT_PARENT_ENV
5493            .iter()
5494            .chain(std::iter::once(&rpi_plugin_sdk::SESSION_ID_ENV))
5495        {
5496            assert!(
5497                rpi_tools::is_host_private_env(name),
5498                "`{name}` must not reach a spawned shell, but rpi-tools excludes only {:?}",
5499                rpi_tools::HOST_PRIVATE_ENV
5500            );
5501        }
5502
5503        // 3. Narrowness — these name how the *user* configured the run and are
5504        //    exactly what a command inside the shell should still see.
5505        for visible in [
5506            crate::args::RPI_OFFLINE_ENV,
5507            crate::config::CONFIG_DIR_ENV,
5508            "PATH",
5509        ] {
5510            assert!(
5511                !rpi_tools::is_host_private_env(visible),
5512                "{visible} describes the user's configuration and must still reach the shell"
5513            );
5514        }
5515    }
5516    #[tokio::test]
5517    async fn reload_shutdown_joins_all_handlers_even_after_veto() {
5518        use rpi_plugin_sdk::{EventTag, StablePluginEvent};
5519        use std::sync::atomic::AtomicUsize;
5520        static CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<AtomicUsize>> =
5521            rpi_plugin_sdk::handles::ToolHandles::new();
5522        struct ContextOwner(usize);
5523        impl Drop for ContextOwner {
5524            fn drop(&mut self) {
5525                drop(CONTEXTS.remove(self.0 as rpi_plugin_sdk::StepHandle));
5526            }
5527        }
5528        extern "C" fn stop(_: StablePluginEvent, data: *mut std::ffi::c_void) -> i32 {
5529            let context = CONTEXTS.get(data).expect("live test context");
5530            let calls = context.lock().clone();
5531            std::thread::sleep(std::time::Duration::from_millis(20));
5532            if calls.fetch_add(1, Ordering::SeqCst) == 0 {
5533                rpi_plugin_sdk::EVENT_HANDLER_ABORT
5534            } else {
5535                0
5536            }
5537        }
5538        let calls = Arc::new(AtomicUsize::new(0));
5539        let context = CONTEXTS.insert(calls.clone());
5540        let _owner = ContextOwner(context as usize);
5541        let mut registry = rpi_extensions::ExtensionRegistry::new();
5542        for name in ["first", "second"] {
5543            registry.register_event_handler(name.into(), EventTag::SessionShutdown, stop, context);
5544        }
5545        super::shutdown_extensions_for_reload(
5546            Some(Arc::new(registry.snapshot())),
5547            rpi_extensions::PluginKeepalive::empty(),
5548        )
5549        .await
5550        .unwrap();
5551        assert_eq!(calls.load(Ordering::SeqCst), 2);
5552    }
5553
5554    // ---- restored-session working directory ----
5555
5556    /// A restore peek must name the directory the session was created in —
5557    /// that is the whole point of recording it. Everything downstream (tool
5558    /// env, system prompt, context files, extensions) keys off the run's cwd,
5559    /// so a peek that falls back to the launch directory would leave the
5560    /// resumed agent editing files in whatever directory `rpi` happened to be
5561    /// started from.
5562    #[tokio::test]
5563    async fn a_restored_session_adopts_its_recorded_directory() {
5564        let tmp = tempfile::tempdir().unwrap();
5565        let project = tmp.path().join("project-a");
5566        let launch = tmp.path().join("launch-dir");
5567        let sessions = tmp.path().join("sessions");
5568        std::fs::create_dir_all(&project).unwrap();
5569        std::fs::create_dir_all(&launch).unwrap();
5570        std::fs::create_dir_all(&sessions).unwrap();
5571        create_jsonl_session_with_id(
5572            &sessions,
5573            &project.to_string_lossy(),
5574            Some("cwdadopt01".into()),
5575        )
5576        .await
5577        .unwrap();
5578
5579        let selection = SessionSelection::ById {
5580            id: "cwdadopt01".into(),
5581            dir: sessions.clone(),
5582        };
5583        let peeked = peek_restored_session_cwd(&selection, &launch)
5584            .await
5585            .expect("a resumable session with a recorded cwd");
5586        assert_eq!(peeked.recorded, project);
5587        assert_eq!(peeked.adopted, Some(project));
5588    }
5589
5590    /// A recorded directory that no longer exists must NOT be adopted: the run
5591    /// falls back to the launch cwd, and the peek hands back the record so the
5592    /// host can say so (instead of the old behaviour of eprintln-ing mid-TUI).
5593    #[tokio::test]
5594    async fn a_missing_recorded_directory_is_reported_not_adopted() {
5595        let tmp = tempfile::tempdir().unwrap();
5596        let gone = tmp.path().join("project-gone");
5597        let launch = tmp.path().join("launch-dir");
5598        let sessions = tmp.path().join("sessions");
5599        std::fs::create_dir_all(&launch).unwrap();
5600        std::fs::create_dir_all(&sessions).unwrap();
5601        create_jsonl_session_with_id(
5602            &sessions,
5603            &gone.to_string_lossy(),
5604            Some("cwdgone001".into()),
5605        )
5606        .await
5607        .unwrap();
5608
5609        let selection = SessionSelection::ById {
5610            id: "cwdgone001".into(),
5611            dir: sessions.clone(),
5612        };
5613        let peeked = peek_restored_session_cwd(&selection, &launch)
5614            .await
5615            .expect("the session itself is resumable");
5616        assert_eq!(peeked.recorded, gone);
5617        assert_eq!(peeked.adopted, None);
5618        let note = crate::session_cwd::missing_session_cwd_note(&peeked.recorded, &launch);
5619        assert!(note.contains("no longer exists"), "{note}");
5620        assert!(note.contains("launch-dir"), "{note}");
5621    }
5622
5623    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5624    async fn legacy_progress_upgrade_normal_open_runs_and_reopens() {
5625        use rpi_ai::providers::faux::{FauxProvider, FauxScript};
5626        use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
5627        use rpi_harness::session::jsonl::{
5628            encode_header, JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
5629            JsonlV4Header,
5630        };
5631        let tmp = tempfile::tempdir().unwrap();
5632        let sessions = tmp.path().join("sessions");
5633        std::fs::create_dir_all(&sessions).unwrap();
5634        let cwd = tmp.path().to_string_lossy().into_owned();
5635        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
5636            fs: Arc::new(OsExecutionEnv::with_cwd(tmp.path().into())),
5637            sessions_root: sessions.to_string_lossy().into_owned(),
5638            clock: Arc::new(SystemClock),
5639            ids: Arc::new(DefaultIdGenerator::new()),
5640        });
5641        let fixture = repo
5642            .create_typed(&JsonlSessionCreateOptions {
5643                id: Some("legacycli001".into()),
5644                parent_session_id: None,
5645                cwd: cwd.clone(),
5646                metadata: None,
5647            })
5648            .await
5649            .unwrap();
5650        let path = PathBuf::from(fixture.jsonl_metadata().path);
5651        drop(fixture);
5652        let sidecar = PathBuf::from(format!("{}.progress.jsonl", path.display()));
5653        std::fs::remove_file(&sidecar).unwrap();
5654        let header = JsonlV4Header::new("legacycli001".into(), 1, cwd.clone(), None, None, None);
5655        std::fs::write(&path, encode_header(&header)).unwrap();
5656        assert!(!sidecar.exists());
5657        for _ in 0..2 {
5658            let restored = open_session_by_id_in_dir("legacycli001", &cwd, &sessions)
5659                .await
5660                .map_err(|e| e.to_string())
5661                .unwrap();
5662            assert_eq!(restored.session.storage().metadata().id, "legacycli001");
5663            let provider =
5664                FauxProvider::new(FauxScript::new().with_text("continued legacy session"));
5665            let harness = AgentHarness::create(AgentHarnessOptions {
5666                model: provider.default_model().clone(),
5667                models: vec![provider],
5668                session: restored.session,
5669                allow_existing_session: true,
5670                ..Default::default()
5671            })
5672            .await
5673            .unwrap();
5674            let run = harness.prompt_text("continue", vec![]).await.unwrap();
5675            assert!(matches!(run.outcome, HarnessRunOutcome::Completed { .. }));
5676        }
5677        let content = std::fs::read_to_string(&path).unwrap();
5678        assert!(content.lines().next().unwrap().contains("progressFormat"));
5679        assert!(sidecar.exists());
5680    }
5681
5682    /// `open_session` hands back the recorded directory as data (for the
5683    /// `/session` hot-switch notes) while still opening the session normally.
5684    #[tokio::test]
5685    async fn open_session_reports_the_recorded_directory() {
5686        let tmp = tempfile::tempdir().unwrap();
5687        let project = tmp.path().join("project-open");
5688        let launch = tmp.path().join("launch-dir");
5689        let sessions = tmp.path().join("sessions");
5690        std::fs::create_dir_all(&project).unwrap();
5691        std::fs::create_dir_all(&launch).unwrap();
5692        std::fs::create_dir_all(&sessions).unwrap();
5693        create_jsonl_session_with_id(
5694            &sessions,
5695            &project.to_string_lossy(),
5696            Some("cwdopen001".into()),
5697        )
5698        .await
5699        .unwrap();
5700
5701        let restored =
5702            open_session_by_id_in_dir("cwdopen001", &launch.to_string_lossy(), &sessions)
5703                .await
5704                .map_err(|error| error.to_string())
5705                .unwrap();
5706        assert_eq!(restored.recorded_cwd, Some(project.clone()));
5707        assert_eq!(restored.session.storage().metadata().id, "cwdopen001");
5708    }
5709
5710    /// The session the peek inspected must be the session the build opens.
5711    ///
5712    /// `-c` means "the most recent session", and the build lists the directory
5713    /// again. Another `rpi` (or a `/session` new-session) can write a newer one
5714    /// between the peek and the build; adopting the peeked session's directory
5715    /// while opening the newer conversation would run the tools in a directory
5716    /// that conversation never used. Pinning the resolved id makes the second
5717    /// listing an exact match instead of a fresh newest-first choice.
5718    #[tokio::test]
5719    async fn the_peeked_session_is_the_one_the_build_opens() {
5720        let tmp = tempfile::tempdir().unwrap();
5721        let first_project = tmp.path().join("project-first");
5722        let second_project = tmp.path().join("project-second");
5723        let launch = tmp.path().join("launch-dir");
5724        let sessions = tmp.path().join("sessions");
5725        for dir in [&first_project, &second_project, &launch, &sessions] {
5726            std::fs::create_dir_all(dir).unwrap();
5727        }
5728        create_jsonl_session_with_id(
5729            &sessions,
5730            &first_project.to_string_lossy(),
5731            Some("cwdrace001".into()),
5732        )
5733        .await
5734        .unwrap();
5735
5736        let mut args = Args {
5737            continue_session: true,
5738            session_dir: Some(sessions.clone()),
5739            ..Default::default()
5740        };
5741        let selection = select_session_in_dir(&args, sessions.clone());
5742        let peeked = peek_restored_session_cwd(&selection, &launch)
5743            .await
5744            .expect("a resumable session");
5745        assert_eq!(peeked.adopted, Some(first_project.clone()));
5746
5747        // A newer session appears in another project before the build runs.
5748        create_jsonl_session_with_id(
5749            &sessions,
5750            &second_project.to_string_lossy(),
5751            Some("cwdrace002".into()),
5752        )
5753        .await
5754        .unwrap();
5755
5756        pin_restored_selection(&mut args, &peeked);
5757        let pinned = select_session_in_dir(&args, sessions.clone());
5758        let reopened = resolve_restore_target(&pinned, &launch.to_string_lossy())
5759            .await
5760            .unwrap()
5761            .expect("the pinned session still exists");
5762        assert_eq!(
5763            reopened.id, peeked.id,
5764            "the build must open the session the peek adopted the directory of"
5765        );
5766        assert_eq!(reopened.cwd, first_project.to_string_lossy());
5767    }
5768
5769    /// Trust must be resolved against the directory it is asked about. A
5770    /// session recorded in another project must not inherit the launch
5771    /// directory's decision — that would run an untrusted project's settings,
5772    /// skills, and context files with trusted privileges.
5773    #[test]
5774    fn trust_is_resolved_per_directory() {
5775        struct RestoreConfigDir(Option<std::ffi::OsString>);
5776
5777        impl Drop for RestoreConfigDir {
5778            fn drop(&mut self) {
5779                match self.0.take() {
5780                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
5781                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
5782                }
5783            }
5784        }
5785
5786        let _guard = crate::config::test_support::env_lock().lock().unwrap();
5787        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
5788        let tmp = tempfile::tempdir().unwrap();
5789        let agent = tmp.path().join("agent");
5790        std::fs::create_dir_all(&agent).unwrap();
5791        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
5792
5793        let untrusted = tmp.path().join("project-untrusted");
5794        let launch = tmp.path().join("project-launch");
5795        std::fs::create_dir_all(&untrusted).unwrap();
5796        std::fs::create_dir_all(&launch).unwrap();
5797        crate::config::set_project_trust(&untrusted, Some(false)).unwrap();
5798
5799        let args = Args::default();
5800        assert!(!resolve_project_trust(&args, &untrusted));
5801        // A directory with no stored decision loads by default.
5802        assert!(resolve_project_trust(&args, &launch));
5803    }
5804}
5805
5806#[cfg(test)]
5807#[path = "session/experimental_dialog_continuity_tests.rs"]
5808mod experimental_dialog_continuity_tests;
5809#[cfg(test)]
5810#[path = "session/experimental_reload_continuity_tests.rs"]
5811mod experimental_reload_continuity_tests;