converge_core/
lib.rs

1// Copyright 2024-2025 Aprio One AB, Sweden
2// Author: Kenneth Pernyer, kenneth@aprio.one
3// SPDX-License-Identifier: LicenseRef-Proprietary
4// All rights reserved. This source code is proprietary and confidential.
5// Unauthorized copying, modification, or distribution is strictly prohibited.
6
7//! # Converge Core
8//!
9//! A correctness-first, context-driven multi-agent runtime.
10//!
11//! Converge is an Agent OS where:
12//! - Context is the API
13//! - Agents collaborate through data, not calls
14//! - Execution proceeds until a fixed point
15//! - Convergence is explicit and observable
16//!
17//! ## Quick Start
18//!
19//! ```
20//! use converge_core::{Engine, Context, ContextKey};
21//! use converge_core::agents::{SeedAgent, ReactOnceAgent};
22//!
23//! // Create engine and register agents
24//! let mut engine = Engine::new();
25//! engine.register(SeedAgent::new("seed-1", "initial data"));
26//! engine.register(ReactOnceAgent::new("hyp-1", "derived insight"));
27//!
28//! // Run until convergence
29//! let result = engine.run(Context::new()).expect("should converge");
30//!
31//! // Inspect results
32//! assert!(result.converged);
33//! assert!(result.context.has(ContextKey::Seeds));
34//! assert!(result.context.has(ContextKey::Hypotheses));
35//! println!("Converged in {} cycles", result.cycles);
36//! ```
37//!
38//! ## Core Concepts
39//!
40//! - [`Context`]: The shared, typed, evolving state of a job
41//! - [`Agent`]: A capability that reads context and emits effects
42//! - [`AgentEffect`]: Buffered output (facts) from an agent
43//! - [`Engine`]: The convergence loop that coordinates agents
44//!
45//! ## Guarantees
46//!
47//! - **Determinism**: Same input → same output
48//! - **Termination**: Budgets prevent infinite loops
49//! - **Isolation**: Agents never call each other
50//! - **Auditability**: All changes are traceable
51//!
52//! # Design Tenets
53//!
54//! These are the nine non-negotiable axioms that `converge-core` exists to encode,
55//! enforce, and protect. Every type, trait, and pattern in this crate serves one
56//! or more of these tenets.
57//!
58//! ## 1. Explicit Authority
59//!
60//! **Axiom**: No defaults that grant authority. Authority is always explicit, typed, and traceable.
61//!
62//! **Why**: Implicit permissions lead to security drift and unauditable systems.
63//!
64//! **In code**: [`AuthorityGrant`] and [`AuthorityScope`] require explicit construction.
65//! The `pub(crate)` constructors on `AuthorityGrant` prevent external code from forging
66//! authority. See also [`PromotionRecord`] which traces approvers.
67//!
68//! ## 2. Convergence Over Control Flow
69//!
70//! **Axiom**: We converge on outcomes via governed proposals, not ad-hoc loops or hidden heuristics.
71//!
72//! **Why**: Control flow hides decisions; convergence makes them observable.
73//!
74//! **In code**: The [`Engine`] runs agents repeatedly until a fixed point is reached.
75//! [`StopReason`] exhaustively enumerates why execution halted. No hidden loops.
76//!
77//! ## 3. Append-Only Truth
78//!
79//! **Axiom**: Facts are never mutated. Corrections are new facts.
80//!
81//! **Why**: Mutable state hides history and prevents audit replay.
82//!
83//! **In code**: [`TypesFact`] has private fields with no `&mut` methods.
84//! [`CorrectionEvent`] creates new correction facts rather than
85//! mutating existing ones. The [`Context`] accumulates facts without overwriting.
86//!
87//! ## 4. Agents Suggest, Engine Decides
88//!
89//! **Axiom**: Agents emit proposals; promotion requires validation gates (and sometimes humans).
90//!
91//! **Why**: Separates suggestion from decision, enabling governance and audit.
92//!
93//! **In code**: [`PromotionGate`] is the ONLY path to create Facts. Agents produce
94//! [`Proposal`] in the `Draft` state which must go through [`ValidationReport`]
95//! before becoming `Validated` and finally [`TypesFact`].
96//!
97//! ## 5. Safety by Construction
98//!
99//! **Axiom**: Make invalid states unrepresentable. Prefer types over conventions.
100//!
101//! **Why**: Runtime checks can be bypassed; type-level guarantees cannot.
102//!
103//! **In code**: The type-state pattern on [`Proposal`] (`Draft` vs `Validated`)
104//! makes it impossible to promote an unvalidated proposal. Newtype IDs like [`FactId`],
105//! [`ProposalId`], and [`ObservationId`] prevent mixing.
106//!
107//! ## 6. Transparent Determinism
108//!
109//! **Axiom**: The system tells the truth about replayability and determinism.
110//!
111//! **Why**: Hidden non-determinism corrupts audit trails and reproducibility.
112//!
113//! **In code**: [`TypesTraceLink`] distinguishes [`LocalTrace`]
114//! (replay-eligible) from [`RemoteRef`] (audit-only). [`Replayability`]
115//! explicitly marks whether operations can be replayed deterministically.
116//!
117//! ## 7. Human Authority First-Class
118//!
119//! **Axiom**: Explicit pause/approve gates for consequential actions.
120//!
121//! **Why**: AI systems must preserve human oversight for high-stakes decisions.
122//!
123//! **In code**: [`Actor`] and [`ActorKind`] distinguish
124//! human from automated approvers. [`PromotionRecord`] records
125//! who approved each fact. The [`ValidationPolicy`] can require human approval.
126//!
127//! ## 8. No Hidden Work
128//!
129//! **Axiom**: No silent background effects, retries, implicit state changes, or shadow decisioning.
130//!
131//! **Why**: Hidden work makes systems unpredictable and unauditable.
132//!
133//! **In code**: [`AgentEffect`] explicitly captures all agent output. The [`Engine`]
134//! budget system ([`CycleBudget`], [`FactBudget`], [`TokenBudget`]) makes resource
135//! consumption visible. [`StopReason`] explains exactly why execution ended.
136//!
137//! ## 9. Scale by Intent Replication
138//!
139//! **Axiom**: Scale by replicating intent and invariants across domains.
140//!
141//! **Why**: Scaling should preserve governance, not bypass it.
142//!
143//! **In code**: [`RootIntent`] and [`Frame`] capture intent as data.
144//! [`Invariant`] enforces governance rules. These types can be serialized and
145//! replicated across distributed systems while preserving their constraints.
146//!
147//! # Purity Declaration
148//!
149//! `converge-core` is the constitutional foundation for Converge. It must remain
150//! **pure**: no I/O, no runtime behavior, no implementation logic. Only types,
151//! traits, and promotion gates.
152//!
153//! ## Allowed Dependencies
154//!
155//! | Crate | Purpose | Rationale |
156//! |-------|---------|-----------|
157//! | `thiserror` | Error derives | Pure derives, no runtime |
158//! | `tracing` | Log macros | Compile-time only when used |
159//! | `serde` | Serialization derives | Pure derives, no I/O |
160//! | `serde_json` | JSON encoding | Value-only, no I/O |
161//! | `typed-builder` | Builder derives | Pure derives |
162//! | `hex` | Hex encoding | Pure transforms |
163//! | Small pure libs | Hashing, encoding | No I/O, no async |
164//!
165//! ## Forbidden Dependencies
166//!
167//! | Crate | Category | Why Forbidden |
168//! |-------|----------|---------------|
169//! | `tokio` | Async runtime | Implies execution |
170//! | `reqwest` | HTTP client | Network I/O |
171//! | `axum` | HTTP server | Network I/O |
172//! | `tonic` | gRPC | Network I/O |
173//! | `prost` | Protobuf | gRPC dependency |
174//! | `burn` | ML runtime | Heavy computation |
175//! | `llama-burn` | LLM inference | Model execution |
176//! | `fastembed` | Embeddings | Model execution |
177//! | `polars` | DataFrames | Heavy computation |
178//! | `arrow` | Columnar data | Analytics dependency |
179//! | `lancedb` | Vector DB | Persistence |
180//! | `surrealdb` | Database | Persistence |
181//! | `postgres` | Database | Persistence |
182//! | `rand` | Randomness | Non-determinism |
183//! | `rayon` | Parallelism | Execution strategy |
184//!
185//! ## The Purity Rule
186//!
187//! > If a module implies execution, I/O, network, model inference, or persistence,
188//! > it does not belong in `converge-core`.
189//!
190//! Capability crates (e.g., `converge-runtime`, `converge-llm`, `converge-provider`)
191//! implement the traits defined here using the forbidden dependencies.
192//!
193//! See `deny.toml` at the crate root for CI enforcement of these rules.
194
195mod agent;
196pub mod agents;
197pub mod backend;
198pub mod capability;
199mod context;
200mod effect;
201mod engine;
202mod error;
203pub mod eval;
204pub mod experience_store;
205pub mod governed_artifact;
206pub mod integrity;
207pub mod invariant;
208pub mod kernel_boundary;
209pub mod llm;
210pub mod model_selection;
211pub mod prompt;
212pub mod recall;
213pub mod root_intent;
214pub mod traits;
215pub mod types;
216pub mod validation;
217pub mod gates;
218
219pub use agent::{Agent, AgentId};
220pub use context::{Context, ContextKey, Fact, ProposedFact, ValidationError};
221pub use effect::AgentEffect;
222pub use engine::{Budget, ConvergeResult, Engine, StreamingCallback};
223pub use error::ConvergeError;
224pub use eval::{Eval, EvalId, EvalOutcome, EvalRegistry, EvalResult};
225pub use experience_store::{
226    ArtifactKind, ArtifactQuery, ContractResultSnapshot, EventQuery, ExperienceEvent,
227    ExperienceEventEnvelope, ExperienceEventKind, ExperienceStore, ExperienceStoreError,
228    ExperienceStoreResult, PolicySnapshot, TimeRange,
229};
230pub use invariant::{Invariant, InvariantClass, InvariantError, InvariantResult, Violation};
231pub use model_selection::{
232    // Legacy types (backward compatibility)
233    AgentRequirements,
234    ComplianceLevel,
235    CostClass,
236    // New orthogonal dimensions (preferred)
237    CostTier,
238    DataSovereignty,
239    Jurisdiction,
240    LatencyClass,
241    ModelSelectorTrait,
242    RequiredCapabilities,
243    SelectionCriteria,
244    TaskComplexity,
245};
246pub use prompt::{AgentPrompt, AgentRole, Constraint, OutputContract, PromptContext, PromptFormat};
247pub use root_intent::{
248    Budgets, ConstraintSeverity, IntentConstraint, IntentId, IntentKind, IntentValidationError,
249    Objective, RootIntent, Scope, ScopeConstraint, SuccessCriteria, SuccessCriterion,
250};
251
252// Re-export core capability types for convenience
253pub use capability::{
254    CapabilityError, CapabilityErrorKind, CapabilityKind, CapabilityMetadata, EmbedInput,
255    EmbedRequest, EmbedResponse, Embedding, GraphEdge, GraphNode, GraphQuery, GraphRecall,
256    GraphResult, Modality, RankedItem, RerankRequest, RerankResponse, Reranking, VectorMatch,
257    VectorQuery, VectorRecall, VectorRecord,
258};
259
260// Re-export capability boundary traits (interfaces for external implementations)
261pub use traits::{Executor, Fingerprint, FingerprintError, Randomness};
262
263// Re-export kernel boundary types (constitutional types for all kernels)
264pub use kernel_boundary::{
265    // Kernel input types (platform-to-kernel contract)
266    KernelIntent, KernelContext, ContextFact, KernelPolicy,
267    // Decision step (reasoning phases)
268    DecisionStep,
269    // TraceLink types (replay vs audit semantics)
270    TraceLink, LocalTraceLink, RemoteTraceLink, Replayability,
271    AdapterTrace, SamplerParams, RecallTrace, ExecutionEnv,
272    // Proposal types (kernel output boundary)
273    KernelProposal, ProposalKind, ProposedContent, ContentKind,
274    // Contract types
275    ContractResult,
276    // Routing policy types
277    RiskTier, DataClassification, RoutingPolicy,
278};
279
280// Re-export governed artifact types (lifecycle governance for any artifact that changes outcomes)
281pub use governed_artifact::{
282    // Lifecycle state machine
283    GovernedArtifactState, validate_transition, InvalidStateTransition,
284    // Audit trail
285    LifecycleEvent,
286    // Rollback types
287    RollbackSeverity, RollbackImpact, RollbackRecord,
288    // Replay integrity
289    ReplayIntegrityViolation,
290};
291
292// Re-export backend types (unified LLM interface for local and remote)
293pub use backend::{
294    // Trait
295    LlmBackend,
296    // Error types
297    BackendError, BackendResult,
298    // Capabilities
299    BackendCapability,
300    // Request types
301    BackendRequest, BackendPrompt, Message, MessageRole,
302    ContractSpec, BackendBudgets, BackendRecallPolicy, BackendAdapterPolicy,
303    // Response types
304    BackendResponse, ContractReport, BackendContractResult, BackendUsage,
305    // Retry and circuit breaker types (production error handling)
306    RetryPolicy, BackoffStrategy, CircuitBreakerConfig, CircuitState,
307};
308
309// Re-export new types module (3-tier hierarchy: Observation -> Proposal -> Fact)
310// Note: types::Fact is the new governed Fact with PromotionRecord
311// The existing context::Fact remains for backward compatibility
312pub use types::{
313    // ID types (newtypes for type safety)
314    FactId, ObservationId, ProposalId, GateId, ApprovalId, ArtifactId,
315    ContentHash, Timestamp,
316    // Observation types (first tier - raw provider output)
317    Observation, ObservationKind, CaptureContext, ProviderIdentity,
318    // Proposal types (second tier - type-state pattern)
319    Proposal, Draft, Validated, ProposedContent as TypesProposedContent,
320    ProposedContentKind, ObservationProvenance,
321    // Fact types (third tier - promoted, governed)
322    // Note: types::Fact as TypesFact to avoid collision with context::Fact
323    Fact as TypesFact, FactContent, FactContentKind,
324    // Provenance types (audit/replay support)
325    PromotionRecord, EvidenceRef, TraceLink as TypesTraceLink,
326    LocalTrace, RemoteRef, Actor, ActorKind, ValidationSummary,
327    // Frame types (six-phase flow - framing)
328    FrameId, Frame, FrameConstraint, ConstraintKind, ConstraintSeverity as TypesConstraintSeverity,
329    Criterion, IntentId as TypesIntentId,
330    // Tension types (six-phase flow - tension/convergence)
331    TensionId, Tension, TensionSide, ConflictType, TensionResolution, ChosenSide, Hypothesis,
332    // Intent types (builder pattern)
333    TypesIntentKind, TypesObjective, RiskPosture, TypesIntentConstraint,
334    TypesBudgets, TypesRootIntent,
335    // Context types (builder pattern)
336    TypesContextKey, ContextBuilder, TypesContextSnapshot,
337    // Correction types (append-only corrections)
338    CorrectionEvent, CorrectionReason, CorrectionScope,
339    // Error types (thiserror)
340    TypeError, PromotionError, TypesValidationError, ObservationError, CorrectionError,
341};
342
343// Gate Pattern (agents suggest, engine decides)
344pub use gates::{
345    // Trait
346    ProposalLifecycle,
347    // Gate implementation
348    PromotionGate, ValidatedProposal, SimpleIntent,
349    // Validation types
350    CheckResult, ValidationContext, ValidationError as GatesValidationError,
351    ValidationPolicy, ValidationReport,
352    // Budget types (guaranteed termination)
353    CycleBudget, FactBudget, TokenBudget, ExecutionBudget,
354    // Stop reasons (exhaustive termination enumeration)
355    StopReason, ErrorCategory,
356    // Boundary types (constitutional kernel-platform contract)
357    AuthorityGrant, AuthorityGrantor, AuthorityScope,
358};
359
360#[cfg(test)]
361mod tests {
362    #[test]
363    fn crate_compiles() {
364        // Placeholder: proves the crate structure is valid
365    }
366}