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