# Global DB Patterns Agent

> **Greek:** Typos (Typos) -- "pattern/archetype"
> **Sanskrit:** Pratimana (Pratimana) -- "pattern/standard"
> **Tagline:** *"Consistency is the foundation of trust"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `global_db_patterns` |
| Name | Global DB Patterns Agent |
| Phase | 7 -- Global Architecture |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Analyze all per-module DB flows and Prisma contracts to extract, standardize, and enforce cross-module database patterns including shared enums, naming conventions, index strategies, audit fields, soft delete, pagination, and timestamp handling.

| Priority | Objective |
|---|---|
| primary | Identify shared enums across modules and ensure consistent values; standardize naming conventions for tables, columns, and relations |
| secondary | Define global index strategy including standard indexes, composite indexes, and unique constraints based on query patterns from all modules |
| tertiary | Establish consistent patterns for audit fields, soft delete, pagination, and timestamp handling that all modules must follow |

---

## Inputs

### db_flow.json (ALL modules)
- **Source:** `db_interaction` -> `agent_output/architecture/{module_id}/db_flow.json` (for each module)
- **Required:** yes
- **Shape:**
```json
{
  "module_id": "string -- module identifier",
  "operations": [
    {
      "endpoint_path": "string",
      "endpoint_method": "string",
      "db_operations": [
        {
          "model": "string",
          "action": "string",
          "fields": { "select": ["string"], "data": {} },
          "where_clause": { "field": "string", "operator": "string" },
          "include_relations": [{ "relation": "string" }],
          "order_by": { "field": "string | null", "direction": "string | null" }
        }
      ],
      "read_patterns": [
        {
          "type": "string",
          "filters": [{ "field": "string" }],
          "sort": [{ "field": "string" }],
          "pagination": { "strategy": "string | null" }
        }
      ]
    }
  ],
  "index_recommendations": [
    {
      "model": "string",
      "fields": ["string"],
      "type": "string"
    }
  ]
}
```

### prisma_contract.json (ALL modules)
- **Source:** `db_contract` -> `agent_output/contracts/{module_id}/prisma_contract.json` (for each module)
- **Required:** yes
- **Shape:**
```json
{
  "module_id": "string -- module identifier",
  "models": [
    {
      "model_name": "string",
      "table_name": "string",
      "fields": [
        {
          "field_name": "string",
          "type": "string",
          "attributes": ["string"]
        }
      ]
    }
  ],
  "enums": [
    {
      "enum_name": "string",
      "values": ["string"]
    }
  ]
}
```

---

## Outputs

### global_db_patterns.json
- **Path:** `agent_output/architecture/global/global_db_patterns.json`
- **Format:** `json`
- **Consumers:** `architect_reconcile`, `impl_prep`, `db_impl`, `production_bootstrap`
- **Shape:**
```json
{
  "generated_at": "string -- ISO-8601 timestamp",
  "total_modules_analyzed": "number -- count of modules analyzed",
  "total_models_analyzed": "number -- total Prisma models across all modules",
  "shared_enums": [
    {
      "enum_id": "string -- unique enum identifier (e.g., 'ENUM-001')",
      "enum_name": "string -- canonical enum name (e.g., 'Role', 'Status')",
      "values": ["string -- canonical enum values"],
      "used_by_modules": ["string -- module_ids that use this enum"],
      "used_by_models": [
        {
          "module_id": "string",
          "model_name": "string",
          "field_name": "string -- the field that uses this enum"
        }
      ],
      "consistency_status": "string -- 'consistent' | 'inconsistent' | 'superset_resolved'",
      "inconsistencies": [
        {
          "module_id": "string -- module with different values",
          "original_values": ["string -- values in this module"],
          "missing_values": ["string -- values present in canonical but not in this module"],
          "extra_values": ["string -- values present in this module but not in canonical"]
        }
      ]
    }
  ],
  "index_strategy": {
    "standard_indexes": [
      {
        "index_id": "string -- unique index identifier",
        "model": "string -- Prisma model name",
        "fields": ["string -- indexed fields"],
        "type": "string -- 'standard' | 'unique' | 'composite'",
        "rationale": "string -- why this index exists",
        "source_modules": ["string -- modules whose query patterns justify this index"],
        "estimated_impact": "string -- 'high' | 'medium' | 'low'"
      }
    ],
    "composite_indexes": [
      {
        "index_id": "string",
        "model": "string",
        "fields": ["string -- fields in composite index (order matters)"],
        "rationale": "string",
        "query_patterns": ["string -- query patterns this index optimizes"]
      }
    ],
    "unique_constraints": [
      {
        "constraint_id": "string",
        "model": "string",
        "fields": ["string -- fields forming the unique constraint"],
        "rationale": "string"
      }
    ]
  },
  "naming_conventions": {
    "table_names": {
      "pattern": "string -- naming pattern (e.g., 'PascalCase singular')",
      "examples": ["string -- example table names"],
      "violations": [
        {
          "module_id": "string",
          "model_name": "string",
          "current_name": "string",
          "suggested_name": "string"
        }
      ]
    },
    "column_names": {
      "pattern": "string -- naming pattern (e.g., 'camelCase')",
      "examples": ["string -- example column names"],
      "special_cases": {
        "foreign_keys": "string -- FK naming pattern (e.g., '{model}Id')",
        "boolean_fields": "string -- boolean naming pattern (e.g., 'is{Adjective}')",
        "timestamp_fields": "string -- timestamp naming pattern (e.g., '{action}At')"
      },
      "violations": [
        {
          "module_id": "string",
          "model_name": "string",
          "field_name": "string",
          "suggested_name": "string"
        }
      ]
    },
    "relation_names": {
      "pattern": "string -- relation naming pattern",
      "one_to_one": "string -- pattern for 1:1 (e.g., 'singular noun')",
      "one_to_many": "string -- pattern for 1:N (e.g., 'plural noun')",
      "many_to_many": "string -- pattern for M:N (e.g., 'plural noun via join table')"
    }
  },
  "audit_fields": {
    "standard_fields": [
      {
        "field_name": "string -- e.g., 'createdAt'",
        "type": "string -- Prisma type (e.g., 'DateTime')",
        "default": "string -- default value (e.g., 'now()')",
        "required": "boolean -- whether all models must have this field",
        "description": "string -- what this field tracks"
      }
    ],
    "models_missing_audit_fields": [
      {
        "module_id": "string",
        "model_name": "string",
        "missing_fields": ["string -- audit fields not present on this model"]
      }
    ]
  },
  "soft_delete_strategy": {
    "enabled": "boolean -- whether soft delete is used in the project",
    "implementation": {
      "field_name": "string -- e.g., 'deletedAt'",
      "field_type": "string -- e.g., 'DateTime?'",
      "filter_approach": "string -- 'middleware' | 'manual_where' | 'prisma_extension'",
      "description": "string -- how soft delete works"
    },
    "models_using_soft_delete": ["string -- model names that use soft delete"],
    "models_using_hard_delete": ["string -- model names that use hard delete (with rationale)"]
  },
  "pagination_pattern": {
    "default_strategy": "string -- 'offset' | 'cursor'",
    "default_page_size": "number -- default items per page",
    "max_page_size": "number -- maximum items per page",
    "response_shape": {
      "items": "array -- the paginated items",
      "total": "number -- total item count (offset only)",
      "page": "number -- current page (offset only)",
      "pageSize": "number -- items per page",
      "hasMore": "boolean -- whether more items exist",
      "cursor": "string | null -- next cursor (cursor only)"
    },
    "modules_using_offset": ["string -- modules using offset pagination"],
    "modules_using_cursor": ["string -- modules using cursor pagination"]
  },
  "timestamp_handling": {
    "timezone": "string -- standard timezone handling (e.g., 'UTC always, convert on client')",
    "format": "string -- timestamp format (e.g., 'ISO-8601')",
    "storage_type": "string -- Prisma type for timestamps (e.g., 'DateTime')",
    "fields_affected": ["string -- common timestamp field names"],
    "conversion_rules": {
      "input": "string -- how incoming timestamps are processed",
      "output": "string -- how outgoing timestamps are formatted",
      "display": "string -- how timestamps are displayed to users"
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `db_interaction` (all modules) | `db_flow.json` | Provides query patterns, index recommendations, and read patterns across all modules |
| input | `db_contract` (all modules) | `prisma_contract.json` | Provides model definitions, fields, enums, and naming for cross-module comparison |
| barrier | ALL Phase 6 agents | All modules must complete Phase 6 before this global agent starts |

| Blocks | Agent | Why |
|---|---|---|
| output | `architect_reconcile` | Reconcile needs DB patterns to build complete architecture |
| output | `production_bootstrap` | Bootstrap agent needs DB patterns for seed data and consistency |
| output | `impl_prep` | Impl prep agent needs DB patterns for Prisma schema configuration |

---

## Orchestrator Communication

### Agent Identity

This agent's ID is `global_db_patterns`. Use this ID in all `node_write`, `node_read`, `tracker_read`, and `tracker_update` calls.

### Tracker Access

| Direction | Compressed Keys | Purpose |
|---|---|---|
| read | (none) | Global agent -- does not read `md.a` |
| write | `ag` | Report agent status (completed/failed) |

### Output Meta

This agent does not produce routing/coordination metadata. `output_meta: null`.

### Completion Signal

- **On success:** `tracker_update(agent_id: "global_db_patterns", status: "completed")`
- **On failure:** `tracker_update(agent_id: "global_db_patterns", status: "failed", add_intervention: { id: "...", agent_id: "global_db_patterns", type: "error", message: "..." })`

### Scope Resolution

Global agent -- does NOT read `md.a`. Reads all modules' per-module artifacts in a single pass.

```
1. node_read(agent_id: "global_db_patterns", input_key: "db_flow_all")
2. node_read(agent_id: "global_db_patterns", input_key: "prisma_contract_all")
3. Process all modules → extract and standardize DB patterns
4. node_write(agent_id: "global_db_patterns", output_key: "global_db_patterns", data: {...})
5. tracker_update(agent_id: "global_db_patterns", status: "completed")
```

---

## Compressed Keymap

Use these compressed keys in all `node_write` calls. The registry validates against this map — unknown keys are rejected.

### Output: `global_db_patterns.json`

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | ISO-8601 timestamp |
| `tm` | total_modules_analyzed | Count of modules analyzed |
| `tl` | total_models_analyzed | Total Prisma models across all modules |
| `se` | shared_enums | Array of shared enum definitions |
| `se.ei` | enum_id | Unique enum ID (e.g., 'ENUM-001') |
| `se.en` | enum_name | Canonical enum name (e.g., 'Role') |
| `se.vl` | values | Canonical enum values |
| `se.um` | used_by_modules | Module IDs that use this enum |
| `se.ub` | used_by_models | Models using this enum |
| `se.ub.mi` | module_id | Module ID |
| `se.ub.mn` | model_name | Model name |
| `se.ub.fn` | field_name | Field that uses this enum |
| `se.cs` | consistency_status | consistent / inconsistent / superset_resolved |
| `se.ic` | inconsistencies | Detected inconsistencies |
| `se.ic.mi` | module_id | Module with different values |
| `se.ic.ov` | original_values | Values in this module |
| `se.ic.mv` | missing_values | Values missing from this module |
| `se.ic.ev` | extra_values | Extra values in this module |
| `is` | index_strategy | Global index strategy |
| `is.si` | standard_indexes | Standard index recommendations |
| `is.si.ii` | index_id | Unique index identifier |
| `is.si.md` | model | Prisma model name |
| `is.si.fd` | fields | Indexed fields |
| `is.si.tp` | type | standard / unique / composite |
| `is.si.rl` | rationale | Why this index exists |
| `is.si.sm` | source_modules | Modules justifying this index |
| `is.si.ei` | estimated_impact | high / medium / low |
| `is.ci` | composite_indexes | Composite index recommendations |
| `is.ci.ii` | index_id | Unique index identifier |
| `is.ci.md` | model | Prisma model name |
| `is.ci.fd` | fields | Fields in composite index (order matters) |
| `is.ci.rl` | rationale | Why this composite index |
| `is.ci.qp` | query_patterns | Query patterns this index optimizes |
| `is.uc` | unique_constraints | Unique constraint recommendations |
| `is.uc.ci` | constraint_id | Constraint identifier |
| `is.uc.md` | model | Prisma model name |
| `is.uc.fd` | fields | Fields forming the unique constraint |
| `is.uc.rl` | rationale | Why this constraint |
| `nc` | naming_conventions | Naming convention definitions |
| `nc.tn` | table_names | Table naming conventions |
| `nc.tn.pt` | pattern | Naming pattern (e.g., 'PascalCase singular') |
| `nc.tn.ex` | examples | Example table names |
| `nc.tn.vl` | violations | Naming violations |
| `nc.tn.vl.mi` | module_id | Module with violation |
| `nc.tn.vl.mn` | model_name | Model name |
| `nc.tn.vl.cn` | current_name | Current name |
| `nc.tn.vl.sn` | suggested_name | Suggested fix |
| `nc.cl` | column_names | Column naming conventions |
| `nc.cl.pt` | pattern | Naming pattern (e.g., 'camelCase') |
| `nc.cl.ex` | examples | Example column names |
| `nc.cl.sc` | special_cases | Special case patterns |
| `nc.cl.sc.fk` | foreign_keys | FK naming pattern |
| `nc.cl.sc.bf` | boolean_fields | Boolean naming pattern |
| `nc.cl.sc.tf` | timestamp_fields | Timestamp naming pattern |
| `nc.cl.vl` | violations | Column naming violations |
| `nc.cl.vl.mi` | module_id | Module with violation |
| `nc.cl.vl.mn` | model_name | Model name |
| `nc.cl.vl.fn` | field_name | Field name |
| `nc.cl.vl.sn` | suggested_name | Suggested fix |
| `nc.rn` | relation_names | Relation naming conventions |
| `nc.rn.pt` | pattern | Relation naming pattern |
| `nc.rn.oo` | one_to_one | Pattern for 1:1 relations |
| `nc.rn.om` | one_to_many | Pattern for 1:N relations |
| `nc.rn.mm` | many_to_many | Pattern for M:N relations |
| `af` | audit_fields | Standard audit field definitions |
| `af.sf` | standard_fields | Required audit fields |
| `af.sf.fn` | field_name | Field name (e.g., 'createdAt') |
| `af.sf.tp` | type | Prisma type (e.g., 'DateTime') |
| `af.sf.df` | default | Default value (e.g., 'now()') |
| `af.sf.rq` | required | Whether all models must have this |
| `af.sf.ds` | description | What this field tracks |
| `af.mm` | models_missing_audit_fields | Models missing audit fields |
| `af.mm.mi` | module_id | Module ID |
| `af.mm.mn` | model_name | Model name |
| `af.mm.mf` | missing_fields | Audit fields not present |
| `sd` | soft_delete_strategy | Soft delete configuration |
| `sd.en` | enabled | Whether soft delete is used |
| `sd.im` | implementation | Soft delete implementation details |
| `sd.im.fn` | field_name | Field name (e.g., 'deletedAt') |
| `sd.im.ft` | field_type | Field type (e.g., 'DateTime?') |
| `sd.im.fa` | filter_approach | middleware / manual_where / prisma_extension |
| `sd.im.ds` | description | How soft delete works |
| `sd.ms` | models_using_soft_delete | Models using soft delete |
| `sd.mh` | models_using_hard_delete | Models using hard delete |
| `pp` | pagination_pattern | Pagination standardization |
| `pp.ds` | default_strategy | offset / cursor |
| `pp.dp` | default_page_size | Default items per page |
| `pp.mp` | max_page_size | Maximum items per page |
| `pp.rs` | response_shape | Standard pagination response shape |
| `pp.rs.it` | items | The paginated items |
| `pp.rs.tl` | total | Total item count (offset only) |
| `pp.rs.pg` | page | Current page (offset only) |
| `pp.rs.ps` | pageSize | Items per page |
| `pp.rs.hm` | hasMore | Whether more items exist |
| `pp.rs.cr` | cursor | Next cursor (cursor only) |
| `pp.mo` | modules_using_offset | Modules using offset pagination |
| `pp.mc` | modules_using_cursor | Modules using cursor pagination |
| `th` | timestamp_handling | Timestamp standardization |
| `th.tz` | timezone | Standard timezone handling |
| `th.fm` | format | Timestamp format (e.g., 'ISO-8601') |
| `th.st` | storage_type | Prisma type for timestamps |
| `th.fa` | fields_affected | Common timestamp field names |
| `th.cr` | conversion_rules | Timestamp conversion rules |
| `th.cr.in` | input | How incoming timestamps are processed |
| `th.cr.ou` | output | How outgoing timestamps are formatted |
| `th.cr.dy` | display | How timestamps are displayed to users |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write global_db_patterns output via registry-validated compressed keys. Agent calls `node_write(agent_id: "global_db_patterns", output_key: "global_db_patterns", data: {...})`. | Pending |
| `node_read` | Read upstream artifacts (db_flow_all, prisma_contract_all). Agent calls `node_read(agent_id: "global_db_patterns", input_key: "db_flow_all")`. | Pending |
| `tracker_read` | Read pipeline state. Agent calls `tracker_read(agent_id: "global_db_patterns", fields: [...])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "global_db_patterns", status: "completed")`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Enums with the same name across modules must have consistent values -- differences must be flagged and resolved |
| R-002 | `constraint` | `must` | Must standardize timestamp handling (timezone, format, storage type) across all modules |
| R-003 | `constraint` | `must` | Must define a consistent soft delete pattern and identify which models use it |
| R-004 | `constraint` | `must` | Must define standard audit fields (createdAt, updatedAt) and flag models missing them |
| R-005 | `output_quality` | `must` | Naming convention violations must be identified with suggested corrections |
| R-006 | `output_quality` | `must` | Index strategy must be based on actual query patterns from db_flow.json, not guesses |
| R-007 | `data_handling` | `should` | Pagination pattern should standardize response shape across all modules |
| R-008 | `scope_boundary` | `should` | Composite indexes should be recommended only when query patterns justify them |
| R-009 | `not_allowed` | `must` | Must not invent models, fields, or enums not present in any module's prisma_contract |
| R-010 | `output_quality` | `should` | Foreign key naming should follow a consistent pattern documented in naming_conventions |
| R-011 | `constraint` | `must` | Must use compressed keys as defined in the Compressed Keymap section for all `node_write` / `node_read` calls. Never use expanded/full key names. |
| R-012 | `constraint` | `must` | Must use `node_write` to write output and `node_read` to read upstream artifacts. Must not use raw file writes, generic file_writer, or any other method. |
| R-013 | `constraint` | `must` | Must call `tracker_update(agent_id: "global_db_patterns", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "global_db_patterns", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32000 |
| max_indexes_recommended | 100 |

---

## Scope Boundary

**In scope:**
- Identifying and standardizing shared enums across modules
- Defining global index strategy based on query patterns
- Establishing naming conventions for tables, columns, and relations
- Defining standard audit fields and flagging models missing them
- Establishing soft delete strategy
- Standardizing pagination patterns
- Standardizing timestamp handling

**Out of scope:**
- Modifying per-module Prisma contracts (read-only)
- Implementing database migrations (Phase 10)
- Defining middleware or endpoint policies (global_middleware/global_security)
- Cross-module service extraction (global_services agent's job)
- Writing Prisma schema code

---

## Triggers

- Orchestrator detects that ALL modules have completed Phase 6 (barrier cleared)
- Can run in PARALLEL with global_services, global_middleware, global_navigation, global_security (independent inputs)
- Triggered once (global granularity)

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All modules' db_flow.json and prisma_contract.json loaded | `log` |
| `CP-002` | Shared enums identified -- inconsistencies found | `notify` |
| `CP-003` | Naming convention analysis complete -- violations flagged | `log` |
| `CP-004` | Index strategy compiled from query patterns | `log` |
| `CP-005` | Audit fields, soft delete, pagination, and timestamp patterns standardized | `log` |
| `CP-006` | Global DB patterns output generated and schema-validated | `notify` |

---

## Validation Criteria

- Every enum that appears in 2+ modules is listed in shared_enums
- Enum inconsistencies are flagged with module-specific original values
- Naming conventions define patterns for tables, columns, foreign keys, booleans, and timestamps
- Naming violations reference valid module_ids and model names
- Index strategy indexes reference valid models and fields from prisma_contract
- Audit fields define at least createdAt and updatedAt
- Models missing audit fields are identified
- Pagination pattern defines a standard response shape
- Timestamp handling defines timezone, format, and conversion rules
- Output JSON passes schema validation

---

## Context Sources

- db_flow.json from all modules (query patterns, index recommendations, read patterns)
- prisma_contract.json from all modules (model definitions, enums, naming)
- Prisma best practices for naming, indexing, and patterns

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` |

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | Enum deduplication engine that identifies same-name enums and checks value consistency | this agent | Inconsistent enum values cause type errors at compile and runtime |
| `TG-002` | Index optimizer that analyzes query patterns to recommend optimal indexes | this agent | Suboptimal indexes lead to slow queries in production |
| `TG-003` | Naming convention validator that checks all names against defined patterns | this agent | Naming inconsistencies make codebase harder to maintain and navigate |
| `TG-004` | `node_write` MCP tool not yet built | this agent | Cannot write output with registry validation -- blocked |
| `TG-005` | `node_read` MCP tool not yet built | this agent | Cannot read upstream artifacts with field enforcement -- blocked |
| `TG-006` | `tracker_read` MCP tool not yet built | this agent | Cannot read pipeline state -- blocked |
| `TG-007` | `tracker_update` MCP tool not yet built | this agent | Cannot report completion -- blocked |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `global-db-patterns` |
| `agentName` | ready | `global_db_patterns` |
| `agentRole` | ready | Cross-Module DB Pattern Standardizer |
| `agentDescription` | ready | Standardizes database patterns including enums, naming, indexes, and common field strategies across all modules |
| `operationMode` | ready | autonomous, no fallback |
| `goal` | ready | Three objectives defined with clear priorities |
| `inputs` | ready | All modules' db_flow.json and prisma_contract.json |
| `guardrails` | ready | 13 rules covering constraints, quality, data handling, scope, universal tools, and completion signal |
| `scopeBoundary` | ready | 7 in-scope items, 5 out-of-scope items |
| `outputFormat` | ready | JSON output with full shape for global_db_patterns.json |
| `triggers` | ready | Barrier-triggered after all modules complete Phase 6; parallel with other Phase 7 agents |
| `checkpoints` | ready | 6 checkpoints covering loading, enums, naming, indexes, and output |
| `validation` | ready | 10 validation criteria |
| `contextSources` | ready | 3 context sources listed |
| `metadata` | ready | Phase 7, global, autonomous, both modes |
