# Phase 1 Technical Specification

## 1. Purpose

This specification defines the **Phase 1 additive implementation** for agentic flow generation while preserving the current human Flow Builder and deterministic runtime.

Phase 1 introduces:

1. Proposal generation API (draft only)
2. Proposal persistence model
3. Normalizer + validator pipeline to current canvas contract
4. Human review and publish via existing Flow Builder path

Phase 1 does **not** change DAG execution, route lookup, or adapter invocation behavior.

---

## 2. Scope and Non-Goals

### In Scope

1. Generate AI proposals from user intent
2. Store proposals with lifecycle status
3. Convert proposal graph to existing `canvas_json` contract
4. Attach optional proposal metadata to flow records
5. Load proposal into existing Flow Builder for manual edits

### Out of Scope

1. Direct AI auto-publish to production
2. Runtime dependence on LLM metadata
3. Changes to `MwRouter.Pipeline`, `MwRouter.DagExecutor`, `MwRouter.Dispatcher`, `MwRouter.RouteTable`
4. MCP callback enforcement on all adapters (deferred to Phase 2)

---

## 3. Functional Requirements

1. Human users can request an AI-generated flow proposal from business intent.
2. System stores the proposal and normalized canvas output.
3. User can open proposal in Flow Builder as editable draft.
4. User may reject proposal, revise manually, or publish through existing path.
5. All publish actions continue using existing route publication behavior.
6. Every proposal has full audit trail (requested by, approved by, timestamps).

---

## 4. Canonical Contracts

## 4.1 Existing Runtime Contract (Unchanged)

The canonical execution contract remains current canvas-to-DAG transformation.

Required shape:

- `canvas_version`: string
- `nodes`: list of canvas nodes
- `connections`: list of typed edges

Node type enum remains:

- `request`
- `slot`
- `adapter`
- `decision`
- `transform`
- `merge`
- `response`
- `webhook_trigger`
- `webhook_action`

Edge type enum remains:

- `primary`
- `fallback`
- `dependency`
- `yes_branch`
- `no_branch`

## 4.2 Proposal Envelope Contract (New)

AI orchestration returns a proposal envelope, not runtime payload directly:

```json
{
  "proposal_id": "ap_01JV...",
  "requested_by": "admin_user_id",
  "tenant_id": "tenant_a",
  "goal": "Route high-value payment via fraud check with fallback",
  "source": "orchestrator_v1",
  "raw_graph": {
    "nodes": [],
    "connections": []
  },
  "normalized_canvas": {
    "canvas_version": "1",
    "nodes": [],
    "connections": []
  },
  "validation": {
    "status": "pass",
    "warnings": [],
    "errors": []
  },
  "status": "draft_generated",
  "created_at": "2026-05-24T12:00:00Z"
}
```

Runtime ignores this envelope. Only `normalized_canvas` is used by editor and downstream save/publish.

---

## 5. Proposal Lifecycle

States:

1. `draft_generated`
2. `draft_opened`
3. `draft_edited`
4. `validation_failed`
5. `approved`
6. `rejected`
7. `published`
8. `archived`

Allowed transitions:

1. `draft_generated -> draft_opened`
2. `draft_opened -> draft_edited`
3. `draft_opened -> approved | rejected | validation_failed`
4. `draft_edited -> approved | rejected | validation_failed`
5. `approved -> published | archived`
6. `rejected -> archived`

Publish prerequisite: state must be `approved` and validation status `pass`.

---

## 6. Persistence Model

## 6.1 New Table: ai_flow_proposals

Suggested relational schema:

- `id` bigint PK
- `proposal_id` varchar(64) unique not null
- `flow_id` bigint null (links to existing flows record after save)
- `tenant_id` varchar(255) null
- `message_type` varchar(255) null
- `goal` text not null
- `source` varchar(100) not null default `orchestrator_v1`
- `status` varchar(50) not null
- `raw_graph_json` longtext not null
- `normalized_canvas_json` longtext null
- `validation_status` varchar(20) not null default `pending`
- `validation_errors_json` longtext null
- `validation_warnings_json` longtext null
- `requested_by` varchar(255) not null
- `approved_by` varchar(255) null
- `published_by` varchar(255) null
- `published_flow_id` bigint null
- `created_at` datetime(6)
- `updated_at` datetime(6)

Indexes:

1. unique index on `proposal_id`
2. index on `(tenant_id, status)`
3. index on `(message_type, status)`
4. index on `flow_id`

## 6.2 New Table: ai_flow_proposal_events

Append-only audit events:

- `id` bigint PK
- `proposal_id` varchar(64) not null
- `event_type` varchar(50) not null
- `actor_id` varchar(255) not null
- `event_payload_json` longtext null
- `created_at` datetime(6)

Event examples:

- `proposal_generated`
- `proposal_opened`
- `proposal_edited`
- `proposal_validated`
- `proposal_approved`
- `proposal_rejected`
- `proposal_published`

---

## 7. API Specification (Admin/Internal)

Base path: `/admin/api/ai/proposals`

## 7.1 Generate Proposal

`POST /admin/api/ai/proposals`

Request:

```json
{
  "goal": "Build payment flow with fraud gate and fallback",
  "tenant_id": "tenant_a",
  "message_type": "dynamic.checkout.v1",
  "constraints": {
    "allowed_adapters": ["AdapterFraud", "AdapterBanking", "AdapterDw"],
    "max_timeout_ms": 8000,
    "require_fallback_for_required_slots": true
  }
}
```

Response: proposal envelope.

## 7.2 Get Proposal

`GET /admin/api/ai/proposals/:proposal_id`

Returns full proposal including raw graph, normalized canvas, validation, and status history summary.

## 7.3 Approve Proposal

`POST /admin/api/ai/proposals/:proposal_id/approve`

Request:

```json
{
  "message_type": "dynamic.checkout.v1",
  "notes": "Approved after minor timeout adjustment"
}
```

## 7.4 Reject Proposal

`POST /admin/api/ai/proposals/:proposal_id/reject`

Request:

```json
{
  "reason": "Uses non-approved adapter for tenant"
}
```

## 7.5 Open in Flow Builder

`POST /admin/api/ai/proposals/:proposal_id/open`

Behavior:

1. Creates or updates corresponding draft flow record
2. Writes normalized canvas into flow canvas payload
3. Returns redirect target to current Flow Builder route

Response:

```json
{
  "flow_id": 123,
  "redirect_to": "/admin/flows/123"
}
```

## 7.6 Publish Proposal (Optional Wrapper)

`POST /admin/api/ai/proposals/:proposal_id/publish`

Implementation must internally call existing Flow Builder publish path.

If omitted in Phase 1, publishing remains UI-only action inside Flow Builder.

---

## 8. Normalizer Contract

Normalizer is mandatory between AI output and canvas persistence.

Signature:

`normalize(raw_graph, opts) -> {:ok, normalized_canvas, metadata, warnings} | {:error, errors}`

Rules:

1. Map aliases (for example `RequestNode`) to canonical node types (`request`).
2. Normalize field names (`position.left/top` to `x/y`, `data` to `config` when required).
3. Enforce allowed node/edge enums.
4. Generate missing edge ids deterministically.
5. Validate adapter names against loaded/known registry.
6. Coerce numeric and boolean config values to current expected types.
7. Reject unknown mandatory structures.

Output must always be compatible with current Flow Builder save/publish parser.

---

## 9. Validation and Policy Gate

Validation stages:

1. Schema validation
2. Graph validation (acyclic, entry/exit constraints)
3. Policy validation
4. Tenant constraints validation

Policy examples:

1. Only allow adapters from tenant allow-list.
2. Enforce timeout bounds.
3. Enforce fallback requirements for critical slots.
4. Require at least one response path from request.

Validation result contract:

```json
{
  "status": "pass|fail",
  "errors": ["..."],
  "warnings": ["..."]
}
```

`fail` blocks approval/publish.

---

## 10. UI Integration with Existing Flow Builder

Phase 1 UI additions are minimal and additive:

1. Add button: `Generate with AI` in flow area.
2. Add proposal review panel (goal, warnings, diff summary).
3. Keep existing canvas editor controls unchanged.
4. Keep existing `Save` and `Publish` semantics unchanged.

No existing human-only path should be removed or renamed.

---

## 11. Security and Audit

1. Only authorized admin roles may generate/approve/reject/publish proposals.
2. Every state transition writes event row in `ai_flow_proposal_events`.
3. Persist actor identity for request, approve, reject, publish.
4. Persist final approved canvas snapshot for compliance review.

---

## 12. Observability

New telemetry events:

1. `[:mw, :ai, :proposal, :generated]`
2. `[:mw, :ai, :proposal, :validated]`
3. `[:mw, :ai, :proposal, :approved]`
4. `[:mw, :ai, :proposal, :rejected]`
5. `[:mw, :ai, :proposal, :published]`

Measurements:

- `count`
- `duration_ms` (for generate and validate)

Metadata:

- `proposal_id`
- `tenant_id`
- `message_type`
- `status`

---

## 13. Rollout Plan

1. Deploy schema migrations and proposal APIs behind feature flag.
2. Enable for internal admin users only.
3. Monitor validation failure rate and publish conversion rate.
4. Expand by tenant allow-list.

Feature flags:

1. `ai_flow_proposals_enabled`
2. `ai_flow_publish_wrapper_enabled`

---

## 14. Acceptance Criteria

1. Existing manual flow creation and publish still works unchanged.
2. AI-generated proposal can be opened and edited in existing Flow Builder.
3. Proposal cannot publish without human approval.
4. Published proposal executes through existing deterministic path.
5. Full audit trail exists for proposal lifecycle.

---

## 15. Risks and Mitigations

1. Risk: AI emits incompatible graph format.
   Mitigation: strict normalizer and schema validation before draft save.

2. Risk: policy drift across tenants.
   Mitigation: tenant-scoped policy gate and allow-list checks.

3. Risk: accidental bypass of human approval.
   Mitigation: approval state check in publish endpoint and UI action guard.

4. Risk: confusion between proposal and production route.
   Mitigation: explicit status badges and separate proposal id vs flow id.

---

## 16. Planning Pack Reference

Execution planning documents for this specification are available at:

1. [planning/00-planning-index.md](planning/00-planning-index.md)
2. [planning/01-roadmap-and-phases.md](planning/01-roadmap-and-phases.md)
3. [planning/02-workstreams-and-ownership.md](planning/02-workstreams-and-ownership.md)
4. [planning/03-sprint-1-week-plan.md](planning/03-sprint-1-week-plan.md)
5. [planning/04-story-backlog.md](planning/04-story-backlog.md)
6. [planning/05-test-and-quality-plan.md](planning/05-test-and-quality-plan.md)
7. [planning/06-rollout-and-operations-plan.md](planning/06-rollout-and-operations-plan.md)
