capability-example 0.1.0

A framework for managing skill tree growth and configuration using automated and manual strategies, ideal for AI-driven environments.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// ---------------- [ File: capability-example/src/partially_grown_model.rs ]
crate::ix!();

#[derive(SaveLoad,Builder,Getters,Setters,Clone,Debug,Serialize,Deserialize)]
#[builder(setter(into))]
#[getset(get = "pub", set = "pub")]
#[serde(deny_unknown_fields)]  // <--- Force parse error on unknown fields
pub struct PartiallyGrownModel {

    #[builder(default)]
    grower_inputs:                                       Option<GrowerInputs>,

    #[builder(default)]
    maybe_ungrown_justified_grower_tree_configuration:   Option<JustifiedGrowerTreeConfiguration>,

    #[builder(default)]
    maybe_ungrown_justified_string_skeleton:             Option<JustifiedStringSkeleton>,

    #[builder(default)]
    maybe_ungrown_stripped_string_skeleton:              Option<StrippedStringSkeleton>,

    #[builder(default)]
    maybe_ungrown_core_string_skeleton:                  Option<CoreStringSkeleton>,

    #[builder(default)]
    maybe_ungrown_annotated_leaf_holder_expansions:      Option<AnnotatedLeafHolderExpansions>,
}

impl From<GrowerInputs> for PartiallyGrownModel {

    fn from(grower_inputs: GrowerInputs) -> Self {
        Self {
            grower_inputs:                                       Some(grower_inputs),
            maybe_ungrown_justified_grower_tree_configuration:   None,
            maybe_ungrown_justified_string_skeleton:             None,
            maybe_ungrown_stripped_string_skeleton:              None,
            maybe_ungrown_core_string_skeleton:                  None,
            maybe_ungrown_annotated_leaf_holder_expansions:      None,
        }
    }
}

impl PartiallyGrownModel {

    pub fn empty() -> Self {
        Self {
            grower_inputs:                                       None,
            maybe_ungrown_justified_grower_tree_configuration:   None,
            maybe_ungrown_justified_string_skeleton:             None,
            maybe_ungrown_stripped_string_skeleton:              None,
            maybe_ungrown_core_string_skeleton:                  None,
            maybe_ungrown_annotated_leaf_holder_expansions:      None,
        }
    }

    pub fn essentially_empty(&self) -> bool {
        self.grower_inputs.is_some() &&
            self.maybe_ungrown_justified_grower_tree_configuration.is_none() &&
            self.maybe_ungrown_justified_string_skeleton.is_none() &&
            self.maybe_ungrown_stripped_string_skeleton.is_none() &&
            self.maybe_ungrown_core_string_skeleton.is_none() &&
            self.maybe_ungrown_annotated_leaf_holder_expansions.is_none()
    }

    pub fn validate(&self) -> Result<(), GrowerModelGenerationInvalidPartial> {

        trace!("Starting validate for PartiallyGrownModel: {:?}", self);

        // Ensure no downstream component is present when an upstream step is missing
        if self.maybe_ungrown_justified_grower_tree_configuration.is_none() {

            if self.maybe_ungrown_justified_string_skeleton.is_some() {
                error!("JustifiedStringSkeleton present without JustifiedGrowerTreeConfiguration");
            }

            if self.maybe_ungrown_stripped_string_skeleton.is_some() {
                error!("StrippedStringSkeleton present without JustifiedGrowerTreeConfiguration");
            }

            if self.maybe_ungrown_core_string_skeleton.is_some() {
                error!("CoreStringSkeleton present without JustifiedGrowerTreeConfiguration");
            }
            if self.maybe_ungrown_annotated_leaf_holder_expansions.is_some() {
                error!("AnnotatedLeafHolderExpansions present without JustifiedGrowerTreeConfiguration");
            }

            return Err(GrowerModelGenerationInvalidPartial::MissingJustifiedGrowerTreeConfiguration);
        }

        if self.maybe_ungrown_justified_string_skeleton.is_none() {

            if self.maybe_ungrown_stripped_string_skeleton.is_some() {
                error!("StrippedStringSkeleton present without JustifiedStringSkeleton");
            }

            if self.maybe_ungrown_core_string_skeleton.is_some() {
                error!("CoreStringSkeleton present without JustifiedStringSkeleton");
            }

            if self.maybe_ungrown_annotated_leaf_holder_expansions.is_some() {
                error!("AnnotatedLeafHolderExpansions present without JustifiedStringSkeleton");
            }

            return Err(GrowerModelGenerationInvalidPartial::MissingJustifiedStringSkeleton);
        }

        if self.maybe_ungrown_stripped_string_skeleton.is_none() {

            if self.maybe_ungrown_core_string_skeleton.is_some() {
                error!("CoreStringSkeleton present without StrippedStringSkeleton");
            }

            if self.maybe_ungrown_annotated_leaf_holder_expansions.is_some() {
                error!("AnnotatedLeafHolderExpansions present without StrippedStringSkeleton");
            }

            return Err(GrowerModelGenerationInvalidPartial::MissingStrippedStringSkeleton);
        }

        if self.maybe_ungrown_core_string_skeleton.is_none() {

            if self.maybe_ungrown_annotated_leaf_holder_expansions.is_some() {
                error!("AnnotatedLeafHolderExpansions present without CoreStringSkeleton");
            }
            return Err(GrowerModelGenerationInvalidPartial::MissingCoreStringSkeleton);
        }

        if self.maybe_ungrown_annotated_leaf_holder_expansions.is_none() {
            return Err(GrowerModelGenerationInvalidPartial::MissingAnnotatedLeafHolderExpansions);
        }

        info!("PartiallyGrownModel validation passed");
        Ok(())
    }
}

impl PartiallyGrownModel {
    #[tracing::instrument(level = "trace", skip_all)]
    pub async fn load_from_file_fuzzy<P: AsRef<std::path::Path> + Send + Sync>(
        path: P,
    ) -> Result<Self, FuzzyLoadPartiallyGrownModelError> {
        use std::fs;

        let raw_contents = fs::read_to_string(&path)?;
        debug!(
            "Read {} bytes from '{:?}' => attempting fuzzy parse of PartiallyGrownModel.",
            raw_contents.len(),
            path.as_ref()
        );

        // Step 1) Convert entire file to a serde_json::Value
        let mut root: serde_json::Value = serde_json::from_str(&raw_contents)?;

        // Flatten "fields" throughout the entire JSON
        recursively_flatten_fields(&mut root);

        // Step 2) We'll try to parse the entire object as a standard PartiallyGrownModel
        match try_deserialize_with_path::<PartiallyGrownModel>(&root) {
            Ok(mut pg) => {
                trace!("Direct parse of PartiallyGrownModel succeeded => returning without further fuzz.");
                let did_fill = pg.try_filling_next_none_field_from_clipboard();
                if did_fill {
                    pg.save_to_file(&path).await?;
                }
                return Ok(pg);
            }
            Err(e) => {
                warn!("Direct parse of PartiallyGrownModel failed => will attempt subfield fuzzy logic. Error string: {}", e);
            }
        }

        // Step 3) We'll treat `root` as an object, manually parse each subfield fuzzily or precisely.
        let mut root_obj = match root.as_object_mut() {
            Some(obj) => obj,
            None => {
                return Err(FuzzyLoadPartiallyGrownModelError::RootOfJSONIsNotAnObjectForPartiallyGrownModel);
            }
        };


        // --- (A) parse "grower_inputs" precisely from JSON or from clipboard (no fuzzy needed) ---
        let grower_inputs_val = root_obj
            .remove("grower_inputs")
            .unwrap_or(serde_json::Value::Null);

        let grower_inputs: GrowerInputs = if grower_inputs_val.is_null() {
            // Attempt parse from clipboard as precise JSON
            match (|| {
                let mut ctx = ClipboardContext::new().map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Clipboard context creation error: {e}"),
                    )
                })?;

                let contents = ctx.get_contents().map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Clipboard get_contents error: {e}"),
                    )
                })?;

                debug!("Clipboard contents retrieved: {}", contents);

                let json_val: serde_json::Value = serde_json::from_str(&contents).map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Clipboard JSON parsing error: {e}"),
                    )
                })?;

                debug!("Parsed JSON value from clipboard for GrowerInputs: {:?}", json_val);

                // Use the standard path-aware approach to parse GrowerInputs exactly
                let gi = try_deserialize_with_path::<GrowerInputs>(&json_val).map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Clipboard to GrowerInputs parse error: {e}"),
                    )
                })?;

                // Explicit result type for E0282 fix:
                Ok::<GrowerInputs, std::io::Error>(gi)
            })() {
                Ok(v) => {
                    trace!("Clipboard parse for 'grower_inputs' succeeded => using that value.");
                    v
                }
                Err(e) => {
                    error!("No JSON for 'grower_inputs' in file and clipboard parse failed => cannot continue. Error: {e}");
                    return Err(FuzzyLoadPartiallyGrownModelError::NoJsonForGrowerInputsAndClipboardParseFailed);
                }
            }
        } else {
            trace!("Attempting standard parse from JSON");
            match try_deserialize_with_path(&grower_inputs_val) {
                Ok(g) => g,
                Err(e) => {
                    error!("Could not parse 'grower_inputs': {e}");
                    return Err(FuzzyLoadPartiallyGrownModelError::CouldNotParseGrowerInputs);
                }
            }
        };

        // --- (B) parse "maybe_ungrown_justified_grower_tree_configuration" fuzzily, fallback clipboard (OPTIONAL) ---
        let mgc_val = root_obj
            .remove("maybe_ungrown_justified_grower_tree_configuration")
            .unwrap_or(serde_json::Value::Null);

        let maybe_ungrown_justified_grower_tree_configuration = if mgc_val.is_null() {
            match fuzzy_parse_clipboard_contents::<JustifiedGrowerTreeConfiguration>(false) {
                Ok(obj) => {
                    trace!("Clipboard parse of JustifiedGrowerTreeConfiguration succeeded => using that value.");
                    Some(obj)
                }
                Err(e) => {
                    warn!("Clipboard parse of JustifiedGrowerTreeConfiguration failed => returning None. Error: {:?}", e);
                    None
                }
            }
        } else {
            match JustifiedGrowerTreeConfiguration::fuzzy_from_json_value(&mgc_val) {
                Ok(obj) => Some(obj),
                Err(e) => {
                    warn!("Fuzzy parse of JustifiedGrowerTreeConfiguration failed => returning None. Error: {:?}", e);
                    None
                }
            }
        };

        // --- (C) parse "maybe_ungrown_justified_string_skeleton" fuzzily, fallback clipboard (OPTIONAL) ---
        let msk_val = root_obj
            .remove("maybe_ungrown_justified_string_skeleton")
            .unwrap_or(serde_json::Value::Null);

        let maybe_ungrown_justified_string_skeleton = if msk_val.is_null() {
            match fuzzy_parse_clipboard_contents::<JustifiedStringSkeleton>(false) {
                Ok(obj) => {
                    trace!("Clipboard parse of JustifiedStringSkeleton succeeded => using that value.");
                    Some(obj)
                }
                Err(e) => {
                    warn!("Clipboard parse of JustifiedStringSkeleton failed => returning None. Error: {:?}", e);
                    None
                }
            }
        } else {
            match JustifiedStringSkeleton::fuzzy_from_json_value(&msk_val) {
                Ok(obj) => Some(obj),
                Err(e) => {
                    warn!("Fuzzy parse of JustifiedStringSkeleton failed => returning None. Error: {:?}", e);
                    None
                }
            }
        };

        // --- (D) parse "maybe_ungrown_stripped_string_skeleton" normally, fallback clipboard (OPTIONAL) ---
        let stripped_val = root_obj
            .remove("maybe_ungrown_stripped_string_skeleton")
            .unwrap_or(serde_json::Value::Null);

        let maybe_ungrown_stripped_string_skeleton = if stripped_val.is_null() {
            match (|| {
                let mut ctx = ClipboardContext::new().map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Clipboard context creation error: {e}"),
                    )
                })?;
                let contents = ctx.get_contents().map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Clipboard get_contents error: {e}"),
                    )
                })?;
                let json_val: serde_json::Value = serde_json::from_str(&contents).map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Clipboard JSON parsing error: {e}"),
                    )
                })?;
                try_deserialize_with_path::<StrippedStringSkeleton>(&json_val).map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Clipboard parse error for StrippedStringSkeleton: {e}"),
                    )
                })
            })() {
                Ok(s) => {
                    trace!("Clipboard parse of StrippedStringSkeleton succeeded => using that value.");
                    Some(s)
                }
                Err(e) => {
                    warn!("Clipboard parse of StrippedStringSkeleton failed => returning None. Error: {:?}", e);
                    None
                }
            }
        } else {
            match try_deserialize_with_path(&stripped_val) {
                Ok(s) => Some(s),
                Err(e) => {
                    warn!("StrippedStringSkeleton parse error => returning None: {}", e);
                    None
                }
            }
        };

        // --- (E) parse "maybe_ungrown_core_string_skeleton" fuzzily, fallback clipboard (OPTIONAL) ---
        let core_val = root_obj
            .remove("maybe_ungrown_core_string_skeleton")
            .unwrap_or(serde_json::Value::Null);

        let maybe_ungrown_core_string_skeleton = if core_val.is_null() {
            match fuzzy_parse_clipboard_contents::<CoreStringSkeleton>(false) {
                Ok(cs) => {
                    trace!("Clipboard parse of CoreStringSkeleton succeeded => using that value.");
                    Some(cs)
                }
                Err(e) => {
                    warn!("Clipboard parse of CoreStringSkeleton failed => returning None. Error: {:?}", e);
                    None
                }
            }
        } else {
            match CoreStringSkeleton::fuzzy_from_json_value(&core_val) {
                Ok(cs) => Some(cs),
                Err(e) => {
                    warn!("Fuzzy parse of CoreStringSkeleton failed => returning None. Error: {:?}", e);
                    None
                }
            }
        };

        // --- (F) parse "maybe_ungrown_annotated_leaf_holder_expansions" fuzzily, fallback clipboard (OPTIONAL) ---
        let ann_val = root_obj
            .remove("maybe_ungrown_annotated_leaf_holder_expansions")
            .unwrap_or(serde_json::Value::Null);

        let maybe_ungrown_annotated_leaf_holder_expansions = if ann_val.is_null() {
            match fuzzy_parse_clipboard_contents::<AnnotatedLeafHolderExpansions>(false) {
                Ok(ann) => {
                    trace!("Clipboard parse of AnnotatedLeafHolderExpansions succeeded => using that value.");
                    Some(ann)
                }
                Err(e) => {
                    warn!("Clipboard parse of AnnotatedLeafHolderExpansions failed => returning None. Error: {:?}", e);
                    None
                }
            }
        } else {
            match AnnotatedLeafHolderExpansions::fuzzy_from_json_value(&ann_val) {
                Ok(ann) => Some(ann),
                Err(e) => {
                    warn!("Fuzzy parse of AnnotatedLeafHolderExpansions failed => returning None. Error: {:?}", e);
                    None
                }
            }
        };

        // --- (G) Build the partial model ---
        let partial = PartiallyGrownModel {
            grower_inputs: Some(grower_inputs),
            maybe_ungrown_justified_grower_tree_configuration,
            maybe_ungrown_justified_string_skeleton,
            maybe_ungrown_stripped_string_skeleton,
            maybe_ungrown_core_string_skeleton,
            maybe_ungrown_annotated_leaf_holder_expansions,
        };

        Ok(partial)
    }
}

/// Attempt to deserialize `val` into `T`, returning an error string on failure
/// that includes the JSON path (e.g. `.capstone.probability`).
pub fn try_deserialize_with_path<T: DeserializeOwned>(val: &serde_json::Value)
    -> Result<T, serde_json::Error>
{
    match from_value_pathaware::<T>(&val) {
        Ok(parsed) => Ok(parsed),
        Err(path_err) => {
            eprintln!(
                "Deserialization failed at path {path_err}",
            );
            Err(path_err)
        }
    }
}