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