vsh-runtime 0.5.0

Native Rust SDK for the VSH validation-first execution engine
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use std::error::Error;
use std::fmt;

use vsh_commit::RecoveryReport;
use vsh_monty::ExecutionStats;
use vsh_policy::{PolicyProfile, PolicyThresholds, RiskFlag, RiskMetrics};
use vsh_store::TransactionRecord;
use vsh_types::{
    BlobId, DiffDigest, DiffEntry, HookId, IntentDigest, PolicyDigest, PrincipalId, ProgramDigest,
    ReadSetDigest, RequestEventId, RuntimeConfigDigest, SnapshotId, TransactionId,
    TransactionState, VPath, WriteSetDigest,
};
use vsh_vfs::EffectEvent;

use crate::runtime::{Receipt, RunMode, RunRequest, Runtime, RuntimeConfig, VshError};

/// Which policy-authorized commit candidates a hook may inspect.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum HookScope {
    /// Invoke the hook only for transactions that deterministic policy escalated.
    #[default]
    ReviewRequired,
    /// Invoke the hook for every successful simulation, including read-only requests.
    AllRequests,
}

impl HookScope {
    pub(crate) const fn tag(self) -> u8 {
        match self {
            Self::ReviewRequired => 1,
            Self::AllRequests => 2,
        }
    }

    pub(crate) const fn applies_to(self, state: TransactionState) -> bool {
        match self {
            Self::ReviewRequired => matches!(state, TransactionState::PendingApproval),
            Self::AllRequests => matches!(
                state,
                TransactionState::AutoApproved | TransactionState::PendingApproval
            ),
        }
    }
}

/// Trusted, transaction-bound configuration for one commit hook.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HookConfig {
    id: HookId,
    scope: HookScope,
    approval_ttl_ms: u64,
    max_reason_bytes: usize,
    max_content_bytes: usize,
}

impl HookConfig {
    /// Build a hook configuration from a stable host-controlled label.
    #[must_use]
    pub fn new(label: &str) -> Self {
        Self {
            id: HookId::digest_label(label),
            scope: HookScope::ReviewRequired,
            approval_ttl_ms: 5 * 60 * 1_000,
            max_reason_bytes: 16 * 1_024,
            max_content_bytes: 0,
        }
    }

    /// Select whether automatic approvals are also reviewed.
    #[must_use]
    pub const fn with_scope(mut self, scope: HookScope) -> Self {
        self.scope = scope;
        self
    }

    /// Set the bounded lifetime of approvals generated by this hook.
    #[must_use]
    pub const fn with_approval_ttl_ms(mut self, approval_ttl_ms: u64) -> Self {
        self.approval_ttl_ms = approval_ttl_ms;
        self
    }

    /// Bound the UTF-8 reason retained in a decision record.
    #[must_use]
    pub const fn with_max_reason_bytes(mut self, max_reason_bytes: usize) -> Self {
        self.max_reason_bytes = max_reason_bytes;
        self
    }

    /// Opt into bounded, immutable before/after and observed-read content evidence.
    ///
    /// Zero (the default) disables additional content capture and delivery.
    #[must_use]
    pub const fn with_max_content_bytes(mut self, maximum: usize) -> Self {
        self.max_content_bytes = maximum;
        self
    }

    /// Return the total content-byte limit for one hook event.
    #[must_use]
    pub const fn max_content_bytes(self) -> usize {
        self.max_content_bytes
    }

    /// Return the opaque hook identity.
    #[must_use]
    pub const fn id(self) -> HookId {
        self.id
    }

    /// Return the configured trigger scope.
    #[must_use]
    pub const fn scope(self) -> HookScope {
        self.scope
    }

    /// Return the hook-generated approval lifetime.
    #[must_use]
    pub const fn approval_ttl_ms(self) -> u64 {
        self.approval_ttl_ms
    }

    /// Return the maximum decision-reason size.
    #[must_use]
    pub const fn max_reason_bytes(self) -> usize {
        self.max_reason_bytes
    }

    pub(crate) fn principal(self) -> PrincipalId {
        PrincipalId::from_bytes(*self.id.as_bytes())
    }
}

impl Default for HookConfig {
    fn default() -> Self {
        Self::new("vsh.commit-hook")
    }
}

/// Deterministic policy outcome that caused a hook event.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HookBaseline {
    /// Policy authorized the transaction without independent review.
    AutoApproved,
    /// Policy required an independent review.
    ReviewRequired,
}

/// Hash-verified bytes for one transaction-owned path/content identity.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReviewContent {
    /// Workspace-relative path authorized for content reading.
    pub path: VPath,
    /// Immutable identity referenced by the canonical diff or an observed read.
    pub blob: BlobId,
    /// Complete bytes; partial blobs are never represented as complete evidence.
    pub bytes: Vec<u8>,
}

/// Immutable, bounded evidence supplied to a commit hook.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RequestEvent {
    /// Event schema understood by the receiver.
    pub schema_version: u16,
    /// Stable delivery identity for idempotent handlers.
    pub event_id: RequestEventId,
    /// Stable configured hook identity.
    pub hook_id: HookId,
    /// Exact transaction that may be committed.
    pub transaction: TransactionId,
    /// State observed while preparing this event.
    pub state: TransactionState,
    /// Policy branch that caused the event.
    pub baseline: HookBaseline,
    /// Immutable base snapshot identity.
    pub base_snapshot: SnapshotId,
    /// Canonical final diff identity.
    pub diff: DiffDigest,
    /// Exact read dependency identity.
    pub read_set: ReadSetDigest,
    /// Exact write precondition identity.
    pub write_set: WriteSetDigest,
    /// Exact untrusted program identity.
    pub program: ProgramDigest,
    /// Exact deterministic policy identity.
    pub policy: PolicyDigest,
    /// Exact security-relevant runtime configuration identity.
    pub runtime_config: RuntimeConfigDigest,
    /// Optional intent identity already bound into the transaction.
    pub intent_digest: Option<IntentDigest>,
    /// Bounded raw intent when available in the artifact.
    pub intent: Option<String>,
    /// Policy profile used for the baseline decision.
    pub policy_profile: PolicyProfile,
    /// Exact policy thresholds used for the baseline decision.
    pub policy_thresholds: PolicyThresholds,
    /// Exact risk metrics evaluated by deterministic policy.
    pub risk_metrics: RiskMetrics,
    /// Stable, sorted risk flags.
    pub risk_flags: Vec<RiskFlag>,
    /// Complete path-ordered canonical diff used by commit.
    pub canonical_diff: Vec<DiffEntry>,
    /// Ordered operation-level effects, containing identities rather than file bytes.
    pub effects: Vec<EffectEvent>,
    /// Independent execution counters.
    pub execution: ExecutionStats,
    /// Whether raw review evidence survived the durable boundary.
    pub evidence_complete: bool,
    /// Whether any evidence was deliberately truncated.
    pub evidence_truncated: bool,
    /// Bounded, read-authorized content from the exact artifact, never live files.
    pub contents: Vec<ReviewContent>,
    /// Whether every canonical content side and observed content read was included.
    ///
    /// Separate from structural evidence completeness. False for missing/stamped,
    /// protected, disabled, or over-budget content.
    pub content_complete: bool,
}

/// Decision returned by a hook handler.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HookDecision {
    /// Preserve deterministic policy: auto approvals commit; reviews remain pending.
    FollowPolicy,
    /// Approve and commit this exact transaction using the configured hook principal.
    Approve {
        /// Bounded explanation retained with the resolution.
        reason: String,
    },
    /// Keep the transaction pending and return actionable review feedback.
    Review {
        /// Bounded feedback for the caller performing the next review.
        feedback: String,
    },
    /// Terminally reject this exact transaction.
    Reject {
        /// Bounded explanation retained with the resolution.
        reason: String,
    },
}

impl HookDecision {
    /// Construct an approval with a bounded human-readable reason.
    #[must_use]
    pub fn approve(reason: impl Into<String>) -> Self {
        Self::Approve {
            reason: reason.into(),
        }
    }

    /// Construct a review requirement with a bounded human-readable reason.
    #[must_use]
    pub fn review(feedback: impl Into<String>) -> Self {
        Self::Review {
            feedback: feedback.into(),
        }
    }

    /// Construct a terminal rejection with a bounded human-readable reason.
    #[must_use]
    pub fn reject(reason: impl Into<String>) -> Self {
        Self::Reject {
            reason: reason.into(),
        }
    }
}

/// Stable normalized outcome retained next to a hook resolution.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HookVerdict {
    /// Deterministic policy was preserved.
    FollowPolicy,
    /// The exact transaction was approved by the handler.
    Approve,
    /// The transaction remains pending with handler feedback.
    Review,
    /// The exact transaction was terminally rejected by the handler.
    Reject,
}

/// Provenance for the hook decision applied to one exact event.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HookDecisionRecord {
    /// Exact immutable event resolved by the handler.
    pub event_id: RequestEventId,
    /// Configured handler identity bound to the event.
    pub hook_id: HookId,
    /// Normalized handler outcome.
    pub verdict: HookVerdict,
    /// Bounded explanation or review feedback supplied by the handler.
    pub reason: String,
    /// Approval principal when and only when the verdict is `Approve`.
    pub principal: Option<PrincipalId>,
}

/// Prepared commit evidence, revalidated by the runtime before resolution.
#[derive(Clone, Debug)]
pub enum CommitPreparation {
    #[doc(hidden)]
    Ready {
        transaction: TransactionId,
        state: TransactionState,
    },
    /// An external handler must decide the supplied immutable event.
    Review(Box<RequestEvent>),
}

impl CommitPreparation {
    /// Return the exact transaction represented by this preparation.
    #[must_use]
    pub const fn transaction(&self) -> TransactionId {
        match self {
            Self::Ready { transaction, .. } => *transaction,
            Self::Review(event) => event.transaction,
        }
    }

    /// Return the request event when a handler must run.
    #[must_use]
    pub fn event(&self) -> Option<&RequestEvent> {
        match self {
            Self::Ready { .. } => None,
            Self::Review(event) => Some(event.as_ref()),
        }
    }

    pub(crate) const fn prepared_state(&self) -> TransactionState {
        match self {
            Self::Ready { state, .. } => *state,
            Self::Review(event) => event.state,
        }
    }
}

/// Result of resolving a prepared commit request.
#[derive(Clone, Debug)]
pub struct CommitResolution {
    /// Current transaction receipt after applying the hook decision.
    pub receipt: Receipt,
    /// Hook provenance, or `None` when deterministic policy was followed directly.
    pub hook: Option<HookDecisionRecord>,
}

/// Contained handler failure. Runtime resolution applies fail-closed semantics first.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HookHandlerError {
    detail: String,
}

impl HookHandlerError {
    /// Construct a contained handler failure.
    #[must_use]
    pub fn new(detail: impl Into<String>) -> Self {
        Self {
            detail: detail.into(),
        }
    }
}

impl fmt::Display for HookHandlerError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.detail)
    }
}

impl Error for HookHandlerError {}

/// Synchronous Rust hook. Async hosts should drive `prepare_commit` and
/// `resolve_commit` around their own executor instead of blocking the runtime.
pub trait CommitHook: Send + Sync {
    /// Return a decision from immutable evidence without mutating runtime state.
    ///
    /// # Errors
    ///
    /// Returns [`HookHandlerError`] when the host-owned handler cannot produce a
    /// trustworthy decision. The runtime then keeps the transaction pending.
    fn handle(&self, event: &RequestEvent) -> Result<HookDecision, HookHandlerError>;
}

impl<F> CommitHook for F
where
    F: Fn(&RequestEvent) -> Result<HookDecision, HookHandlerError> + Send + Sync,
{
    fn handle(&self, event: &RequestEvent) -> Result<HookDecision, HookHandlerError> {
        self(event)
    }
}

/// Native runtime plus a host-owned commit handler.
pub struct HookedRuntime<H> {
    runtime: Runtime,
    handler: H,
}

impl<H: CommitHook> HookedRuntime<H> {
    /// Open a runtime whose direct commit path cannot bypass this hook.
    ///
    /// # Errors
    ///
    /// Returns a typed runtime, store, snapshot, or recovery error when the
    /// configured workspace cannot be opened safely.
    pub fn open(config: RuntimeConfig, hook: HookConfig, handler: H) -> Result<Self, VshError> {
        Ok(Self {
            runtime: Runtime::open(config.with_commit_hook(hook))?,
            handler,
        })
    }

    /// Execute one transaction, invoking the handler only for auto mode candidates.
    ///
    /// # Errors
    ///
    /// Returns any simulation, handler, validation, or commit error produced while
    /// processing the exact transaction.
    pub fn run(&self, mut request: RunRequest<'_>, now_unix_ms: u64) -> Result<Receipt, VshError> {
        let mode = request.mode;
        request.mode = RunMode::Preview;
        let receipt = self.runtime.preview(request)?;
        if mode == RunMode::Auto
            && matches!(
                receipt.state,
                TransactionState::AutoApproved | TransactionState::PendingApproval
            )
        {
            return self
                .commit(receipt.transaction, now_unix_ms)
                .map(|resolution| resolution.receipt);
        }
        Ok(receipt)
    }

    /// Execute without invoking the hook or changing host files.
    ///
    /// # Errors
    ///
    /// Returns the same typed simulation failures as [`Runtime::preview`].
    pub fn preview(&self, request: RunRequest<'_>) -> Result<Receipt, VshError> {
        self.runtime.preview(request)
    }

    /// Prepare, invoke the handler without runtime locks, and resolve exactly once.
    ///
    /// # Errors
    ///
    /// Returns a typed preparation, handler, state-validation, approval, or commit
    /// error. Handler failures leave automatic approvals pending.
    pub fn commit(
        &self,
        transaction: TransactionId,
        now_unix_ms: u64,
    ) -> Result<CommitResolution, VshError> {
        let preparation = self.runtime.prepare_commit(transaction)?;
        let decision = match preparation.event() {
            Some(event) => match self.handler.handle(event) {
                Ok(decision) => decision,
                Err(source) => {
                    self.runtime.fail_hook(&preparation)?;
                    return Err(VshError::HookHandler(source));
                }
            },
            None => HookDecision::FollowPolicy,
        };
        self.runtime
            .resolve_commit(&preparation, &decision, now_unix_ms)
    }

    /// Bind an independent approval grant to a pending transaction.
    ///
    /// # Errors
    ///
    /// Returns a typed binding, lifetime, store, or state-transition error.
    pub fn approve(
        &self,
        transaction: TransactionId,
        principal: PrincipalId,
        issued_at_unix_ms: u64,
        expires_at_unix_ms: u64,
    ) -> Result<TransactionRecord, VshError> {
        self.runtime.approve(
            transaction,
            principal,
            issued_at_unix_ms,
            expires_at_unix_ms,
        )
    }

    /// Discard an uncommitted transaction artifact.
    ///
    /// # Errors
    ///
    /// Returns a typed store or artifact-retention error.
    pub fn discard_preview(&self, transaction: TransactionId) -> Result<bool, VshError> {
        self.runtime.discard_preview(transaction)
    }

    /// Recover interrupted commits found in durable state.
    ///
    /// # Errors
    ///
    /// Returns a typed recovery, host-filesystem, or store error.
    pub fn recover(&self) -> Result<RecoveryReport, VshError> {
        self.runtime.recover()
    }

    /// Load the durable record for one transaction.
    ///
    /// # Errors
    ///
    /// Returns a typed store error when the transaction is missing or corrupt.
    pub fn transaction(&self, transaction: TransactionId) -> Result<TransactionRecord, VshError> {
        self.runtime.transaction(transaction)
    }
}