# README

## Overview

The Audit module provides a centralized, append-only audit trail for tracking data changes across all ERP modules. It records who or what performed an action, when it occurred, and what data changed — capturing both the old and new values at the field level. The module is designed as cross-cutting infrastructure: other modules emit structured audit events that the Audit module stores, indexes, and exposes for query. All audit entries are append-only and immutable once written, ensuring that stored records cannot be retroactively altered or deleted. Note: because ingestion is eventually consistent and decoupled from the emitting module's transaction, the module provides best-effort delivery — it does not guarantee that every mutation is captured (see [Audit Event Logging](docs/features/audit-event-logging.md) for the ingestion contract and failure semantics).

The module supports both company-scoped entities (e.g., sales orders, invoices) and global entities (e.g., user accounts, currencies) — entries for global entities omit companyId and are queryable without company scope.

Access to audit data and policy management is controlled by explicit permissions. Because audit entries can contain sensitive before/after values, viewing and administering the audit trail requires dedicated privileges separate from the permissions on the audited entities themselves. The module defines four coarse permissions: `viewAuditHistory` (query audit entries and change details), `viewAuditSummary` (view aggregated audit summaries without field-level details), `manageAuditPolicies` (create, update, activate, deactivate, delete audit policies, query policies, and register auditable entities), and `logAuditEvent` (ingest audit events from emitting modules). At runtime, command shells enforce per-command permission keys (e.g., `audit:createAuditPolicy`, `audit:registerAuditableEntity`), and policy query endpoints (`getAuditPolicy`, `listAuditPolicies`) require the coarse `audit:manageAuditPolicies` key directly. The `manageAuditPolicies` alias (defined in `permissions.ts`) expands to both the coarse `manageAuditPolicies` key itself and all per-command keys; the application's RBAC layer should use this alias when populating `ctx.permissions` to ensure both command and query authorization work correctly. Each permission is company-scoped — holders can only access entries and policies for their assigned companies — or global-scoped for company-unscoped entries and policies. The audit module does not define its own roles; it exposes permissions that the application's role-based access control system assigns to roles as needed.

## Key Features

- **Audit Event Logging** — Captures create, update, and delete operations as immutable audit entries with unique eventId, optional correlationId for operation grouping, actor identity (actorType + actorId), timestamp, entity reference, and operation type
- **Field-Level Change Tracking** — Records old and new values for each changed field within an audit entry, with configurable sensitivity modes (capture, mask, hash, exclude) to protect sensitive data
- **Audit Policy Configuration** — Allows administrators to define which entities, fields, and operation types are audited, controlling granularity, sensitivity handling, and performance impact

## Module Scope

### In Scope

- Immutable storage of audit log entries (append-only, no update or delete)
- Field-level change detail recording (old value / new value pairs) with sensitivity-aware value processing
- Configurable audit policies at entity and field granularity with sensitivity modes
- Query and filtering of audit logs by actor, entity, record, operation type, and date range
- Record-level change history retrieval
- Actor identity capture supporting multiple actor types (USER, SYSTEM, SERVICE) with optional delegation (onBehalfOf)
- Company-scoped and global (company-unscoped) audit entries
- Permission-based access control for audit viewing and policy administration

### Out of Scope

- User authentication and session tracking (owned by user-management / infrastructure layer)
- Compliance framework mapping and automated evidence collection (application-level concern)
- Anomaly detection, alerting, and real-time notifications
- Log archival, long-term retention policies, and storage tiering
- Dashboard visualizations and audit analytics

### Scope Decision Rationale

The module focuses on the foundational audit trail capabilities that all ERP deployments require: capturing changes, storing them immutably once written, and making them queryable. The ingestion contract is best-effort — applications that require guaranteed delivery for strict compliance scenarios should layer an outbox or replay mechanism on top of this module. Authentication logging is excluded because it belongs to the identity/infrastructure layer, not the domain data change layer. Compliance framework mapping, anomaly detection, and retention management are excluded as application-level or operational concerns that can be layered on top of the core audit trail. This separation keeps the module focused, testable, and reusable across different compliance contexts.

## Module Dependencies

- **user-management** — References userId as one type of actorId on audit entries (data reference only; no domain logic dependency)
- **organization** — References companyId for multi-company scoping of company-bound audit entries (data reference only; companyId is optional for global entities)
- **all emitting modules** (reverse dependency) — The audit module is cross-cutting: other modules depend on it, not the other way around. Emitting modules register their auditable entities (name, scope, field list) at initialization time and submit structured audit event payloads (including a unique `eventId` for idempotency) after committing their own transactions. The ingestion contract is idempotent on `eventId` for safe retries, and the audit module does not participate in the emitting module's transaction (eventually consistent). See the [Audit Event Logging](docs/features/audit-event-logging.md) feature documentation for the full ingestion contract.
