Skip to main content

folderbase_core/
guide_policy.rs

1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub enum MaintenanceTrigger {
3    UserInvoked,
4    Heartbeat { enabled: bool },
5}
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct BudgetLimits {
9    pub tokens: u64,
10    /// Currency represented as integer millionths to avoid floating-point
11    /// budget drift.
12    pub cost_micros: u64,
13}
14
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub struct BudgetUsage {
17    pub tokens: u64,
18    pub cost_micros: u64,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct ModelRequestBudget {
23    /// Maximum tokens the runner is permitted to consume, not an estimate.
24    pub max_tokens: u64,
25    /// Maximum charge the runner is permitted to accrue.
26    pub max_cost_micros: u64,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct BudgetLedger {
31    limits: BudgetLimits,
32    usage: BudgetUsage,
33}
34
35impl BudgetLedger {
36    pub fn new(limits: BudgetLimits) -> Self {
37        Self {
38            limits,
39            usage: BudgetUsage::default(),
40        }
41    }
42
43    pub fn from_usage(limits: BudgetLimits, usage: BudgetUsage) -> Self {
44        Self { limits, usage }
45    }
46
47    pub fn limits(&self) -> BudgetLimits {
48        self.limits
49    }
50
51    pub fn usage(&self) -> BudgetUsage {
52        self.usage
53    }
54
55    pub fn remaining(&self) -> BudgetUsage {
56        BudgetUsage {
57            tokens: self.limits.tokens.saturating_sub(self.usage.tokens),
58            cost_micros: self
59                .limits
60                .cost_micros
61                .saturating_sub(self.usage.cost_micros),
62        }
63    }
64
65    /// Atomically account for observed usage. The ledger is unchanged if the
66    /// charge would cross either hard limit.
67    pub fn charge(&mut self, delta: BudgetUsage) -> Result<(), BudgetExceeded> {
68        let token_total = self.usage.tokens.checked_add(delta.tokens);
69        let cost_total = self.usage.cost_micros.checked_add(delta.cost_micros);
70        let exceeded = BudgetExceeded {
71            tokens: token_total.is_none_or(|total| total > self.limits.tokens),
72            cost: cost_total.is_none_or(|total| total > self.limits.cost_micros),
73        };
74
75        if exceeded.any() {
76            return Err(exceeded);
77        }
78
79        self.usage = BudgetUsage {
80            tokens: token_total.expect("checked above"),
81            cost_micros: cost_total.expect("checked above"),
82        };
83        Ok(())
84    }
85
86    fn can_reserve(self, request: ModelRequestBudget) -> Result<(), BudgetExceeded> {
87        let exceeded = BudgetExceeded {
88            tokens: self
89                .usage
90                .tokens
91                .checked_add(request.max_tokens)
92                .is_none_or(|total| total > self.limits.tokens),
93            cost: self
94                .usage
95                .cost_micros
96                .checked_add(request.max_cost_micros)
97                .is_none_or(|total| total > self.limits.cost_micros),
98        };
99        if exceeded.any() {
100            Err(exceeded)
101        } else {
102            Ok(())
103        }
104    }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub struct BudgetExceeded {
109    pub tokens: bool,
110    pub cost: bool,
111}
112
113impl BudgetExceeded {
114    pub fn any(self) -> bool {
115        self.tokens || self.cost
116    }
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub struct PreflightInput {
121    pub trigger: MaintenanceTrigger,
122    /// Count produced by deterministic inventory/change detection. Model
123    /// inference must not be used to manufacture this signal.
124    pub meaningful_change_count: u64,
125    pub request: ModelRequestBudget,
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum NoOpReason {
130    NoMeaningfulChange,
131    HeartbeatDisabled,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum PreflightDecision {
136    /// The caller must not invoke a model.
137    NoOp(NoOpReason),
138    /// A meaningful update exists, but the maximum possible request would
139    /// cross a hard budget. The caller must not invoke a model.
140    BlockedByBudget(BudgetExceeded),
141    /// The model may be invoked with exactly these hard ceilings.
142    InvokeModel(ModelRequestBudget),
143}
144
145impl PreflightDecision {
146    pub fn permits_model_call(self) -> bool {
147        matches!(self, Self::InvokeModel(_))
148    }
149}
150
151/// Decide whether maintenance should reach model inference.
152///
153/// Deterministic no-op checks deliberately run before budget checks so an
154/// unchanged heartbeat remains a cheap no-op even when its budget is empty.
155pub fn deterministic_preflight(input: PreflightInput, budget: &BudgetLedger) -> PreflightDecision {
156    if input.meaningful_change_count == 0 {
157        return PreflightDecision::NoOp(NoOpReason::NoMeaningfulChange);
158    }
159    if matches!(
160        input.trigger,
161        MaintenanceTrigger::Heartbeat { enabled: false }
162    ) {
163        return PreflightDecision::NoOp(NoOpReason::HeartbeatDisabled);
164    }
165
166    match budget.can_reserve(input.request) {
167        Ok(()) => PreflightDecision::InvokeModel(input.request),
168        Err(exceeded) => PreflightDecision::BlockedByBudget(exceeded),
169    }
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum ObjectLifecycle {
174    Draft,
175    Canonical,
176    Superseded,
177    Archived,
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum ScopeChange {
182    Unchanged,
183    Narrow,
184    Expand,
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum GuideAction {
189    AnalyzeInventory,
190    AskMigrationQuestions,
191    ProposeStructure,
192    ProposeRelationship,
193    RefreshDerivedSummary,
194    RefreshStaleSignals,
195    WriteMigrationPlan { approved: bool },
196    ChangePermissions { broadens_access: bool },
197    DeleteObject { lifecycle: ObjectLifecycle },
198    MoveObject { lifecycle: ObjectLifecycle },
199    MergeObjects { includes_canonical: bool },
200    ArchiveObject { active_work: bool },
201    ChangeScope { change: ScopeChange },
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum AuthorityReason {
206    PermissionBroadening,
207    PermissionChangeRequiresApproval,
208    CanonicalDeletion,
209    CanonicalMove,
210    CanonicalMerge,
211    ActiveArchive,
212    ArchiveRequiresApproval,
213    ScopeExpansion,
214    StructuralChangeRequiresApproval,
215    MigrationPlanNotApproved,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum AuthorityDecision {
220    Allowed,
221    RequiresApproval(AuthorityReason),
222    Denied(AuthorityReason),
223}
224
225impl AuthorityDecision {
226    pub fn is_allowed(self) -> bool {
227        self == Self::Allowed
228    }
229}
230
231/// Apply the Guide's autonomous-authority boundary.
232///
233/// Denied operations cannot be converted into direct Guide writes by passing
234/// an approval flag. An approved structural change must be handed to the
235/// migration/change-set executor, preserving separation of authority.
236pub fn authorize(action: GuideAction) -> AuthorityDecision {
237    match action {
238        GuideAction::AnalyzeInventory
239        | GuideAction::AskMigrationQuestions
240        | GuideAction::ProposeStructure
241        | GuideAction::ProposeRelationship
242        | GuideAction::RefreshDerivedSummary
243        | GuideAction::RefreshStaleSignals
244        | GuideAction::ChangeScope {
245            change: ScopeChange::Unchanged | ScopeChange::Narrow,
246        } => AuthorityDecision::Allowed,
247        GuideAction::WriteMigrationPlan { approved: true } => AuthorityDecision::Allowed,
248        GuideAction::WriteMigrationPlan { approved: false } => {
249            AuthorityDecision::RequiresApproval(AuthorityReason::MigrationPlanNotApproved)
250        }
251        GuideAction::ChangePermissions {
252            broadens_access: true,
253        } => AuthorityDecision::Denied(AuthorityReason::PermissionBroadening),
254        GuideAction::ChangePermissions {
255            broadens_access: false,
256        } => AuthorityDecision::RequiresApproval(AuthorityReason::PermissionChangeRequiresApproval),
257        GuideAction::DeleteObject {
258            lifecycle: ObjectLifecycle::Canonical,
259        } => AuthorityDecision::Denied(AuthorityReason::CanonicalDeletion),
260        GuideAction::MoveObject {
261            lifecycle: ObjectLifecycle::Canonical,
262        } => AuthorityDecision::Denied(AuthorityReason::CanonicalMove),
263        GuideAction::MergeObjects {
264            includes_canonical: true,
265        } => AuthorityDecision::Denied(AuthorityReason::CanonicalMerge),
266        GuideAction::ArchiveObject { active_work: true } => {
267            AuthorityDecision::Denied(AuthorityReason::ActiveArchive)
268        }
269        GuideAction::ChangeScope {
270            change: ScopeChange::Expand,
271        } => AuthorityDecision::Denied(AuthorityReason::ScopeExpansion),
272        GuideAction::ArchiveObject { active_work: false } => {
273            AuthorityDecision::RequiresApproval(AuthorityReason::ArchiveRequiresApproval)
274        }
275        GuideAction::DeleteObject { .. }
276        | GuideAction::MoveObject { .. }
277        | GuideAction::MergeObjects { .. } => {
278            AuthorityDecision::RequiresApproval(AuthorityReason::StructuralChangeRequiresApproval)
279        }
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    fn budget(tokens: u64, cost_micros: u64) -> BudgetLedger {
288        BudgetLedger::new(BudgetLimits {
289            tokens,
290            cost_micros,
291        })
292    }
293
294    fn changed_request() -> PreflightInput {
295        PreflightInput {
296            trigger: MaintenanceTrigger::Heartbeat { enabled: true },
297            meaningful_change_count: 1,
298            request: ModelRequestBudget {
299                max_tokens: 100,
300                max_cost_micros: 50,
301            },
302        }
303    }
304
305    #[test]
306    fn unchanged_heartbeat_is_a_model_free_no_op() {
307        let mut input = changed_request();
308        input.meaningful_change_count = 0;
309        let decision = deterministic_preflight(input, &budget(0, 0));
310
311        assert_eq!(
312            decision,
313            PreflightDecision::NoOp(NoOpReason::NoMeaningfulChange)
314        );
315        assert!(!decision.permits_model_call());
316    }
317
318    #[test]
319    fn a_disabled_heartbeat_does_not_invoke_a_model_for_changes() {
320        let mut input = changed_request();
321        input.trigger = MaintenanceTrigger::Heartbeat { enabled: false };
322
323        assert_eq!(
324            deterministic_preflight(input, &budget(1_000, 1_000)),
325            PreflightDecision::NoOp(NoOpReason::HeartbeatDisabled)
326        );
327    }
328
329    #[test]
330    fn preflight_enforces_maximum_token_and_cost_reservations() {
331        let at_limit = deterministic_preflight(changed_request(), &budget(100, 50));
332        assert!(at_limit.permits_model_call());
333
334        assert_eq!(
335            deterministic_preflight(changed_request(), &budget(99, 50)),
336            PreflightDecision::BlockedByBudget(BudgetExceeded {
337                tokens: true,
338                cost: false,
339            })
340        );
341        assert_eq!(
342            deterministic_preflight(changed_request(), &budget(100, 49)),
343            PreflightDecision::BlockedByBudget(BudgetExceeded {
344                tokens: false,
345                cost: true,
346            })
347        );
348
349        let already_exhausted = BudgetLedger::from_usage(
350            BudgetLimits {
351                tokens: 100,
352                cost_micros: 50,
353            },
354            BudgetUsage {
355                tokens: 101,
356                cost_micros: 51,
357            },
358        );
359        let mut zero_request = changed_request();
360        zero_request.request = ModelRequestBudget {
361            max_tokens: 0,
362            max_cost_micros: 0,
363        };
364        assert_eq!(
365            deterministic_preflight(zero_request, &already_exhausted),
366            PreflightDecision::BlockedByBudget(BudgetExceeded {
367                tokens: true,
368                cost: true,
369            })
370        );
371    }
372
373    #[test]
374    fn ledger_never_mutates_when_a_charge_would_cross_a_hard_limit() {
375        let mut ledger = budget(100, 50);
376        ledger
377            .charge(BudgetUsage {
378                tokens: 90,
379                cost_micros: 40,
380            })
381            .unwrap();
382        let before = ledger.usage();
383
384        let error = ledger
385            .charge(BudgetUsage {
386                tokens: 11,
387                cost_micros: 1,
388            })
389            .unwrap_err();
390        assert_eq!(
391            error,
392            BudgetExceeded {
393                tokens: true,
394                cost: false,
395            }
396        );
397        assert_eq!(ledger.usage(), before);
398    }
399
400    #[test]
401    fn authority_guard_denies_every_forbidden_autonomous_action() {
402        let forbidden = [
403            (
404                GuideAction::ChangePermissions {
405                    broadens_access: true,
406                },
407                AuthorityReason::PermissionBroadening,
408            ),
409            (
410                GuideAction::DeleteObject {
411                    lifecycle: ObjectLifecycle::Canonical,
412                },
413                AuthorityReason::CanonicalDeletion,
414            ),
415            (
416                GuideAction::MoveObject {
417                    lifecycle: ObjectLifecycle::Canonical,
418                },
419                AuthorityReason::CanonicalMove,
420            ),
421            (
422                GuideAction::MergeObjects {
423                    includes_canonical: true,
424                },
425                AuthorityReason::CanonicalMerge,
426            ),
427            (
428                GuideAction::ArchiveObject { active_work: true },
429                AuthorityReason::ActiveArchive,
430            ),
431            (
432                GuideAction::ChangeScope {
433                    change: ScopeChange::Expand,
434                },
435                AuthorityReason::ScopeExpansion,
436            ),
437        ];
438
439        for (action, reason) in forbidden {
440            assert_eq!(
441                authorize(action),
442                AuthorityDecision::Denied(reason),
443                "{action:?}"
444            );
445        }
446    }
447
448    #[test]
449    fn safe_analysis_and_approved_plan_writes_are_allowed() {
450        for action in [
451            GuideAction::AnalyzeInventory,
452            GuideAction::AskMigrationQuestions,
453            GuideAction::ProposeStructure,
454            GuideAction::ProposeRelationship,
455            GuideAction::RefreshDerivedSummary,
456            GuideAction::RefreshStaleSignals,
457            GuideAction::WriteMigrationPlan { approved: true },
458        ] {
459            assert_eq!(authorize(action), AuthorityDecision::Allowed);
460        }
461
462        assert!(matches!(
463            authorize(GuideAction::ArchiveObject { active_work: false }),
464            AuthorityDecision::RequiresApproval(AuthorityReason::ArchiveRequiresApproval)
465        ));
466    }
467}