# Global Services Agent

> **Greek:** Koinonia (Koinonia) -- "community/sharing"
> **Sanskrit:** Seva (Seva) -- "service/dedication"
> **Tagline:** *"What one module needs, all modules share"*

---

## Agent Identity

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

---

## Goal & Objectives

**Goal:** Analyze all per-module policy flows and DB flows to extract services used by multiple modules, creating a shared services registry that eliminates duplication and defines clear API boundaries for cross-module functionality.

| Priority | Objective |
|---|---|
| primary | Identify and extract shared services -- functions and patterns used by two or more modules -- into a global services registry with clear API boundaries |
| secondary | Define service dependencies to prevent circular references and establish a clean service dependency graph |
| tertiary | Ensure single-module services remain module-scoped and are not incorrectly promoted to shared status |

---

## 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",
      "handler": {
        "service_function": "string -- service function name (e.g., 'UserService.createUser')",
        "params": [
          {
            "name": "string",
            "source": "string",
            "field": "string"
          }
        ],
        "returns": {
          "type": "string",
          "schema_ref": "string"
        }
      },
      "story_refs": ["string"]
    }
  ]
}
```

### 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",
      "service_function": "string",
      "db_operations": [
        {
          "model": "string -- Prisma model",
          "action": "string -- CRUD action",
          "fields": { "select": ["string"], "data": {} }
        }
      ]
    }
  ],
  "transactions": [
    {
      "transaction_id": "string",
      "operations": [{ "operation_id": "string", "order": "number" }]
    }
  ]
}
```

---

## Outputs

### global_services_registry.json
- **Path:** `agent_output/architecture/global/global_services_registry.json`
- **Format:** `json`
- **Consumers:** `architect_reconcile`, `impl_prep`, `be_impl`
- **Shape:**
```json
{
  "generated_at": "string -- ISO-8601 timestamp",
  "total_services": "number -- total shared services identified",
  "total_modules_analyzed": "number -- count of modules analyzed",
  "services": [
    {
      "service_id": "string -- unique service identifier (e.g., 'SVC-001')",
      "name": "string -- service name (e.g., 'NotificationService')",
      "description": "string -- what this service does",
      "category": "string -- 'data_access' | 'business_logic' | 'integration' | 'utility' | 'notification' | 'file_handling'",
      "used_by_modules": ["string -- module_ids that use this service"],
      "usage_count": "number -- total number of endpoint references across all modules",
      "functions": [
        {
          "function_name": "string -- function identifier (e.g., 'sendEmail')",
          "description": "string -- what this function does",
          "params": [
            {
              "name": "string -- parameter name",
              "type": "string -- parameter type",
              "required": "boolean",
              "description": "string -- parameter description"
            }
          ],
          "returns": {
            "type": "string -- return type",
            "description": "string -- what is returned"
          },
          "side_effects": ["string -- side effects (e.g., 'sends email', 'writes to audit log', 'publishes event')"],
          "source_endpoints": [
            {
              "module_id": "string -- module where this function is referenced",
              "endpoint_path": "string -- endpoint that calls this function",
              "endpoint_method": "string -- HTTP method"
            }
          ]
        }
      ],
      "dependencies": [
        {
          "service_id": "string -- service this service depends on",
          "dependency_type": "string -- 'calls' | 'data_from' | 'event_from'"
        }
      ],
      "data_models_accessed": ["string -- Prisma model names this service reads/writes"],
      "recommended_location": "string -- suggested file path (e.g., 'src/services/notification.service.ts')"
    }
  ],
  "module_only_services": [
    {
      "service_name": "string -- service that stays module-scoped",
      "module_id": "string -- the single module that uses it",
      "reason": "string -- why it was not promoted to shared (e.g., 'used by only one module')"
    }
  ],
  "dependency_graph": {
    "nodes": ["string -- service_ids"],
    "edges": [
      {
        "from": "string -- dependent service_id",
        "to": "string -- dependency service_id",
        "type": "string -- 'calls' | 'data_from' | 'event_from'"
      }
    ],
    "circular_dependencies": ["string -- description of any detected circular deps (should be empty)"]
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `be_policy` (all modules) | `be_policy_flow.json` | Provides handler function definitions and endpoint-to-service mappings |
| input | `db_interaction` (all modules) | `db_flow.json` | Provides DB operation details showing which models each service accesses |
| barrier | ALL Phase 6 agents | All modules must complete Phase 6 before this global agent starts |

| Blocks | Agent | Why |
|---|---|---|
| output | `architect_reconcile` | Reconcile needs shared services to build complete architecture |
| output | `impl_prep` | Impl prep agent needs service registry to generate shared service files |

---

## Orchestrator Communication

### Agent Identity

This agent's ID is `global_services`. 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_services", status: "completed")`
- **On failure:** `tracker_update(agent_id: "global_services", status: "failed", add_intervention: { id: "...", agent_id: "global_services", 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_services", input_key: "be_policy_flow_all")
2. node_read(agent_id: "global_services", input_key: "db_flow_all")
3. Process all modules → extract shared services
4. node_write(agent_id: "global_services", output_key: "global_services_registry", data: {...})
5. tracker_update(agent_id: "global_services", 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_services_registry.json`

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | ISO-8601 timestamp |
| `ts` | total_services | Total shared services identified |
| `tm` | total_modules_analyzed | Count of modules analyzed |
| `sv` | services | Array of shared service definitions |
| `sv.si` | service_id | Unique service ID (e.g., 'SVC-001') |
| `sv.nm` | name | Service name (e.g., 'NotificationService') |
| `sv.ds` | description | What this service does |
| `sv.ct` | category | data_access / business_logic / integration / utility / notification / file_handling |
| `sv.um` | used_by_modules | Module IDs that use this service |
| `sv.uc` | usage_count | Total endpoint references across all modules |
| `sv.fn` | functions | Array of service function definitions |
| `sv.fn.nm` | function_name | Function identifier (e.g., 'sendEmail') |
| `sv.fn.ds` | description | What this function does |
| `sv.fn.pm` | params | Function parameters |
| `sv.fn.pm.nm` | name | Parameter name |
| `sv.fn.pm.tp` | type | Parameter type |
| `sv.fn.pm.rq` | required | Whether required |
| `sv.fn.pm.ds` | description | Parameter description |
| `sv.fn.rt` | returns | Return type definition |
| `sv.fn.rt.tp` | type | Return type |
| `sv.fn.rt.ds` | description | What is returned |
| `sv.fn.se` | side_effects | Side effects (e.g., 'sends email', 'publishes event') |
| `sv.fn.ep` | source_endpoints | Endpoints that call this function |
| `sv.fn.ep.mi` | module_id | Module where this function is referenced |
| `sv.fn.ep.pt` | endpoint_path | Endpoint that calls this function |
| `sv.fn.ep.mt` | endpoint_method | HTTP method |
| `sv.dp` | dependencies | Services this service depends on |
| `sv.dp.si` | service_id | Dependent service ID |
| `sv.dp.dt` | dependency_type | calls / data_from / event_from |
| `sv.dm` | data_models_accessed | Prisma model names this service reads/writes |
| `sv.rl` | recommended_location | Suggested file path |
| `ms` | module_only_services | Services that stay module-scoped |
| `ms.sn` | service_name | Service that stays module-scoped |
| `ms.mi` | module_id | The single module that uses it |
| `ms.rs` | reason | Why it was not promoted to shared |
| `dg` | dependency_graph | Service dependency graph |
| `dg.nd` | nodes | Service IDs |
| `dg.ed` | edges | Dependency edges |
| `dg.ed.fr` | from | Dependent service ID |
| `dg.ed.to` | to | Dependency service ID |
| `dg.ed.tp` | type | calls / data_from / event_from |
| `dg.cd` | circular_dependencies | Detected circular deps (should be empty) |

---

## Tools Required

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

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must identify services used by 2+ modules -- single-module services stay module-scoped |
| R-002 | `constraint` | `must` | Must not create a shared service for functionality used by only one module |
| R-003 | `constraint` | `must` | Must define clear API boundaries (params, returns, side effects) for every shared service function |
| R-004 | `output_quality` | `must` | Service dependency graph must have no circular dependencies |
| R-005 | `data_handling` | `must` | Must track which endpoints in which modules use each service for full traceability |
| R-006 | `scope_boundary` | `should` | Services should be categorized (data_access, business_logic, integration, utility, etc.) |
| R-007 | `output_quality` | `should` | Side effects of each function should be explicitly documented |
| R-008 | `not_allowed` | `must` | Must not invent services not backed by actual endpoint handler references |
| R-009 | `constraint` | `should` | Similar service functions across modules (same behavior, different names) should be unified under one shared service |
| R-010 | `output_quality` | `should` | Module-only services should be documented with reason for not promoting |
| 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_services", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "global_services", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32000 |
| max_services | 50 |
| max_functions_per_service | 20 |

---

## Scope Boundary

**In scope:**
- Scanning all modules' be_policy_flow.json and db_flow.json for cross-module patterns
- Identifying shared services (used by 2+ modules)
- Defining service APIs (functions, params, returns, side effects)
- Building service dependency graph
- Documenting module-only services and why they are not shared
- Recommending file locations for shared services

**Out of scope:**
- Implementing service code (Phase 10 BE implementation)
- Defining middleware (global_middleware agent's job)
- Modifying per-module contracts or flows (read-only)
- Cross-module security policy (global_security agent's job)
- Database pattern standardization (global_db_patterns agent's job)

---

## Triggers

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

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All modules' be_policy_flow.json and db_flow.json loaded | `log` |
| `CP-002` | Cross-module pattern analysis complete -- shared patterns identified | `log` |
| `CP-003` | Shared services extracted and APIs defined | `log` |
| `CP-004` | Circular dependency detected in service graph | `notify` |
| `CP-005` | Global services registry generated and schema-validated | `notify` |

---

## Validation Criteria

- Every shared service is used by at least 2 modules (used_by_modules.length >= 2)
- No module-only services appear in the shared services list
- Service dependency graph has no circular dependencies
- Every service function has defined params, returns, and side_effects
- All source_endpoints reference valid module_ids and endpoint paths from input data
- All service_ids are unique
- Total services count matches services array length
- Output JSON passes schema validation

---

## Context Sources

- be_policy_flow.json from all modules (handler functions and endpoint mappings)
- db_flow.json from all modules (DB operation details and model access patterns)
- Common service patterns in web applications (auth, notification, file upload, etc.)

---

## Operation Mode

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

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | Cross-module service detector that identifies service patterns appearing in multiple modules | this agent | Must manually compare handler functions across all modules; risk of missing shared patterns |
| `TG-002` | Service deduplication engine that unifies similar functions with different names | this agent | Near-duplicate services remain separate; code duplication in implementation |
| `TG-003` | Dependency graph analyzer that detects circular references in the service graph | this agent | Circular dependencies cause runtime issues; 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-services` |
| `agentName` | ready | `global_services` |
| `agentRole` | ready | Shared Services Extractor |
| `agentDescription` | ready | Identifies and extracts shared services across 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 db_flow.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_services_registry.json |
| `triggers` | ready | Barrier-triggered after all modules complete Phase 6; parallel with other Phase 7 agents |
| `checkpoints` | ready | 5 checkpoints covering loading, analysis, extraction, and output |
| `validation` | ready | 8 validation criteria |
| `contextSources` | ready | 3 context sources listed |
| `metadata` | ready | Phase 7, global, autonomous, both modes |
