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