Skip to main content

rpi_cli/
resource_selection.rs

1//! Opt-in native startup resource selection. This is a host contract, not a package format.
2use sha2::{Digest, Sha256};
3use std::collections::HashSet;
4use std::io::Read;
5use std::path::{Component, Path, PathBuf};
6use std::sync::{Mutex, OnceLock, Weak};
7
8use rpi_harness::agent_harness::AgentHarness;
9use rpi_harness::session::types::SessionStorage;
10use serde::{Deserialize, Serialize};
11use serde_json::{json, Value};
12
13use crate::args::{Args, Mode};
14mod fork;
15pub(crate) use fork::initial_values as fork_initial_values;
16pub(crate) use fork::initial_values_for_selection as fork_initial_values_for_selection;
17
18pub const MAX_SELECTION_BYTES: usize = 64 * 1024;
19pub const MAX_STATE_BYTES: usize = 256 * 1024;
20pub(crate) fn transition_capability() -> Value {
21    json!({"version":1, "startupFlag":"--resource-transition", "maxRequestBytes":MAX_SELECTION_BYTES,
22        "maxOperationIdBytes":128,"operationIdPattern":"^[A-Za-z0-9._-]{1,128}$",
23        "request":{"requiredFields":["version","operation_id","expected","target"],
24            "unknownFields":"reject","duplicateFields":"reject",
25            "expected":{"revision":"u64","fingerprint":"lowercase-sha256-or-null","unboundRevision":0},
26            "target":"complete-exact-selection-v1"},
27        "expected":"revision-and-fingerprint", "retry":"same-operation-current-binding", "legacyTarget":false})
28}
29
30pub(crate) const MAX_CAPABILITIES_BYTES: usize = 16 * 1024;
31/// Pure static profile; no environment, filesystem, provider or native loader.
32pub(crate) fn capabilities() -> Value {
33    json!({"version":1,"type":"resource_capabilities","maxResponseBytes":MAX_CAPABILITIES_BYTES,
34        "host":{"name":crate::APP_NAME,"version":crate::VERSION},
35        "exactSelection":{"versions":[1],"startupFlag":"--resource-config","mode":"rpc",
36            "maxConfigBytes":MAX_SELECTION_BYTES,"maxSnapshotBytes":MAX_STATE_BYTES,
37            "stateCommand":"get_resource_state","toolModes":["default","only","none"],
38            "packageScopes":["project","global"],"ordinaryReopen":"immutable","hotApply":false},
39        "management":crate::resource_management::capabilities(),
40        "transition":transition_capability(),"savedSessionRead":crate::saved_session_read::capabilities(),"loadedFacts":false})
41}
42const SESSION_KEY: &str = "rpi.resource-selection.v1";
43
44/// Only public generic append APIs are restricted. Native SessionValueWriter
45/// remains available for the host's atomic declaration/inventory persistence.
46pub(crate) fn validate_public_entry(custom_type: &str, data: Option<&Value>) -> Result<(), String> {
47    if custom_type == rpi_harness::session::values::VALUE_CUSTOM_TYPE
48        && data
49            .and_then(|d| d.get("key"))
50            .and_then(Value::as_str)
51            .is_some_and(|key| {
52                key.starts_with("rpi.resource-selection.")
53                    || key.starts_with("rpi.resource-inventory.")
54            })
55    {
56        return Err(
57            "host-owned resource session values cannot be appended through public APIs".into(),
58        );
59    }
60    Ok(())
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub struct ResourceSelection {
66    pub version: u32,
67    pub main_package: Option<MainPackage>,
68    #[serde(default)]
69    pub skills: Vec<PathBuf>,
70    #[serde(default)]
71    pub extensions: Vec<PathBuf>,
72    #[serde(default)]
73    pub instructions: Vec<PathBuf>,
74    pub tools: ToolSelection,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct MainPackage {
80    pub name: String,
81    #[serde(
82        default,
83        skip_serializing_if = "crate::resource_management::Scope::is_project"
84    )]
85    pub scope: crate::resource_management::Scope,
86    /// Explicit package-relative persistent instruction files. Prompts are never auto-executed.
87    #[serde(default)]
88    pub instructions: Vec<PathBuf>,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
92#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
93pub enum ToolSelection {
94    Default {},
95    Only { names: Vec<String> },
96    None {},
97}
98
99#[derive(Debug, Clone, Serialize)]
100pub struct ResolvedPackage {
101    pub name: String,
102    pub version: Option<String>,
103    pub source: String,
104    pub cargo_package: Option<String>,
105    pub root: PathBuf,
106}
107
108#[derive(Debug, Clone)]
109pub struct ResolvedSelection {
110    pub package: Option<ResolvedPackage>,
111    pub selection: ResourceSelection,
112    pub skills: Vec<PathBuf>,
113    pub extensions: Vec<PathBuf>,
114    pub instructions: Vec<(PathBuf, String, String)>,
115    pub transition: Option<ResourceTransition>,
116    pub(crate) package_commands: crate::agent_package::Commands,
117    validated_skills: Option<ValidatedSkills>,
118}
119
120#[derive(Debug, Clone)]
121pub(crate) struct ValidatedSkills {
122    pub skills: Vec<rpi_harness::types::Skill>,
123    inventory: Value,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127#[serde(deny_unknown_fields)]
128pub struct ResourceTransition {
129    pub version: u32,
130    pub operation_id: String,
131    pub expected: ExpectedBinding,
132    pub target: ResourceSelection,
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
136#[serde(deny_unknown_fields)]
137pub struct ExpectedBinding {
138    pub revision: u64,
139    pub fingerprint: Option<String>,
140}
141
142impl ResourceTransition {
143    fn validate(&self) -> Result<(), String> {
144        if self.version != 1
145            || self.operation_id.is_empty()
146            || self.operation_id.len() > 128
147            || !self
148                .operation_id
149                .bytes()
150                .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
151            || (self.expected.revision == 0) != self.expected.fingerprint.is_none()
152            || self.expected.fingerprint.as_ref().is_some_and(|f| {
153                f.len() != 64
154                    || !f
155                        .bytes()
156                        .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
157            })
158        {
159            return Err(
160                "invalid resource transition version, operation ID or expected binding".into(),
161            );
162        }
163        Ok(())
164    }
165}
166
167pub(crate) fn contained(path: &Path, root: &Path) -> Result<PathBuf, String> {
168    let path = std::fs::canonicalize(path).map_err(|e| e.to_string())?;
169    if !path.starts_with(root) || path == root {
170        return Err(format!(
171            "package resource escapes canonical package root: {}",
172            path.display()
173        ));
174    }
175    Ok(path)
176}
177
178// Validate nested symlinks/junctions too, before feeding package directories to
179// the existing recursive loader. Explicit standalone sources are caller-authorized.
180fn validate_package_tree(
181    path: &Path,
182    root: &Path,
183    visited: &mut HashSet<PathBuf>,
184) -> Result<(), String> {
185    let path = contained(path, root)?;
186    if path.is_dir() {
187        if !visited.insert(path.clone()) {
188            return Err("package resource directory cycle/alias".into());
189        }
190        for entry in std::fs::read_dir(path).map_err(|e| e.to_string())? {
191            validate_package_tree(&entry.map_err(|e| e.to_string())?.path(), root, visited)?;
192        }
193    }
194    Ok(())
195}
196
197pub(crate) fn read_limited(path: &Path) -> Result<Vec<u8>, String> {
198    let mut bytes = Vec::new();
199    std::fs::File::open(path)
200        .map_err(|e| format!("{}: {e}", path.display()))?
201        .take((MAX_SELECTION_BYTES + 1) as u64)
202        .read_to_end(&mut bytes)
203        .map_err(|e| e.to_string())?;
204    if bytes.len() > MAX_SELECTION_BYTES {
205        return Err(format!("resource input exceeds 64 KiB: {}", path.display()));
206    }
207    Ok(bytes)
208}
209fn fingerprint(path: &Path) -> Result<String, String> {
210    let mut reader = std::fs::File::open(path).map_err(|e| e.to_string())?;
211    let mut hash = Sha256::new();
212    let mut buf = [0; 8192];
213    loop {
214        let n = reader.read(&mut buf).map_err(|e| e.to_string())?;
215        if n == 0 {
216            break;
217        }
218        hash.update(&buf[..n]);
219    }
220    Ok(format!("{:x}", hash.finalize()))
221}
222
223pub(crate) fn file(path: &Path) -> Result<PathBuf, String> {
224    if !path.is_file() {
225        return Err(format!("missing resource file: {}", path.display()));
226    }
227    std::fs::canonicalize(path).map_err(|e| e.to_string())
228}
229fn unique_paths(paths: &[PathBuf]) -> Result<(), String> {
230    let mut seen = HashSet::new();
231    for path in paths {
232        if !seen.insert(path) {
233            return Err(format!("duplicate resource: {}", path.display()));
234        }
235    }
236    Ok(())
237}
238pub(crate) fn relative(path: &Path) -> Result<(), String> {
239    if path.as_os_str().is_empty()
240        || path
241            .components()
242            .any(|c| !matches!(c, Component::Normal(_)))
243    {
244        return Err(format!(
245            "expected a package-relative path: {}",
246            path.display()
247        ));
248    }
249    Ok(())
250}
251
252pub(crate) fn validate_tool_names(names: &[String]) -> Result<(), String> {
253    let mut seen = HashSet::new();
254    for name in names {
255        if name.is_empty() || !seen.insert(name) {
256            return Err("empty or duplicate tool name".into());
257        }
258    }
259    Ok(())
260}
261
262impl ResolvedSelection {
263    pub fn load(args: &Args, cwd: &Path, trusted: bool) -> Result<Option<Self>, String> {
264        Self::load_for(&crate::config::AgentHome::process(), args, cwd, trusted)
265    }
266
267    pub fn load_for(
268        home: &crate::config::AgentHome,
269        args: &Args,
270        cwd: &Path,
271        trusted: bool,
272    ) -> Result<Option<Self>, String> {
273        let Some(config) = args
274            .resource_transition
275            .as_ref()
276            .or(args.resource_config.as_ref())
277        else {
278            return Ok(None);
279        };
280        if let Some(error) = args.fork_cut_errors().first() {
281            return Err((*error).to_owned());
282        }
283        if (args.resource_config.is_some() && args.resource_transition.is_some())
284            || (args.resource_transition.is_some()
285                && (args.name.is_some()
286                    || args.fork.is_some()
287                    || args.no_session
288                    || !args.messages.is_empty()))
289            || args.mode != Mode::Rpc
290            || args.dev_local_only
291            || args.project_only
292            || args.trust_override == Some(false)
293            || !trusted
294            || args.system_prompt.is_some()
295            || !args.append_system_prompt.is_empty()
296            || args.tools.is_some()
297            || args.exclude_tools.is_some()
298            || args.no_tools
299            || args.no_builtin_tools
300            || args.no_skills
301            || args.no_prompt_templates
302            || args.no_extensions
303            || args.no_context_files
304            || !args.skill.is_empty()
305            || !args.prompt_template.is_empty()
306            || !args.extension.is_empty()
307            || !args.extensions_dir.is_empty()
308            || !args.unknown_flags.is_empty()
309        {
310            return Err("--resource-config requires trusted --mode rpc and conflicts with resource/tool/prompt/discovery/dev flags and unknown extension flags".into());
311        }
312        let bytes = read_limited(&cwd.join(config))?;
313        let transition: Option<ResourceTransition> = if args.resource_transition.is_some() {
314            let request: ResourceTransition = serde_json::from_slice(&bytes)
315                .map_err(|e| format!("invalid resource transition: {e}"))?;
316            request.validate()?;
317            Some(request)
318        } else {
319            None
320        };
321        let selection: ResourceSelection = if let Some(request) = &transition {
322            request.target.clone()
323        } else {
324            serde_json::from_slice(&bytes).map_err(|e| format!("invalid resource config: {e}"))?
325        };
326        if selection.version != 1 {
327            return Err("unsupported resource config version".into());
328        }
329        if let ToolSelection::Only { names } = &selection.tools {
330            validate_tool_names(names)?;
331        }
332        let mut skills = Vec::new();
333        let mut extensions = Vec::new();
334        let mut instructions = Vec::new();
335        let mut resolved_package = None;
336        let mut package_commands = crate::agent_package::Commands::default();
337        if let Some(main) = &selection.main_package {
338            let native_root = main.scope.root(home, cwd)?;
339            let package = crate::packages::selected_package_at(&native_root, &main.name)?;
340            let packages_root =
341                std::fs::canonicalize(native_root.join("packages")).map_err(|e| e.to_string())?;
342            let root = std::fs::canonicalize(packages_root.join(&main.name))
343                .map_err(|e| format!("missing package directory: {e}"))?;
344            if !root.is_dir() || !root.starts_with(&packages_root) || root == packages_root {
345                return Err("package root escapes .rpi/packages".into());
346            }
347            package_commands = crate::agent_package::Commands::load(
348                &root,
349                &main.name,
350                (!package.version.is_empty()).then_some(package.version.as_str()),
351            )?;
352            let skill_dir = root.join("skills");
353            if skill_dir.exists() {
354                let skill_dir = contained(&skill_dir, &root)?;
355                validate_package_tree(&skill_dir, &root, &mut HashSet::new())?;
356                skills.push(skill_dir);
357            }
358            for artifact in &package.artifacts {
359                relative(Path::new(artifact))?;
360                extensions.push(contained(
361                    &file(&root.join("extensions").join(artifact))?,
362                    &root,
363                )?);
364            }
365            for instruction in &main.instructions {
366                relative(instruction)?;
367                let path = contained(&file(&root.join(instruction))?, &root)?;
368                instructions.push((path, format!("package:{}", main.name), String::new()));
369            }
370            resolved_package = Some(ResolvedPackage {
371                name: package.name,
372                version: if package.version.is_empty() {
373                    None
374                } else {
375                    Some(package.version)
376                },
377                source: package.source,
378                cargo_package: if package.cargo_package.is_empty() {
379                    None
380                } else {
381                    Some(package.cargo_package)
382                },
383                root,
384            });
385        }
386        // Explicit additions first: use the existing first-registration-wins loader.
387        let mut additions = Vec::new();
388        for skill in &selection.skills {
389            let path = cwd.join(skill);
390            if !path.exists() {
391                return Err(format!("missing skill: {}", path.display()));
392            }
393            additions.push(std::fs::canonicalize(path).map_err(|e| e.to_string())?);
394        }
395        additions.extend(skills);
396        skills = additions;
397        for extension in &selection.extensions {
398            extensions.push(file(&cwd.join(extension))?);
399        }
400        for instruction in &selection.instructions {
401            instructions.push((
402                file(&cwd.join(instruction))?,
403                "explicit".into(),
404                String::new(),
405            ));
406        }
407        unique_paths(&skills)?;
408        unique_paths(&extensions)?;
409        unique_paths(&instructions.iter().map(|i| i.0.clone()).collect::<Vec<_>>())?;
410        for extension in &extensions {
411            if extension.extension().and_then(|e| e.to_str())
412                != Some(std::env::consts::DLL_EXTENSION)
413            {
414                return Err(format!("not a native extension: {}", extension.display()));
415            }
416        }
417        for (path, _, text) in &mut instructions {
418            *text = String::from_utf8(read_limited(path)?)
419                .map_err(|e| format!("instruction {}: {e}", path.display()))?;
420        }
421        Ok(Some(Self {
422            package: resolved_package,
423            selection,
424            skills,
425            extensions,
426            instructions,
427            transition,
428            package_commands,
429            validated_skills: None,
430        }))
431    }
432
433    /// Host-only instruction subset of v1. No Args, ambient package scope,
434    /// discovery, skills or executable code. Text is frozen from bounded reads.
435    pub(crate) fn host_instructions(selection: ResourceSelection) -> Result<Self, String> {
436        if selection.version != 1
437            || selection.main_package.is_some()
438            || !selection.skills.is_empty()
439            || !selection.extensions.is_empty()
440            || selection.instructions.len() > 32
441            || matches!(selection.tools, ToolSelection::Default {})
442        {
443            return Err("unsupported Host instruction resource selection".into());
444        }
445        let mut instructions = Vec::new();
446        let mut total = 0usize;
447        for path in &selection.instructions {
448            if !path.is_absolute() {
449                return Err("Host instruction path must be absolute".into());
450            }
451            let path = file(path)?;
452            let text = String::from_utf8(read_limited(&path)?)
453                .map_err(|_| "Host instruction must be UTF-8")?;
454            total = total
455                .checked_add(text.len())
456                .ok_or("instruction size overflow")?;
457            if total > MAX_SELECTION_BYTES {
458                return Err("Host instructions exceed 64 KiB".into());
459            }
460            instructions.push((path, "explicit".into(), text));
461        }
462        unique_paths(&instructions.iter().map(|i| i.0.clone()).collect::<Vec<_>>())?;
463        Ok(Self {
464            selection,
465            package: None,
466            skills: Vec::new(),
467            extensions: Vec::new(),
468            instructions,
469            transition: None,
470            package_commands: Default::default(),
471            validated_skills: Some(ValidatedSkills {
472                skills: Vec::new(),
473                inventory: json!([]),
474            }),
475        })
476    }
477
478    /// Resolve once, before code or native writers. Hash the very bytes parsed
479    /// by the existing loader, preserving ignore/recursion and first-wins rules.
480    pub(crate) async fn validate_skills(
481        &mut self,
482        env: &std::sync::Arc<dyn rpi_tools::ExecutionEnv>,
483    ) -> Result<(), String> {
484        let hashes = Mutex::new(std::collections::HashMap::new());
485        let observe = |path: &str, raw: &str| {
486            hashes.lock().unwrap().insert(
487                path.to_owned(),
488                format!("{:x}", Sha256::digest(raw.as_bytes())),
489            );
490        };
491        let mut skills = Vec::new();
492        let mut diagnostics = Vec::new();
493        for path in &self.skills {
494            let loaded = rpi_harness::skills::load_skills_with_source_observer(
495                env,
496                &[path.to_string_lossy().into_owned()],
497                &observe,
498            )
499            .await;
500            if loaded.skills.is_empty() {
501                return Err(format!(
502                    "selected skill source loaded no Skills: {}",
503                    path.display()
504                ));
505            }
506            skills.extend(loaded.skills);
507            diagnostics.extend(loaded.diagnostics);
508        }
509        let skills = crate::resource_dirs::dedupe_skills(skills, &mut diagnostics);
510        if !diagnostics.is_empty() {
511            return Err(format!("selected skill diagnostics: {diagnostics:?}"));
512        }
513        let hashes = hashes.into_inner().unwrap();
514        let inventory = json!(skills
515            .iter()
516            .map(|skill| json!({
517                "name": skill.name, "path": skill.file_path, "sha256": hashes[&skill.file_path]
518            }))
519            .collect::<Vec<_>>());
520        self.validated_skills = Some(ValidatedSkills { skills, inventory });
521        Ok(())
522    }
523
524    pub(crate) fn validated_skills(&self) -> Result<&ValidatedSkills, String> {
525        self.validated_skills
526            .as_ref()
527            .ok_or_else(|| "selected Skills were not preflight validated".into())
528    }
529
530    pub fn active_tools(&self, registered: &[String]) -> Result<Vec<String>, String> {
531        match &self.selection.tools {
532            ToolSelection::Default {} => Ok(registered.to_vec()),
533            ToolSelection::None {} => Ok(Vec::new()),
534            ToolSelection::Only { names } => {
535                for name in names {
536                    if !registered.contains(name) {
537                        return Err(format!("unknown selected tool: {name}"));
538                    }
539                }
540                Ok(names.clone())
541            }
542        }
543    }
544
545    pub fn provenance(&self) -> Value {
546        json!(self.instructions.iter().map(|(path, source, text)| json!({"path": path, "source": source, "sha256": format!("{:x}",Sha256::digest(text.as_bytes()))})).collect::<Vec<_>>())
547    }
548}
549
550// CLI attachment keyed by allocation, not durable session ID: concurrent hosts reopening
551// the same transcript must not inherit each other's startup observations.
552type Attachment = (
553    Weak<dyn SessionStorage>,
554    Value,
555    crate::agent_package::Commands,
556);
557fn states() -> &'static Mutex<Vec<Attachment>> {
558    static STATES: OnceLock<Mutex<Vec<Attachment>>> = OnceLock::new();
559    STATES.get_or_init(|| Mutex::new(Vec::new()))
560}
561pub(crate) fn attach(
562    harness: &AgentHarness,
563    state: Value,
564    commands: crate::agent_package::Commands,
565) {
566    let mut states = states().lock().unwrap();
567    states.retain(|(storage, _, _)| storage.strong_count() > 0);
568    states.push((
569        std::sync::Arc::downgrade(&harness.session().storage()),
570        state,
571        commands,
572    ));
573}
574
575pub(crate) fn package_commands(harness: &AgentHarness) -> crate::agent_package::Commands {
576    let storage = harness.session().storage();
577    states()
578        .lock()
579        .unwrap()
580        .iter()
581        .find_map(|(weak, _, commands)| {
582            weak.upgrade()
583                .filter(|value| std::sync::Arc::ptr_eq(value, &storage))
584                .map(|_| commands.clone())
585        })
586        .unwrap_or_default()
587}
588
589pub async fn get_resource_state(harness: &AgentHarness) -> Result<Value, String> {
590    let storage = harness.session().storage();
591    let state = states().lock().unwrap().iter().find_map(|(s, state, _)| {
592        s.upgrade()
593            .filter(|s| std::sync::Arc::ptr_eq(s, &storage))
594            .map(|_| state.clone())
595    });
596    let mut state = state.ok_or("get_resource_state requires --resource-config v1")?;
597    let metadata = harness
598        .session()
599        .get_metadata()
600        .await
601        .map_err(|e| e.to_string())?;
602    let resources = harness.get_resources().await.map_err(|e| e.to_string())?;
603    let registered: Vec<_> = harness
604        .get_tools()
605        .await
606        .map_err(|e| e.to_string())?
607        .iter()
608        .map(|t| t.tool.schema().name.clone())
609        .collect();
610    let execution = harness.execution_context().map_err(|e| e.to_string())?;
611    let active = execution["tools"].clone();
612    let read = active
613        .as_array()
614        .is_some_and(|names| names.iter().any(|n| n == "read"));
615    state["sessionId"] = json!(metadata.id);
616    let values = rpi_harness::session::SessionValues::load(harness.session())
617        .await
618        .map_err(|e| e.to_string())?;
619    if let Some(binding) = values.get(SESSION_KEY) {
620        validate_persisted_binding(binding)?;
621    }
622    state["binding"] = binding_state(&values);
623    state["transition"] = transition_capability();
624    state["registeredTools"] = json!(registered);
625    state["modelEffectiveTools"] = active;
626    state["loadedSkills"] = json!(resources.skills.unwrap_or_default().iter().map(|s| json!({
627        "name": s.name, "path": s.file_path, "modelVisible": read && !s.disable_model_invocation.unwrap_or(false)
628    })).collect::<Vec<_>>());
629    state["promptTemplates"] = json!(resources
630        .prompt_templates
631        .unwrap_or_default()
632        .iter()
633        .map(|t| &t.name)
634        .collect::<Vec<_>>());
635    if serde_json::to_vec(&state).map_err(|e| e.to_string())?.len() > MAX_STATE_BYTES {
636        return Err("resource snapshot exceeds 256 KiB".into());
637    }
638    Ok(state)
639}
640
641fn declaration(s: &ResolvedSelection) -> Value {
642    json!({"selection": s.selection, "package": s.package, "skills": s.skills, "extensions": s.extensions, "instructions": s.provenance()})
643}
644
645pub(crate) async fn bind_session(
646    session: &rpi_harness::session::Session,
647    selected: Option<&ResolvedSelection>,
648) -> Result<(), String> {
649    use rpi_harness::session::SessionValues;
650    let values = SessionValues::load(session)
651        .await
652        .map_err(|e| e.to_string())?;
653    validate_session_binding(&values, selected)
654}
655
656/// Shared read-only check for preflight facts and the accepted writer's session.
657pub(crate) fn validate_session_binding(
658    values: &rpi_harness::session::SessionValues,
659    selected: Option<&ResolvedSelection>,
660) -> Result<(), String> {
661    if let Some(binding) = values.get(SESSION_KEY) {
662        validate_persisted_binding(binding)?;
663    }
664    if let Some(request) = selected.and_then(|s| s.transition.as_ref()) {
665        validate_transition(values, request)?;
666        // A committed retry must still verify its original artifact inventory.
667        if values
668            .get(SESSION_KEY)
669            .and_then(|v| v.get("operationId"))
670            .and_then(Value::as_str)
671            != Some(request.operation_id.as_str())
672        {
673            return Ok(());
674        }
675    }
676    match (values.get(SESSION_KEY), selected) {
677        (Some(old), Some(selected)) if old.get("declaration") == Some(&declaration(selected)) => {
678            // Code identity is checked before dlopen/registration, not just after
679            // the schema registry has been constructed. No provider callback runs here.
680            let extensions = selected.extensions.iter().map(|path| Ok(json!({"path":path,"sha256":fingerprint(path)?})))
681                .collect::<Result<Vec<_>, String>>()?;
682            if old.pointer("/inventory/extensions") != Some(&json!(extensions)) {
683                return Err("session resource artifact inventory changed; restore original resources or use a new session".into());
684            }
685            if old.pointer("/inventory/packageCommandsSha256").and_then(Value::as_str) != selected.package_commands.digest() {
686                return Err("session package command inventory changed; restore original resources or use a new session".into());
687            }
688            if old.pointer("/inventory/skills") != Some(&selected.validated_skills()?.inventory) {
689                return Err("session resource Skill inventory changed; restore original resources or use a new session".into());
690            }
691            Ok(())
692        },
693        (Some(_), _) => Err("session resource selection differs or is missing; restart with the same declared selection or use a new session".into()),
694        (None, _) => Ok(()),
695    }
696}
697
698/// Fingerprint only native binding facts, not caller operation metadata.
699fn binding_fingerprint(binding: &Value) -> String {
700    format!(
701        "{:x}",
702        Sha256::digest(
703            serde_json::to_vec(&json!({
704                "declaration": binding["declaration"], "inventory": binding["inventory"]
705            }))
706            .expect("JSON binding")
707        )
708    )
709}
710
711fn valid_digest(value: &Value) -> bool {
712    value.as_str().is_some_and(|s| {
713        s.len() == 64
714            && s.bytes()
715                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
716    })
717}
718
719/// Missing old-v1 fields are compatible; present malformed facts are never defaults.
720fn validate_persisted_binding(binding: &Value) -> Result<u64, String> {
721    let invalid = || "invalid persisted resource binding metadata".to_string();
722    let object = binding.as_object().ok_or_else(invalid)?;
723    if !object.get("declaration").is_some_and(Value::is_object)
724        || !object.get("inventory").is_some_and(Value::is_object)
725        || serde_json::to_vec(binding).map_err(|_| invalid())?.len() > MAX_STATE_BYTES
726    {
727        return Err(invalid());
728    }
729    let revision = match object.get("revision") {
730        None if !object.contains_key("operationId") && !object.contains_key("operations") => 1,
731        Some(value) => value.as_u64().filter(|r| *r > 0).ok_or_else(invalid)?,
732        None => return Err(invalid()),
733    };
734    let operations = match object.get("operations") {
735        Some(value) => Some(value.as_object().ok_or_else(invalid)?),
736        None => None,
737    };
738    let current = match object.get("operationId") {
739        Some(value) => Some(value.as_str().ok_or_else(invalid)?),
740        None => None,
741    };
742    let mut revisions = std::collections::HashSet::new();
743    if let Some(operations) = operations {
744        for (id, operation) in operations {
745            if id.is_empty()
746                || id.len() > 128
747                || !id
748                    .bytes()
749                    .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
750            {
751                return Err(invalid());
752            }
753            let op = operation.as_object().ok_or_else(invalid)?;
754            if op.len() != 4
755                || !valid_digest(&operation["target"])
756                || !valid_digest(&operation["fingerprint"])
757            {
758                return Err(invalid());
759            }
760            let expected: ExpectedBinding =
761                serde_json::from_value(operation["expected"].clone()).map_err(|_| invalid())?;
762            if (expected.revision == 0) != expected.fingerprint.is_none()
763                || expected
764                    .fingerprint
765                    .as_ref()
766                    .is_some_and(|f| !valid_digest(&json!(f)))
767            {
768                return Err(invalid());
769            }
770            let result = operation["revision"].as_u64().ok_or_else(invalid)?;
771            if expected.revision.checked_add(1) != Some(result)
772                || result > revision
773                || !revisions.insert(result)
774            {
775                return Err(invalid());
776            }
777            if current == Some(id.as_str()) {
778                let target = format!(
779                    "{:x}",
780                    Sha256::digest(
781                        serde_json::to_vec(&binding["declaration"]["selection"])
782                            .map_err(|_| invalid())?
783                    )
784                );
785                if result != revision
786                    || operation["fingerprint"] != binding_fingerprint(binding)
787                    || operation["target"] != target
788                {
789                    return Err(invalid());
790                }
791            } else if result == revision {
792                return Err(invalid());
793            }
794            // Ledger entries are never pruned. Validate every retained predecessor
795            // association, not only the operation being retried.
796            if let Some(previous) = operations
797                .values()
798                .find(|p| p["revision"].as_u64() == Some(expected.revision))
799            {
800                if previous["fingerprint"] != json!(expected.fingerprint) {
801                    return Err(invalid());
802                }
803            }
804        }
805    }
806    if let Some(operations) = operations {
807        if !operations.is_empty() {
808            let first = *revisions.iter().min().ok_or_else(invalid)?;
809            if first > 2
810                || revision.checked_sub(first).and_then(|n| n.checked_add(1))
811                    != Some(operations.len() as u64)
812            {
813                return Err(invalid());
814            }
815        }
816    }
817    match current {
818        Some(id) if !operations.is_some_and(|ops| ops.contains_key(id)) => return Err(invalid()),
819        None if operations.is_some_and(|ops| !ops.is_empty()) || revision != 1 => {
820            return Err(invalid())
821        }
822        _ => {}
823    }
824    Ok(revision)
825}
826
827pub(crate) fn saved_binding_state(
828    values: &rpi_harness::session::SessionValues,
829) -> Result<Value, String> {
830    if let Some(binding) = values.get(SESSION_KEY) {
831        validate_persisted_binding(binding)?;
832    }
833    Ok(binding_state(values))
834}
835pub(crate) fn binding_state(values: &rpi_harness::session::SessionValues) -> Value {
836    match values.get(SESSION_KEY) {
837        Some(binding) => match validate_persisted_binding(binding) {
838            Ok(revision) => json!({"revision": revision,
839                "fingerprint": binding_fingerprint(binding), "operationId": binding.get("operationId")}),
840            Err(error) => json!({"error": error}),
841        },
842        None => json!({"revision": 0, "fingerprint": null, "operationId": null}),
843    }
844}
845
846fn target_fingerprint(request: &ResourceTransition) -> String {
847    format!(
848        "{:x}",
849        Sha256::digest(serde_json::to_vec(&request.target).expect("typed target"))
850    )
851}
852
853fn validate_transition(
854    values: &rpi_harness::session::SessionValues,
855    request: &ResourceTransition,
856) -> Result<(), String> {
857    let old = values.get(SESSION_KEY);
858    if let Some(binding) = old {
859        validate_persisted_binding(binding)?;
860    }
861    let actual = binding_state(values);
862    if let Some(operation) = old
863        .and_then(|v| v.get("operations"))
864        .and_then(|v| v.get(&request.operation_id))
865    {
866        if operation["target"] != target_fingerprint(request)
867            || operation["expected"] != json!(request.expected)
868            || actual["operationId"] != request.operation_id
869            || operation["revision"] != actual["revision"]
870            || operation["fingerprint"] != actual["fingerprint"]
871        {
872            return Err("resource transition operation conflict or superseded retry".into());
873        }
874        return Ok(());
875    }
876    if actual["revision"] != request.expected.revision
877        || actual["fingerprint"] != json!(request.expected.fingerprint)
878    {
879        return Err("stale resource transition expected binding".into());
880    }
881    Ok(())
882}
883
884/// Reopening observes the same files/registrations, not merely the same JSON.
885/// Native values remain in the native transcript, outside model-visible history.
886pub(crate) async fn bind_inventory(
887    harness: &AgentHarness,
888    selected: &ResolvedSelection,
889) -> Result<(), String> {
890    let resources = harness.get_resources().await.map_err(|e| e.to_string())?;
891    let mut skills = Vec::new();
892    for skill in resources.skills.unwrap_or_default() {
893        skills.push(json!({"name": skill.name, "path": skill.file_path, "sha256": fingerprint(Path::new(&skill.file_path))?}));
894    }
895    // Defense in depth: neither a registration-time file edit nor a different
896    // constructed resource set may bind source bytes other than those parsed.
897    if json!(skills) != selected.validated_skills()?.inventory {
898        return Err("session resource Skill inventory changed after preflight".into());
899    }
900    let mut extensions = Vec::new();
901    for path in &selected.extensions {
902        extensions.push(json!({"path": path, "sha256": fingerprint(path)?}));
903    }
904    let tools: Vec<_> = harness
905        .get_tools()
906        .await
907        .map_err(|e| e.to_string())?
908        .iter()
909        .map(|t| json!(t.tool.schema()))
910        .collect();
911    let mut inventory = json!({"skills":skills, "extensions":extensions, "toolSchemasSha256":format!("{:x}",Sha256::digest(serde_json::to_vec(&tools).map_err(|e| e.to_string())?))});
912    if let Some(digest) = selected.package_commands.digest() {
913        inventory["packageCommandsSha256"] = json!(digest);
914    }
915    bind_inventory_to_session(harness.session(), selected, inventory).await
916}
917
918/// Pure inventory validation, including tool schemas, before a Host claims its
919/// writer or repairs a torn journal. No new binding is written during preflight.
920pub(crate) fn validate_exact_inventory(
921    values: &rpi_harness::session::SessionValues,
922    selected: &ResolvedSelection,
923    inventory: &Value,
924) -> Result<(), String> {
925    validate_session_binding(values, Some(selected))?;
926    let candidate = json!({"declaration":declaration(selected),"inventory":inventory,"revision":1});
927    if serde_json::to_vec(&candidate)
928        .map_err(|e| e.to_string())?
929        .len()
930        > MAX_STATE_BYTES
931    {
932        return Err("resource binding exceeds 256 KiB".into());
933    }
934    if values
935        .get(SESSION_KEY)
936        .is_some_and(|old| old.get("inventory") != Some(inventory))
937    {
938        return Err("session resource inventory changed".into());
939    }
940    Ok(())
941}
942
943/// Shared atomic native-value append, also usable before Harness creation. The
944/// caller owns writer custody and must establish its required sync barrier.
945pub(crate) async fn bind_inventory_to_session(
946    session: &rpi_harness::session::Session,
947    selected: &ResolvedSelection,
948    inventory: Value,
949) -> Result<(), String> {
950    use rpi_harness::session::{SessionValueWriter, SessionValues};
951    let values = SessionValues::load(session)
952        .await
953        .map_err(|e| e.to_string())?;
954    validate_session_binding(&values, Some(selected))?;
955    let old = values.get(SESSION_KEY);
956    let retry = selected.transition.as_ref().is_some_and(|r| {
957        old.and_then(|v| v.get("operationId"))
958            .and_then(Value::as_str)
959            == Some(r.operation_id.as_str())
960    });
961    if let Some(old) = old.filter(|_| selected.transition.is_none() || retry) {
962        if old.get("inventory") != Some(&inventory)
963            || old.get("declaration") != Some(&declaration(selected))
964        {
965            return Err(
966                "session resource inventory changed; use original resources or a new session"
967                    .into(),
968            );
969        }
970    } else {
971        // One native append commits the full binding and operation association.
972        let revision = binding_state(&values)["revision"]
973            .as_u64()
974            .unwrap()
975            .checked_add(1)
976            .ok_or("resource binding revision overflow")?;
977        let mut binding = json!({"declaration": declaration(selected), "inventory": inventory, "revision": revision});
978        if let Some(request) = &selected.transition {
979            let mut operations = old
980                .and_then(|v| v.get("operations"))
981                .cloned()
982                .unwrap_or(json!({}));
983            operations[&request.operation_id] = json!({"target": target_fingerprint(request), "expected": request.expected,
984                "revision": revision, "fingerprint": binding_fingerprint(&binding)});
985            binding["operations"] = operations;
986            binding["operationId"] = json!(request.operation_id);
987        }
988        if serde_json::to_vec(&binding)
989            .map_err(|e| e.to_string())?
990            .len()
991            > MAX_STATE_BYTES
992        {
993            return Err("resource binding/operation ledger exceeds 256 KiB".into());
994        }
995        SessionValueWriter::new(session.clone())
996            .set(SESSION_KEY, binding)
997            .await
998            .map_err(|e| e.to_string())?;
999    }
1000    Ok(())
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005    use super::*;
1006    #[test]
1007    fn typed_schema_rejects_unknown_and_duplicate_fields_at_each_level() {
1008        for input in [
1009            r#"{"version":1,"tools":{"mode":"none","unexpected":1}}"#,
1010            r#"{"version":1,"tools":{"mode":"default","names":[]}}"#,
1011            r#"{"version":1,"main_package":{"name":"x","unexpected":1},"tools":{"mode":"none"}}"#,
1012            r#"{"version":1,"version":1,"tools":{"mode":"none"}}"#,
1013            r#"{"version":1,"tools":{"mode":"only","names":[],"unexpected":1}}"#,
1014        ] {
1015            assert!(
1016                serde_json::from_str::<ResourceSelection>(input).is_err(),
1017                "{input}"
1018            );
1019        }
1020        for path in ["../outside.md", "./instruction.md", ""] {
1021            assert!(relative(Path::new(path)).is_err());
1022        }
1023    }
1024
1025    #[test]
1026    fn configuration_instruction_and_registry_reads_are_bounded() {
1027        let temp = tempfile::tempdir().unwrap();
1028        let root = temp.path();
1029        let input = root.join("input.md");
1030        std::fs::write(&input, vec![b'x'; MAX_SELECTION_BYTES]).unwrap();
1031        assert_eq!(read_limited(&input).unwrap().len(), MAX_SELECTION_BYTES);
1032        std::fs::write(&input, vec![b'x'; MAX_SELECTION_BYTES + 1]).unwrap();
1033        assert!(read_limited(&input).unwrap_err().contains("exceeds 64 KiB"));
1034        std::fs::create_dir(root.join(".rpi")).unwrap();
1035        std::fs::write(
1036            root.join(".rpi/packages.json"),
1037            vec![b' '; MAX_STATE_BYTES + 1],
1038        )
1039        .unwrap();
1040        assert!(crate::packages::selected_project_package(root, "valid")
1041            .unwrap_err()
1042            .contains("exceeds 256 KiB"));
1043    }
1044
1045    #[tokio::test]
1046    async fn real_storage_v1_reopen_and_complete_committed_retry_never_double_revision() {
1047        use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
1048        use rpi_harness::session::{Session, SessionValueWriter, SessionValues};
1049        let temp = tempfile::tempdir().unwrap();
1050        let path = temp.path().join("history.jsonl");
1051        let fs: std::sync::Arc<dyn rpi_tools::FileSystem> =
1052            std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(temp.path().into()));
1053        let clock = std::sync::Arc::new(rpi_harness::session::memory::SystemClock);
1054        let ids = std::sync::Arc::new(rpi_harness::session::session::DefaultIdGenerator::new());
1055        let storage = JsonlSessionStorage::create(
1056            fs.clone(),
1057            path.to_str().unwrap(),
1058            JsonlV4Header::new(
1059                "binding-retry".into(),
1060                1,
1061                temp.path().to_string_lossy().into(),
1062                None,
1063                None,
1064                None,
1065            ),
1066            clock.clone(),
1067            ids.clone(),
1068        )
1069        .await
1070        .unwrap();
1071        let session = Session::new(std::sync::Arc::new(storage), None);
1072        let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
1073            session: session.clone(),
1074            ..Default::default()
1075        })
1076        .await
1077        .unwrap();
1078        let message = session
1079            .append_message(rpi_agent::message::AgentMessage::User(
1080                rpi_ai::types::UserMessage::new("preserved real message", 1),
1081            ))
1082            .await
1083            .unwrap();
1084        let mut selected = ResolvedSelection {
1085            package: None,
1086            selection: serde_json::from_value(json!({"version":1,"tools":{"mode":"none"}}))
1087                .unwrap(),
1088            skills: vec![],
1089            extensions: vec![],
1090            instructions: vec![],
1091            transition: None,
1092            package_commands: Default::default(),
1093            validated_skills: None,
1094        };
1095        let env: std::sync::Arc<dyn rpi_tools::ExecutionEnv> =
1096            std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(temp.path().into()));
1097        selected.validate_skills(&env).await.unwrap();
1098        bind_inventory(&harness, &selected).await.unwrap();
1099        // Construct a real old-v1 fixture through native storage, not transcript
1100        // rewriting. Ordinary exact reopen must not migrate its binding fields.
1101        let mut old = SessionValues::load(&session)
1102            .await
1103            .unwrap()
1104            .get(SESSION_KEY)
1105            .unwrap()
1106            .clone();
1107        old.as_object_mut().unwrap().remove("revision");
1108        let original = old.clone();
1109        for (field, value) in [
1110            ("revision", json!("corrupt")),
1111            ("revision", json!(null)),
1112            ("revision", json!(0)),
1113            ("operations", json!([])),
1114            ("operations", json!(1)),
1115            ("operationId", json!(7)),
1116            ("operations", json!({"bad":null})),
1117            (
1118                "operations",
1119                json!({"bad":{"target":"bad","expected":{"revision":0,"fingerprint":null},"revision":1,"fingerprint":"bad"}}),
1120            ),
1121        ] {
1122            let mut damaged = original.clone();
1123            damaged[field] = value;
1124            SessionValueWriter::new(session.clone())
1125                .set(SESSION_KEY, damaged)
1126                .await
1127                .unwrap();
1128            let before = std::fs::read(&path).unwrap();
1129            assert!(bind_session(&session, Some(&selected))
1130                .await
1131                .unwrap_err()
1132                .contains("invalid persisted"));
1133            assert!(bind_inventory(&harness, &selected).await.is_err());
1134            let facts = SessionValues::load(&session).await.unwrap();
1135            assert!(binding_state(&facts).get("error").is_some());
1136            assert_eq!(std::fs::read(&path).unwrap(), before);
1137        }
1138        SessionValueWriter::new(session.clone())
1139            .set(SESSION_KEY, original)
1140            .await
1141            .unwrap();
1142        let bytes = std::fs::read(&path).unwrap();
1143        bind_session(&session, Some(&selected)).await.unwrap();
1144        bind_inventory(&harness, &selected).await.unwrap();
1145        assert_eq!(std::fs::read(&path).unwrap(), bytes);
1146        let base = binding_state(&SessionValues::load(&session).await.unwrap());
1147        assert_eq!(base["revision"], 1);
1148        selected.selection.tools = ToolSelection::Only { names: vec![] };
1149        selected.transition = Some(ResourceTransition {
1150            version: 1,
1151            operation_id: "committed-with-lost-result".into(),
1152            expected: serde_json::from_value(
1153                json!({"revision":base["revision"],"fingerprint":base["fingerprint"]}),
1154            )
1155            .unwrap(),
1156            target: selected.selection.clone(),
1157        });
1158        bind_inventory(&harness, &selected).await.unwrap();
1159        drop(harness);
1160        drop(session);
1161        let committed = std::fs::read(&path).unwrap();
1162        let storage = JsonlSessionStorage::load_for_resource_transition(
1163            fs,
1164            path.to_str().unwrap(),
1165            clock,
1166            ids,
1167        )
1168        .await
1169        .unwrap();
1170        let session = Session::new(std::sync::Arc::new(storage), None);
1171        let harness = AgentHarness::create(rpi_harness::types::AgentHarnessOptions {
1172            session: session.clone(),
1173            allow_existing_session: true,
1174            ..Default::default()
1175        })
1176        .await
1177        .unwrap();
1178        // This is the same production retry path used when the storage fault
1179        // regression leaves a whole new record despite reporting append error.
1180        bind_session(&session, Some(&selected)).await.unwrap();
1181        bind_inventory(&harness, &selected).await.unwrap();
1182        assert_eq!(std::fs::read(&path).unwrap(), committed);
1183        let state = binding_state(&SessionValues::load(&session).await.unwrap());
1184        assert_eq!(state["revision"], 2);
1185        assert_eq!(state["operationId"], "committed-with-lost-result");
1186        assert!(session.get_entry(&message).await.unwrap().is_some());
1187    }
1188
1189    #[test]
1190    fn persisted_operation_associations_are_validated_in_full() {
1191        let selected = json!({"version":1,"tools":{"mode":"none"}});
1192        let target = format!(
1193            "{:x}",
1194            Sha256::digest(serde_json::to_vec(&selected).unwrap())
1195        );
1196        let mut binding = json!({"declaration":{"selection":selected},"inventory":{},"revision":2,"operationId":"one"});
1197        let fingerprint = binding_fingerprint(&binding);
1198        binding["operations"] = json!({"one":{"target":target,"expected":{"revision":1,"fingerprint":"a".repeat(64)},"revision":2,"fingerprint":fingerprint}});
1199        assert_eq!(validate_persisted_binding(&binding).unwrap(), 2);
1200        for (pointer, value) in [
1201            ("/operationId", json!("missing")),
1202            ("/operations/one/target", json!("b".repeat(64))),
1203            ("/operations/one/fingerprint", json!("b".repeat(64))),
1204            (
1205                "/operations/one/expected",
1206                json!({"revision":1,"fingerprint":null}),
1207            ),
1208            (
1209                "/operations/one/expected",
1210                json!({"revision":0,"fingerprint":"a".repeat(64)}),
1211            ),
1212            ("/operations/one/revision", json!(3)),
1213            ("/operations/one/expected/revision", json!("1")),
1214        ] {
1215            let mut damaged = binding.clone();
1216            *damaged.pointer_mut(pointer).unwrap() = value;
1217            assert!(validate_persisted_binding(&damaged).is_err(), "{pointer}");
1218        }
1219        let mut damaged = binding.clone();
1220        damaged["operations"]["older"] = json!({"target":"c".repeat(64),"expected":{"revision":0,"fingerprint":null},"revision":1,"fingerprint":"d".repeat(64)});
1221        assert!(validate_persisted_binding(&damaged).is_err());
1222        damaged["operations"]["one"]["expected"]["fingerprint"] = json!("d".repeat(64));
1223        assert!(validate_persisted_binding(&damaged).is_ok());
1224    }
1225
1226    #[tokio::test]
1227    async fn validated_skills_keep_parsed_content_and_exact_source_hash() {
1228        let temp = tempfile::tempdir().unwrap();
1229        let root = temp.path();
1230        std::fs::create_dir_all(root.join("review")).unwrap();
1231        let path = root.join("review/SKILL.md");
1232        let raw = "---\r\nname: review\r\ndescription: Review fixture\r\n---\r\nOriginal body\r\n";
1233        std::fs::write(&path, raw).unwrap();
1234        std::fs::write(
1235            root.join("resources.json"),
1236            r#"{"version":1,"skills":["review"],"tools":{"mode":"none"}}"#,
1237        )
1238        .unwrap();
1239        let args = Args {
1240            mode: Mode::Rpc,
1241            resource_config: Some("resources.json".into()),
1242            ..Default::default()
1243        };
1244        let mut selected = ResolvedSelection::load(&args, root, true).unwrap().unwrap();
1245        let env: std::sync::Arc<dyn rpi_tools::ExecutionEnv> =
1246            std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(root.to_path_buf()));
1247        selected.validate_skills(&env).await.unwrap();
1248        let validated = selected.validated_skills().unwrap();
1249        assert_eq!(
1250            validated.inventory[0]["sha256"],
1251            format!("{:x}", Sha256::digest(raw.as_bytes()))
1252        );
1253        assert_eq!(validated.skills[0].name, "review");
1254        let content = validated.skills[0].content.clone();
1255        // Construction must retain these parsed Skills, not do a weaker second
1256        // read/discovery after native code has had a chance to alter the file.
1257        std::fs::write(&path, "---\nname: [\n---\nMalformed replacement").unwrap();
1258        assert_eq!(
1259            selected.validated_skills().unwrap().skills[0].content,
1260            content
1261        );
1262        assert_ne!(
1263            selected.validated_skills().unwrap().inventory[0]["sha256"],
1264            fingerprint(&path).unwrap()
1265        );
1266    }
1267
1268    #[tokio::test]
1269    async fn overlapping_skill_roots_fail_closed_without_validated_inventory() {
1270        let temp = tempfile::tempdir().unwrap();
1271        let root = temp.path();
1272        std::fs::create_dir(root.join("review")).unwrap();
1273        std::fs::write(
1274            root.join("review/SKILL.md"),
1275            "---\nname: review\ndescription: Review fixture\n---\nValid body\n",
1276        )
1277        .unwrap();
1278        std::fs::write(
1279            root.join("resources.json"),
1280            r#"{"version":1,"skills":["review","review/SKILL.md"],"tools":{"mode":"none"}}"#,
1281        )
1282        .unwrap();
1283        let args = Args {
1284            mode: Mode::Rpc,
1285            resource_config: Some("resources.json".into()),
1286            ..Default::default()
1287        };
1288        // Distinct overlapping roots pass declaration-level path uniqueness,
1289        // but repeat a Skill name even though both reads have the same path.
1290        let mut selected = ResolvedSelection::load(&args, root, true).unwrap().unwrap();
1291        let env: std::sync::Arc<dyn rpi_tools::ExecutionEnv> =
1292            std::sync::Arc::new(rpi_tools::OsExecutionEnv::with_cwd(root.to_path_buf()));
1293        let error = selected.validate_skills(&env).await.unwrap_err();
1294        assert!(error.contains("selected skill diagnostics"), "{error}");
1295        assert!(error.contains("shadowed"), "{error}");
1296        assert!(error.contains("first-registration wins"), "{error}");
1297        assert!(selected.validated_skills().is_err());
1298    }
1299
1300    #[tokio::test]
1301    async fn snapshot_errors_without_exact_mode_and_when_oversized() {
1302        let harness = AgentHarness::create(Default::default()).await.unwrap();
1303        assert!(get_resource_state(&harness)
1304            .await
1305            .unwrap_err()
1306            .contains("requires --resource-config"));
1307        harness.seal_resources(vec![]).unwrap();
1308        attach(
1309            &harness,
1310            json!({"oversized": "x".repeat(MAX_STATE_BYTES)}),
1311            Default::default(),
1312        );
1313        assert!(get_resource_state(&harness)
1314            .await
1315            .unwrap_err()
1316            .contains("exceeds 256 KiB"));
1317    }
1318}