Skip to main content

AI Governance & Audit: Setting Rules for AI

When 80% of business code is generated by AI, a brand-new engineering challenge emerges: How do we ensure every line of code written by AI is auditable, interpretable, and strictly authorized?

Traditional coding standards rely on documentation and Code Review, but AI won't read your Wiki, nor will it attend stand-up meetings. TeaQL's answer is: Encode the rules directly into the compiler, so non-compliant code simply won't compile.

1. MustComment: Compiler-Enforced Semantic Annotation

At the application layer of TeaQL, the return values of all tool calls (whether pure computation or IO operations) are wrapped in a zero-cost sealed structure MustComment<T>. If the developer (or AI) fails to call .comment("business intent"), the real data cannot be extracted, and the compiler will throw an error immediately.

// ❌ Compilation Error: MustComment<String> cannot be used as String
let my_id = ctx.id().uuid();

// ✅ Compilation Passed: AI is forced to write down a business explanation
let my_id = ctx.id().uuid().comment("Generate trace ID for payment callback");

Why is this important?

This means there is no code executing for unknown reasons in a TeaQL application. Every computation, every network request, and every file I/O comes with a human-readable English intent description. This description is:

  • For humans: New engineers can read the business context for every line.
  • For AI: AI Agents can understand the intent behind every step during debugging.
  • For auditors: During compliance reviews, every IO operation has an undeniable motivation record.

Zero Performance Overhead

MustComment<T> uses the #[repr(transparent)] attribute, meaning its memory layout is identical to the original type. The .comment() method is marked with #[inline(always)], which will be completely optimized down to zero instructions by LLVM in Release builds. This is not a runtime check, but a pure compile-time constraint.

2. Context Facade: A Complete Ban on Stateless Calls

TeaQL provides a powerful static tool facade T:: (for time, IDs, cryptography, etc.), but at the application layer, T:: is completely banned.

Why?

Because T::time().today() returns "today" based on the server's physical time zone. In a globalized system, "today" in Beijing is not the same as "today" in New York. If an AI calls T::time().today() directly, it could lead to catastrophic errors in cross-timezone business logic.

TeaQL strictly mandates that all application-layer code initiates calls through the UserContext (ctx). The ctx carries crucial context such as the current request's time zone, language, and operator identity:

// Correct: ctx automatically injects the tenant's time zone and returns an accurate local date
let deadline = ctx.time().today().add_days(7).comment("Calculate payment deadline");

// Correct: ctx automatically records the operator's identity and audit trail
let data = ctx.http().get("https://api.partner.com/rates")
.comment("Fetch exchange rates for settlement")
.await?;

Compiler-Level Physical Isolation

By configuring clippy.toml at the project root, architects can proactively block all attempts to bypass ctx at the compiler level once and for all:

disallowed-types = [
"teaql_tool::T", # Ban stateless tool facade
"chrono::Utc", # Ban context-bypassing time fetching
"chrono::Local",
"std::fs::File", # Ban low-level direct file operations
]

disallowed-methods = [
"std::fs::read",
"std::fs::write",
"reqwest::get",
"std::process::Command::new",
]

Any code attempting to call std::fs::read() or T::time().today() directly in business logic will be instantly blocked at compile time, regardless of whether it was written by a human or an AI.

3. Closed Audit Configuration: Order from the Menu, Stay Out of the Kitchen

Traditional logging frameworks (like log4j or tracing) fully expose logging APIs to developers. Developers can call log.info() or tracing::debug!() arbitrarily, leading to inconsistent log quality, chaotic formatting, and missing records for key operations.

TeaQL takes a radically different approach: The application layer cannot see any logging APIs. The only thing developers can do is annotate intent via .comment(), and select an audit level from a closed enum menu.

Modular Audit Configuration

// Production environment: Full audit for IO, silent for pure computations
let ctx = UserContext::new()
.with_audit_config(AuditConfig::production());

// Development & debugging: Focus only on the HTTP module, silence everything else
let ctx = UserContext::new()
.with_audit_config(AuditConfig::focus_on(Module::Http));

// Deep troubleshooting: Full audit for HTTP + Full audit for Money, silence the rest
let ctx = UserContext::new()
.with_audit_config(
AuditConfig::silent_all()
.enable(Module::Http, AuditLevel::FullWithPayload { max_bytes: 4096 })
.enable(Module::Money, AuditLevel::Full)
);

Four Audit Levels

LevelOutput ContentTypical Scenarios
SilentNo outputCI testing, pure computation modules
SummaryOperation type + DurationSecurity modules, performance monitoring
FullOperation type + Intent + Target + Duration + Trace IDProduction compliance auditing
FullWithPayloadFull + Request/Response body (truncated)Deep troubleshooting, financial-grade auditing

Why use a closed enum?

AuditLevel and Module are both Rust Enums marked with #[non_exhaustive], rather than open-ended Traits. This means:

  • ✅ The application layer can choose from predefined audit strategies
  • ❌ The application layer cannot customize new audit strategies
  • ❌ The application layer cannot invoke any low-level logging APIs

It's like a vending machine: you can press A, B, or C to choose a drink, but you cannot open the machine to mix it yourself.

4. Optimized Full-Chain Closed Loop for AI Agents

The true value of this architecture lies in the fact that it not only constrains AI, but it also serves AI.

AI writes code → Must write .comment() → Compiler enforces compliance

Framework automatically generates structured audit logs

AI reads logs to understand runtime behavior

AI locates and fixes Bugs based on logs

The fixed code comes with .comment() again ...

In this closed loop:

  • The code is written by AI, with mandatory business intent annotations on every line.
  • Logs are auto-generated by the framework, uniformly formatted, structured, and machine-parseable.
  • Debugging is done by AI, precisely focusing on problematic modules via AuditConfig::focus_on(Module::Http).
  • Human architects only need to do two things: define whitelists and adjust audit levels.

No Recursive Auditing Issues

The auditing system itself belongs to the Infrastructure Layer and is inherently exempt from audit constraints. .comment() is not a logging command—it is a static semantic annotation. Whether it gets translated into an audit log is entirely determined by the framework according to the AuditConfig configuration. Developers have neither the authority to interfere nor the need to be aware of this.

Summary: Fundamental Differences from Competitors

DimensionTraditional ORM / FrameworkTeaQL
Code CommentsRelies on discipline (optional)Compiler-enforced (error if omitted)
IO AuditingManual log.info() callsAuto-captured by framework (transparent to dev)
Logging APIFully open, called arbitrarilyCompletely closed, configuration only
Time Zone SafetyHandled by developersAuto-injected by framework from Context
AI GovernanceRelies on Prompt remindersCompiler + Clippy physical isolation

TeaQL isn't "suggesting" how AI should write code; it is "forcing" AI to strictly follow the rules. This is the world's first data runtime framework that elevates AI governance from "prompt constraints" to "compiler constraints".