File size: 10,129 Bytes
80d7559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// CARRY β€” Braid Topology Module
// Three strands form a braid group B₃
// Crossings are state transitions; writhe is the integrity invariant
// The braid word [σ₁, Οƒβ‚‚] encodes the full authority transfer:
//   Curry β†’ Crystal β†’ C3 (C3 rises to position 1 = authority)

use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Strand {
    Curry,
    Crystal,
    C3,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrossingSign {
    Positive, // Οƒα΅’   β€” over (authority taken)
    Negative, // σᡒ⁻¹ β€” under (authority yielded)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Generator {
    Sigma1,       // σ₁: strands at positions 1,2 cross
    Sigma2,       // Οƒβ‚‚: strands at positions 2,3 cross
    Sigma1Inv,    // σ₁⁻¹
    Sigma2Inv,    // σ₂⁻¹
    Sigma12,      // σ₁·σ₂ composite (full descent)
    Identity,     // terminal
}

impl Generator {
    pub fn sign(&self) -> CrossingSign {
        match self {
            Generator::Sigma1 => CrossingSign::Positive,
            Generator::Sigma2 => CrossingSign::Positive,
            Generator::Sigma12 => CrossingSign::Positive,
            Generator::Identity => CrossingSign::Positive,
            Generator::Sigma1Inv => CrossingSign::Negative,
            Generator::Sigma2Inv => CrossingSign::Negative,
        }
    }

    pub fn writhe_contribution(&self) -> i32 {
        match self.sign() {
            CrossingSign::Positive => 1,
            CrossingSign::Negative => -1,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Crossing {
    pub generator: Generator,
    pub over_strand: Strand,
    pub under_strand: Strand,
    pub entropy: f32,
    pub rule_name: &'static str,
}

#[derive(Debug, Clone)]
pub struct BraidState {
    pub positions: [Strand; 3], // positions[0] = leftmost (highest authority)
    pub crossings: Vec<Crossing>,
    pub writhe: i32,
}

impl BraidState {
    pub fn new() -> Self {
        Self {
            positions: [Strand::Curry, Strand::Crystal, Strand::C3],
            crossings: Vec::new(),
            writhe: 0,
        }
    }

    pub fn apply_crossing(&mut self, crossing: Crossing) -> Result<(), BraidError> {
        // Entropy gate
        if crossing.entropy > 0.20 {
            return Err(BraidError::EntropyExceeded {
                value: crossing.entropy,
                at_crossing: crossing.generator,
            });
        }

        // Apply the permutation
        match crossing.generator {
            Generator::Sigma1 => {
                self.positions.swap(0, 1);
            }
            Generator::Sigma2 => {
                self.positions.swap(1, 2);
            }
            Generator::Sigma1Inv => {
                self.positions.swap(0, 1);
            }
            Generator::Sigma2Inv => {
                self.positions.swap(1, 2);
            }
            Generator::Sigma12 => {
                self.positions.swap(0, 1);
                self.positions.swap(1, 2);
            }
            Generator::Identity => {}
        }

        self.writhe += crossing.generator.writhe_contribution();
        self.crossings.push(crossing);
        Ok(())
    }

    pub fn authority_holder(&self) -> Strand {
        self.positions[0]
    }

    pub fn verify_invariant(&self) -> Result<BraidProof, BraidError> {
        if self.writhe < 2 {
            return Err(BraidError::WritheInsufficient {
                expected: 2,
                actual: self.writhe,
            });
        }

        if self.authority_holder() != Strand::C3 {
            return Err(BraidError::AuthorityNotTransferred {
                holder: self.authority_holder(),
            });
        }

        // Verify no Reidemeister-I cancellation exists (no σ·σ⁻¹ adjacent)
        for window in self.crossings.windows(2) {
            if cancels(&window[0].generator, &window[1].generator) {
                return Err(BraidError::TrivialCrossing);
            }
        }

        Ok(BraidProof {
            word_length: self.crossings.len(),
            writhe: self.writhe,
            authority: self.authority_holder(),
            final_positions: self.positions,
        })
    }

    pub fn canonical_pipeline() -> Vec<Crossing> {
        // σ₂·σ₁: C3 rises through Crystal, then through Curry
        // [Curry, Crystal, C3] β†’ Οƒβ‚‚ β†’ [Curry, C3, Crystal] β†’ σ₁ β†’ [C3, Curry, Crystal]
        vec![
            Crossing {
                generator: Generator::Sigma2,
                over_strand: Strand::C3,
                under_strand: Strand::Crystal,
                entropy: 0.0,
                rule_name: "R2_NATIVE_BINDING",
            },
            Crossing {
                generator: Generator::Sigma1,
                over_strand: Strand::C3,
                under_strand: Strand::Curry,
                entropy: 0.0,
                rule_name: "R1_FFI_C_ABI",
            },
        ]
    }
}

fn cancels(a: &Generator, b: &Generator) -> bool {
    matches!(
        (a, b),
        (Generator::Sigma1, Generator::Sigma1Inv)
            | (Generator::Sigma1Inv, Generator::Sigma1)
            | (Generator::Sigma2, Generator::Sigma2Inv)
            | (Generator::Sigma2Inv, Generator::Sigma2)
    )
}

#[derive(Debug)]
pub struct BraidProof {
    pub word_length: usize,
    pub writhe: i32,
    pub authority: Strand,
    pub final_positions: [Strand; 3],
}

impl fmt::Display for BraidProof {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "BRAID PROOF β€” CARRY PIPELINE")?;
        writeln!(f, "  Word length:  {}", self.word_length)?;
        writeln!(f, "  Writhe:       {} (β‰₯2 required)", self.writhe)?;
        writeln!(f, "  Authority:    {:?} (position 0)", self.authority)?;
        writeln!(f, "  Positions:    {:?}", self.final_positions)?;
        writeln!(f, "  Status:       INVARIANT HOLDS")
    }
}

#[derive(Debug)]
pub enum BraidError {
    EntropyExceeded { value: f32, at_crossing: Generator },
    WritheInsufficient { expected: i32, actual: i32 },
    AuthorityNotTransferred { holder: Strand },
    TrivialCrossing,
}

impl fmt::Display for BraidError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BraidError::EntropyExceeded { value, at_crossing } => {
                write!(f, "ENTROPY_GATE: {:.3} > 0.20 at {:?}", value, at_crossing)
            }
            BraidError::WritheInsufficient { expected, actual } => {
                write!(f, "WRITHE_VIOLATION: {} < {} (authority not fully transferred)", actual, expected)
            }
            BraidError::AuthorityNotTransferred { holder } => {
                write!(f, "AUTHORITY_VIOLATION: {:?} holds position 0, expected C3", holder)
            }
            BraidError::TrivialCrossing => {
                write!(f, "TRIVIAL_CROSSING: σ·σ⁻¹ detected (Reidemeister-I cancellation)")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn canonical_pipeline_proves() {
        let mut braid = BraidState::new();
        for crossing in BraidState::canonical_pipeline() {
            braid.apply_crossing(crossing).unwrap();
        }
        let proof = braid.verify_invariant().unwrap();
        assert_eq!(proof.authority, Strand::C3);
        assert_eq!(proof.writhe, 2);
        assert_eq!(proof.final_positions, [Strand::C3, Strand::Curry, Strand::Crystal]);
    }

    #[test]
    fn entropy_gate_blocks() {
        let mut braid = BraidState::new();
        let bad_crossing = Crossing {
            generator: Generator::Sigma1,
            over_strand: Strand::Curry,
            under_strand: Strand::Crystal,
            entropy: 0.50,
            rule_name: "BAD",
        };
        assert!(braid.apply_crossing(bad_crossing).is_err());
    }

    #[test]
    fn inverse_cancellation_detected() {
        let mut braid = BraidState::new();
        let crossings = vec![
            Crossing {
                generator: Generator::Sigma1,
                over_strand: Strand::Curry,
                under_strand: Strand::Crystal,
                entropy: 0.1,
                rule_name: "R1",
            },
            Crossing {
                generator: Generator::Sigma1Inv,
                over_strand: Strand::Crystal,
                under_strand: Strand::Curry,
                entropy: 0.1,
                rule_name: "R1_INV",
            },
            Crossing {
                generator: Generator::Sigma2,
                over_strand: Strand::Crystal,
                under_strand: Strand::C3,
                entropy: 0.1,
                rule_name: "R2",
            },
        ];
        for c in crossings {
            let _ = braid.apply_crossing(c);
        }
        assert!(braid.verify_invariant().is_err());
    }

    #[test]
    fn authority_transfer_correct() {
        let mut braid = BraidState::new();
        assert_eq!(braid.authority_holder(), Strand::Curry);

        // Οƒβ‚‚: C3 crosses over Crystal
        braid.apply_crossing(Crossing {
            generator: Generator::Sigma2,
            over_strand: Strand::C3,
            under_strand: Strand::Crystal,
            entropy: 0.05,
            rule_name: "R2",
        }).unwrap();
        assert_eq!(braid.positions, [Strand::Curry, Strand::C3, Strand::Crystal]);

        // σ₁: C3 crosses over Curry β†’ C3 reaches position 0
        braid.apply_crossing(Crossing {
            generator: Generator::Sigma1,
            over_strand: Strand::C3,
            under_strand: Strand::Curry,
            entropy: 0.05,
            rule_name: "R1",
        }).unwrap();
        assert_eq!(braid.positions, [Strand::C3, Strand::Curry, Strand::Crystal]);
        assert_eq!(braid.authority_holder(), Strand::C3);
    }
}