# SPECIFICATIONS/05_ALGORITHMS/05_NARRATIVE_GENERATION.md

**PURPOSE:** Defines the format and rules for generating self-contained narrative text in audit logs. This file answers "what exactly goes into the narrative text?" — it contains zero implementation code.

> **Narrative independence rule (CRITICAL — narrative must not depend on payments table):** `../01_BUSINESS_CONTEXT/03_BUSINESS_RULES.md` → BR-004-9
> **Translation of these narratives into user-facing text:** `../../CONSTITUTIONS/07_BOUNDARY_LAYERS.md` → Localization Confinement

---

## Narrative Patterns

Each event type has a defined pattern with required placeholders:

| Event Type | Pattern | Required Placeholders |
|:---|:---|:---|
| Company Payout | `narrative.company_payout` | `{amount}` |
| Initial Payment | `narrative.initial_payment` | `{amount}` |
| Installment Payment | `narrative.installment_payment` | `{installment_number}`, `{amount}` |
| Payment Deletion | `narrative.payment_deleted` | `{amount}` |
| Payment Update | `narrative.payment_updated` | `{amount}` |

**Installment numbers:** Use plain digits (1, 2, 12...) — not Arabic ordinal words. The mobile app handles any UI-level localization.

---

## Generation Rules

1. At the point of creating any audit log entry, generate the narrative text immediately
2. Use the appropriate translation key for the event type
3. Inject all required values into the placeholders
4. Store the final resolved text in `narrative_text`
5. For update events: also store `old_values` and `new_values` as JSONB for detailed change tracking

---

## Update Auditing

For date/notes modifications (algorithm 3.4 in Payment Engine), the audit log captures additional structured data beyond the narrative:

| Field | Content |
|:---|:---|
| `narrative_text` | Self-contained description of the change including the amount |
| `old_values` | `{ "payment_date": "2024-01-15", "notes": "old note" }` |
| `new_values` | `{ "payment_date": "2024-01-20", "pattern": "new note" }` |

This structured data allows the UI to show a detailed diff if needed, while the narrative text remains readable even without the `payments` table.

---

## Timeline Retrieval

The contract timeline is retrieved by querying audit logs for a given contract, ordered by `created_at` ascending, and extracting the `narrative_text` field.

No JOINs to the payments table are required — the narrative text is self-contained.

> **Index supporting this query:** `../04_DATABASE/03_INDEXES.md` → `idx_audit_logs_contract_created`