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