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