> ## Documentation Index
> Fetch the complete documentation index at: https://docs.finwatch.finance/llms.txt
> Use this file to discover all available pages before exploring further.

# Git-Ops Management

FinWatch treats fraud detection rules as code. Rules are plain-text `.ws` files that can be stored in a Git repository, reviewed in pull requests, and deployed automatically when merged. This guide covers everything you need to know about managing the rule lifecycle using Git — FinWatch's native approach.

***

## Why GitOps for Fraud Rules?

Traditional fraud detection platforms manage rules through web UIs or proprietary configuration systems. This creates several problems:

* **No audit trail.** Who changed the rule? When? Why? Most UIs don't track this well.
* **No review process.** A single analyst can change a rule that blocks millions of dollars in transactions, with no second pair of eyes.
* **No rollback.** If a rule change causes false positives, reverting is manual and error-prone.
* **No testing.** There's no staging environment, no CI pipeline, no way to test a rule change before it goes live.

GitOps solves all of these:

| Problem           | GitOps Solution                                                         |
| ----------------- | ----------------------------------------------------------------------- |
| No audit trail    | Every change is a Git commit with author, timestamp, and message        |
| No review process | Pull requests require approval before merging                           |
| No rollback       | `git revert` restores any previous version instantly                    |
| No testing        | CI pipelines can validate rule syntax before deployment                 |
| No collaboration  | Branch-based workflows let multiple people work on rules simultaneously |

***

## Setting Up a Rules Repository

### Creating the Repository

Create a dedicated Git repository for your fraud detection rules:

```bash theme={null}
mkdir finwatch-rules
cd finwatch-rules
git init
```

### Recommended Directory Structure

```text theme={null}
finwatch-rules/
├── README.md                    # Overview of your rule set
├── rules/
│   ├── thresholds/
│   │   ├── HighValueCheck.ws
│   │   └── MicroTransactionCheck.ws
│   ├── velocity/
│   │   ├── HighFrequencyDestination.ws
│   │   ├── SourceHighOutflow.ws
│   │   └── RapidSmallBurst.ws
│   ├── compliance/
│   │   ├── SanctionedCountryCheck.ws
│   │   └── SuspiciousDescriptionCheck.ws
│   ├── temporal/
│   │   ├── UnusualTransactionTime.ws
│   │   └── WeekendTransactionCheck.ws
│   └── sequential/
│       └── BlockIfPreviousFailed.ws
└── variables/
    └── lists.json               # External variable definitions
```

**Key conventions:**

* **One rule per `.ws` file.** Always.
* **Organize by category.** Group rules by the type of fraud pattern they detect.
* **Include a README.** Document the purpose of each category and any team-specific conventions.
* **Store variable definitions alongside rules.** This keeps everything in one place.

### Initial Commit

```bash theme={null}
git add .
git commit -m "Initial rule set: threshold checks and compliance rules"
git remote add origin git@github.com:your-org/finwatch-rules.git
git push -u origin main
```

***

## Connecting FinWatch to Your Repository

FinWatch connects to your Git repository using two environment variables:

| Variable                  | Description                      | Example                                          |
| ------------------------- | -------------------------------- | ------------------------------------------------ |
| `WATCH_SCRIPT_GIT_REPO`   | The Git repository URL           | `https://github.com/your-org/finwatch-rules.git` |
| `WATCH_SCRIPT_GIT_BRANCH` | The branch to track              | `main` (default)                                 |
| `WATCH_SCRIPT_DIR`        | Local directory for cloned rules | `watch_scripts` (default)                        |

### Configuration

```bash theme={null}
export WATCH_SCRIPT_GIT_REPO="https://github.com/your-org/finwatch-rules.git"
export WATCH_SCRIPT_GIT_BRANCH="main"
export WATCH_SCRIPT_DIR="watch_scripts"
```

Or in Docker:

```bash theme={null}
docker run -d \
  --name finwatch \
  -p 8081:8081 \
  -e WATCH_SCRIPT_GIT_REPO="https://github.com/your-org/finwatch-rules.git" \
  -e WATCH_SCRIPT_GIT_BRANCH="main" \
  -e WATCH_SCRIPT_DIR="/app/watch_scripts" \
  finwatch/finwatch:latest
```

### What Happens at Startup

When FinWatch starts with a Git repository configured:

1. **Validation:** Checks that Git is installed on the system. If not, startup fails with a fatal error.
2. **Clone or Update:** If the local directory doesn't exist, clones the repository. If it exists but isn't a valid Git repo, removes it and re-clones. If it's already a valid repo, pulls the latest changes.
3. **Process Existing Scripts:** Scans the directory for all `.ws` files and compiles them into the instruction database.
4. **Start Periodic Sync:** Begins polling the remote repository for changes every 30 seconds.
5. **Start File Watcher:** Monitors the local directory for file system changes using `fsnotify`.

***

## The Rule Lifecycle

The complete lifecycle of a fraud detection rule in a GitOps workflow:

```text theme={null}
┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐
│  Write   │ →  │  Commit  │ →  │  Pull    │ →  │  Merge   │ →  │  Live    │
│  Rule    │    │  to      │    │  Request │    │  to      │    │  in      │
│  (.ws)   │    │  Branch  │    │  Review  │    │  main    │    │ FinWatch │
└──────────┘    └──────────┘    └──────────┘    └──────────┘    └──────────┘
```

### Step 1: Write the Rule

Create a new `.ws` file on a feature branch:

```bash theme={null}
git checkout -b rule/high-frequency-destination
```

Write the rule:

```bash theme={null}
cat > rules/velocity/HighFrequencyDestination.ws << 'EOF'
rule HighFrequencyDestination {
    description "Unusually frequent payments to the same destination may require scrutiny."

    when count(when destination == $current.destination, "PT24H") > 10
     and amount > 100

    then review
         score  0.5
         reason "High frequency of transactions to same destination in 24 hours"
}
EOF
```

### Step 2: Commit with a Clear Message

```bash theme={null}
git add rules/velocity/HighFrequencyDestination.ws
git commit -m "Add velocity rule: flag >10 transactions to same destination in 24h

- Threshold: 10 transactions per destination per 24 hours
- Minimum amount: $100 (filters out micro-transactions)
- Verdict: review (not block — needs analyst confirmation)
- Score: 0.5 (medium confidence)

Addresses: FRAUD-1234"
```

**Commit message best practices:**

* **First line:** Short summary of what changed.
* **Body:** Explain the thresholds, the reasoning behind score/verdict choices, and any regulatory context.
* **Reference:** Link to the fraud investigation ticket or compliance requirement that prompted the rule.

### Step 3: Open a Pull Request

Push the branch and open a PR:

```bash theme={null}
git push origin rule/high-frequency-destination
```

Your PR should include:

* **Description:** What fraud pattern does this rule detect? Why is it needed?
* **Thresholds justification:** Why 10 transactions? Why 24 hours? Why \$100 minimum?
* **Testing evidence:** Show test transactions that trigger and don't trigger the rule.
* **Scoring rationale:** Why 0.5 and not 0.8?

### Step 4: Review

Your team reviews the rule. Common review checklist:

* Rule name is descriptive and follows `PascalCase` convention.
* Description is clear and written for a non-technical audience.
* Conditions are logically correct and cover the intended pattern.
* Cheap conditions are placed before expensive ones (performance).
* Score is appropriate for the confidence level.
* Reason is specific and actionable.
* No typos in field names.
* Time windows are appropriate (not too large, not too small).

### Step 5: Merge and Auto-Deploy

Once approved, merge the PR to `main`. Within 30 seconds (the default polling interval), FinWatch:

1. Pulls the latest changes from the repository.
2. Detects the new `.ws` file.
3. Compiles the rule.
4. Adds it to the active rule set.

No restart required. No manual deployment. The rule is live.

***

## File Watching

FinWatch uses two complementary mechanisms to detect rule changes:

### Git Polling (Remote Changes)

The `GitManager` periodically polls the remote repository for new commits:

* **Default interval:** Every 30 seconds.
* **Mechanism:** Executes `git pull` on the tracked branch.
* **Behavior:** If new commits are found, the updated/new `.ws` files are automatically recompiled.

### File System Watching (Local Changes)

For immediate feedback during development, FinWatch also watches the local directory using the `fsnotify` library:

* **Events monitored:** File creation, modification, and deletion.
* **File filter:** Only `.ws` files trigger recompilation.
* **Behavior:** When a `.ws` file is saved locally, FinWatch recompiles it within seconds.

This dual approach means:

* **In production:** The Git polling mechanism picks up merged changes.
* **In development:** Saving a file locally triggers immediate recompilation, giving you instant feedback.

***

## Validation and Error Handling

### What Happens When a Malformed Rule is Pushed

If a `.ws` file with a syntax error is committed and pushed, FinWatch will:

1. Pull the change.
2. Attempt to compile the rule.
3. **Log a parse error** with the specific line and column number:
   ```text theme={null}
   ERR Failed to compile watch script error="parse error at line 5, column 12: expected verdict (allow, block, review)"
   ```
4. **Skip the malformed rule.** Other valid rules continue to function normally.
5. **Not crash.** A single bad rule does not bring down the engine.

### Common Parse Errors

| Error                                     | Cause                                       | Fix                                                                |
| ----------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------ |
| `expected verdict (allow, block, review)` | Invalid or missing verdict in `then` clause | Use one of: `allow`, `block`, `review`, `approve`, `deny`, `alert` |
| `expected number after 'score'`           | Non-numeric value after `score` keyword     | Ensure score is a valid number (e.g., `0.7`)                       |
| `expected string after 'reason'`          | Missing quotes around reason                | Wrap reason in double quotes: `reason "..."`                       |
| `unexpected token in then clause`         | Unknown keyword in `then` block             | Only `score` and `reason` are valid after the verdict              |

### Pre-Merge Validation

To catch errors before they reach production, add a validation step to your CI pipeline. You can use FinWatch's parser as a linter:

```bash theme={null}
# Validate all .ws files in the rules directory
for file in rules/**/*.ws; do
    finwatch validate "$file"
    if [ $? -ne 0 ]; then
        echo "FAILED: $file"
        exit 1
    fi
done
```

***

## Rolling Back a Rule

One of the strongest advantages of GitOps is the ability to roll back changes instantly.

### Revert a Specific Commit

```bash theme={null}
# Find the commit that introduced the problematic rule
git log --oneline rules/velocity/HighFrequencyDestination.ws

# Revert that specific commit
git revert abc1234
git push origin main
```

FinWatch picks up the revert within 30 seconds, and the rule is removed or restored to its previous state.

### Revert to a Known-Good State

```bash theme={null}
# Reset the rules directory to a known-good tag
git checkout v1.2.0 -- rules/
git commit -m "Rollback rules to v1.2.0 due to false positive spike"
git push origin main
```

### Emergency: Delete a Rule

If a rule is causing immediate harm (blocking legitimate transactions), the fastest fix is to delete the file:

```bash theme={null}
git rm rules/velocity/HighFrequencyDestination.ws
git commit -m "EMERGENCY: Remove HighFrequencyDestination rule — causing false positives"
git push origin main
```

FinWatch will stop evaluating the deleted rule within 30 seconds.

***

## Team Workflows

### Branch Naming Convention

```shellscript theme={null}
rule/<rule-name>          # New rule
fix/<rule-name>           # Fix to an existing rule
tune/<rule-name>          # Score/threshold adjustment
remove/<rule-name>        # Rule removal
```

### Required PR Labels

Consider labeling PRs to categorize changes:

* `new-rule` — Adding a new rule.
* `tune` — Adjusting thresholds or scores.
* `critical` — Changes that affect `block` verdicts.
* `compliance` — Changes driven by regulatory requirements.

### Review Requirements

* **Any rule change:** At least one peer review from an engineer.
* **`block` verdict rules:** Additional review from a compliance officer or fraud analyst.
* **Score changes above 0.8:** Requires senior engineer approval.
* **Variable list updates:** Can be approved by the compliance team directly.

### Tagging Releases

Tag your rule set after significant changes:

```bash theme={null}
git tag -a v1.3.0 -m "Add velocity detection rules and update sanctions list"
git push origin v1.3.0
```

Tags provide clear rollback targets and make it easy to track which rule set was active at any point in time.

***

## Triggering a Manual Sync

If you need FinWatch to pull changes immediately (without waiting for the 30-second polling interval), use the Git sync API endpoint:

```bash theme={null}
curl -X POST http://localhost:8081/git/sync
```

This triggers an immediate `git pull` and recompilation of any changed `.ws` files.

### Checking Repository Status

```bash theme={null}
curl http://localhost:8081/git/status
```

Returns the current Git repository status, including the current branch, latest commit, and sync status.

***

## Next Steps

* [**Integration Guide**](integration-guide.md) — Connect FinWatch to your application's transaction pipeline.
* [**Production Deployment**](production-deployment.md) — Deploy FinWatch with Git-based rules in a production environment.
* [**The Rule Cookbook**](rule-cookbook.md) — A library of production-ready rules to seed your repository.
* [**Troubleshooting**](troubleshooting.md) — Resolve common Git sync and rule compilation issues.
