Skip to main content

aios_spec/
governance.rs

1//! 动作治理协议类型
2//!
3//! 本模块定义 Action Bus 治理边界上的协议数据:不可信的 `ActionProposal`、
4//! 确定性坐标 `ActionCoord`、副作用分级 `EffectClass`、生命周期状态
5//! `ActionState`、审计记录 `AuditRecord` 以及裁决/执行相关的 outcome/error 类型。
6//!
7//! 注意:真正“可执行”的凭证 `AuthorizedAction` 不在这里定义——它必须和
8//! 唯一能够构造它的状态机同处一个 crate,以便由编译器保证不可伪造性。
9
10use serde::{Deserialize, Serialize};
11
12use crate::event::SourceTier;
13use crate::intent::{ActionType, DecisionRoute, DenialReason, SuggestedAction};
14
15/// 确定性动作坐标。
16///
17/// 不含 UUID、wall-clock 等运行时随机量,是单次 replay/run 内的 canonical
18/// 主键。`window_ordinal` 由驱动循环按窗口处理顺序赋号,用于消除跨窗口的
19/// `(intent_ordinal, action_ordinal)` 碰撞。
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
21pub struct ActionCoord {
22    pub window_ordinal: u32,
23    pub intent_ordinal: u32,
24    pub action_ordinal: u32,
25}
26
27/// 动作副作用分级(按当前 5 个动作的真实副作用裁剪,不照搬设计文档 6 级)。
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
29pub enum EffectClass {
30    /// 纯读/无状态变更,例如 NoOp。
31    PureRead,
32    /// 本地缓存写,例如 PrefetchFile。
33    LocalCacheWrite,
34    /// 本地进程/系统状态变更,例如 PreWarmProcess、KeepAlive、ReleaseMemory。
35    LocalStateChange,
36}
37
38impl EffectClass {
39    /// 按 `ActionType` 推导其副作用分级。
40    pub fn from_action_type(action_type: &ActionType) -> Self {
41        match action_type {
42            ActionType::NoOp => Self::PureRead,
43            ActionType::PrefetchFile => Self::LocalCacheWrite,
44            ActionType::PreWarmProcess | ActionType::KeepAlive | ActionType::ReleaseMemory => {
45                Self::LocalStateChange
46            },
47        }
48    }
49}
50
51/// 不可信侧治理 envelope。
52///
53/// core 在边界处为来自 planner 的 `SuggestedAction` 建立此 envelope:填入确定
54/// 性坐标、由可信侧推导 effect。裹在里面的 `action` 字段本身仍是不可信输入。
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct ActionProposal {
57    /// 运行时关联用(含随机 UUID),不进 canonical hash。
58    pub intent_id: String,
59    /// 确定性坐标,进 canonical hash。
60    pub coord: ActionCoord,
61    /// 来自 planner 的不可信建议动作。
62    pub action: SuggestedAction,
63    /// 由 core 可信侧推导填入的副作用分级,非外部输入。
64    pub effect: EffectClass,
65    /// 提议时间(epoch ms),运行时 volatile,不进 canonical hash。
66    pub proposed_at_ms: i64,
67}
68
69/// 动作生命周期状态(精简版,9 态)。
70///
71/// 只保留当前管线可达的状态;budget/调度/privacy 相关终态延后到机制存在时。
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
73pub enum ActionState {
74    // 正常路径
75    Proposed,
76    SchemaValidated,
77    PolicyChecked,
78    Dispatched,
79    /// 终态:执行成功。
80    Succeeded,
81    // 拒绝/失败终态
82    /// 终态:schema 校验失败(如缺失必需 target、非法 risk/effect 组合)。
83    RejectedInvalidSchema,
84    /// 终态:能力等级拒绝(`PolicyEngine` 的 RiskExceedsCapability /
85    /// ActionCapabilityDenied)。
86    DeniedByCapability,
87    /// 终态:策略拒绝(风险超配置、置信度过低、target 不在上下文等)。
88    DeniedByPolicy,
89    /// 终态:adapter 执行返回 Err。
90    Failed,
91}
92
93impl ActionState {
94    /// 是否为终态。
95    pub fn is_terminal(self) -> bool {
96        matches!(
97            self,
98            Self::Succeeded
99                | Self::RejectedInvalidSchema
100                | Self::DeniedByCapability
101                | Self::DeniedByPolicy
102                | Self::Failed
103        )
104    }
105}
106
107/// 动作执行结果(adapter 返回)。
108///
109/// `Ok(ActionOutcome)` 即表示执行成功;失败通过 `Result::Err(AdapterError)`
110/// 表达。本结构体可能包含运行时 volatile 字段(如实际 latency),因此不能
111/// 直接进 hash;需先投影为 `ActionOutcomeSummary`。
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct ActionOutcome {
114    pub action_type: String,
115    pub target: Option<String>,
116    pub summary: String,
117    pub latency_us: u64,
118}
119
120/// 确定性 outcome 摘要,不含 wall-clock / 随机,纳入 `audit_hash`。
121#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
122pub struct ActionOutcomeSummary {
123    pub action_type: String,
124    pub target: Option<String>,
125    pub summary: String,
126}
127
128impl ActionOutcomeSummary {
129    /// 从 `ActionOutcome` 投影为确定性摘要。
130    pub fn from_outcome(outcome: &ActionOutcome) -> Self {
131        Self {
132            action_type: outcome.action_type.clone(),
133            target: outcome.target.clone(),
134            summary: outcome.summary.clone(),
135        }
136    }
137}
138
139/// Adapter 执行错误。
140///
141/// 注意:不设置 `Unsupported` variant。`ActionType` 是封闭枚举且 adapter 全覆盖,
142/// 未知 action_type 在更早的 schema/反序列化阶段就被拒,归 `RejectedInvalidSchema`。
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
144pub enum AdapterError {
145    #[error("simulated resource unavailable: {0}")]
146    SimulatedResourceUnavailable(String),
147    #[error("android bridge error: {0}")]
148    AndroidBridgeError(String),
149    #[error("execution error: {0}")]
150    ExecutionError(String),
151}
152
153/// 策略裁决。
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155pub enum PolicyVerdict {
156    Approved,
157    Denied(DenialReason),
158}
159
160/// PolicyEngine 对单条建议动作的逐 action 裁决。
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162pub struct PolicyActionDecision {
163    pub intent_ordinal: u32,
164    pub action_ordinal: u32,
165    pub verdict: PolicyVerdict,
166}
167
168/// 审计记录。
169///
170/// 每个 `ActionProposal`(即每个 `ActionCoord`)在生命周期中产出恰好一条。
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct AuditRecord {
173    /// 确定性主键,进 canonical hash。
174    pub coord: ActionCoord,
175    /// 运行时关联(含 UUID),volatile,不进 canonical hash。
176    pub intent_id: String,
177    pub action_type: ActionType,
178    pub target: Option<String>,
179    pub effect: EffectClass,
180    /// 产生该动作的后端路由,确定性,进 canonical hash。
181    pub route: DecisionRoute,
182    /// 后端失败/熔断等诊断信息,volatile,不进 canonical hash。
183    pub backend_error: Option<String>,
184    /// 完整迁移序列。
185    pub transitions: Vec<ActionState>,
186    /// 终态(冗余但便于查询/golden)。
187    pub terminal: ActionState,
188    /// 成功时写入 adapter outcome 的确定性摘要,进 canonical hash。
189    pub outcome: Option<ActionOutcomeSummary>,
190    /// 拒绝原因(终态为拒绝时)。
191    pub denial_reason: Option<DenialReason>,
192    /// 错误信息(终态为 Failed 时)。
193    pub error: Option<String>,
194    /// Source tier of the window that produced this action proposal.
195    /// Deterministic, included in canonical hash.
196    pub source_tier: SourceTier,
197}
198
199impl AuditRecord {
200    /// 从初态 `Proposed` 开始构建一条审计记录。
201    pub fn new(proposal: &ActionProposal, route: DecisionRoute, source_tier: SourceTier) -> Self {
202        Self {
203            coord: proposal.coord,
204            intent_id: proposal.intent_id.clone(),
205            action_type: proposal.action.action_type.clone(),
206            target: proposal.action.target.clone(),
207            effect: proposal.effect,
208            route,
209            backend_error: None,
210            transitions: vec![ActionState::Proposed],
211            terminal: ActionState::Proposed,
212            outcome: None,
213            denial_reason: None,
214            error: None,
215            source_tier,
216        }
217    }
218
219    /// 追加一个状态迁移,并更新 `terminal`。
220    pub fn transition(&mut self, state: ActionState) {
221        self.transitions.push(state);
222        self.terminal = state;
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn action_state_terminal_detection() {
232        assert!(!ActionState::Proposed.is_terminal());
233        assert!(!ActionState::SchemaValidated.is_terminal());
234        assert!(!ActionState::PolicyChecked.is_terminal());
235        assert!(!ActionState::Dispatched.is_terminal());
236        assert!(ActionState::Succeeded.is_terminal());
237        assert!(ActionState::RejectedInvalidSchema.is_terminal());
238        assert!(ActionState::DeniedByCapability.is_terminal());
239        assert!(ActionState::DeniedByPolicy.is_terminal());
240        assert!(ActionState::Failed.is_terminal());
241    }
242
243    #[test]
244    fn effect_class_derived_from_action_type() {
245        assert_eq!(
246            EffectClass::from_action_type(&ActionType::NoOp),
247            EffectClass::PureRead
248        );
249        assert_eq!(
250            EffectClass::from_action_type(&ActionType::PrefetchFile),
251            EffectClass::LocalCacheWrite
252        );
253        assert_eq!(
254            EffectClass::from_action_type(&ActionType::PreWarmProcess),
255            EffectClass::LocalStateChange
256        );
257        assert_eq!(
258            EffectClass::from_action_type(&ActionType::KeepAlive),
259            EffectClass::LocalStateChange
260        );
261        assert_eq!(
262            EffectClass::from_action_type(&ActionType::ReleaseMemory),
263            EffectClass::LocalStateChange
264        );
265    }
266}