Skip to content
awatermaPublic

About

A RETE rules engine for durable enforcement of project conventions in LLM-assisted work.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Phronesis

Practical wisdom for LLM-assisted work.

Phronesis (φρόνησις) is a domain-neutral RETE rules engine designed to provide durable, deterministic governance for non-deterministic AI agents. It addresses the "contextual drift" that occurs in long-running LLM sessions, where project-specific guidance (like CLAUDE.md) slowly fades as the context window fills and auto-compaction triggers.

Rules in Phronesis live on disk, are evaluated by lightweight hooks at the moment of action, and fire the same in token nine hundred thousand as they do in token eight hundred.

Community

Using Phronesis, trying it out, or deciding whether it fits? Tell us what you're building. Experiments, questions, and feedback are welcome; sharing a project link is optional. Visit Discussions for Q&A, ideas, and show-and-tell, or Issues for reproducible bugs. Please keep private source code and credentials private.

Public community signals explains our weekly snapshots and why downloads and search hits are not user counts.

For AI Coding Agents

Phronesis provides persistent code graphs, rule-based inference, provenance, and verification evidence through MCP. If you are an AI coding agent working on code analysis, change impact, test selection, or verification, see Phronesis for Coding Agents to decide whether it helps with your task — including a read-only way to evaluate it on your own repository. (Working on Phronesis itself? See AGENTS.md.)

Go and contributor language packs

phr-mcp init --packs go selects the bundled Go starter's structural rules and go build / go vet / textual go test toolchains. phr-mcp pack list --json shows built-in and installed packs; list_language_packs {} provides the same read-only inventory to a connected MCP client. External authors can use bundled grammars, queries, bounded Rhai, fixtures, and namespaced rules without changing the core adapter. See Language packs and the query-only/Rhai Python starter. Source relationships are static evidence; run the actual compiler and tests.

The Premise

Anthropic's Claude Code, OpenAI Codex, Google's Gemini CLI, and other LLM environments share a common pattern: they load project-level guidance at session start. As the session continues, that window fills with code, output, and conversation. The directive you most need at hour three may have last been read carefully in token eight hundred.

Phronesis moves enforcement out of the conversation entirely. Rules live in .phronesis/rules.json, are re-read by hooks at every tool call, and fire from outside the context window. They cannot be compressed away because they were never loaded into context to begin with.

How It Works

A Phronesis tool call flows through a host hook and RETE matching to an allow, warn, or block decision.

At the top level, Phronesis is a boundary around agent actions: the host normalizes a proposed tool call, the engine evaluates durable rules, and the host receives an allow, warning, or blocking decision.

Next: open the visual explainer for the end-to-end hook lifecycle and the Alpha-memory, Beta-join, and production-state internals. From there, the rule catalogue shows exactly how those mechanics become concrete governance.

Subsystems

Beyond the syntactic language packs, the default platform includes grounded subsystems that extend enforcement past pattern-matching on edits.

Five durable Phronesis subsystems feed one governance core: context, journey, confidence, structural graph, and drift.

Durable context keeps compact project guidance in .phronesis/durable.md and re-injects it at session and interaction boundaries. It preserves the smallest high-value instructions; enforcement still belongs in rules.

Confidence scoring (SPEC-confidence-scoring) reads build, test, and known-bug signals through declarative toolchain definitions: Cargo, xcodebuild, and SwiftPM ship as built-ins, while .phronesis/toolchains.json can extend or override the registry for other toolchains. A generic parser turns matched command outcomes into neutral signals and warns on Git mutations when confidence evidence is incomplete or failing — three grounded signals say "this is real," not three syntactic checks. The default platform writes .phronesis/confidence.json; phr-mcp confidence reports the current band.

Journey facts (SPEC-journey-facts) keep a durable per-call journal under .phronesis/journey/ and let project-defined taggers in .phronesis/journey.json stamp executed tool calls. journey_* aggregator facts (occurrence, count, seen, since-last, distinct) over c/m/h/d/s windows let rules match cross-call temporal patterns — auth churn over a session, recent SQL in the last five calls, build staleness — without any in-memory accumulation. Surfaces: phr-mcp journey and the get_journey MCP tool.

Lifecycle events (SPEC-agent-lifecycle-events) record the shape of the conversation around those tool calls — sub-agent start and stop, human prompts classified fresh / mid_turn / correction, interrupts, turn stops, and commits detected from HEAD movement rather than command text. A mid_turn or correction prompt is an intervention: the human changing the plan, not merely replying. Rules match them through lifecycle:* and kalpa:* selectors in the same journey_* family; existing journey rules are unchanged. phr-mcp kalpa names a theme spanning sessions and phr-mcp unit names the work item an agent is building, so phr-mcp stats, phr-mcp kalpa show, and phr-mcp unit show can report interventions per commit and governed throughput against a stated retention window. Prompt text lives only in the gitignored action log, never in the journal.

Structural code graph parses Rust, Python, TypeScript, Swift, and Java into queryable relations such as defines_fn, calls_api, tested_by, and no_direct_test. Rules can bind to concrete code referents, structural packs can reason over relationships, and clients can inspect freshness or rebuild derived state over MCP.

Java discovers Maven and Bazel compilation units and reports dependencies between declared packages. The existing structural pack warns about package import cycles. Build-file edits refresh unchanged importers; diagnostics expose unsupported build constructs and unresolved project imports. See the Java design and limitations for the classpath approximation and corpus-validation requirements.

The default base is intentionally language-neutral: it includes LLM, confidence, journey, structural-graph, and durable-context capabilities. Selecting a language pack adds only that language's syntax and rules; graph construction and the other shared subsystems are already present.

Source code becomes typed structural relations, rule bindings, freshness evidence, and recoverable MCP graph state.

get_code_graph_status reports freshness, generation, and binding state; query_code_graph retrieves relationships; rebuild_code_graph rebuilds the server-rooted graph and reconciles bindings. If graph or binding state is corrupt or mismatched, Phronesis preserves blocking authority rather than silently treating missing evidence as safe.

Drift detection compares rules with durable guidance, agent memory, ADR decisions, and bound code. phr-mcp drift consolidates those sources into review leads. Its similarity and staleness findings are evidence for triage, not proof that documentation or enforcement is wrong.

Extensible predicates (SPEC-extensible-predicates) let project Rhai providers under .phronesis/predicates/ derive new, validated LHS facts from normalized hook events. Multi-file operations expose a once-per-operation event.files change-set view before per-file event.file_path evaluation. MCP tools can test and manage providers, allowing an agent to add new predicate vocabulary before adding the rules that consume it.

The Workspace

  • phronesis (crates/phronesis) — The core library: a high-performance, domain-neutral RETE rules engine (Alpha/Beta networks, P-states, join-sharing) with Consequence/Actor/Provenance primitives.
  • phronesis-governance (embedding guide) — Policy compilation, ordered composition, isolated fact-snapshot evaluation, and structured decisions. Embedders supply facts and evaluators; repository discovery, storage, and transport stay in adapters.
  • phronesis-mcp (crates/phronesis-mcp) — An MCP server that hosts the engine behind Claude Code, Codex, and Gemini CLI hooks. Builds the phr-mcp binary.
  • phronesis-rhai (crates/phronesis-rhai) — A sandboxed Rhai evaluator for __script__ guard conditions and extensible predicate providers. The MCP binary enables it by default.

Documentation

All documentation lives in one canonical hierarchy under docs/: tutorials, guides, reference, architecture, decisions, specs, contributing, and archive — start at the documentation index. Rendered on GitHub Pages: awaterma.github.io/phronesis (explainer, catalogue).

Highlights: Loop-Based Agent Programming · Phronesis for Coding Agents · Command Reference · Specs · Contributing

Quick Start

# 1. Install the binary
cargo install --path crates/phronesis-mcp

# 2. Register as a global MCP server
phr-mcp install

# 3. Initialize Phronesis in your project
cd /your/project && phr-mcp init --packs rust

# Inspect local state and remove only rebuildable graph caches
phr-mcp state
phr-mcp clean --cache

state distinguishes authored configuration from caches, history, runtime state, backups, and potentially sensitive payload captures. clean --cache removes only graph.jsonl, graph.index, and bindings.json; rebuild them with phr-mcp graph rebuild.

Codex uses the generated project-local .codex/hooks.json and .codex/config.toml. Review new or changed hooks with /hooks; Phronesis does not bypass Codex's trust flow.

Refreshing starter rules

Run phr-mcp init --rules-only --packs llm,rust to add new starter rules and upgrade unchanged ones while preserving local edits and custom rules. The .phronesis/starter-rules.json baseline records installed starter definitions; older projects without it keep conflicting definitions and receive warnings. Use --dry-run to preview or --force to replace the selected rules file.

The Rust code graph also traces Rhai registrations through single-expression forwarding closures, including a single call inside a block. Complex closures remain unresolved rather than assigning an arbitrary backing function.

Lineage

The engine is a modern Rust implementation of the RETE algorithm (Forgy, 1982). It was extracted from a high-performance game logic system and repurposed for LLM-agent governance.

Aristotle distinguished Episteme (theoretical knowledge) from Phronesis (practical wisdom). Phronesis is the deliberative virtue of knowing what to do here, now, in this particular case. This project aims to preserve that wisdom across the "fading" boundaries of modern AI interaction.

License

MIT. See LICENSE.

About

A RETE rules engine for durable enforcement of project conventions in LLM-assisted work.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages