---
name: cortex-iterate
description: Apply ONE targeted, hypothesis-driven fix to an existing Ninjo agent's SDK based on real conversations or user feedback, then deploy and verify via the cortex-gateway MCP (with rollback on failure). Use when the user reports an issue, wants to improve, fix, tweak, or iterate on a deployed agent's behavior.
---

# cortex-iterate — one fix, deployed and verified (MCP-first)

Iterate on a deployed agent: find the root cause from real data, apply **one** fix, deploy via
`deploy_agent_sdk`, verify, and roll back if it didn't land.

## 1. Load context — pull the LIVE config first
- **Multi-influencer token?** If `get_me` returns `scope: "multi-influencer"` (agency token), the connection is **unscoped** — pass `influencer_id` (the **Influencer ID** from `meta.md`; resolve a user's "@handle" via `get_me`'s `influencers` map) on **every** cortex-gateway call, starting with `get_agent_config`. Single-influencer tokens ignore it, so passing it is always safe. See `knowledge/mcp-tool-reference.md` › Ground rules › **Influencer scope**.
- **Start with `get_agent_config`** — the deployed agent is the source of truth, not the local files (which may be
  stale, or a non-persistent upload in web/app sessions). Edit from what's actually live.
- **Check the config isn't degenerate first.** If the live `v5Config` came back as **only `{keywords:[…]}`**
  (or is missing content sections like `knowledge_base`/`examples`), this is a degenerate keywords-only
  config — the agent was shipped keywords-only and never had its content sections populated. Don't patch one
  field onto emptiness; **backfill the full set** in this deploy — `examples` and `knowledge_base` with real
  content (`system` stays intact), plus `keywords` or `program`; author from `agents/sample-*` for a close
  vertical or a sibling agent. The other sections may stay empty.
- Then read `agents/<name>/meta.md` (agent_id, template, **flavor**, use case, vertical) and `changelog.md`
  (past fixes). **Reconcile drift:** if the live `current_prompt_version_id` is ahead of your `changelog.md`, or
  live fields differ from the local `sdk/`, the operator changed the agent since you last synced — refresh the
  local copy from the live config before editing, or you'll overwrite their changes on deploy (PAT-054/PAT-049).
- `templates/principles.md` **plus** the agent's motion flavor (`templates/principles-<flavor>.md`
  from `meta.md`) — its target metrics and link/qualification policy bound the fix — and
  `knowledge/best-practices-top10.md` (the quality contract — never introduce BP-4/BP-5/BP-7 violations).

## 2. Get the evidence
Ask for the user's feedback, AND pull real conversations to ground it:
- `get_conversations` with the mode that targets the complaint: `recent`, `bad` (high funnel/low
  quality), `stuck` (≥6 agent msgs, funnel <3), `low-happy`, `high-funnel`, `booking`. **Or**
  `search_conversations` when the complaint is specific — cross filters to isolate the failing
  cohort (e.g. `min_funnel: 4, has_booking_link: false, min_messages: 5, last_message_after: "<date>"`),
  or pull one conversation by `conversation_id`/`contact_username`.
Use the actual transcripts as the basis for the fix — quote the failing exchange.

## 3. Root cause → fix type (ONE hypothesis)
Identify what in the SDK *allowed* the unwanted behavior. Then choose the fix type:
1. **Behavior shown in a conversation?** (repeats links, mishandles objection, won't close) →
   **add/edit an example** in `examples.md` (the default fix — base it on the real transcript,
   keep the lead's lines, fix the agent's; voice-ground every agent line).
2. **Factual constraint the model can't infer?** (no prices in chat, never interpret results) →
   add/refine a **principle** in `system.md` (principles template: keep ≤7 — merge/retire before adding).
3. **Data issue?** (wrong URL, missing product, stale price) → fix the **JSON** (`resources.json`,
   `program.json`, `keywords.json`).

**Principles-template guardrails:** never add hard-rule lists; formatting/tone/flow fixes go in
voice/examples, not rules; prefer improving an existing example over adding a new one; keep
`system.md` ≤ ~2k tokens.

## 4. Propose
Show the user: **Problem · Root cause · Fix type (justified) · before/after diff · why it won't
break other behaviors.** Run the BP-top10 self-check on the diff (BP-4/5/7/9). Wait for approval.

## 5. Apply + deploy
1. Edit the relevant `agents/<name>/sdk/` file(s).
2. `deploy_agent_sdk` with **only the changed fields** (PATCH semantics — omitted = untouched).
   Always include `keywords` if you touched them (it re-syncs `trigger_keywords`). **Exception:** if
   step 1 found a degenerate keywords-only config, pass **all 8 sections** this once to heal it.
3. Read the deploy report. **`verified: false` / `partial: true` ⇒ call `restore_prompt_version`
   with the returned `rollback_version_id`** and report the failure — do not leave a half-deploy.
4. `get_agent_config` to confirm the change is live — and that any `keywords`/`program`/`resources`/
   `case_studies` you touched came back as **objects/arrays, not JSON-encoded strings** (a string
   there means a double-encoded deploy; redeploy the parsed value — see `knowledge/platform-internals.md` §3e).

## 6. Record
Append to `agents/<name>/changelog.md`:
```
## vN — YYYY-MM-DD
**Problem**: …    **Root cause**: …
**Fix**: example | principle | data — what changed and why
**Deploy**: deploy_agent_sdk → version <id> (verified: true)
**Breaking changes**: None | …
```
Suggest `/cortex-analyze` after a few days to confirm the fix moved the metric.

## Reasoning leaks
If the agent narrates its internal logic to the lead (`necesito verificar…`, `el lead…`, `STEP 0`, `procedo con el cierre`), it's fixable — `knowledge/reasoning-leak.md` has the diagnosis, the generic prompt guard, and the shape catalog. The fix is a normal prompt iteration (reword the offending imperative/threshold step into a silent condition, redeploy, validate with `cortex-test`). The platform `responseFilter` is a complementary safety net — set it with `update_agent_config`'s `response_filter` field (see `knowledge/reasoning-leak.md`).

## When a tool fails or a capability is missing
Follow `knowledge/self-sufficiency.md`. Skill-specific: if `get_conversations`/`search_conversations` times out, retry, then narrow the window or fall back to a sample the user provides — don't abandon the diagnosis. On a failed `deploy_agent_sdk` (`verified:false`/`partial:true`), `restore_prompt_version` with the report's `rollback_version_id` immediately, then re-diagnose before re-deploying.
