manglekit

package module
v0.13.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ¶

Go License

Manglekit

Manglekit is the Zero-Trust Policy Gate for AI Agent Actions.

"LLMs propose, symbolic logic approves."

Modern AI applications require deterministic safety and auditability (financial limits, compliance checks, permission boundaries), but LLMs are inherently probabilistic (hallucinatory, jailbreakable, non-deterministic).

Manglekit solves this by placing every AI agent action behind a fail-closed, auditable Datalog gate before the action is dispatched.

  1. Deterministic Verification: Policies written in Datalog (Google Mangle) verify actions against relational facts, multi-tier priorities (T0–T3), and integer arithmetic (:gt, :lt, :ge, :le).
  2. Zero-Trust Supervision: A fail-closed gate interceptor evaluates incoming action requests before handler execution and verifies outputs afterward.
  3. Audit Provenance: Every denied or allowed action produces a mathematically grounded derivation tree proving which rule fired and why.
  4. Polyglot Sidecar: Run in-process in Go or as a lightweight HTTP/JSON sidecar (mkit serve) for Python, TypeScript, and multi-agent frameworks.

Quick Start: Enterprise Financial Guard

Three steps: define a Datalog policy, register a supervised action, and execute it through the gate.

1. Define the policy (policy.mg)

Gate payment refunds: require manager approval for amounts over $1,000 (100,000 cents), and block unverified destination accounts:

Decl amount_cents(Req, Cents).
Decl destination_account(Req, Account).
Decl account_verified(Account).
Decl manager_approval(Req, Approver).
Decl has_manager_approval(Req).

has_manager_approval(Req) :- manager_approval(Req, _).

% Trusted baseline accounts
account_verified("acc_verified_123").

% T1 Halt: refund exceeds threshold without manager approval
halt("Req", "refund exceeds limit without manager approval", "T1") :-
    action_operation("Req", "process_refund"),
    amount_cents("Req", Amount),
    :gt(Amount, 100000),
    !has_manager_approval("Req").

% T1 Halt: destination account is unverified (account takeover risk)
halt("Req", "refund destination account is unverified", "T1") :-
    action_operation("Req", "process_refund"),
    destination_account("Req", Acc),
    !account_verified(Acc).
2. Write the skill (main.go)
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/duynguyendang/manglekit"
    "github.com/duynguyendang/manglekit/adapters/func"
    "github.com/duynguyendang/manglekit/core"
)

type RefundRequest struct {
    AmountCents int    `mangle:"amount_cents"`
    Destination string `mangle:"destination_account"`
}

func main() {
    ctx := context.Background()

    client, err := manglekit.NewClient(ctx, manglekit.WithPolicyPath("policy.mg"))
    if err != nil {
        log.Fatalf("client init: %v", err)
    }
    defer client.Shutdown(ctx)

    // Register a supervised action
    client.RegisterSupervised("process_refund", function.New("process_refund",
        func(ctx context.Context, in RefundRequest) (string, error) {
            return fmt.Sprintf("Disbursed %d cents to %s", in.AmountCents, in.Destination), nil
        }))

    // Execute an unapproved $1,500 refund
    _, err = client.ExecuteByName(ctx, "process_refund", RefundRequest{
        AmountCents: 150000,
        Destination: "acc_verified_123",
    })

    if err != nil {
        fmt.Println("🛑 Action Blocked by Policy Gate:")
        fmt.Println(err)

        // Query the explanation proof tree
        expl, _ := client.Explain(ctx, `halt("Req", Reason, Tier)`, []string{
            `action_operation("Req", "process_refund").`,
            `amount_cents("Req", 150000).`,
            `destination_account("Req", "acc_verified_123").`,
        })
        fmt.Printf("\n--- Derivation Proof Tree ---\n%s\n", expl.String())
    }
}
3. Run it
go run .

Output:

🛑 Action Blocked by Policy Gate:
policy violation: blocked at tier T1 (rule: refund exceeds limit without manager approval) (action: process_refund): Supervisor Pre-Flight check failed. [matched: halt("Req", "refund exceeds limit without manager approval", "T1")]

--- Derivation Proof Tree ---
query: halt("Req", Reason, Tier)
halt("Req","refund exceeds limit without manager approval","T1")
  └─ via rule [T1]: halt("Req","refund exceeds limit without manager approval","T1") :- action_operation("Req","process_refund"), amount_cents("Req",Amount), :gt(Amount,100000), !has_manager_approval("Req").
  action_operation("Req","process_refund")
  └─ [base fact]
  amount_cents("Req",150000)
  └─ [base fact]
  150000 > 100000
  └─ [builtin]
  !has_manager_approval("Req")
  └─ [negation]

The handler was never called. The action was halted by the fail-closed supervisor before execution, and the audit trail contains the grounded arithmetic proof (150000 > 100000).


Canonical Guard Templates

Full runnable implementations and contract tests are available in manglekit-examples/governance/enterprise_guards:

  1. Financial & Refund Guard: Limits disbursements, prevents unverified destination rerouting, and enforces dual-authorization facts.
  2. Destructive Infrastructure Guard: Blocks terraform destroy, DROP TABLE, and container termination unless the requester is a verified owner and possesses a valid break-glass token.
  3. Communication & OTP Guard: Prevents outbound notification tools from transmitting authentication codes or PII to unverified phone numbers or unencrypted channels.
  4. Production Showcase — Mosaic: High-throughput data-cleaning and regulatory compliance pipeline running MangleKit in production.

System Architecture

MangleKit maintains a strict boundary between its governance core and optional extensions:

manglekit/
├── core/               # Domain vocabulary, types, errors (leaf package)
├── sdk/                # User facade: Client, Supervise, ExecuteByName, Explain
├── internal/
│   ├── supervisor/     # Zero-Trust Gate: fail-closed pre-check and post-check
│   └── engine/         # Datalog solver: Mangle runtime, AST analysis, IDB cache
├── adapters/           # Modular bridges: HTTP, MCP tools, Genkit, resilience
└── x/                  # Optional extensions (core never imports x/)
    ├── ooda/           # OODA loop runtime (ADR-004)
    ├── oodaflow/       # Genkit flow bridge for OODA
    ├── east/           # Entropy and steering (ADR-002)
    └── genes/          # Signed crystallized rule packages (ADR-003)
Trust Tiers

Policies in MangleKit are organized by four trust tiers:

Tier Name Semantics
T0 Axiom Hard safety boundary (cannot be overridden by any lower rule). Blocks immediately.
T1 Governance Organizational rules, limits, and role-based constraints. Blocks immediately.
T2 Playbook Advisory operational guidance. Surfaces warnings, logged in audit trail, non-blocking.
T3 User Preference Advisory user habits. Logged in audit trail, non-blocking.

Polyglot Usage: Sidecar Mode

For Python, TypeScript, and foreign runtimes, MangleKit runs as a standalone sidecar service:

# Start the HTTP policy gate
mkit serve --port 8080 --policy policy.mg

Send tool-call intent to /v1/assess before executing it in your agent runtime. Decisions are returned with decision IDs, SHA-256 policy fingerprints, and complete derivation trees.


Contributing & Development

make test       # go test -race -count=1 ./... -v
make coverage   # coverage report (gate >= 60%)
make build      # build mkit CLI

See CONTRIBUTING.md for pull request guidelines.

License

Apache 2.0

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func Define ¶

func Define[In any, Out any](
	c *Client,
	name string,
	handler func(context.Context, In) (Out, error),
) *sdk.Runnable[In, Out]

Define is the public entry point for creating Actions

func MustReadFile ¶ added in v0.4.0

func MustReadFile(path string) []byte

MustReadFile reads the file at path and panics on error. It is a small convenience for example/demo setup code where a missing fixture is fatal.

The path is resolved cwd-independently for relative paths: if the file cannot be found relative to the current working directory, it is resolved relative to the source directory of MustReadFile's caller (via runtime.Caller). This makes examples and tests work whether they are run from the repo root, the example's directory, or `go test`.

func NewRequestEnv ¶ added in v0.4.0

func NewRequestEnv(text, action string, labels []string) core.Envelope

NewRequestEnv builds an envelope for a request gated by a policy. It sets the payload to text, attaches the provided security labels (e.g. "tainted"), and emits an action_operation fact so policies keyed on the action name can match.

func WithExtractor ¶ added in v0.7.0

func WithExtractor(action core.Action, ext ports.Extractor) core.Action

WithExtractor sets the text-to-struct extractor on a supervised action, enabling the neuro-symbolic bridge.

Types ¶

type Client ¶

type Client = sdk.Client

--- Aliases ---

func Must ¶

func Must(c *Client, err error) *Client

Must helper for panic-on-error initialization

func MustNewClient ¶ added in v0.4.0

func MustNewClient(ctx context.Context, opts ...ClientOption) *Client

MustNewClient creates a client and panics if initialization fails.

func NewClient ¶

func NewClient(ctx context.Context, opts ...ClientOption) (*Client, error)

NewClient initializes the client with defaults. It implements the "Batteries Included" philosophy by leveraging SDK defaults.

func QuickClient ¶ added in v0.7.0

func QuickClient(ctx context.Context, policyPath string) (*Client, error)

QuickClient is the shortest path to a governed client: it constructs a Client and loads the Datalog policy at policyPath (same as WithPolicyPath), returning typed errors for a missing file or an invalid policy. For anything beyond a policy file, use NewClient with options.

client, err := manglekit.QuickClient(ctx, "policy.mg")

type ClientOption ¶

type ClientOption = sdk.ClientOption

func WithConfig ¶ added in v0.7.0

func WithConfig(cfg *config.Config) ClientOption

WithConfig applies settings from a loaded configuration struct.

func WithConfigFile ¶ added in v0.7.0

func WithConfigFile(path string) ClientOption

WithConfigFile loads configuration from a YAML file and applies it.

func WithEngine ¶ added in v0.7.0

func WithEngine(e core.Evaluator) ClientOption

WithEngine allows injecting a custom or mock core.Evaluator.

func WithHistory ¶

func WithHistory(store core.HistoryStore) ClientOption

WithHistory sets only the chat-history component of the memory, composing with an existing HybridMemory. It returns an error at construction time (rather than silently discarding it) if a custom non-hybrid memory was configured via WithMemory.

func WithLLM ¶ added in v0.7.0

func WithLLM(gen core.TextGenerator) ClientOption

WithLLM configures the AI backend for the client.

func WithLogger ¶

func WithLogger(l core.Logger) ClientOption

WithLogger sets a custom logger for the client.

func WithMemory ¶

func WithMemory(mem core.AgentMemory) ClientOption

WithMemory replaces the whole memory implementation (history + RAG).

func WithPolicyPath ¶

func WithPolicyPath(path string) ClientOption

WithPolicyPath specifies the file path of the Datalog policy to load at client construction. This is the canonical option name; it matches config `policy.path` and the CLI `--policy` flag.

func WithProviderConfig ¶ added in v0.7.0

func WithProviderConfig(name string, cfg config.ActionConfig) ClientOption

WithProviderConfig wires a provider-backed action from config.

func WithStateProvider ¶ added in v0.7.0

func WithStateProvider(provider core.StateProvider) ClientOption

WithStateProvider configures durable session persistence.

func WithStdoutTracer ¶ added in v0.7.0

func WithStdoutTracer() ClientOption

WithStdoutTracer enables a console tracer for debugging.

func WithSteeringEnabled ¶ added in v0.7.0

func WithSteeringEnabled() ClientOption

WithSteeringEnabled enables policy-driven routing (route/retry).

func WithTracerProvider ¶ added in v0.7.0

func WithTracerProvider(tp trace.TracerProvider) ClientOption

WithTracerProvider configures the OpenTelemetry tracer provider.

type ExecuteOption ¶

type ExecuteOption = sdk.ExecuteOption

func WithMetadata ¶

func WithMetadata(key, value string) ExecuteOption

WithMetadata injects custom key-value pairs into the execution envelope's metadata.

func WithSessionID ¶

func WithSessionID(id string) ExecuteOption

WithSessionID activates persistent stateful mode for the execution.

func WithTransientMemory ¶

func WithTransientMemory() ExecuteOption

WithTransientMemory activates in-memory stateful mode.

Directories ¶

Path Synopsis
adapters
ai
mcp
scoring
Package scoring brings the fixed-choice classification pattern — score a small set of single-token options, normalize over exactly those labels, and let a policy decide what may act — into the kernel.
Package scoring brings the fixed-choice classification pattern — score a small set of single-token options, normalize over exactly those labels, and let a policy decide what may act — into the kernel.
storage/meb
Package meb provides a MEB (Mangle Extension for Badger) storage adapter that implements the KnowledgeStore interface for the OODA loop.
Package meb provides a MEB (Mangle Extension for Badger) storage adapter that implements the KnowledgeStore interface for the OODA loop.
storage/session
Package session provides a transient, in-memory store for coordination facts during OODA loop execution.
Package session provides a transient, in-memory store for coordination facts during OODA loop execution.
cmd
mkit command
mkit/commands/check
Package check implements the `mkit check` and `mkit lint` subcommands: load, parse, compile, and lint a Datalog policy without running a query.
Package check implements the `mkit check` and `mkit lint` subcommands: load, parse, compile, and lint a Datalog policy without running a query.
mkit/commands/exitcode
Package exitcode defines the mkit CLI exit-code contract and maps errors to exit codes.
Package exitcode defines the mkit CLI exit-code contract and maps errors to exit codes.
mkit/commands/test
Package testcmd implements the `mkit test` subcommand: declarative fixture testing for Datalog policies without writing Go code.
Package testcmd implements the `mkit test` subcommand: declarative fixture testing for Datalog policies without writing Go code.
mkit/commands/version
Package version implements the `mkit version` subcommand.
Package version implements the `mkit version` subcommand.
internal
providers
predicates
Package predicates provides reference external predicates for use in Datalog policies.
Package predicates provides reference external predicates for use in Datalog policies.
Package scenario provides a tiny, dependency-free test harness for running behavior-driven policy scenarios against a Manglekit client.
Package scenario provides a tiny, dependency-free test harness for running behavior-driven policy scenarios against a Manglekit client.
sdk
Package sdk provides the Manglekit SDK.
Package sdk provides the Manglekit SDK.
Package testutil provides deterministic, dependency-free test doubles for building examples and tests against manglekit without external services or API keys:
Package testutil provides deterministic, dependency-free test doubles for building examples and tests against manglekit without external services or API keys:
x
agents
Package agents provides the Architect Agent implementation using the OODA Chassis SDK with Dual Memory architecture.
Package agents provides the Architect Agent implementation using the OODA Chassis SDK with Dual Memory architecture.
agents/tools
Package tools provides the tool implementations for the Architect Agent
Package tools provides the tool implementations for the Architect Agent
east
Package east implements EAST (Entropy-Activity-Steering-Throttling), the OODA v4 generative/research path.
Package east implements EAST (Entropy-Activity-Steering-Throttling), the OODA v4 generative/research path.
genes
Package genes provides an OPTIONAL, file-based "crystallized logic" extension for learned Datalog rules — genes — that are applied to the policy engine through its official source channel (sdk.Client.LoadPolicy).
Package genes provides an OPTIONAL, file-based "crystallized logic" extension for learned Datalog rules — genes — that are applied to the policy engine through its official source channel (sdk.Client.LoadPolicy).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL