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