Behavior Rules
A behavioral design pattern that lets an AI agent switch between behaviors at runtime as its context changes.
Intent
Define an agent's behaviors as independent rules. Each rule describes a situation the agent can recognize and an action it can take. Evaluate the rules against the agent's current context so that the same agent can respond differently over the course of a task.
Problem
Consider two coding agents working on the same project. One reads a file and prepares an edit. While it is reasoning, the other agent changes the file. The first agent still has the same goal and the same pending tool call, but the edit was prepared against an earlier version. It now needs to read the file again and reconsider the change.
It is straightforward to add a version check to the file tool. Then a reviewer asks to approve changes to a particular file. An agent working alone can usually proceed, an agent with a stale edit should reconsider, and an agent awaiting review should wait. Each behavior makes sense on its own. Embedding all three in the tool makes file editing responsible for decisions about reasoning and collaboration. Putting them all in the loop gives the loop the same burden.
How can an agent acquire new ways of handling a situation while keeping the mechanics of running the agent stable?
Solution
Represent each behavior as a rule that pairs a condition with an action. Group the rules that an agent can use into a policy. Whenever the agent reaches a decision point, evaluate its policy against the facts available at that moment.
Three operations give the pattern its shape.
- Observe the situation. Capture the facts that matter to this decision, such as the pending edit, the revision the agent read, and the current revision.
- Evaluate the rules. Test each relevant condition against those facts. The policy determines how to handle overlapping behaviors when they can occur together.
- Apply the behavior. Give the action the input it needs. When its result or an external event changes the situation, evaluate again at the next decision point.
The rules themselves can stay the same throughout a run. An agent that could apply an edit a moment ago can now reconsider it because one fact changed. A developer can also give the agent another behavior by extending its policy.
Structure

The diagram shows the conceptual model. Mozaik represents a rule as a definition that refers to a condition, an input resolver, and a command by name.
Participants
| Participant | Responsibility |
|---|---|
| Agent | Reaches a decision point and supplies the context needed to decide how to act. |
| Agent context | Describes the situation at that point. It can include facts about the agent, its environment, and its peers. |
| Policy | Groups the behaviors available to the agent and defines how applicable rules take effect. |
| Behavior rule | Associates a recognizable situation with an action. |
| Condition | Determines whether the situation described by a rule holds. |
| Input resolver | Maps the current agent context to the input expected by the command. |
| Command | Carries out the response or returns a directive for the agent harness to carry out. |
Collaborations
The agent reaches a pending file edit. Its harness supplies the policy with the revision the agent read and the revision now in the workspace. The condition examines those facts. When its rule applies, the input resolver extracts the file path from the context. The command receives that path and returns a directive telling the harness how to proceed.

Reconsidering an edit creates a fresh decision point. The agent checks the revised edit too, since a peer may have changed the file again.
Implementation
The following TypeScript example uses the rule definition, conditions, resolvers, commands, and policy evaluation API from Mozaik Rule Engine. The edit context and directives are specific to this example.
1. Model the agent's situation
type EditContext = {
path: string
readRevision: string
currentRevision: string
}
type EditInput = { path: string }The harness evaluates this policy when an edit is pending. It already holds the proposed edit, so the rules only need the facts that can change the decision.
2. Define the conditions
@Condition({ name: "revision-current" })
class RevisionCurrent extends ConditionContract<EditContext> {
isSatisfiedBy(edit: EditContext) {
return edit.readRevision === edit.currentRevision
}
}
@Condition({ name: "revision-changed" })
class RevisionChanged extends ConditionContract<EditContext> {
isSatisfiedBy(edit: EditContext) {
return edit.readRevision !== edit.currentRevision
}
}3. Resolve the action input
@InputResolver({ name: "edit-input" })
class ResolveEditInput implements InputResolverContract<EditContext, EditInput> {
async resolve(edit: EditContext): Promise<EditInput> {
return { path: edit.path }
}
}Both actions need the file path. The revision comparison belongs to the conditions.
4. Represent the behaviors as commands
type EditDirective = {
type: "apply-edit" | "reconsider-edit"
path: string
}
@Command({ name: "apply-edit" })
class ApplyEdit implements CommandContract<EditInput, EditDirective> {
invoke({ path }: EditInput): EditDirective {
return { type: "apply-edit", path }
}
}
@Command({ name: "reconsider-edit" })
class ReconsiderEdit implements CommandContract<EditInput, EditDirective> {
invoke({ path }: EditInput): EditDirective {
return { type: "reconsider-edit", path }
}
}The harness handles these directives. For the first, it attempts the pending write against the expected revision. For the second, it discards the stale proposal, reads the latest contents, and returns them to the model.
5. Compose the agent's policy
const editPolicy: PolicyDefinition = {
rules: [
{
condition: "revision-current",
inputResolver: "edit-input",
command: "apply-edit",
},
{
condition: "revision-changed",
inputResolver: "edit-input",
command: "reconsider-edit",
},
],
}These conditions are mutually exclusive. For policies whose conditions overlap, Mozaik executes the highest-priority match. Another implementation could apply several compatible behaviors, such as recording a review request and notifying the reviewer.
6. Evaluate at the decision point
const rule = await this.ruleEvaluator.findMatchingRule(policy, state)
if (!rule) {
return undefined
}
const inputResolver = this.inputResolverRegistry.get(rule.getInput())
if (!inputResolver) {
throw new Error(`Input ${rule.getInput()} not found`)
}
const input = await inputResolver.resolve(state)
const command = this.commandRegistry.get(rule.getCommand())
if (!command) {
return undefined
}
return await command.invoke(input)Evaluation finds the rule whose condition holds, resolves that rule's input, and invokes its command. A missing input resolver is an error. No matching rule, or a command that is not registered, means there is nothing to apply.
Example
Two agents are moving a function to a new module. The first prepares a change to its callers using revision 17. Before it writes, the second agent moves the function and commits revision 18. The first agent's policy directs it to reread the file. It discovers that one of its planned edits is already present and prepares a smaller change.
At the next decision point, the agent has read revision 18 and the workspace still contains revision 18. The same policy now directs it to apply the smaller edit. Its goal, tools, and rule definitions stayed the same throughout the task.
Consequences
Benefits
- Behaviors can evolve independently. A developer can introduce a review requirement through a condition and an action while preserving the agent loop.
- One agent can handle more situations. A change in the environment, a tool result, or a message from a peer can make a different response applicable during the same task.
- Decisions can be tested directly. A test can supply two revisions and verify the resulting directive without running inference or modifying a file.
Liabilities
- The context must expose the relevant facts. An agent that records only the file path cannot recognize that its proposed edit is stale.
- Rules can interact. If an edit is both stale and awaiting approval, the policy needs to say whether the agent should reconsider it first or seek approval for the current proposal.
- Facts can change after evaluation. For a shared file, the write itself must check the expected revision. A conflict gives the agent a new situation to evaluate.
Applicability
Use Behavior Rules when the same agent should respond differently at the same decision point depending on what has happened during execution. Typical cases include a coding agent coordinating edits with peers, a research agent seeking another source when evidence conflicts, and a support agent requesting human review when a customer disputes a proposed resolution.
The pattern earns its place when these responses have independent reasons to change and embedding each one in the loop makes the agent harder to extend.
Related patterns
- Loop Breakpoint. Exposes a pending instruction before it executes. Behavior Rules can use that boundary to decide how the agent should respond.
- Specification. Encapsulates a condition such as whether a revision is current. A behavior rule connects that condition to an action.
- Command. Encapsulates the action a rule invokes. Several rules can reuse the same command when different situations call for the same response.
Conclusion
A coding agent can prepare a valid edit and still need to reconsider it by the time it writes. Behavior Rules gives that change of mind an explicit place in the design. The developer defines the situations the agent recognizes and the actions available to it. As the task unfolds, the agent evaluates those rules again and changes how it acts.
References
Implementation: Mozaik Rule Engine — a TypeScript implementation of the rule engine.
Related pattern: Loop Breakpoint — the execution boundary at which an agent can consult its rules before the next instruction runs.