# Rule Manager - User Guide

**Multi-Project Governance Manager for Tractatus Framework**

---

## Table of Contents

1. [Overview](#overview)
2. [Getting Started](#getting-started)
3. [Dashboard Tour](#dashboard-tour)
4. [Managing Rules](#managing-rules)
5. [Understanding Rule Properties](#understanding-rule-properties)
6. [Best Practices](#best-practices)
7. [Troubleshooting](#troubleshooting)

---

## Overview

The Rule Manager is a web-based interface for managing governance rules in the Tractatus framework. It replaces the fragile `.claude/instruction-history.json` file with a robust, database-backed solution that supports:

- **Multi-project governance** - Apply rules universally or to specific projects
- **Real-time validation** - Ensure rules meet framework standards
- **Variable substitution** - Use `${VAR_NAME}` for project-specific values
- **Quality scoring** - AI-calculated clarity, specificity, and actionability scores
- **Advanced filtering** - Find rules quickly by scope, quadrant, persistence, etc.

---

## Getting Started

### Accessing the Rule Manager

1. Navigate to `http://localhost:9000/admin/dashboard.html`
2. Log in with your admin credentials
3. Click "🔧 Rule Manager" in the navigation bar

### Initial Setup

The Rule Manager comes pre-populated with 18 existing governance rules migrated from `.claude/instruction-history.json`. You can:

- **View** existing rules to understand their structure
- **Edit** rules to improve clarity or add variables
- **Create** new rules for your project needs
- **Delete** obsolete rules (soft delete by default)

---

## Dashboard Tour

### Statistics Cards

At the top of the page, you'll see four key metrics:

1. **Total Rules** - Count of all active rules
2. **Universal** - Rules that apply to all projects
3. **Validated** - Rules that have passed validation tests
4. **Avg Clarity** - Average clarity score across all rules

### Filters Panel

The filters panel allows you to narrow down the rule list:

- **Scope** - UNIVERSAL (all projects) or PROJECT_SPECIFIC
- **Quadrant** - STRATEGIC, OPERATIONAL, TACTICAL, SYSTEM, STORAGE
- **Persistence** - HIGH (always enforced), MEDIUM, LOW
- **Validation** - PASSED, FAILED, NEEDS_REVIEW, NOT_VALIDATED
- **Status** - Active Only, All, Inactive Only
- **Sort By** - Priority, Clarity Score, Rule ID, Last Updated

### Search Box

Use the search box to perform full-text search across rule text. The search is debounced (500ms delay) to avoid excessive API calls.

### Rules Grid

Each rule is displayed as a card showing:

- **Scope badge** - Blue (Universal) or Gray (Project-Specific)
- **Quadrant badge** - Color-coded by quadrant
- **Persistence badge** - Red (High), Orange (Medium), Yellow (Low)
- **Rule ID** - Unique identifier (inst_xxx)
- **Rule text** - Truncated to 2 lines
- **Priority** - 0-100 scale
- **Variables** - Count of detected `${VARIABLE}` placeholders
- **Enforcements** - Number of times rule was enforced
- **Clarity score** - Visual progress bar (Green ≥80%, Yellow ≥60%, Red <60%)
- **Action buttons** - View, Edit, Delete

### Pagination

Rules are paginated with 20 items per page. Use the pagination controls at the bottom to navigate between pages.

---

## Managing Rules

### Creating a New Rule

1. Click the **"New Rule"** button in the top-right
2. Fill in the required fields:
   - **Rule ID** - Unique identifier (e.g., `inst_019`, `inst_020`)
   - **Rule Text** - The governance instruction
     - Use `${VAR_NAME}` for variables (e.g., `${DB_TYPE}`, `${PROJECT_NAME}`)
     - Use strong imperatives: MUST, SHALL, REQUIRED, PROHIBITED
     - Avoid weak language: try, maybe, consider, might
   - **Quadrant** - Select the appropriate Tractatus quadrant
   - **Persistence** - How long this rule should remain active
3. Configure optional settings:
   - **Scope** - Universal or Project-Specific
   - **Category** - Technical, Content, Security, Privacy, Process, Values, Other
   - **Priority** - 0 (low) to 100 (high)
   - **Temporal Scope** - Immediate, Session, Project, Permanent
   - **Active** - Whether the rule is currently enforced
   - **Examples** - Add example scenarios (optional)
   - **Notes** - Additional clarifications (optional)
4. Monitor the **Clarity Score Preview** in the right panel
   - Adjust your rule text to achieve a higher score
   - Green (≥80%) indicates good clarity
5. Click **"Create Rule"**

### Viewing a Rule

1. Click the **"View"** button on any rule card
2. The view modal displays:
   - All rule properties
   - Quality scores (clarity, specificity, actionability)
   - Detected variables
   - Metadata (created date, updated date, creator)
3. Click **"Edit Rule"** to switch to edit mode
4. Click **"Close"** to return to the dashboard

### Editing a Rule

1. Click the **"Edit"** button on any rule card
2. Modify any fields (except Rule ID, which is immutable)
3. **Automatic processing:**
   - If you change the rule text:
     - Variables are re-detected automatically
     - Clarity score is recalculated
     - Validation status resets to NOT_VALIDATED
     - An entry is added to the optimization history
4. Click **"Save Changes"**

**Note:** After saving, the rule manager list refreshes automatically to show your changes.

### Deleting a Rule

1. Click the **"Delete"** button on any rule card
2. Confirm the deletion in the dialog
3. **Soft delete** (default):
   - Sets `active: false`
   - Preserves all rule data
   - Can be reactivated later
4. **Hard delete** (API only):
   - Permanently removes the rule
   - Use with caution!
   - See API documentation for details

**Protection:** The system prevents deletion of UNIVERSAL rules that are in use by multiple projects.

---

## Understanding Rule Properties

### Rule ID

- **Format:** `inst_XXX` where XXX is a number
- **Purpose:** Unique identifier for the rule
- **Immutable:** Cannot be changed after creation
- **Convention:** Start with `inst_001` and increment

### Rule Text

- **Purpose:** The actual governance instruction
- **Variables:** Use `${VAR_NAME}` for project-specific values
  - Example: `Database MUST use ${DB_TYPE} on port ${DB_PORT}`
  - Variable names must be UPPERCASE with underscores
  - Automatically detected and displayed
- **Best practices:**
  - Use strong imperatives: MUST, SHALL, REQUIRED, PROHIBITED, NEVER
  - Be specific: Include numbers, paths, URLs where applicable
  - Avoid vague language: try, maybe, consider, might, probably
  - Include context: WHO, WHAT, WHEN, WHERE, WHY

### Scope

- **PROJECT_SPECIFIC** (default)
  - Applies only to this project
  - No variable substitution needed
- **UNIVERSAL**
  - Applies to all projects in your portfolio
  - Should use variables for project-specific values
  - Example: `MongoDB MUST run on port ${DB_PORT} for ${PROJECT_NAME} database`

### Quadrant

Classification based on the [Tractatus framework](../docs/markdown/core-concepts.md):

- **STRATEGIC** - High-level project goals, architecture decisions, values
- **OPERATIONAL** - Day-to-day workflows, processes, standards
- **TACTICAL** - Specific implementation details, code patterns
- **SYSTEM** - Infrastructure, environments, deployment
- **STORAGE** - Data persistence, state management

### Persistence

How long the rule remains active:

- **HIGH** - Always enforced, never expires, critical rules
- **MEDIUM** - Enforced during project lifecycle, may expire
- **LOW** - Temporary, context-specific, short-term

### Temporal Scope

When the rule applies:

- **PERMANENT** - Forever (default)
- **PROJECT** - Duration of the project
- **SESSION** - Single Claude Code session only
- **IMMEDIATE** - One-time instruction

### Priority

- **Range:** 0 (low) to 100 (high)
- **Default:** 50
- **Purpose:** Determines enforcement order when rules conflict
- **Guidelines:**
  - 90-100: Critical infrastructure, security
  - 70-89: Important standards, conventions
  - 50-69: Standard practices
  - 30-49: Preferences
  - 0-29: Nice-to-haves

### Category

Helps organize rules:

- **technical** - Code, architecture, implementation
- **content** - Documentation, messages, UX copy
- **security** - Authentication, authorization, data protection
- **privacy** - User data, GDPR compliance
- **process** - Workflows, approvals, reviews
- **values** - Ethical guidelines, mission alignment
- **other** - Doesn't fit other categories

### Clarity Score

- **Range:** 0-100%
- **Calculation:** Heuristic-based (will be improved by AI optimizer in Phase 2)
- **Factors:**
  - **-10 points** for each weak word (try, maybe, consider, might, probably, possibly)
  - **-10 points** if no strong imperatives (MUST, SHALL, REQUIRED, PROHIBITED)
  - **-5 points** if no specificity indicators (numbers, variables)
- **Color coding:**
  - **Green (≥80%)** - Good clarity
  - **Yellow (60-79%)** - Needs improvement
  - **Red (<60%)** - Poor clarity, revise

### Validation Status

- **NOT_VALIDATED** - Has not been tested (default for new/edited rules)
- **PASSED** - Passed all validation tests
- **FAILED** - Failed one or more validation tests
- **NEEDS_REVIEW** - Passed but with warnings

*Note: Validation testing will be implemented in Phase 4*

---

## Best Practices

### Writing High-Quality Rules

1. **Be Specific**
   - ❌ "Try to use MongoDB"
   - ✅ "Database MUST use MongoDB on port 27017"

2. **Use Strong Language**
   - ❌ "Consider adding error handling"
   - ✅ "All functions MUST include try-catch error handling"

3. **Include Context**
   - ❌ "Use environment variables"
   - ✅ "Sensitive credentials MUST be stored in .env files, never in code"

4. **Use Variables for Universal Rules**
   - ❌ "MongoDB port is 27017" (project-specific)
   - ✅ "Database MUST use ${DB_TYPE} on port ${DB_PORT}" (universal)

5. **Add Examples**
   - Clarify edge cases
   - Show concrete scenarios
   - Help AI understand intent

6. **Link Related Rules**
   - Reference other rules by ID
   - Build a rule hierarchy
   - Avoid redundancy

### Organizing Your Rules

1. **Start with Infrastructure (SYSTEM quadrant)**
   - Database configuration
   - Port assignments
   - Environment setup

2. **Define Architecture (STRATEGIC quadrant)**
   - Tech stack choices
   - Design patterns
   - Project boundaries

3. **Establish Workflows (OPERATIONAL quadrant)**
   - Git conventions
   - Testing requirements
   - Deployment process

4. **Document Standards (TACTICAL quadrant)**
   - Code style
   - Naming conventions
   - File structure

5. **Set Storage Rules (STORAGE quadrant)**
   - Session state management
   - Data persistence
   - Cache strategies

### Maintaining Rules

- **Regular Reviews:** Quarterly review all rules for relevance
- **Update Obsolete Rules:** Deactivate rules that no longer apply
- **Improve Clarity:** Aim for ≥80% clarity score on all rules
- **Add Variables:** Convert project-specific rules to universal when reusable
- **Track Changes:** Use optimization history to understand rule evolution

---

## Troubleshooting

### "Failed to load rules" error

**Cause:** API connection issue or authentication failure

**Solutions:**
1. Check that the server is running (`npm start`)
2. Verify your JWT token is valid (re-login if expired)
3. Check browser console for specific error messages

### Rule not appearing after creation

**Cause:** Filters may be hiding the rule

**Solutions:**
1. Click "Clear Filters" button
2. Check the "Status" filter is set to "Active Only"
3. Verify the rule was actually created (check Network tab)

### Clarity score is low

**Cause:** Rule text contains weak language or lacks specificity

**Solutions:**
1. Replace weak words (try, maybe, consider) with strong imperatives (MUST, SHALL)
2. Add numbers, paths, or variables for specificity
3. Use explicit language instead of vague terms

### Cannot delete a rule

**Cause:** Rule is a UNIVERSAL rule in use by multiple projects

**Solution:**
1. Review which projects are using the rule
2. Either keep the rule or remove it from those projects first
3. Alternatively, soft-delete (deactivate) instead of hard-delete

### Variables not detected

**Cause:** Incorrect variable syntax

**Solution:**
- Use `${VAR_NAME}` format (curly braces, uppercase)
- ❌ `$VAR_NAME` (missing braces)
- ❌ `${var_name}` (lowercase)
- ✅ `${VAR_NAME}` (correct)

### Pagination not working

**Cause:** JavaScript error or API failure

**Solutions:**
1. Check browser console for errors
2. Refresh the page
3. Try a different browser
4. Check that JavaScript is enabled

---

## Keyboard Shortcuts

*Coming in future update*

---

## Related Documentation

- **API Reference:** [docs/api/RULES_API.md](../api/RULES_API.md)
- **Core Concepts:** [docs/markdown/core-concepts.md](../markdown/core-concepts.md)
- **Implementation Plan:** [docs/MULTI_PROJECT_GOVERNANCE_IMPLEMENTATION_PLAN.md](../MULTI_PROJECT_GOVERNANCE_IMPLEMENTATION_PLAN.md)
- **Maintenance Guide:** [CLAUDE_Tractatus_Maintenance_Guide.md](../../CLAUDE_Tractatus_Maintenance_Guide.md)

---

## Getting Help

- **GitHub Issues:** Report bugs or request features
- **API Documentation:** See [RULES_API.md](../api/RULES_API.md) for technical details
- **Framework Documentation:** See [core-concepts.md](../markdown/core-concepts.md) for Tractatus theory

---

**Last Updated:** 2025-10-11
**Version:** 1.0.0 (Phase 1 Complete)
**Next Features:** Phase 2 - AI Optimization & CLAUDE.md Migration
