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