proofborne-core 0.1.0-alpha.4

Versioned contracts, events, provider types, and proof graph for Proofborne
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use uuid::Uuid;

use crate::{AssuranceLevel, SCHEMA_VERSION, hash_bytes};

/// Semantic category of one provenance-bound context statement.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ContextKind {
    /// Runtime-observed tool, process, Git, or completion evidence.
    Observation,
    /// Unverified model-authored conclusion.
    Assertion,
    /// Explicit human or runtime policy decision.
    Decision,
    /// User-authored durable preference.
    UserPreference,
    /// Statement imported from an external source.
    External,
}

/// Provenance anchor for one context statement.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ContextSource {
    /// Session whose causal event introduced this statement.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<Uuid>,
    /// Hash of the source event in the session event chain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_id: Option<String>,
    /// Source event sequence in the session event chain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_seq: Option<u64>,
    /// Runtime evidence represented by this context item.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence_id: Option<Uuid>,
    /// Runtime generation observed by the source.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_generation: Option<u64>,
    /// Canonical workspace digest observed by the source.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state_binding: Option<String>,
    /// Optional external provenance URI.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_uri: Option<String>,
}

/// Scope in which a context statement may be retrieved.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ContextScope {
    /// Secret-free digest of the canonical workspace identity.
    pub workspace_id: String,
    /// Optional repository identity supplied by a trusted runtime integration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repository: Option<String>,
    /// Optional branch identity supplied by a trusted runtime integration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    /// Workspace-relative path, when the statement is path-scoped.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Language symbol, when the statement is symbol-scoped.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    /// Task contract that caused the observation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_contract_id: Option<Uuid>,
}

/// Authority that produced a context statement.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ContextAuthority {
    /// Stable producer identity.
    pub producer: String,
    /// Assurance boundary inherited from the source observation.
    pub assurance_level: AssuranceLevel,
    /// Whether the producer and classification are runtime-owned.
    pub runtime_owned: bool,
}

/// Public indication that sensitive input was removed before persistence.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SecretTaint {
    /// No configured secret matched the persisted public statement.
    #[default]
    None,
    /// Sensitive material matched and only a redacted statement was retained.
    Redacted,
}

/// Immutable, content-addressed context statement.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ContextItem {
    /// Public schema identifier.
    pub schema_version: String,
    /// Stable item identifier.
    pub id: Uuid,
    /// Statement category.
    pub kind: ContextKind,
    /// Public, redacted statement body.
    pub content: String,
    /// BLAKE3 digest of the exact UTF-8 statement body.
    pub content_digest: String,
    /// Causal provenance.
    pub source: ContextSource,
    /// Retrieval boundary.
    pub scope: ContextScope,
    /// Source observation time.
    pub observed_at: DateTime<Utc>,
    /// Producer authority.
    pub authority: ContextAuthority,
    /// Sensitive-data handling result.
    #[serde(default)]
    pub secret_taint: SecretTaint,
    /// Public structured attributes; never used as verification evidence by itself.
    #[serde(default)]
    pub attributes: Value,
}

impl ContextItem {
    /// Creates one runtime-owned observation from a redacted evidence statement.
    #[must_use]
    pub fn runtime_observation(
        content: impl Into<String>,
        source: ContextSource,
        scope: ContextScope,
        observed_at: DateTime<Utc>,
        authority: ContextAuthority,
        secret_taint: SecretTaint,
        attributes: Value,
    ) -> Self {
        let content = content.into();
        Self {
            schema_version: SCHEMA_VERSION.to_owned(),
            id: Uuid::now_v7(),
            kind: ContextKind::Observation,
            content_digest: hash_bytes(content.as_bytes()),
            content,
            source,
            scope,
            observed_at,
            authority,
            secret_taint,
            attributes,
        }
    }

    /// Validates public shape, digest, provenance, and scope invariants.
    pub fn validate(&self) -> Result<(), ContextError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ContextError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.content.trim().is_empty() {
            return Err(ContextError::EmptyContent);
        }
        if self.content_digest != hash_bytes(self.content.as_bytes()) {
            return Err(ContextError::ContentDigest);
        }
        if !valid_digest(&self.scope.workspace_id) {
            return Err(ContextError::WorkspaceIdentity);
        }
        if self.authority.producer.trim().is_empty() {
            return Err(ContextError::EmptyProducer);
        }
        if !self.attributes.is_object() {
            return Err(ContextError::Attributes);
        }
        match (&self.source.event_id, self.source.event_seq) {
            (Some(event_id), Some(_)) if valid_digest(event_id) => {}
            (None, None) => {}
            _ => return Err(ContextError::EventAnchor),
        }
        if self.source.state_binding.is_some() != self.source.workspace_generation.is_some() {
            return Err(ContextError::WorkspaceAnchor);
        }
        if self
            .source
            .state_binding
            .as_deref()
            .is_some_and(|binding| !valid_digest(binding))
        {
            return Err(ContextError::WorkspaceAnchor);
        }
        if self.authority.runtime_owned
            && (self.source.session_id.is_none()
                || self.source.event_id.is_none()
                || self.source.evidence_id.is_none())
        {
            return Err(ContextError::RuntimeProvenance);
        }
        if self
            .scope
            .path
            .as_deref()
            .is_some_and(|path| !valid_relative_scope_path(path))
        {
            return Err(ContextError::ScopePath);
        }
        Ok(())
    }
}

/// Durable retrieval lifecycle of one context item.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MemoryStatus {
    /// Bound to the latest workspace state observed by the runtime.
    Current,
    /// Not bound to a workspace state and therefore never current evidence.
    Unbound,
    /// Invalidated by a later observed workspace state.
    Stale,
    /// Replaced by a newer context item.
    Superseded,
    /// Explicitly invalidated by the runtime.
    Invalidated,
}

/// Runtime-owned reason a memory item ceased to be current.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ContextInvalidationReason {
    /// A different canonical workspace state was observed.
    WorkspaceChanged,
    /// A newer item explicitly replaced this item.
    Superseded,
    /// Runtime policy rejected continued use.
    Policy,
    /// Source provenance failed validation.
    Provenance,
}

/// Durable invalidation receipt.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ContextInvalidation {
    /// Runtime-owned invalidation reason.
    pub reason: ContextInvalidationReason,
    /// Time the invalidation was persisted.
    pub at: DateTime<Utc>,
    /// Workspace epoch at invalidation time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observed_workspace_generation: Option<u64>,
    /// Workspace digest that caused invalidation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observed_state_binding: Option<String>,
    /// Newer context item when supersession caused invalidation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_context_id: Option<Uuid>,
}

/// Persisted context plus its runtime-owned lifecycle state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MemoryItem {
    /// Public schema identifier.
    pub schema_version: String,
    /// Immutable context payload.
    pub context: ContextItem,
    /// Current retrieval lifecycle.
    pub status: MemoryStatus,
    /// Newer context item, when superseded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub superseded_by: Option<Uuid>,
    /// Runtime-owned invalidation receipt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invalidation: Option<ContextInvalidation>,
    /// First durable persistence time.
    pub stored_at: DateTime<Utc>,
    /// Last lifecycle transition time.
    pub updated_at: DateTime<Utc>,
}

impl MemoryItem {
    /// Validates the context and lifecycle consistency.
    pub fn validate(&self) -> Result<(), ContextError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ContextError::UnsupportedSchema(self.schema_version.clone()));
        }
        self.context.validate()?;
        if self.updated_at < self.stored_at {
            return Err(ContextError::TimestampOrder);
        }
        match self.status {
            MemoryStatus::Current => {
                if self.context.source.state_binding.is_none()
                    || self.invalidation.is_some()
                    || self.superseded_by.is_some()
                {
                    return Err(ContextError::Lifecycle);
                }
            }
            MemoryStatus::Unbound => {
                if self.context.source.state_binding.is_some()
                    || self.invalidation.is_some()
                    || self.superseded_by.is_some()
                {
                    return Err(ContextError::Lifecycle);
                }
            }
            MemoryStatus::Stale | MemoryStatus::Invalidated => {
                if self.invalidation.is_none() || self.superseded_by.is_some() {
                    return Err(ContextError::Lifecycle);
                }
            }
            MemoryStatus::Superseded => {
                if self.invalidation.is_none() || self.superseded_by.is_none() {
                    return Err(ContextError::Lifecycle);
                }
            }
        }
        Ok(())
    }
}

fn valid_digest(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn valid_relative_scope_path(path: &str) -> bool {
    !path.is_empty()
        && !path.starts_with('/')
        && !path.starts_with('\\')
        && !path.contains(':')
        && !path
            .split(['/', '\\'])
            .any(|component| component.is_empty() || component == "." || component == "..")
}

/// Context contract validation failure.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum ContextError {
    /// Unsupported public schema identifier.
    #[error("unsupported context schema: {0}")]
    UnsupportedSchema(String),
    /// Statement body is empty.
    #[error("context content must not be empty")]
    EmptyContent,
    /// Statement digest does not match its body.
    #[error("context content digest is invalid")]
    ContentDigest,
    /// Workspace identity is not a canonical digest.
    #[error("context workspace identity is invalid")]
    WorkspaceIdentity,
    /// Producer identity is empty.
    #[error("context producer must not be empty")]
    EmptyProducer,
    /// Attributes are not a JSON object.
    #[error("context attributes must be an object")]
    Attributes,
    /// Event sequence and event digest are incomplete or malformed.
    #[error("context event anchor is invalid")]
    EventAnchor,
    /// Workspace generation and state binding are incomplete or malformed.
    #[error("context workspace anchor is invalid")]
    WorkspaceAnchor,
    /// Runtime-owned statements lack causal session/event/evidence provenance.
    #[error("runtime-owned context lacks causal provenance")]
    RuntimeProvenance,
    /// Path scope is absolute, ambiguous, or traverses a parent.
    #[error("context path scope must be a normalized workspace-relative path")]
    ScopePath,
    /// Updated timestamp precedes initial persistence.
    #[error("memory lifecycle timestamp order is invalid")]
    TimestampOrder,
    /// Status, invalidation, binding, and supersession disagree.
    #[error("memory lifecycle state is inconsistent")]
    Lifecycle,
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn item() -> ContextItem {
        ContextItem::runtime_observation(
            "cargo test passed",
            ContextSource {
                session_id: Some(Uuid::now_v7()),
                event_id: Some("a".repeat(64)),
                event_seq: Some(4),
                evidence_id: Some(Uuid::now_v7()),
                workspace_generation: Some(2),
                state_binding: Some("b".repeat(64)),
                external_uri: None,
            },
            ContextScope {
                workspace_id: "c".repeat(64),
                repository: None,
                branch: None,
                path: Some("src/lib.rs".to_owned()),
                symbol: None,
                task_contract_id: Some(Uuid::now_v7()),
            },
            Utc::now(),
            ContextAuthority {
                producer: "verify.exec".to_owned(),
                assurance_level: AssuranceLevel::Observed,
                runtime_owned: true,
            },
            SecretTaint::None,
            json!({"success": true}),
        )
    }

    #[test]
    fn runtime_context_and_current_memory_validate() {
        let context = item();
        context.validate().unwrap();
        let now = Utc::now();
        let memory = MemoryItem {
            schema_version: SCHEMA_VERSION.to_owned(),
            context,
            status: MemoryStatus::Current,
            superseded_by: None,
            invalidation: None,
            stored_at: now,
            updated_at: now,
        };
        memory.validate().unwrap();
    }

    #[test]
    fn tampered_content_and_parent_scope_are_rejected() {
        let mut context = item();
        context.content.push('!');
        assert_eq!(context.validate(), Err(ContextError::ContentDigest));
        let mut context = item();
        context.scope.path = Some("../secret".to_owned());
        assert_eq!(context.validate(), Err(ContextError::ScopePath));
    }

    #[test]
    fn current_memory_requires_a_workspace_binding() {
        let mut context = item();
        context.source.workspace_generation = None;
        context.source.state_binding = None;
        let now = Utc::now();
        let memory = MemoryItem {
            schema_version: SCHEMA_VERSION.to_owned(),
            context,
            status: MemoryStatus::Current,
            superseded_by: None,
            invalidation: None,
            stored_at: now,
            updated_at: now,
        };
        assert_eq!(memory.validate(), Err(ContextError::Lifecycle));
    }
    #[test]
    fn context_retrieval_is_not_default_task_evidence() {
        let requirement = crate::EvidenceRequirement::task();
        assert!(
            !requirement
                .allowed_kinds
                .contains(&crate::EvidenceKind::Context)
        );
    }
}