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