# Global Middleware Agent

> **Greek:** Mesites (Mesites) -- "mediator"
> **Sanskrit:** Madhyastha (Madhyastha) -- "mediator/arbiter"
> **Tagline:** *"The invisible hand between request and response"*

---

## Agent Identity

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

---

## Goal & Objectives

**Goal:** Deduplicate and unify middleware definitions across all modules, producing a global middleware registry that establishes shared middleware with module-specific variants, consistent ordering rules, and a single source of truth for all request processing layers.

| Priority | Objective |
|---|---|
| primary | Deduplicate identical middleware across modules into shared middleware definitions while preserving module-specific configuration variants |
| secondary | Establish global ordering rules that all modules follow, ensuring consistent middleware execution order application-wide |
| tertiary | Identify opportunities to consolidate near-identical middleware (same type, slightly different config) into parameterized shared middleware |

---

## Inputs

### be_policy_flow.json (ALL modules)
- **Source:** `be_policy` -> `agent_output/architecture/{module_id}/be_policy_flow.json` (for each module)
- **Required:** yes
- **Shape:**
```json
{
  "module_id": "string -- module identifier",
  "endpoints": [
    {
      "path": "string -- API path",
      "method": "string -- HTTP method",
      "middleware_chain": [
        {
          "middleware_id": "string",
          "type": "string -- middleware type",
          "name": "string",
          "order": "number",
          "config": {
            "strategy": "string | null",
            "schema_ref": "string | null",
            "window_ms": "number | null",
            "max_requests": "number | null",
            "custom_config": "object | null"
          }
        }
      ]
    }
  ]
}
```

### middleware_registry.json (ALL modules)
- **Source:** `be_policy` -> `agent_output/architecture/{module_id}/middleware_registry.json` (for each module)
- **Required:** yes
- **Shape:**
```json
{
  "module_id": "string -- module identifier",
  "middleware": [
    {
      "middleware_id": "string",
      "name": "string",
      "type": "string",
      "description": "string",
      "default_config": {
        "strategy": "string | null",
        "schema_ref": "string | null",
        "window_ms": "number | null",
        "max_requests": "number | null",
        "custom_config": "object | null"
      },
      "used_by_endpoints": [
        {
          "path": "string",
          "method": "string",
          "config_override": "object | null"
        }
      ],
      "ordering_rules": {
        "must_run_before": ["string"],
        "must_run_after": ["string"]
      }
    }
  ],
  "standard_chain_order": [
    {
      "order": "number",
      "type": "string",
      "rationale": "string"
    }
  ]
}
```

---

## Outputs

### global_middleware_registry.json
- **Path:** `agent_output/architecture/global/global_middleware_registry.json`
- **Format:** `json`
- **Consumers:** `architect_reconcile`, `impl_prep`, `be_impl`
- **Shape:**
```json
{
  "generated_at": "string -- ISO-8601 timestamp",
  "total_middleware": "number -- total unique middleware in global registry",
  "total_modules_analyzed": "number -- count of modules analyzed",
  "deduplication_summary": {
    "original_count": "number -- total middleware across all modules before deduplication",
    "deduplicated_count": "number -- unique middleware after deduplication",
    "savings_percentage": "number -- percentage reduction"
  },
  "middleware": [
    {
      "middleware_id": "string -- global unique middleware identifier (e.g., 'GMW-001')",
      "name": "string -- human-readable name (e.g., 'JWT Authentication')",
      "type": "string -- 'auth' | 'validation' | 'rate_limit' | 'logging' | 'transform' | 'cache' | 'cors' | 'sanitization'",
      "description": "string -- what this middleware does",
      "shared": "boolean -- true if used by 2+ modules, false if module-specific",
      "default_config": {
        "strategy": "string | null -- e.g., 'jwt', 'api_key'",
        "window_ms": "number | null -- rate limit window",
        "max_requests": "number | null -- rate limit max",
        "cache_ttl": "number | null -- cache TTL",
        "log_level": "string | null -- logging level",
        "custom_config": "object | null -- additional config"
      },
      "variants": [
        {
          "variant_id": "string -- unique variant identifier",
          "module_id": "string -- module this variant applies to",
          "config_overrides": {
            "field_name": "any -- the overridden value"
          },
          "reason": "string -- why this module needs a different config"
        }
      ],
      "used_by_modules": ["string -- module_ids using this middleware"],
      "used_by_endpoints_count": "number -- total endpoint references across all modules",
      "ordering_rules": {
        "global_order": "number -- position in the global standard chain",
        "must_run_before": ["string -- middleware types that must come after"],
        "must_run_after": ["string -- middleware types that must come before"],
        "rationale": "string -- why this ordering"
      },
      "source_middleware_ids": ["string -- original per-module middleware_ids that were merged into this"]
    }
  ],
  "global_chain_order": [
    {
      "order": "number -- 1-based position",
      "type": "string -- middleware type",
      "middleware_id": "string -- reference to middleware in registry",
      "rationale": "string -- why this position in the chain",
      "optional": "boolean -- whether this middleware is always present or conditionally applied"
    }
  ],
  "ordering_conflicts": [
    {
      "conflict_id": "string -- unique conflict identifier",
      "modules_involved": ["string -- module_ids with conflicting orders"],
      "middleware_a": "string -- first middleware type",
      "middleware_b": "string -- second middleware type",
      "conflict_description": "string -- what the ordering conflict is",
      "resolution": "string -- how the conflict was resolved"
    }
  ]
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `be_policy` (all modules) | `be_policy_flow.json` | Provides middleware chains for all endpoints across all modules |
| input | `be_policy` (all modules) | `middleware_registry.json` | Provides per-module middleware catalogs with configs and ordering rules |
| barrier | ALL Phase 6 agents | All modules must complete Phase 6 before this global agent starts |

| Blocks | Agent | Why |
|---|---|---|
| output | `architect_reconcile` | Reconcile needs global middleware to build complete architecture |
| output | `impl_prep` | Impl prep agent uses global middleware to generate middleware files |

---

## Orchestrator Communication

### Agent Identity

This agent's ID is `global_middleware`. 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_middleware", status: "completed")`
- **On failure:** `tracker_update(agent_id: "global_middleware", status: "failed", add_intervention: { id: "...", agent_id: "global_middleware", 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_middleware", input_key: "be_policy_flow_all")
2. node_read(agent_id: "global_middleware", input_key: "middleware_registry_all")
3. Process all modules → deduplicate and unify middleware
4. node_write(agent_id: "global_middleware", output_key: "global_middleware_registry", data: {...})
5. tracker_update(agent_id: "global_middleware", 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_middleware_registry.json`

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | ISO-8601 timestamp |
| `tm` | total_middleware | Total unique middleware in global registry |
| `ta` | total_modules_analyzed | Count of modules analyzed |
| `ds` | deduplication_summary | Deduplication statistics |
| `ds.oc` | original_count | Total middleware before deduplication |
| `ds.dc` | deduplicated_count | Unique middleware after deduplication |
| `ds.sp` | savings_percentage | Percentage reduction |
| `mw` | middleware | Array of global middleware definitions |
| `mw.mi` | middleware_id | Global unique middleware ID (e.g., 'GMW-001') |
| `mw.nm` | name | Human-readable name |
| `mw.tp` | type | auth / validation / rate_limit / logging / transform / cache / cors / sanitization |
| `mw.ds` | description | What this middleware does |
| `mw.sh` | shared | True if used by 2+ modules |
| `mw.dc` | default_config | Default middleware configuration |
| `mw.dc.sg` | strategy | Auth strategy (jwt, api_key) |
| `mw.dc.wm` | window_ms | Rate limit window |
| `mw.dc.mr` | max_requests | Rate limit max requests |
| `mw.dc.ct` | cache_ttl | Cache TTL |
| `mw.dc.ll` | log_level | Logging level |
| `mw.dc.cc` | custom_config | Additional config |
| `mw.vr` | variants | Module-specific config variants |
| `mw.vr.vi` | variant_id | Unique variant identifier |
| `mw.vr.mi` | module_id | Module this variant applies to |
| `mw.vr.co` | config_overrides | Overridden config values |
| `mw.vr.rs` | reason | Why this module needs a different config |
| `mw.um` | used_by_modules | Module IDs using this middleware |
| `mw.ue` | used_by_endpoints_count | Total endpoint references across modules |
| `mw.or` | ordering_rules | Ordering constraints |
| `mw.or.go` | global_order | Position in global standard chain |
| `mw.or.mb` | must_run_before | Middleware types that must come after |
| `mw.or.ma` | must_run_after | Middleware types that must come before |
| `mw.or.rl` | rationale | Why this ordering |
| `mw.sm` | source_middleware_ids | Original per-module middleware IDs merged into this |
| `gc` | global_chain_order | Global middleware chain ordering |
| `gc.or` | order | 1-based position |
| `gc.tp` | type | Middleware type |
| `gc.mi` | middleware_id | Reference to middleware in registry |
| `gc.rl` | rationale | Why this position |
| `gc.op` | optional | Whether conditionally applied |
| `oc` | ordering_conflicts | Detected ordering conflicts |
| `oc.ci` | conflict_id | Unique conflict identifier |
| `oc.mi` | modules_involved | Module IDs with conflicting orders |
| `oc.ma` | middleware_a | First middleware type |
| `oc.mb` | middleware_b | Second middleware type |
| `oc.cd` | conflict_description | What the ordering conflict is |
| `oc.rs` | resolution | How the conflict was resolved |

---

## Tools Required

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

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must deduplicate identical middleware across modules -- same type + same config = one shared middleware |
| R-002 | `constraint` | `must` | Must preserve module-specific config variants as named variants on the shared middleware |
| R-003 | `constraint` | `must` | Must define global ordering rules that are consistent across all modules |
| R-004 | `output_quality` | `must` | All ordering conflicts between modules must be detected and resolved with documented rationale |
| R-005 | `data_handling` | `must` | Must track source_middleware_ids linking back to original per-module middleware for traceability |
| R-006 | `scope_boundary` | `should` | Near-identical middleware (same type, minor config differences) should be consolidated into parameterized shared middleware with variants |
| R-007 | `output_quality` | `should` | Each middleware should document why it occupies its position in the global chain |
| R-008 | `not_allowed` | `must` | Must not invent middleware not present in any module's registry |
| R-009 | `constraint` | `should` | Shared middleware (used by 2+ modules) should be marked shared=true |
| R-010 | `output_quality` | `must` | Deduplication summary must accurately reflect counts before and after deduplication |
| 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_middleware", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "global_middleware", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32000 |
| max_global_middleware | 50 |
| max_variants_per_middleware | 20 |

---

## Scope Boundary

**In scope:**
- Deduplicating middleware across all modules
- Merging identical middleware into shared definitions
- Preserving module-specific configuration variants
- Establishing global middleware chain ordering
- Detecting and resolving ordering conflicts
- Tracking source middleware for traceability

**Out of scope:**
- Implementing middleware code (Phase 10 BE implementation)
- Defining per-endpoint middleware chains (be_policy agent already did this)
- Modifying per-module policy flows (read-only)
- Security policy definition (global_security agent's job)
- Service extraction (global_services agent's job)

---

## Triggers

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

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All modules' be_policy_flow.json and middleware_registry.json loaded | `log` |
| `CP-002` | Deduplication analysis complete -- identical middleware identified | `log` |
| `CP-003` | Near-identical middleware consolidated into parameterized variants | `log` |
| `CP-004` | Ordering conflict detected between modules | `notify` |
| `CP-005` | Global middleware registry generated and schema-validated | `notify` |

---

## Validation Criteria

- Every middleware from every module's registry appears in the global registry (either as shared or as a variant)
- No duplicate middleware (same type + same config) exists as separate entries
- Global chain order has no contradictions (no middleware ordered both before and after another)
- All ordering conflicts are documented with resolutions
- Deduplication summary counts match actual data
- All middleware_ids and variant_ids are unique
- Source_middleware_ids reference valid per-module middleware
- Output JSON passes schema validation

---

## Context Sources

- be_policy_flow.json from all modules (middleware chains per endpoint)
- middleware_registry.json from all modules (middleware catalogs with configs)
- Industry-standard middleware ordering patterns

---

## Operation Mode

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

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | Middleware deduplication engine that identifies identical and near-identical middleware across modules | this agent | Duplicate middleware definitions waste implementation effort and cause inconsistency |
| `TG-002` | Config merger that intelligently merges middleware configs, identifying defaults and variants | this agent | Config conflicts may go unresolved; manual merging is error-prone |
| `TG-003` | Ordering conflict detector that identifies contradictory middleware ordering rules across modules | this agent | Ordering conflicts cause runtime errors; undetected until implementation |
| `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-middleware` |
| `agentName` | ready | `global_middleware` |
| `agentRole` | ready | Global Middleware Deduplicator |
| `agentDescription` | ready | Deduplicates and unifies middleware across all modules into a global registry |
| `operationMode` | ready | autonomous, no fallback |
| `goal` | ready | Three objectives defined with clear priorities |
| `inputs` | ready | All modules' be_policy_flow.json and middleware_registry.json |
| `guardrails` | ready | 13 rules covering constraints, quality, data handling, scope, universal tools, and completion signal |
| `scopeBoundary` | ready | 6 in-scope items, 5 out-of-scope items |
| `outputFormat` | ready | JSON output with full shape for global_middleware_registry.json |
| `triggers` | ready | Barrier-triggered after all modules complete Phase 6; parallel with other Phase 7 agents |
| `checkpoints` | ready | 5 checkpoints covering loading, deduplication, conflicts, and output |
| `validation` | ready | 8 validation criteria |
| `contextSources` | ready | 3 context sources listed |
| `metadata` | ready | Phase 7, global, autonomous, both modes |
