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