runifold-workflow 0.5.3

Durable workflow and Agent orchestration runtime for Runifold
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! Capability-scoped control plane for Task tombstone governance.

use std::{
    collections::{BTreeMap, BTreeSet},
    future::Future,
    pin::Pin,
    sync::Arc,
};

use runifold_core::CheckpointId;
use thiserror::Error;

use crate::{
    LeaseDuration, WorkerId, WorkflowStoreError, WorkflowTaskCleanupLease, WorkflowTaskLegalHold,
    WorkflowTaskLegalHoldReason, WorkflowTaskTombstone, WorkflowTaskTombstoneApprovalInboxItem,
    WorkflowTaskTombstoneApprovalInboxLimit, WorkflowTaskTombstoneApprovalLease,
    WorkflowTaskTombstoneApprovalWindow, WorkflowTaskTombstoneCursor,
    WorkflowTaskTombstoneExportReceipt, WorkflowTaskTombstoneGovernanceStore,
    WorkflowTaskTombstoneLimit, WorkflowTaskTombstonePurgeEvidence, WorkflowTaskTombstonePurgeId,
    WorkflowTaskTombstonePurgeIntent, WorkflowTaskTombstonePurgeLimit,
    WorkflowTaskTombstoneRejectionReason, WorkflowTaskTombstoneRetention, WorkflowTenantId,
};

/// One tenant-scoped tombstone governance authority.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum WorkflowTaskGovernancePermission {
    /// Place a legal hold.
    PlaceHold,
    /// Release a legal hold.
    ReleaseHold,
    /// Export tombstone details and confirm an archive receipt.
    Export,
    /// Prepare a bounded purge intent.
    PreparePurge,
    /// Independently approve a purge intent.
    ApprovePurge,
    /// Read the tenant's bounded approval inbox.
    ReadApprovalInbox,
    /// Claim one approval request for independent review.
    ClaimPurgeApproval,
    /// Reject a claimed purge request with a durable reason.
    RejectPurge,
    /// Execute an approved purge under a fenced lease.
    ExecutePurge,
    /// Read immutable purge evidence.
    ReadEvidence,
}

/// Low-cardinality governance outcome for telemetry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WorkflowTaskGovernanceOutcome {
    /// The operation completed successfully.
    Succeeded,
    /// Policy rejected the principal.
    Denied,
    /// Authorization infrastructure failed closed.
    AuthorizationError,
    /// Durable store execution failed.
    StoreError,
    /// External archive execution failed.
    ArchiveError,
}

/// Optional observer that must not retain tenant or principal identities.
pub trait WorkflowTaskGovernanceObserver: Send + Sync {
    /// Observes one terminal control-plane outcome.
    fn observe(
        &self,
        permission: WorkflowTaskGovernancePermission,
        outcome: WorkflowTaskGovernanceOutcome,
    );
}

#[derive(Debug, Default)]
struct NoopWorkflowTaskGovernanceObserver;

impl WorkflowTaskGovernanceObserver for NoopWorkflowTaskGovernanceObserver {
    fn observe(
        &self,
        _permission: WorkflowTaskGovernancePermission,
        _outcome: WorkflowTaskGovernanceOutcome,
    ) {
    }
}

/// Safe authorizer failure. Control-plane operations fail closed.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("Task tombstone governance authorization failed: {message}")]
pub struct WorkflowTaskGovernanceAuthorizationError {
    message: String,
}

impl WorkflowTaskGovernanceAuthorizationError {
    /// Creates a bounded safe authorization failure.
    pub fn new(message: impl Into<String>) -> Self {
        let mut message = message.into();
        message.truncate(512);
        Self { message }
    }
}

/// Borrowing future returned by a governance authorizer.
pub type WorkflowTaskGovernanceAuthorizationFuture<'a> = Pin<
    Box<dyn Future<Output = Result<bool, WorkflowTaskGovernanceAuthorizationError>> + Send + 'a>,
>;

/// Pluggable policy boundary for principal, tenant, and permission checks.
pub trait WorkflowTaskGovernanceAuthorizer: Send + Sync {
    /// Returns `true` only for an explicit grant.
    fn authorize(
        &self,
        principal: &WorkerId,
        tenant_id: &WorkflowTenantId,
        permission: WorkflowTaskGovernancePermission,
    ) -> WorkflowTaskGovernanceAuthorizationFuture<'_>;
}

/// Immutable in-process authorizer for simple deployments and tests.
#[derive(Clone, Debug, Default)]
pub struct StaticWorkflowTaskGovernanceAuthorizer {
    grants: BTreeMap<(WorkerId, WorkflowTenantId), BTreeSet<WorkflowTaskGovernancePermission>>,
}

impl StaticWorkflowTaskGovernanceAuthorizer {
    /// Creates an empty deny-by-default policy.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds one explicit principal and tenant grant.
    #[must_use]
    pub fn with_grant(
        mut self,
        principal: WorkerId,
        tenant_id: WorkflowTenantId,
        permission: WorkflowTaskGovernancePermission,
    ) -> Self {
        self.grants
            .entry((principal, tenant_id))
            .or_default()
            .insert(permission);
        self
    }
}

impl WorkflowTaskGovernanceAuthorizer for StaticWorkflowTaskGovernanceAuthorizer {
    fn authorize(
        &self,
        principal: &WorkerId,
        tenant_id: &WorkflowTenantId,
        permission: WorkflowTaskGovernancePermission,
    ) -> WorkflowTaskGovernanceAuthorizationFuture<'_> {
        let allowed = self
            .grants
            .get(&(principal.clone(), tenant_id.clone()))
            .is_some_and(|grants| grants.contains(&permission));
        Box::pin(async move { Ok(allowed) })
    }
}

/// Stable failure class for archive retry and observability policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WorkflowTaskTombstoneArchiveErrorKind {
    /// Archive configuration or local signing policy is invalid.
    Configuration,
    /// Remote credentials or policy rejected the request.
    Authorization,
    /// The bounded archive operation elapsed.
    Timeout,
    /// The remote archive is temporarily unavailable.
    Unavailable,
    /// A committed object did not match the stable batch payload.
    Integrity,
    /// Commit state could not be determined after reconciliation.
    Ambiguous,
    /// A safe fallback for adapters without a more specific classification.
    Other,
}

/// Safe archive adapter failure.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("Task tombstone archive failed ({kind:?}): {message}")]
pub struct WorkflowTaskTombstoneArchiveError {
    kind: WorkflowTaskTombstoneArchiveErrorKind,
    message: String,
}

impl WorkflowTaskTombstoneArchiveError {
    /// Creates a bounded safe archive failure with the fallback classification.
    pub fn new(message: impl Into<String>) -> Self {
        Self::with_kind(WorkflowTaskTombstoneArchiveErrorKind::Other, message)
    }

    /// Creates a bounded safe archive failure with a stable classification.
    pub fn with_kind(
        kind: WorkflowTaskTombstoneArchiveErrorKind,
        message: impl Into<String>,
    ) -> Self {
        let mut message = message.into();
        message.truncate(512);
        Self { kind, message }
    }

    /// Returns the stable failure class without exposing provider detail.
    pub const fn kind(&self) -> WorkflowTaskTombstoneArchiveErrorKind {
        self.kind
    }
}

/// Stable idempotency identity for one ordered archive batch.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct WorkflowTaskTombstoneArchiveBatchId(String);

impl WorkflowTaskTombstoneArchiveBatchId {
    /// Validates an externally restored stable batch identity.
    ///
    /// # Errors
    ///
    /// Rejects blank, oversized, or control-character-bearing values.
    pub fn parse(value: impl Into<String>) -> Result<Self, WorkflowStoreError> {
        let value = value.into();
        if value.trim().is_empty() || value.len() > 512 || value.chars().any(char::is_control) {
            return Err(WorkflowStoreError::new(
                crate::WorkflowStoreErrorKind::InvalidInput,
                "Task tombstone archive batch ID must contain 1..=512 printable bytes",
            ));
        }
        Ok(Self(value))
    }

    fn from_batch(
        tenant_id: &WorkflowTenantId,
        first: WorkflowTaskTombstoneCursor,
        last: WorkflowTaskTombstoneCursor,
    ) -> Self {
        Self(format!(
            "{}:{}:{}",
            tenant_id.as_str(),
            first.get(),
            last.get()
        ))
    }

    /// Returns the stable archive idempotency key.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Exact ordered tombstone batch delivered to an external archive.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkflowTaskTombstoneArchiveBatch {
    /// Stable idempotency key reused after partial failure.
    pub batch_id: WorkflowTaskTombstoneArchiveBatchId,
    /// Owning tenant.
    pub tenant_id: WorkflowTenantId,
    /// Detailed tombstones in ascending cursor order.
    pub tombstones: Vec<WorkflowTaskTombstone>,
}

/// Borrowing future returned by an external tombstone archive.
pub type WorkflowTaskTombstoneArchiveFuture<'a> = Pin<
    Box<
        dyn Future<
                Output = Result<
                    WorkflowTaskTombstoneExportReceipt,
                    WorkflowTaskTombstoneArchiveError,
                >,
            > + Send
            + 'a,
    >,
>;

/// Idempotent external archive boundary.
pub trait WorkflowTaskTombstoneArchive: Send + Sync {
    /// Stores the exact batch or replays its original receipt.
    fn archive(
        &self,
        batch: WorkflowTaskTombstoneArchiveBatch,
    ) -> WorkflowTaskTombstoneArchiveFuture<'_>;
}

/// Result of one bounded archive-and-confirm cycle.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkflowTaskTombstoneArchiveReport {
    /// Stable batch key, absent when the source page was empty.
    pub batch_id: Option<WorkflowTaskTombstoneArchiveBatchId>,
    /// Number of detailed tombstones archived.
    pub tombstones_exported: u32,
    /// Confirmed cursor, absent when the source page was empty.
    pub through: Option<WorkflowTaskTombstoneCursor>,
    /// Archive receipt persisted with the watermark.
    pub receipt: Option<WorkflowTaskTombstoneExportReceipt>,
}

/// Fail-closed tombstone governance failure.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum WorkflowTaskGovernanceError {
    /// The principal lacks the exact tenant-scoped permission.
    #[error("principal is not authorized for {permission:?}")]
    Denied {
        /// Rejected operation.
        permission: WorkflowTaskGovernancePermission,
    },
    /// The policy backend failed and the operation was not attempted.
    #[error(transparent)]
    Authorization(#[from] WorkflowTaskGovernanceAuthorizationError),
    /// Durable governance state failed.
    #[error(transparent)]
    Store(#[from] WorkflowStoreError),
    /// External archive failed before durable confirmation.
    #[error(transparent)]
    Archive(#[from] WorkflowTaskTombstoneArchiveError),
    /// A fenced lease was supplied by a different principal.
    #[error("cleanup lease owner does not match the authenticated principal")]
    LeasePrincipalMismatch,
    /// A reviewer lease was supplied by a different principal.
    #[error("approval lease reviewer does not match the authenticated principal")]
    ApprovalLeasePrincipalMismatch,
}

/// Authorized facade over the destructive tombstone governance store.
pub struct WorkflowTaskGovernanceControlPlane<S, A> {
    store: Arc<S>,
    authorizer: Arc<A>,
    observer: Arc<dyn WorkflowTaskGovernanceObserver>,
}

impl<S, A> WorkflowTaskGovernanceControlPlane<S, A>
where
    S: WorkflowTaskTombstoneGovernanceStore,
    A: WorkflowTaskGovernanceAuthorizer,
{
    /// Creates a fail-closed control plane.
    pub fn new(store: Arc<S>, authorizer: Arc<A>) -> Self {
        Self {
            store,
            authorizer,
            observer: Arc::new(NoopWorkflowTaskGovernanceObserver),
        }
    }

    /// Attaches a low-cardinality outcome observer.
    #[must_use]
    pub fn with_observer(mut self, observer: Arc<dyn WorkflowTaskGovernanceObserver>) -> Self {
        self.observer = observer;
        self
    }

    /// Places a hold using the authenticated principal as the audit actor.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority or store failure.
    pub async fn place_hold(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        checkpoint_id: CheckpointId,
        reason: WorkflowTaskLegalHoldReason,
    ) -> Result<WorkflowTaskLegalHold, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::PlaceHold;
        self.authorize(principal, &tenant_id, permission).await?;
        let result = self
            .store
            .place_task_tombstone_hold(tenant_id, checkpoint_id, principal.clone(), reason)
            .await;
        self.store_result(permission, result)
    }

    /// Releases a hold using the authenticated principal as the audit actor.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority or store failure.
    pub async fn release_hold(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        checkpoint_id: CheckpointId,
    ) -> Result<WorkflowTaskLegalHold, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ReleaseHold;
        self.authorize(principal, &tenant_id, permission).await?;
        let result = self
            .store
            .release_task_tombstone_hold(tenant_id, checkpoint_id, principal.clone())
            .await;
        self.store_result(permission, result)
    }

    /// Archives one page and confirms its watermark only after receipt.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority, source-store failure, archive
    /// failure, or durable confirmation failure.
    pub async fn export_next_page<R>(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        after: Option<WorkflowTaskTombstoneCursor>,
        limit: WorkflowTaskTombstoneLimit,
        archive: &R,
    ) -> Result<WorkflowTaskTombstoneArchiveReport, WorkflowTaskGovernanceError>
    where
        R: WorkflowTaskTombstoneArchive,
    {
        let permission = WorkflowTaskGovernancePermission::Export;
        self.authorize(principal, &tenant_id, permission).await?;
        let tombstones = match self
            .store
            .list_task_tombstones(tenant_id.clone(), after, limit)
            .await
        {
            Ok(tombstones) => tombstones,
            Err(error) => return Err(self.store_error(permission, error)),
        };
        let (Some(first), Some(last)) = (tombstones.first(), tombstones.last()) else {
            self.observer
                .observe(permission, WorkflowTaskGovernanceOutcome::Succeeded);
            return Ok(WorkflowTaskTombstoneArchiveReport {
                batch_id: None,
                tombstones_exported: 0,
                through: None,
                receipt: None,
            });
        };
        let batch_id =
            WorkflowTaskTombstoneArchiveBatchId::from_batch(&tenant_id, first.cursor, last.cursor);
        let through = last.cursor;
        let count = u32::try_from(tombstones.len()).unwrap_or(u32::MAX);
        let receipt = match archive
            .archive(WorkflowTaskTombstoneArchiveBatch {
                batch_id: batch_id.clone(),
                tenant_id: tenant_id.clone(),
                tombstones,
            })
            .await
        {
            Ok(receipt) => receipt,
            Err(error) => {
                self.observer
                    .observe(permission, WorkflowTaskGovernanceOutcome::ArchiveError);
                return Err(error.into());
            }
        };
        if let Err(error) = self
            .store
            .confirm_task_tombstone_export(tenant_id, through, receipt.clone(), principal.clone())
            .await
        {
            return Err(self.store_error(permission, error));
        }
        self.observer
            .observe(permission, WorkflowTaskGovernanceOutcome::Succeeded);
        Ok(WorkflowTaskTombstoneArchiveReport {
            batch_id: Some(batch_id),
            tombstones_exported: count,
            through: Some(through),
            receipt: Some(receipt),
        })
    }

    /// Prepares a purge only when the lease belongs to the principal.
    ///
    /// # Errors
    ///
    /// Rejects denied authority, a mismatched lease principal, or store
    /// failure.
    pub async fn prepare_purge(
        &self,
        principal: &WorkerId,
        lease: WorkflowTaskCleanupLease,
        retention: WorkflowTaskTombstoneRetention,
        limit: WorkflowTaskTombstonePurgeLimit,
        approval_window: WorkflowTaskTombstoneApprovalWindow,
    ) -> Result<WorkflowTaskTombstonePurgeIntent, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::PreparePurge;
        self.require_lease_principal(principal, &lease, permission)?;
        self.authorize(principal, &lease.tenant_id, permission)
            .await?;
        let result = self
            .store
            .prepare_task_tombstone_purge(lease, retention, limit, approval_window)
            .await;
        self.store_result(permission, result)
    }

    /// Approves using the authenticated principal, preserving four-eyes checks.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority or store governance failure.
    pub async fn approve_purge(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        purge_id: WorkflowTaskTombstonePurgeId,
    ) -> Result<WorkflowTaskTombstonePurgeIntent, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ApprovePurge;
        self.authorize(principal, &tenant_id, permission).await?;
        let result = self
            .store
            .approve_task_tombstone_purge(tenant_id, purge_id, principal.clone())
            .await;
        self.store_result(permission, result)
    }

    /// Lists the tenant's bounded durable approval inbox.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority or store failure.
    pub async fn list_purge_approvals(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        limit: WorkflowTaskTombstoneApprovalInboxLimit,
    ) -> Result<Vec<WorkflowTaskTombstoneApprovalInboxItem>, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ReadApprovalInbox;
        self.authorize(principal, &tenant_id, permission).await?;
        let result = self
            .store
            .list_task_tombstone_purge_approvals(tenant_id, limit)
            .await;
        self.store_result(permission, result)
    }

    /// Claims the oldest eligible approval using the authenticated reviewer.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority or store failure.
    pub async fn claim_purge_approval(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        lease: LeaseDuration,
    ) -> Result<Option<WorkflowTaskTombstoneApprovalLease>, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ClaimPurgeApproval;
        self.authorize(principal, &tenant_id, permission).await?;
        let result = self
            .store
            .claim_task_tombstone_purge_approval(tenant_id, principal.clone(), lease)
            .await;
        self.store_result(permission, result)
    }

    /// Approves an exact principal-owned reviewer lease.
    ///
    /// # Errors
    ///
    /// Rejects a mismatched reviewer, denied authority, or stale lease.
    pub async fn approve_claimed_purge(
        &self,
        principal: &WorkerId,
        lease: WorkflowTaskTombstoneApprovalLease,
    ) -> Result<WorkflowTaskTombstonePurgeIntent, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ApprovePurge;
        self.require_approval_principal(principal, &lease, permission)?;
        self.authorize(principal, &lease.tenant_id, permission)
            .await?;
        let result = self.store.approve_claimed_task_tombstone_purge(lease).await;
        self.store_result(permission, result)
    }

    /// Rejects an exact principal-owned reviewer lease with durable evidence.
    ///
    /// # Errors
    ///
    /// Rejects a mismatched reviewer, denied authority, or stale lease.
    pub async fn reject_claimed_purge(
        &self,
        principal: &WorkerId,
        lease: WorkflowTaskTombstoneApprovalLease,
        reason: WorkflowTaskTombstoneRejectionReason,
    ) -> Result<WorkflowTaskTombstoneApprovalInboxItem, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::RejectPurge;
        self.require_approval_principal(principal, &lease, permission)?;
        self.authorize(principal, &lease.tenant_id, permission)
            .await?;
        let result = self
            .store
            .reject_claimed_task_tombstone_purge(lease, reason)
            .await;
        self.store_result(permission, result)
    }

    /// Executes using an exact principal-owned fenced lease.
    ///
    /// # Errors
    ///
    /// Rejects denied authority, a mismatched lease principal, or store
    /// execution failure.
    pub async fn execute_purge(
        &self,
        principal: &WorkerId,
        lease: WorkflowTaskCleanupLease,
        purge_id: WorkflowTaskTombstonePurgeId,
    ) -> Result<WorkflowTaskTombstonePurgeEvidence, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ExecutePurge;
        self.require_lease_principal(principal, &lease, permission)?;
        self.authorize(principal, &lease.tenant_id, permission)
            .await?;
        let result = self
            .store
            .execute_task_tombstone_purge(lease, purge_id)
            .await;
        self.store_result(permission, result)
    }

    /// Reads evidence under an explicit tenant-scoped grant.
    ///
    /// # Errors
    ///
    /// Fails closed on denied authority or store failure.
    pub async fn get_evidence(
        &self,
        principal: &WorkerId,
        tenant_id: WorkflowTenantId,
        purge_id: WorkflowTaskTombstonePurgeId,
    ) -> Result<Option<WorkflowTaskTombstonePurgeEvidence>, WorkflowTaskGovernanceError> {
        let permission = WorkflowTaskGovernancePermission::ReadEvidence;
        self.authorize(principal, &tenant_id, permission).await?;
        let result = self
            .store
            .get_task_tombstone_purge_evidence(tenant_id, purge_id)
            .await;
        self.store_result(permission, result)
    }

    async fn authorize(
        &self,
        principal: &WorkerId,
        tenant_id: &WorkflowTenantId,
        permission: WorkflowTaskGovernancePermission,
    ) -> Result<(), WorkflowTaskGovernanceError> {
        match self
            .authorizer
            .authorize(principal, tenant_id, permission)
            .await
        {
            Ok(true) => Ok(()),
            Ok(false) => {
                self.observer
                    .observe(permission, WorkflowTaskGovernanceOutcome::Denied);
                Err(WorkflowTaskGovernanceError::Denied { permission })
            }
            Err(error) => {
                self.observer.observe(
                    permission,
                    WorkflowTaskGovernanceOutcome::AuthorizationError,
                );
                Err(error.into())
            }
        }
    }

    fn require_lease_principal(
        &self,
        principal: &WorkerId,
        lease: &WorkflowTaskCleanupLease,
        permission: WorkflowTaskGovernancePermission,
    ) -> Result<(), WorkflowTaskGovernanceError> {
        if lease.owner == *principal {
            Ok(())
        } else {
            self.observer
                .observe(permission, WorkflowTaskGovernanceOutcome::Denied);
            Err(WorkflowTaskGovernanceError::LeasePrincipalMismatch)
        }
    }

    fn require_approval_principal(
        &self,
        principal: &WorkerId,
        lease: &WorkflowTaskTombstoneApprovalLease,
        permission: WorkflowTaskGovernancePermission,
    ) -> Result<(), WorkflowTaskGovernanceError> {
        if lease.reviewer == *principal {
            Ok(())
        } else {
            self.observer
                .observe(permission, WorkflowTaskGovernanceOutcome::Denied);
            Err(WorkflowTaskGovernanceError::ApprovalLeasePrincipalMismatch)
        }
    }

    fn store_result<T>(
        &self,
        permission: WorkflowTaskGovernancePermission,
        result: Result<T, WorkflowStoreError>,
    ) -> Result<T, WorkflowTaskGovernanceError> {
        match result {
            Ok(value) => {
                self.observer
                    .observe(permission, WorkflowTaskGovernanceOutcome::Succeeded);
                Ok(value)
            }
            Err(error) => Err(self.store_error(permission, error)),
        }
    }

    fn store_error(
        &self,
        permission: WorkflowTaskGovernancePermission,
        error: WorkflowStoreError,
    ) -> WorkflowTaskGovernanceError {
        self.observer
            .observe(permission, WorkflowTaskGovernanceOutcome::StoreError);
        error.into()
    }
}

impl<S, A> std::fmt::Debug for WorkflowTaskGovernanceControlPlane<S, A> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WorkflowTaskGovernanceControlPlane")
            .field("store", &"<governance-store>")
            .field("authorizer", &"<governance-authorizer>")
            .field("observer", &"<governance-observer>")
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::{WorkflowTaskTombstoneArchiveError, WorkflowTaskTombstoneArchiveErrorKind};

    #[test]
    fn archive_error_preserves_kind_and_bounds_safe_message() {
        let error = WorkflowTaskTombstoneArchiveError::with_kind(
            WorkflowTaskTombstoneArchiveErrorKind::Ambiguous,
            "x".repeat(1_024),
        );

        assert_eq!(
            error.kind(),
            WorkflowTaskTombstoneArchiveErrorKind::Ambiguous
        );
        assert!(error.to_string().len() < 600);
        assert_eq!(
            WorkflowTaskTombstoneArchiveError::new("fallback").kind(),
            WorkflowTaskTombstoneArchiveErrorKind::Other
        );
    }
}