Skip to main content

rpi_cli/
session.rs

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