Skip to main content

rpi_cli/
session.rs

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