Skip to main content

webizen_studio/
lexicon_catalog.rs

1//! Framing chips, held-gate copy, and `lexicon_manifest` result mapping.
2//!
3//! Cherry-picked from `crates/poet/src/browser/lexicon_bay/model.rs` so Desktop
4//! Aether chrome and WASM Poet share one Catalog · Lexicon dialect. No Host widen.
5
6/// Live ALL_BOUND id. Do not invent a Host method.
7pub const INVOKE_ID: &str = "GraphDatabase.lexicon_manifest";
8
9/// Soft why-text for missing / unknown / E300. Never "broken".
10pub const HELD_WHY: &str = "held / not yet — open lexicon pack";
11
12pub const LIVING_SAYABLE: &str = "person / living / country";
13pub const ARTIFACT_SAYABLE: &str = "tool / volume / file";
14pub const MACHINE_SAYABLE: &str = "Capability.method";
15
16pub const LIVING_CHIP: &str = "living";
17pub const ARTIFACT_CHIP: &str = "artifact";
18pub const MACHINE_CHIP: &str = "machine";
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Framing {
22    LivingShacl,
23    ArtifactOwl,
24    Mixed,
25}
26
27impl Framing {
28    /// `&str` form.
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::LivingShacl => "living-SHACL",
32            Self::ArtifactOwl => "artifact-OWL",
33            Self::Mixed => "mixed",
34        }
35    }
36
37    /// Parses.
38    pub fn parse(raw: &str) -> Option<Self> {
39        match raw.trim() {
40            "living-SHACL" | "living_shacl" | "living" => Some(Self::LivingShacl),
41            "artifact-OWL" | "artifact_owl" | "artifact" => Some(Self::ArtifactOwl),
42            "mixed" => Some(Self::Mixed),
43            _ => None,
44        }
45    }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum FramingChip {
50    Living,
51    Artifact,
52    Machine,
53}
54
55impl FramingChip {
56    /// Token.
57    pub fn token(self) -> &'static str {
58        match self {
59            Self::Living => LIVING_CHIP,
60            Self::Artifact => ARTIFACT_CHIP,
61            Self::Machine => MACHINE_CHIP,
62        }
63    }
64
65    /// Sayable name.
66    pub fn sayable(self) -> &'static str {
67        match self {
68            Self::Living => LIVING_SAYABLE,
69            Self::Artifact => ARTIFACT_SAYABLE,
70            Self::Machine => MACHINE_SAYABLE,
71        }
72    }
73
74    /// Tone.
75    pub fn tone(self) -> &'static str {
76        match self {
77            Self::Living => "warm",
78            Self::Artifact => "crisp",
79            Self::Machine => "muted",
80        }
81    }
82}
83
84/// Framing drives the chip set. Mixed splits living + artifact; machine is
85/// always the Capability.method filter. Never collapse living into Thing.
86pub fn chips_for_framing(framing: Framing) -> &'static [FramingChip] {
87    match framing {
88        Framing::LivingShacl => &[FramingChip::Living, FramingChip::Machine],
89        Framing::ArtifactOwl => &[FramingChip::Artifact, FramingChip::Machine],
90        Framing::Mixed => &[
91            FramingChip::Living,
92            FramingChip::Artifact,
93            FramingChip::Machine,
94        ],
95    }
96}
97
98/// Catalog filter row before a pack arrives — all three chips, muted.
99pub fn catalog_filter_chips() -> &'static [FramingChip] {
100    &[
101        FramingChip::Living,
102        FramingChip::Artifact,
103        FramingChip::Machine,
104    ]
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum RecipeBeat {
109    Arrive,
110    Hold,
111    Leave,
112    Commit,
113}
114
115impl RecipeBeat {
116    /// `&str` form.
117    pub fn as_str(self) -> &'static str {
118        match self {
119            Self::Arrive => "arrive",
120            Self::Hold => "hold",
121            Self::Leave => "leave",
122            Self::Commit => "commit",
123        }
124    }
125
126    /// Named beats only (entrance · dwell · exit). Reduced-motion still maps.
127    pub fn named_beat(self) -> &'static str {
128        match self {
129            Self::Arrive => "entrance",
130            Self::Hold | Self::Commit => "dwell",
131            Self::Leave => "exit",
132        }
133    }
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum RecipeEvent {
138    PackOpen,
139    BreakingIdsShown,
140    Dismiss,
141    PackWriteOk,
142    PackWriteHeld,
143}
144
145/// Recipe beat.
146pub fn recipe_beat(event: RecipeEvent) -> RecipeBeat {
147    match event {
148        RecipeEvent::PackOpen => RecipeBeat::Arrive,
149        RecipeEvent::BreakingIdsShown | RecipeEvent::PackWriteHeld => RecipeBeat::Hold,
150        RecipeEvent::Dismiss => RecipeBeat::Leave,
151        RecipeEvent::PackWriteOk => RecipeBeat::Commit,
152    }
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct PackCard {
157    pub pack_id: String,
158    pub pack_semver: String,
159    pub framing: Framing,
160    pub uplift_from: String,
161    pub concept_ids: Vec<String>,
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub enum ManifestOutcome {
166    Held { why: String },
167    Open(PackCard),
168}
169
170/// Held outcome.
171pub fn held_outcome(why: impl Into<String>) -> ManifestOutcome {
172    ManifestOutcome::Held {
173        why: sanitize_held_why(&why.into()),
174    }
175}
176
177/// Never surface "broken" or Thing-wash living senses.
178pub fn sanitize_held_why(raw: &str) -> String {
179    let folded = raw.to_ascii_lowercase();
180    if folded.contains("broken")
181        || raw.trim().is_empty()
182        || folded.contains("owl:thing")
183        || folded.contains("a thing")
184    {
185        return HELD_WHY.to_string();
186    }
187    if folded.contains("held") || folded.contains("open lexicon") {
188        raw.trim().to_string()
189    } else {
190        HELD_WHY.to_string()
191    }
192}
193
194/// Interprets an invoke.
195pub fn interpret_invoke(ok: bool, value: &str, diagnostic: Option<&str>) -> ManifestOutcome {
196    if ok {
197        if let Some(card) = parse_pack_card(value) {
198            return ManifestOutcome::Open(card);
199        }
200        // ok:true but strict card parse missed — still arrive if framing+semver present
201        // (format_value key order / extra fields must not strand the bay on held).
202        if let Some(card) = parse_pack_card_lenient(value) {
203            return ManifestOutcome::Open(card);
204        }
205    }
206    let blob = diagnostic.unwrap_or(value);
207    let why = if blob.to_ascii_lowercase().contains("e300")
208        || blob.contains("held / not yet")
209        || blob.contains("open lexicon pack")
210    {
211        extract_held_fix(blob)
212            .map(|fix| sanitize_held_why(&fix))
213            .unwrap_or_else(|| HELD_WHY.to_string())
214    } else {
215        HELD_WHY.to_string()
216    };
217    ManifestOutcome::Held { why }
218}
219
220fn extract_held_fix(blob: &str) -> Option<String> {
221    for needle in ["held / not yet", "suggested_fix"] {
222        if let Some(idx) = blob.find(needle) {
223            let rest = blob[idx..].lines().next().unwrap_or("").trim();
224            let rest = rest
225                .trim_start_matches("suggested_fix")
226                .trim_start_matches(':')
227                .trim();
228            if !rest.is_empty() {
229                return Some(rest.to_string());
230            }
231        }
232    }
233    None
234}
235
236/// Parses pack-card.
237pub fn parse_pack_card(src: &str) -> Option<PackCard> {
238    let framing = extract_quoted_field(src, "framing").and_then(|s| Framing::parse(&s))?;
239    let pack_semver = extract_quoted_field(src, "packSemVer")
240        .or_else(|| extract_quoted_field(src, "pack_semver"))?;
241    let pack_id = extract_quoted_field(src, "pack_id")
242        .or_else(|| extract_quoted_field(src, "packId"))
243        .or_else(|| extract_quoted_field(src, "id"))
244        .unwrap_or_default();
245    let uplift_from = extract_quoted_field(src, "upliftFrom")
246        .or_else(|| extract_quoted_field(src, "uplift_from"))
247        .unwrap_or_default();
248    let concept_ids = extract_string_list(src, "conceptIds")
249        .or_else(|| extract_string_list(src, "concept_ids"))
250        .unwrap_or_default();
251    Some(PackCard {
252        pack_id,
253        pack_semver,
254        framing,
255        uplift_from,
256        concept_ids,
257    })
258}
259
260/// Best-effort card when invoke ok but one field is oddly formatted.
261fn parse_pack_card_lenient(src: &str) -> Option<PackCard> {
262    let framing = extract_quoted_field(src, "framing")
263        .and_then(|s| Framing::parse(&s))
264        .or_else(|| {
265            if src.contains("mixed") {
266                Some(Framing::Mixed)
267            } else if src.contains("living") {
268                Some(Framing::LivingShacl)
269            } else if src.contains("artifact") {
270                Some(Framing::ArtifactOwl)
271            } else {
272                None
273            }
274        })?;
275    let pack_semver = extract_quoted_field(src, "packSemVer")
276        .or_else(|| extract_quoted_field(src, "pack_semver"))
277        .or_else(|| {
278            // bare 0.1.0 near packSemVer key
279            src.find("packSemVer").and_then(|i| {
280                let rest = &src[i..i.saturating_add(40)];
281                rest.split('"').nth(1).map(|s| s.to_string())
282            })
283        })?;
284    let pack_id = extract_quoted_field(src, "pack_id")
285        .or_else(|| extract_quoted_field(src, "packId"))
286        .unwrap_or_default();
287    Some(PackCard {
288        pack_id,
289        pack_semver,
290        framing,
291        uplift_from: extract_quoted_field(src, "upliftFrom").unwrap_or_default(),
292        concept_ids: extract_string_list(src, "conceptIds").unwrap_or_default(),
293    })
294}
295
296fn extract_quoted_field(src: &str, key: &str) -> Option<String> {
297    let patterns = [
298        format!("{key}: \""),
299        format!("{key}:\""),
300        format!("\"{key}\": \""),
301        format!("\"{key}\":\""),
302    ];
303    for pat in patterns {
304        if let Some(start) = src.find(&pat) {
305            let rest = &src[start + pat.len()..];
306            if let Some(end) = rest.find('"') {
307                return Some(rest[..end].to_string());
308            }
309        }
310    }
311    None
312}
313
314fn extract_string_list(src: &str, key: &str) -> Option<Vec<String>> {
315    let markers = [format!("{key}: ["), format!("\"{key}\": [")];
316    for marker in markers {
317        if let Some(start) = src.find(&marker) {
318            let rest = &src[start + marker.len()..];
319            let end = rest.find(']')?;
320            let inner = &rest[..end];
321            let ids = inner
322                .split(',')
323                .filter_map(|part| {
324                    let p = part.trim().trim_matches('"');
325                    (!p.is_empty()).then(|| p.to_string())
326                })
327                .collect();
328            return Some(ids);
329        }
330    }
331    None
332}
333
334/// `true` when copy avoids broken terms.
335pub fn copy_avoids_broken(text: &str) -> bool {
336    !text.to_ascii_lowercase().contains("broken")
337}
338
339/// `true` when copy avoids thing-wash.
340pub fn copy_avoids_thing_wash(text: &str) -> bool {
341    let folded = text.to_ascii_lowercase();
342    !folded.contains("owl:thing") && !folded.contains("a thing")
343}
344
345/// `true` when copy avoids "unavailable".
346pub fn copy_avoids_unavailable(text: &str) -> bool {
347    !text.to_ascii_lowercase().contains("unavailable")
348}
349
350/// Wait-honest copy for Mesh / Aura / SHACL / Pulse / Job / Graph / Morpha
351/// when the bind is missing. Never "unavailable".
352pub const HELD_BIND_MISSING: &str = "held / not yet";
353
354/// Desktop / Poet chrome when `127.0.0.1:4242` `/health` answers.
355pub const NATIVE_CONNECTED_LABEL: &str = "Native Connected to 127.0.0.1:4242";
356
357/// Framing copy.
358pub fn framing_copy(framing: Framing) -> &'static str {
359    match framing {
360        Framing::LivingShacl => LIVING_SAYABLE,
361        Framing::ArtifactOwl => ARTIFACT_SAYABLE,
362        Framing::Mixed => "living and artifact senses stay split",
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn bind_is_live_lexicon_manifest() {
372        assert_eq!(INVOKE_ID, "GraphDatabase.lexicon_manifest");
373        assert!(!INVOKE_ID.contains("qualia."));
374    }
375
376    #[test]
377    fn framing_chips_split_mixed_and_never_thing_wash_living() {
378        assert_eq!(
379            chips_for_framing(Framing::LivingShacl),
380            &[FramingChip::Living, FramingChip::Machine]
381        );
382        assert_eq!(
383            chips_for_framing(Framing::ArtifactOwl),
384            &[FramingChip::Artifact, FramingChip::Machine]
385        );
386        let mixed = chips_for_framing(Framing::Mixed);
387        assert!(mixed.contains(&FramingChip::Living));
388        assert!(mixed.contains(&FramingChip::Artifact));
389        assert!(mixed.contains(&FramingChip::Machine));
390        assert_eq!(FramingChip::Living.sayable(), LIVING_SAYABLE);
391        assert_eq!(FramingChip::Artifact.sayable(), ARTIFACT_SAYABLE);
392        assert!(!LIVING_SAYABLE.to_ascii_lowercase().contains("thing"));
393        assert_eq!(Framing::parse("mixed"), Some(Framing::Mixed));
394    }
395
396    #[test]
397    fn live_daemon_format_value_opens_pack_card() {
398        // Exact shape returned by POST :4242/invoke GraphDatabase.lexicon_manifest
399        // on en-core (Capt B4 host curl). Must arrive Open, never default held.
400        let value = r#"{conceptIds: ["concept:arrive", "concept:hold", "concept:leave"], framing: "mixed", gate: "open", manifest_path: "/workspace/qualiaDB/crates/vibe/fixtures/lexicon/en-core.lexicon.json", packSemVer: "0.1.0", pack_id: "en-core@0.1.0", upliftFrom: "", volume_ok: false, volume_path: ""}"#;
401        match interpret_invoke(true, value, None) {
402            ManifestOutcome::Open(card) => {
403                assert_eq!(card.pack_semver, "0.1.0");
404                assert_eq!(card.pack_id, "en-core@0.1.0");
405            }
406            other => panic!("expected Open, got {other:?}"),
407        }
408    }
409
410    #[test]
411    fn held_gate_copy_never_says_broken() {
412        assert_eq!(sanitize_held_why("volume broken"), HELD_WHY);
413        assert_eq!(sanitize_held_why(""), HELD_WHY);
414        assert_eq!(
415            sanitize_held_why("held / not yet — open lexicon pack"),
416            HELD_WHY
417        );
418        assert!(copy_avoids_broken(HELD_WHY));
419        assert!(copy_avoids_thing_wash(HELD_WHY));
420        assert!(copy_avoids_unavailable(HELD_WHY));
421        assert!(copy_avoids_unavailable(HELD_BIND_MISSING));
422        for text in [
423            "Mesh · held / not yet — no live mesh bind",
424            "Pulse bus · held / not yet — Pulse waits on the local daemon",
425            "Aura / SHACL · held / not yet — SHACL waits on the local daemon",
426            "Job · held / not yet — no live job-queue bind",
427        ] {
428            assert!(copy_avoids_unavailable(text), "{text}");
429            assert!(text.contains(HELD_BIND_MISSING), "{text}");
430        }
431        assert!(copy_avoids_unavailable(NATIVE_CONNECTED_LABEL));
432        assert!(NATIVE_CONNECTED_LABEL.contains("127.0.0.1:4242"));
433        assert!(copy_avoids_thing_wash(LIVING_SAYABLE));
434        assert!(copy_avoids_thing_wash(ARTIFACT_SAYABLE));
435        match interpret_invoke(false, "", Some("E300@0..0: lexicon pack not found")) {
436            ManifestOutcome::Held { why } => {
437                assert_eq!(why, HELD_WHY);
438                assert!(copy_avoids_broken(&why));
439            }
440            other => panic!("{other:?}"),
441        }
442    }
443
444    #[test]
445    fn success_parses_live_format_value_shape() {
446        let src = r#"{conceptIds: ["concept:arrive", "concept:hold", "concept:leave"], framing: "mixed", gate: "open", manifest_path: "/tmp/en-core.lexicon.json", packSemVer: "0.1.0", pack_id: "en-core@0.1.0", upliftFrom: "", volume_ok: false, volume_path: ""}"#;
447        match interpret_invoke(true, src, None) {
448            ManifestOutcome::Open(card) => {
449                assert_eq!(card.pack_semver, "0.1.0");
450                assert_eq!(card.framing, Framing::Mixed);
451            }
452            other => panic!("{other:?}"),
453        }
454    }
455
456    #[test]
457    fn success_parses_pack_card_and_arrive_beat() {
458        let src = r#"{pack_id: "en-core@0.1.0", packSemVer: "0.1.0", framing: "mixed", upliftFrom: "", conceptIds: ["concept:arrive", "concept:hold"]}"#;
459        let card = parse_pack_card(src).expect("card");
460        assert_eq!(card.pack_semver, "0.1.0");
461        assert_eq!(card.framing, Framing::Mixed);
462        assert_eq!(card.concept_ids.len(), 2);
463        match interpret_invoke(true, src, None) {
464            ManifestOutcome::Open(open) => assert_eq!(open.pack_id, "en-core@0.1.0"),
465            other => panic!("{other:?}"),
466        }
467        assert_eq!(recipe_beat(RecipeEvent::PackOpen), RecipeBeat::Arrive);
468        assert_eq!(recipe_beat(RecipeEvent::BreakingIdsShown), RecipeBeat::Hold);
469        assert_eq!(recipe_beat(RecipeEvent::Dismiss), RecipeBeat::Leave);
470        assert_eq!(recipe_beat(RecipeEvent::PackWriteOk), RecipeBeat::Commit);
471        assert_eq!(recipe_beat(RecipeEvent::PackWriteHeld), RecipeBeat::Hold);
472        assert_eq!(RecipeBeat::Arrive.named_beat(), "entrance");
473        assert_eq!(RecipeBeat::Leave.named_beat(), "exit");
474    }
475
476    #[test]
477    fn chip_tones_are_warm_crisp_muted() {
478        assert_eq!(FramingChip::Living.tone(), "warm");
479        assert_eq!(FramingChip::Artifact.tone(), "crisp");
480        assert_eq!(FramingChip::Machine.tone(), "muted");
481        assert_eq!(FramingChip::Machine.sayable(), MACHINE_SAYABLE);
482    }
483}