> For the complete documentation index, see [llms.txt](https://help.clabassistant.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.clabassistant.com/engineering/clab-pattern-agent.md).

# clabPatternAgent Architecture

`clabPatternAgent` is a server-side Next.js orchestration flow for pattern measurements and settings. It uses the OpenAI Agents SDK through a local provider adapter and keeps CLAB Django as the stateless owner of pattern knowledge and simulation.

## Runtime Flow

1. The Next.js `/plan` route loads the current pattern, anatomical set snapshot, saved pattern measurements, calculated pattern measures, and settings from the frontend database.
2. Next.js sends that complete snapshot to Django `POST /pattern/agent-context`.
3. Django returns a static `catalog` plus `resolved_state` for current measurement and setting values. The catalog owns profile version, enabled actions, measurement intent rules, setting intent rules, package intents, layout constraints, operation phrases, and reset phrases.
4. The provider-agnostic planner interface asks the OpenAI Agents SDK adapter for a semantic `PatternAgentRunPlan`.
5. The local compiler splits immediate operations from deferred intents that require regenerated state.
6. Immediate operations are validated locally into `ValidatedPatternAgentChange[]`.
7. If deferred intents remain, Next.js calls Django `POST /pattern/agent-simulate` with a non-persistent draft snapshot, refreshes runtime context, and asks the planner again.
8. Planning stops after three stages. Only the final validated proposal is persisted.
9. `/apply` persists approved measurements and settings with the existing save flow.

Every reset or simulation is a state boundary. Operations planned after that boundary must use the regenerated context as their reference state, and the proposal must preserve `oldValue`, `newValue`, and `delta` relative to that regenerated state. Do not rebase post-simulation changes onto the originally persisted values just to make them look like a single-step edit.

## Provider Boundary

Core files use local interfaces:

* `PatternAgentPlannerProvider`
* `PatternAgentRunPlan`
* `PlanCompiler`
* `PatternAgentRunOrchestrator` behavior in `runtime.ts`

Only `src/lib/agent/clabPatternAgent/planner/openAiAgentsPatternPlanner.ts` imports `@openai/agents`. The boundary is tested by `plannerBoundary.test.ts`.

## Decision Ownership

The model/agent owns interpretation of user requests and selection of measurement, setting, and modeling actions. Do not add deterministic frontend/backend code paths that recognize specific user phrasings and directly create proposals, measurement changes, setting changes, layout constraints, or staged operations.

Allowed deterministic logic is limited to orchestration and safety:

* Detecting a generic reset-measurements intent and creating the single `reset_measurements` operation.
* Validating that model-selected actions exist in the current catalog and are safe to apply.
* Compiling model-selected semantic operations into persistence-ready changes.
* Simulating non-persistent state between stages and giving the regenerated context back to the agent.
* Rejecting or clarifying unsupported, unsafe, ambiguous, or invalid model output.

Do not add prompt-specific fallbacks, synonym-based confidence boosts, or validator rescue paths that turn user text into accepted actions without the model selecting those actions. When a new user prompt fails, first improve context, catalog shape, planner instructions, schema, validation feedback, or backend knowledge. Do not fix it by hardcoding that prompt or a narrow family of phrasings into code. Pattern-specific knowledge can describe available editables, labels, synonyms, constraints, and modeling concepts, but it must be supplied as context for the agent to interpret rather than executable branching that bypasses the agent.

## Knowledge Ownership

Django is the source of truth for pattern-agent knowledge. Frontend code must not add pattern-specific JSON files for measurement rules, setting rules, package intents, layout constraints, synonyms, or reset phrases. The frontend may keep only a minimal supported-profile gate and generic normalization/filtering helpers.

Backend knowledge is composed by an aggregator:

* common operation/reset phrases live in the backend aggregator;
* pattern-host knowledge lives next to the host pattern, such as `apc/patterns/men/jacket/agent_knowledge.py`;
* package-family knowledge lives near the library package family, such as `apc/patterns/library/pockets/agent_knowledge.py`;
* the aggregator includes package intents and layout constraints only when the host pattern exposes the required editable measurements and settings.

When adding a pattern type, expose its host knowledge through `POST /pattern/agent-context`; package knowledge should become available automatically when that host pattern exposes the required package measures/settings.

## Backend Snapshot Contract

`POST /pattern/agent-context` receives:

```json
{
  "gender": "men",
  "pattern": "jacket",
  "anatomical_measurements": {},
  "pattern_measurements": {},
  "calculated_pattern_measures": [],
  "settings": []
}
```

It returns:

```json
{
  "status": "ok",
  "catalog": {},
  "resolved_state": {
    "measurements": [],
    "settings": []
  }
}
```

`POST /pattern/agent-simulate` receives the same shape under `snapshot`, plus optional `related_measure_codes`, and returns a non-persistent recalculated snapshot, processed measurements, and calculated pattern measures.

## Environment

* Next.js requires the normal OpenAI key used by server-side AI flows.
* The Agents SDK dependency is `@openai/agents`.
* Django remains stateless for these endpoints and does not read the frontend database.

## V1 Limits

* Supported scope: measurements, reset measurements, and settings.
* Unsupported scope: geometry point edits, PDF analysis, imports, and free-form style changes.
* No stage audit database tables are written in v1; stage details live in provider traces and local run behavior.

## Validation

* FE: `npm test -- src/lib/agent/clabPatternAgent`
* FE: `npm run typecheck`
* FE: `npm run lint`
* BE: `venv/bin/python manage.py test apc.tests.test_agent_context`
