# How the Rules Module Interacts with the Graph Module in Hivemind

> Discover how Hivemind's rules module and graph module interact. The rules module stores governance logic, while the graph module uses it to enforce policies and validate mutations.

- Repository: [Activeloop/hivemind](https://github.com/activeloopai/hivemind)
- Tags: internals
- Published: 2026-06-11

---

**The rules module persists governance logic to the `hivemind_rules` table while the graph module queries this data to enforce policies, render LLM context blocks, and validate mutations across the workspace.**

In the `activeloopai/hivemind` repository, the rules and graph modules form a tight bidirectional integration that governs how agents interact with workspace data. Understanding how the rules module interacts with the graph module is essential for implementing custom policies and contextual prompts. This coupling ensures that rule definitions drive graph rendering, query execution, and access control through a shared SQL-based storage layer.

## Architecture Overview

The interaction operates across four distinct layers that bridge data persistence and policy enforcement.

| Layer | Rules Module Responsibility | Graph Module Consumption |
|-------|----------------------------|-------------------------|
| **Data-layer** | Persists rule objects to `hivemind_rules` via [`src/rules/write.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/write.ts) and [`src/rules/read.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/read.ts) | Calls `ensureRulesTable()` to lazily initialize or heal the rules table before operations |
| **Query-layer** | Exposes `SELECT` queries returning versioned rule records | Executes rule queries first, then merges results with goal data (`hivemind_goals`) for context rendering |
| **Execution-layer** | Holds logic for rules like `localMinedRule` and `referralInviteRule` | Listens for rule matches via session hooks to update node metadata or trigger side effects |
| **Policy-layer** | Defines scopes (`team`, `project`) and versioning constraints | Validates rule scopes before allowing edge mutations, ensuring authorized access |

## Data Persistence: Writing Rules to the Graph Store

The rules module treats the SQL database as the source of truth. In [`src/rules/write.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/write.ts), the `writeRule` function translates JSON rule specifications into parameterized SQL statements that populate the `hivemind_rules` table.

```typescript
// src/rules/write.ts – persisting a new rule
import { api } from '../utils/sql';

export async function writeRule(rule: Rule) {
  await api.run(`
    INSERT INTO "hivemind_rules"
    (rule_id, text, match, version, created_at, agent, assigned_by)
    VALUES (?, ?, ?, ?, datetime('now'), ?, ?)
  `, [rule.id, rule.text, rule.match.source, 1, rule.agent, rule.assignedBy]);
}

```

This function uses the shared `api` instance from [`src/utils/sql.ts`](https://github.com/activeloopai/hivemind/blob/main/src/utils/sql.ts), ensuring that both modules operate on the same underlying Deeplake driver. The graph module relies on this persistence layer to access rule definitions during workspace initialization.

## Query Integration: Fetching Rules for Graph Operations

When the graph module needs to build LLM context, it queries the rules table before fetching goals. The `renderContextBlock` utility in [`src/graph/renderContextBlock.ts`](https://github.com/activeloopai/hivemind/blob/main/src/graph/renderContextBlock.ts) demonstrates this sequence: it first selects all rules from `hivemind_rules`, formats them into a **HIVEMIND RULES** section, then appends goal data.

```typescript
// src/graph/renderContextBlock.ts – pulling rules into a prompt
import { api } from '../utils/sql';

export async function renderContextBlock(opts) {
  const rules = await api.query(`SELECT * FROM "hivemind_rules" ORDER BY version DESC`);
  const ruleSection = formatRules(rules);          // creates “HIVEMIND RULES” text
  const goals = await api.query(`SELECT * FROM "hivemind_goals"`); // may be empty
  return `${ruleSection}\n${formatGoals(goals)}`;
}

```

By querying the rules table directly, the graph module treats rules as first-class metadata. The shared schema discovery mechanism (`api.listTables()`) automatically includes rule tables in the graph's available dataset.

## Execution and Policy Enforcement

Beyond data retrieval, the rules module enforces behavioral constraints on graph mutations. When a rule's `match` pattern corresponds to a node or edge, execution hooks in the graph module fire associated actions. The policy layer validates rule scopes—such as `team` or `project` assignments—before permitting edge modifications.

This enforcement ensures that only authorized agents can modify specific graph partitions. The graph module checks these scopes during mutation operations, effectively using the rules module as an authorization backend.

## Key Files in the Integration

The following source files define the contract between the two modules:

- **[`src/rules/write.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/write.ts)**: Handles CRUD operations for rule persistence, including version management and agent assignment.
- **[`src/rules/read.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/read.ts)**: Provides SELECT helpers for fetching the latest rule versions.
- **[`src/graph/renderContextBlock.ts`](https://github.com/activeloopai/hivemind/blob/main/src/graph/renderContextBlock.ts)**: Consumes rule data to construct LLM prompt sections.
- **[`src/utils/sql.ts`](https://github.com/activeloopai/hivemind/blob/main/src/utils/sql.ts)**: Shared database driver used by both modules for schema discovery and query execution.
- **[`tests/shared/graph/layers.test.ts`](https://github.com/activeloopai/hivemind/blob/main/tests/shared/graph/layers.test.ts)**: Validates that root-level folders follow the same rule constraints as nested structures.
- **[`tests/shared/context-renderer.test.ts`](https://github.com/activeloopai/hivemind/blob/main/tests/shared/context-renderer.test.ts)**: Verifies that rules render before goals and that query failures remain isolated.

## Summary

- The **rules module** persists governance data to `hivemind_rules` using parameterized SQL via [`src/rules/write.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/write.ts).
- The **graph module** queries this table through [`src/rules/read.ts`](https://github.com/activeloopai/hivemind/blob/main/src/rules/read.ts) and `renderContextBlock` to inject rules into LLM contexts.
- Both modules share the database driver from [`src/utils/sql.ts`](https://github.com/activeloopai/hivemind/blob/main/src/utils/sql.ts), enabling automatic schema discovery and unified transaction handling.
- Rule scopes defined in the policy layer constrain graph mutations, enforcing authorization at the edge level.
- Execution hooks bridge the modules, allowing rules to trigger side effects when matching nodes or edges.

## Frequently Asked Questions

### How does the graph module ensure the rules table exists before querying?

The graph API lazily calls `ensureRulesTable()` during workspace initialization to create or heal the `hivemind_rules` table. This defensive pattern prevents query errors when agents access workspaces that haven't yet persisted rule definitions.

### Can rules restrict which nodes or edges an agent can modify?

Yes. The policy layer validates rule scopes—such as `team` or `project` assignments—before allowing edge mutations. The graph module checks these constraints during write operations, ensuring agents only modify authorized graph partitions.

### Where are rules injected into the LLM context?

The `renderContextBlock` function in [`src/graph/renderContextBlock.ts`](https://github.com/activeloopai/hivemind/blob/main/src/graph/renderContextBlock.ts) fetches rules via `SELECT * FROM "hivemind_rules"` and formats them into a **HIVEMIND RULES** section. This section prepends goal data in the final prompt sent to the language model.

### How do rules and goals interact during context rendering?

Rules are queried and rendered first, followed by goals from `hivemind_goals`. The [`context-renderer.test.ts`](https://github.com/activeloopai/hivemind/blob/main/context-renderer.test.ts) suite verifies that failures in one query do not affect the other, ensuring robust context construction even when goal tables are empty.