Skip to main content

rpi_cli/
session.rs

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