npm package: @peacethinking/escalation-detector
Description: Hybrid escalation detection for conflict resolution — rule-based (OSS) + LLM-powered (API)
Latest version: 0.1.0

# @peacethinking/escalation-detector

[![npm](https://img.shields.io/npm/v/@peacethinking/escalation-detector)](https://www.npmjs.com/package/@peacethinking/escalation-detector)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)

Detect escalating conflicts in online conversations before they become toxic. A two-level hybrid architecture: Level 1 (OSS) runs entirely locally with rule-based pattern matching — no LLM, no API calls, zero latency. Level 2 adds LLM-enhanced detection with cultural nuance via prompt templates you send to your own LLM. Based on Gottman's Four Horsemen research and the Peacethinking 6-Dimensions Conflict Framework.

## Two-Level Architecture

### Level 1 — Rule-Based (OSS)

Pattern matching for contempt, defensiveness, stonewalling, criticism, and six additional trigger types. Scores 0–1 and maps to five escalation stages (CALM through HOSTILE). Runs entirely locally — no API key, no network call, sub-millisecond latency. Supports English and German.

### Level 2 — LLM-Enhanced (Bring Your Own LLM)

A prompt builder that generates structured `system` + `user` message pairs. You call your own LLM (OpenAI, Anthropic, Ollama — any provider). The response is validated against a Zod schema (`EscalationOutputSchema`) that captures stage, score, cultural context, emotional dimensions, and the recommended intervention type.

## Installation

```bash
npm install @peacethinking/escalation-detector
# or
pnpm add @peacethinking/escalation-detector
```

## Quick Start

### Level 1: Rule-Based (no LLM needed, zero latency)

```ts
import { detectEscalation } from '@peacethinking/escalation-detector';

const result = detectEscalation({
  messages: 'You always do this! You never listen to me!',
  language: 'en',
});

console.log(result.stage);   // 'TENSE'
console.log(result.score);   // 0.35
console.log(result.signals); // [{ type: 'generalization', matched_text: 'You always', ... }]
console.log(result.interventions); // [{ type: 'NUDGE', message_en: '...', blocking: false }]
```

### Level 2: LLM-Enhanced (bring your own LLM)

```ts
import { buildEscalationPrompt, EscalationOutputSchema } from '@peacethinking/escalation-detector/prompts';

const { system, user } = buildEscalationPrompt({
  messages: ['You always do this!', 'That is not what I said...'],
  language_code: 'en',
});

// Send to your LLM, then validate the response:
const output = EscalationOutputSchema.parse(JSON.parse(llmResponse));
// output.stage, output.score, output.cultural_context, output.recommended_intervention
```

## API

### Main Entry Point (`@peacethinking/escalation-detector`)

| Export | Description |
|--------|-------------|
| `detectEscalation(options)` | Run Level 1 rule-based detection. Returns `DetectionResult`. |
| `mergeResults(r1, r2)` | Merge two detection results (e.g. Level 1 + Level 2). |
| `matchPatterns(text, language)` | Low-level: match raw patterns and return `DetectedSignal[]`. |
| `calculateEscalationScore(signals)` | Aggregate signals into a 0–1 score. |
| `scoreToStage(score)` | Map a score to an `EscalationStage`. |
| `analyzeTrajectory(scoreHistory)` | Detect ESCALATING / STABLE / DE_ESCALATING trend. |
| `recommendInterventions(stage, signals)` | Get prioritized `Intervention[]` for a given stage. |
| `buildEscalationPrompt(params)` | Build Level 2 prompt (also exported from `/prompts`). |
| `EscalationOutputSchema` | Zod schema for validating LLM responses (also from `/prompts`). |
| `ESCALATION_PATTERNS` | The full pattern registry used by Level 1. |
| `RULES_VERSION` | Semver string of the current rule set. |

### Sub-Path Imports

| Import path | Contents |
|-------------|----------|
| `@peacethinking/escalation-detector` | `detectEscalation`, `mergeResults`, all rule functions, types |
| `@peacethinking/escalation-detector/rules` | Rule engine internals (`matchPatterns`, `calculateEscalationScore`, etc.) |
| `@peacethinking/escalation-detector/prompts` | `buildEscalationPrompt`, `EscalationOutputSchema` |
| `@peacethinking/escalation-detector/types` | All TypeScript types and Zod schemas |

## Escalation Stages

| Stage | Score Range | Description |
|-------|-------------|-------------|
| `CALM` | 0.0 – 0.19 | No significant conflict signals detected |
| `TENSE` | 0.2 – 0.39 | Mild tension; generalizations or mild defensiveness |
| `ESCALATING` | 0.4 – 0.59 | Active escalation; contempt or blame shifting present |
| `FLOODING` | 0.6 – 0.79 | Gottman flooding threshold reached; emotional regulation failing |
| `HOSTILE` | 0.8 – 1.0 | Dehumanization, ultimatums, or sustained attack patterns |

## Trigger Types

The rule engine detects ten trigger types aligned with Gottman's Four Horsemen and online communication research:

`personal_attack`, `generalization`, `emotional_flooding`, `contempt`, `stonewalling`, `whataboutism`, `strawman`, `ultimatum`, `blame_shifting`, `dehumanization`

## Intervention Types

Graduated interventions based on Gottman's Repair Attempts model:

| Type | When triggered |
|------|----------------|
| `NUDGE` | TENSE — gentle redirect suggestion |
| `REFLECTION` | TENSE/ESCALATING — mirror emotional content |
| `COOLDOWN` | ESCALATING — suggest a pause |
| `MEDIATION` | FLOODING — escalate to structured mediation |
| `MODERATOR_ALERT` | HOSTILE — flag for human moderator |

## Use Cases

- **Forum moderation** — detect thread escalation before manual intervention is needed
- **Chat applications** — real-time per-message scoring with graduated nudges
- **Customer support** — identify when agent-customer exchanges are deteriorating
- **Community platforms** — automated escalation scoring for community health dashboards
- **Social media monitoring** — batch analysis of conversation threads

## Part of the Peacethinking Ecosystem

`@peacethinking/escalation-detector` is the open-source detection layer of the Peacethinking Resolution Platform.

| Package | Description |
|---------|-------------|
| [`@peacethinking/conflict-framework`](../conflict-framework) | Shared types, schemas, and the 6-Dimensions Conflict Framework |
| [`@peacethinking/mediation-prompts`](../mediation-prompts) | LLM prompt builders for verdict, perspective, and mediation flows |
| [`@peacethinking/mediation-workflows`](../mediation-workflows) | XState-based mediation state machines |
| [`@peacethinking/llm-eval`](../llm-eval) | Benchmark any LLM on conflict resolution scenarios |
| [`@peacethinking/ai-gateway`](../ai-gateway) | Provider-agnostic LLM gateway with PII redaction and cost tracking |

## License

MIT — see [LICENSE](./LICENSE).

Built by [peacethinking.ai](https://peacethinking.ai).