# Technical Documentation: Agenta-AI/agenta

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/Agenta-AI/agenta)

### Overview (README.md)

<p align="center">
  <a href="https://agenta.ai?utm_source=github&utm_medium=referral&utm_campaign=readme">
      <picture >
        <source width="275" media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/97e31bfc-b1fc-4d19-b443-5aedf6029017"  >
        <source width="275" media="(prefers-color-scheme: light)" srcset="https://github.com/user-attachments/assets/fdc5f23f-2095-4cfc-9511-14c6851c1262"  >
        <img alt="Shows the logo of agenta" src="https://github.com/user-attachments/assets/fdc5f23f-2095-4cfc-9511-14c6851c1262" >
      </picture>
  </a>
  
<div align="center">
  <strong> <h1> The open-source workspace for your agents and your team </h1></strong>

  Build AI coworkers by chatting. Share them with your team. Talk to them in Slack, WhatsApp or Telegram.
  
  ---
  
<a href="https://youtu.be/7Wfvtv428Fs?si=bTBUoS9JJC2Crkxs">
  <img
    width="900"
    alt="Watch the 2-minute Agenta product tour"
    src="./.github/images/readme/agenta-product-tour.png"
  />
</a>

  ---



</div>

</div>


<h3 align="center">
  <a href="https://agenta.ai/docs/?utm_source=github&utm_medium=referral&utm_campaign=readme"><b>Documentation</b></a> &bull;
  <a href="https://agenta.ai?utm_source=github&utm_medium=referral&utm_campaign=readme"><b>Website</b></a> &bull;
  <a href="https://cloud.agenta.ai?utm_source=github&utm_medium=referral&utm_campaign=readme"><b>Agenta Cloud</b></a>
</h3>

<p align="center">
  <a href="./README.md"><img alt="README in English" src="https://img.shields.io/badge/English-d9d9d9"></a>
  <a href="./README.cn.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
  <a href="./README.ja.md"><img alt="日本語のREADME" src="https://img.shields.io/badge/日本語-d9d9d9"></a>
  <a href="./README.kr.md"><img alt="README in Korean" src="https://img.shields.io/badge/한국어-d9d9d9"></a>
</p>
<div align="center">

<a href="https://trendshift.io/repositories/46?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-46" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/46" alt="Agenta-AI%2Fagenta | Trendshift" width="250" height="55"/></a>
</div>

---

<p align="center">
  <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT license." />
  <a href="https://agenta.ai/docs/?utm_source=github&utm_medium=referral&utm_campaign=readme">
    <img src="https://img.shields.io/badge/Doc-online-green" alt="Doc">
  </a>
  <a href="https://github.com/Agenta-AI/agenta/blob/main/CONTRIBUTING.md">
    <img src="https://img.shields.io/badge/PRs-Welcome-brightgreen" alt="PRs welcome" />
  </a>
  <a href="https://pypi.org/project/agenta/">
    <img src="https://img.shields.io/pypi/dm/agenta" alt="PyPI - Downloads">
  </a>
</br>
</p>

<p align="center">
    <a href="https://join.slack.com/t/agenta-hq/shared_invite/zt-37pnbp5s6-mbBrPL863d_oLB61GSNFjw">
        <img src="https://custom-icon-badges.demolab.com/badge/Slack-4A154B?logo=slack&logoColor=fff" alt="Join us on Slack" />
    </a>
    <a href="https://www.linkedin.com/company/agenta-ai/">
        <img src="https://custom-icon-badges.demolab.com/badge/LinkedIn-0A66C2?logo=linkedin-white&logoColor=fff" alt="Follow Agenta on LinkedIn" />
    </a>
    <a  href="https://twitter.com/agenta_ai">
        <img src="https://img.shields.io/twitter/follow/agenta_ai?style=social" height="28" alt="Follow @agenta_ai on X" />
    </a>
</p>

<p align="center">
  <a href="https://cloud.agenta.ai?utm_source=github&utm_medium=referral&utm_campaign=readme">
      <picture >
        <source width="200" media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/a2069e7b-c3e0-4a5e-9e41-8ddc4660d1f2"  >
        <source width="200" media="(prefers-color-scheme: light)" srcset="https://github.com/user-attachments/assets/a2069e7b-c3e0-4a5e-9e41-8ddc4660d1f2"  >
        <img alt="Try Agenta Live Demo" src="https://github.com/user-attachments/assets/a2069e7b-c3e0-4a5e-9e41-8ddc4660d1f2" >
      </picture>
  </a>
</p>

---

## What is Agenta?

Agenta is an open-source workspace where you build specialized agents that automate and augment your work.

You build agents by chatting with them. You describe the work, connect the apps they need, and improve them through feedback.

You can work with your agents in the web app, or talk to them where you already are: **Slack**, **Telegram** or **WhatsApp Business**.

For recurring work, you can create automations. Your agents run on a schedule or when an event occurs in a connected app, and you can see what every run did.

## Tutorials

Step-by-step videos. Each one builds a real agent from scratch, by chatting.

<table>
  <tr>
    <td width="33%" valign="top">
      <a href="https://youtu.be/TFsEXgdNowY"><img src="./.github/images/readme/tutorial-first-ai-coworker.png" alt="Tutorial: build your first AI coworker" width="100%"></a>
      <br><b><a href="https://youtu.be/TFsEXgdNowY">Build your first AI coworker</a></b> · 10 min
      <br>Connect your tools, give the agent a role, save a skill, and automate sales-call prep.
    </td>
    <td width="33%" valign="top">
      <a href="https://youtu.be/c3iVw0MBZTE"><img src="./.github/images/readme/tutorial-competitor-tracker.png" alt="Tutorial: build an agent that tracks your competitors" width="100%"></a>
      <br><b><a href="https://youtu.be/c3iVw0MBZTE">Track your competitors while you sleep</a></b> · 7 min
      <br>Give an agent web search, schedule it for every Monday, and get the digest in Gmail.
    </td>
    <td width="33%" valign="top">
      <a href="https://youtu.be/hk8TMNTCZvU"><img src="./.github/images/readme/tutorial-inbound-outreach.png" alt="Tutorial: build an inbound outreach agent without code" width="100%"></a>
      <br><b><a href="https://youtu.be/hk8TMNTCZvU">Build an inbound outreach agent with no code</a></b> · 17 min
      <br>Research every new lead, qualify it, and send a personalized reply.
    </td>
  </tr>
</table>

More tutorials on our [YouTube channel](https://www.youtube.com/@agentaAI).

## Why use Agenta?

Agenta is the wrong tool if you are looking for:

- **an agentic development environment** for writing code, like ocra, Claude Code or OpenCode.
  
  *Agenta is built for the work around and beyond code: IT ops, GTM, HR, legal, finance, support...*
- **a single-user personal assistant**, like openclaw or Hermes.
  
  *Agenta is built for teams: agents are shared, multi-user, and run where the team works (e.g. Slack).*
- **a low-code workflow builder**, like n8n or Zapier.
  
  *In Agenta you do not draw workflows. You build autonomous agents that figure out the steps and solve problems on their own.*

Agenta is built for work, with professionals in mind from day one. That means:

1. **Multiplayer by default.** Give your team (or customers) access, set roles, and share agents and chat sessions.
2. **Transparent.** You see each agent's configuration, its versions, and every change.
3. **Controllable, with you in the loop.** You set exact permissions per agent: which tools it can use, and whether it can read or write with them. You decide what it does on its own and what goes through you first.
4. **Secure.** Each session runs in its own sandbox, isolated from every other. Model credentials are never seen by the agent.
5. **Auditable.** Every run is traced. Every cost is tracked.
6. **Yours.** Open source, self-hostable, on your models, with your data on your servers.
7. **For technical and non-technical teammates.** You build agents by chatting, so anyone on the team can build them and work with them, not only engineers.

## Features

**Talk to your agents in Slack, Telegram or WhatsApp.** Your team and your clients use agents from the chat apps they already have, with no new tool to learn. The web app works on your phone too.

**Use your Claude or ChatGPT subscription.** Run agents on the subscription you already pay for, instead of metered API billing.

**Use any model.** Hosted models through an API, or self-hosted models with Ollama. Pick a cheap model for routine jobs and a strong one where it matters, and see what each agent costs.

**Agents that learn.** Correct an agent once and it remembers. Agents keep memory, create and refine their own skills, and update their own instructions, so they need less supervision every week.

**Automations.** Run agents on a schedule or when an event occurs in a connected app. See the history of every run, and continue a run's session to fix or improve it.

**Each agent has its own computer.** A browser and a file system, so agents can work on any website and any file, not only on apps that have an integration.

**Integrations.** Connect your agents through MCP, or to more than 1,000 apps through Composio, including Gmail, Slack, Notion, and GitHub. Add your own secrets for the tools that need them.

**Workspaces for you and your agents.** Work together on files in a shared workspace: documents, research, a wiki, with comments and previews. Agents can also build small apps, like a board or a form, for your team to use.

**Teams of agents.** Agents can call other agents and hand work to each other, so one coworker can coordinate specialists.

**Skills and templates.** Start from templates, bring in skills from the agent ecosystem, and grow your own skill library over time.

## Get started

### Try Agenta Cloud

The fastest way to try Agenta.

<p align="center">
  <a href="https://cloud.agenta.ai?utm_source=github&utm_medium=referral&utm_campaign=readme">
      <picture >
        <source width="200" media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/3aa96780-b7e5-4b6f-bfee-8feaa36ff3b2"  >
        <source width="200" media="(prefers-color-scheme: light)" srcset="https://github.com/user-attachments/assets/3aa96780-b7e5-4b6f-bfee-8feaa36ff3b2"  >
        <img alt="Try Agenta Cloud" src="https://github.com/user-attachments/assets/3aa96780-b7e5-4b6f-bfee-8feaa36ff3b2" >
      </picture>
  </a>
</p>

### Self-host Agenta

Paste this into your agent and it will walk you through setup and testing:

```text
1. Install the Agenta self-hosting skill: npx skills add Agenta-AI/agenta-skills
2. Help me self-host Agenta with its repository.
```

For more details, read the [self-hosting documentation](https://agenta.ai/docs/self-host/quick-start?utm_source=github&utm_medium=referral&utm_campaign=readme).

## How Agenta compares

### n8n, Activepieces, and Zapier

These products are designed for building workflows with predefined steps. Agenta is designed for work that requires an agent to plan, use tools, and adapt its approach. Use a workflow builder for predictable processes. Use Agenta when the work needs judgment, or when you want the same agent to work with you in chat and run in the background.

### Claude Cowork

Claude Cowork provides a workspace built around Claude. Agenta is open source and lets you choose your harness and model, inspect the components of your agents, and run them interactively or in the background.

### Claude Code, Codex, Pi, and OpenCode

These coding agents provide the execution layer that plans work and uses tools. Agenta adds the shared workspace around that execution layer: files, team access, triggers, versions, and traces. Agenta supports Claude Code, Pi, and Codex today. Support for more harnesses is on the roadmap.

## Roadmap

See the [complete roadmap](https://agenta.ai/docs/?utm_source=github&utm_medium=referral&utm_campaign=readme). Want to help with one of these items? [Open a discussion](https://github.com/Agenta-AI/agenta/discussions) or contribute.

## Community and contributing

Agenta is open source under the MIT License. You can inspect the code, run it yourself, and help shape what we build next.

- [Read the documentation](https://agenta.ai/docs/?utm_source=github&utm_medium=referral&utm_campaign=readme)
- [Report a bug](https://github.com/Agenta-AI/agenta/issues)
- [Request a feature or share an idea](https://github.com/Agenta-AI/agenta/discussions)
- [Read the contributing guide](CONTRIBUTING.md)
- [Join the Slack community](https://join.slack.com/t/agenta-hq/shared_invite/zt-37pnbp5s6-mbBrPL863d_oLB61GSNFjw)

If Agenta is useful to you, star the repository and tell us what you build.

## ⭐ Star Agenta

**Consider giving us a star!** It helps us grow our community and gets Agenta in front of more developers.
</br>
</br>
<p align="center">
    <a href="https://github.com/agenta-ai/agenta">

  <img width="300" alt="Star us" src="https://github.com/user-attachments/assets/2c8e580a-c930-4312-bf1b-08f631b41c62" />
    <a href="https://cloud.agenta.ai?utm_source=github&utm_medium=referral&utm_campaign=readme">

</p>

## Contributors ✨


[](#contributors-)


Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):




<table>
  <tbody>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/SamMethnani"><img src="https://avatars.githubusercontent.com/u/57623556?v=4&size=100" width="100px" height="100px" alt="Sameh Methnani"/><br /><sub><b>Sameh Methnani</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=SamMethnani" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=SamMethnani" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/suadsuljovic"><img src="https://avatars.githubusercontent.com/u/8658374?v=4&size=100" width="100px" height="100px" alt="Suad Suljovic"/><br /><sub><b>Suad Suljovic</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=suadsuljovic" title="Code">💻</a> <a href="#design-suadsuljovic" title="Design">🎨</a> <a href="#mentoring-suadsuljovic" title="Mentoring">🧑‍🏫</a> <a href="https://github.com/Agenta-AI/agenta/pulls?q=is%3Apr+reviewed-by%3Asuadsuljovic" title="Reviewed Pull Requests">👀</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/burtenshaw"><img src="https://avatars.githubusercontent.com/u/19620375?v=4&size=100" width="100px" height="100px" alt="burtenshaw"/><br /><sub><b>burtenshaw</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=burtenshaw" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://abram.tech"><img src="https://avatars.githubusercontent.com/u/55067204?v=4&size=100" width="100px" height="100px" alt="Abram"/><br /><sub><b>Abram</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=aybruhm" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=aybruhm" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://israelabebe.com"><img src="https://avatars.githubusercontent.com/u/7479824?v=4&size=100" width="100px" height="100px" alt="Israel Abebe"/><br /><sub><b>Israel Abebe</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Avernu" title="Bug reports">🐛</a> <a href="#design-vernu" title="Design">🎨</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=vernu" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/SohaibAnwaar"><img src="https://avatars.githubusercontent.com/u/29427728?v=4&size=100" width="100px" height="100px" alt="Master X"/><br /><sub><b>Master X</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=SohaibAnwaar" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://main-portfolio-26wv6oglp-witehound.vercel.app/"><img src="https://avatars.githubusercontent.com/u/26417477?v=4&size=100" width="100px" height="100px" alt="corinthian"/><br /><sub><b>corinthian</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=witehound" title="Code">💻</a> <a href="#design-witehound" title="Design">🎨</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Pajko97"><img src="https://avatars.githubusercontent.com/u/25198892?v=4&size=100" width="100px" height="100px" alt="Pavle Janjusevic"/><br /><sub><b>Pavle Janjusevic</b></sub></a><br /><a href="#infra-Pajko97" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://kaosiso-ezealigo.netlify.app"><img src="https://avatars.githubusercontent.com/u/99529776?v=4&size=100" width="100px" height="100px" alt="Kaosi Ezealigo"/><br /><sub><b>Kaosi Ezealigo</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Abekossy" title="Bug reports">🐛</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=bekossy" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/albnunes"><img src="https://avatars.githubusercontent.com/u/46302915?v=4&size=100" width="100px" height="100px" alt="Alberto Nunes"/><br /><sub><b>Alberto Nunes</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Aalbnunes" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/mohammed-maaz-6290b0116/"><img src="https://avatars.githubusercontent.com/u/17180132?v=4&size=100" width="100px" height="100px" alt="Maaz Bin Khawar"/><br /><sub><b>Maaz Bin Khawar</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=MohammedMaaz" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/pulls?q=is%3Apr+reviewed-by%3AMohammedMaaz" title="Reviewed Pull Requests">👀</a> <a href="#mentoring-MohammedMaaz" title="Mentoring">🧑‍🏫</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/devgenix"><img src="https://avatars.githubusercontent.com/u/56418363?v=4&size=100" width="100px" height="100px" alt="Nehemiah Onyekachukwu Emmanuel"/><br /><sub><b>Nehemiah Onyekachukwu Emmanuel</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=devgenix" title="Code">💻</a> <a href="#example-devgenix" title="Examples">💡</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=devgenix" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/philipokiokio"><img src="https://avatars.githubusercontent.com/u/55271518?v=4&size=100" width="100px" height="100px" alt="Philip Okiokio"/><br /><sub><b>Philip Okiokio</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=philipokiokio" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://sweetdevil144.github.io/My-Website/"><img src="https://avatars.githubusercontent.com/u/117591942?v=4&size=100" width="100px" height="100px" alt="Abhinav Pandey"/><br /><sub><b>Abhinav Pandey</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Sweetdevil144" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/RamchandraWarang9822"><img src="https://avatars.githubusercontent.com/u/92023869?v=4&size=100" width="100px" height="100px" alt="Ramchandra Warang"/><br /><sub><b>Ramchandra Warang</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=RamchandraWarang9822" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/issues?q=author%3ARamchandraWarang9822" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/lazyfuhrer"><img src="https://avatars.githubusercontent.com/u/64888892?v=4&size=100" width="100px" height="100px" alt="Biswarghya Biswas"/><br /><sub><b>Biswarghya Biswas</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=lazyfuhrer" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/okieLoki"><img src="https://avatars.githubusercontent.com/u/96105929?v=4&size=100" width="100px" height="100px" alt="Uddeepta Raaj Kashyap"/><br /><sub><b>Uddeepta Raaj Kashyap</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=okieLoki" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://www.linkedin.com/in/nayeem-abdullah-317098141"><img src="https://avatars.githubusercontent.com/u/32274108?v=4&size=100" width="100px" height="100px" alt="Nayeem Abdullah"/><br /><sub><b>Nayeem Abdullah</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=nayeem01" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/kangsuhyun-yanolja"><img src="https://avatars.githubusercontent.com/u/124246127?v=4&size=100" width="100px" height="100px" alt="Kang Suhyun"/><br /><sub><b>Kang Suhyun</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=kangsuhyun-yanolja" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/yeokyeong-yanolja"><img src="https://avatars.githubusercontent.com/u/128676129?v=4&size=100" width="100px" height="100px" alt="Yoon"/><br /><sub><b>Yoon</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=yeokyeong-yanolja" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://mrkirthi24.netlify.app/"><img src="https://avatars.githubusercontent.com/u/53830546?v=4&size=100" width="100px" height="100px" alt="Kirthi Bagrecha Jain"/><br /><sub><b>Kirthi Bagrecha Jain</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=mrkirthi-24" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/navdeep1840"><img src="https://avatars.githubusercontent.com/u/80774259?v=4&size=100" width="100px" height="100px" alt="Navdeep"/><br /><sub><b>Navdeep</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=navdeep1840" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/rhythm-sharma-708a421a8/"><img src="https://avatars.githubusercontent.com/u/64489317?v=4&size=100" width="100px" height="100px" alt="Rhythm Sharma"/><br /><sub><b>Rhythm Sharma</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Rhythm-08" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://osinachi.me"><img src="https://avatars.githubusercontent.com/u/40396070?v=4&size=100" width="100px" height="100px" alt="Osinachi Chukwujama "/><br /><sub><b>Osinachi Chukwujama </b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=vicradon" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://liduos.com/"><img src="https://avatars.githubusercontent.com/u/47264881?v=4&size=100" width="100px" height="100px" alt="莫尔索"/><br /><sub><b>莫尔索</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=morsoli" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://luccithedev.com"><img src="https://avatars.githubusercontent.com/u/22600781?v=4&size=100" width="100px" height="100px" alt="Agunbiade Adedeji"/><br /><sub><b>Agunbiade Adedeji</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=dejongbaba" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://techemmy.github.io/"><img src="https://avatars.githubusercontent.com/u/43725109?v=4&size=100" width="100px" height="100px" alt="Emmanuel Oloyede"/><br /><sub><b>Emmanuel Oloyede</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=techemmy" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=techemmy" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Dhaneshwarguiyan"><img src="https://avatars.githubusercontent.com/u/116065351?v=4&size=100" width="100px" height="100px" alt="Dhaneshwarguiyan"/><br /><sub><b>Dhaneshwarguiyan</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Dhaneshwarguiyan" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/PentesterPriyanshu"><img src="https://avatars.githubusercontent.com/u/98478305?v=4&size=100" width="100px" height="100px" alt="Priyanshu Prajapati"/><br /><sub><b>Priyanshu Prajapati</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=PentesterPriyanshu" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://venkataravitejagullapudi.github.io/"><img src="https://avatars.githubusercontent.com/u/70102577?v=4&size=100" width="100px" height="100px" alt="Raviteja"/><br /><sub><b>Raviteja</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=VenkataRavitejaGullapudi" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/ArijitCloud"><img src="https://avatars.githubusercontent.com/u/81144422?v=4&size=100" width="100px" height="100px" alt="Arijit"/><br /><sub><b>Arijit</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=ArijitCloud" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Yachika9925"><img src="https://avatars.githubusercontent.com/u/147185379?v=4&size=100" width="100px" height="100px" alt="Yachika9925"/><br /><sub><b>Yachika9925</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Yachika9925" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Dhoni77"><img src="https://avatars.githubusercontent.com/u/53973174?v=4&size=100" width="100px" height="100px" alt="Aldrin"/><br /><sub><b>Aldrin</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Dhoni77" title="Tests">⚠️</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/seungduk-yanolja"><img src="https://avatars.githubusercontent.com/u/115020208?v=4&size=100" width="100px" height="100px" alt="seungduk.kim.2304"/><br /><sub><b>seungduk.kim.2304</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=seungduk-yanolja" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://dandrei.com/"><img src="https://avatars.githubusercontent.com/u/59015981?v=4&size=100" width="100px" height="100px" alt="Andrei Dragomir"/><br /><sub><b>Andrei Dragomir</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=andreiwebdev" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://diegolikescode.me/"><img src="https://avatars.githubusercontent.com/u/57499868?v=4&size=100" width="100px" height="100px" alt="diego"/><br /><sub><b>diego</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=diegolikescode" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/brockWith"><img src="https://avatars.githubusercontent.com/u/105627491?v=4&size=100" width="100px" height="100px" alt="brockWith"/><br /><sub><b>brockWith</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=brockWith" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://denniszelada.wordpress.com/"><img src="https://avatars.githubusercontent.com/u/219311?v=4&size=100" width="100px" height="100px" alt="Dennis Zelada"/><br /><sub><b>Dennis Zelada</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=denniszelada" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/romainrbr"><img src="https://avatars.githubusercontent.com/u/10381609?v=4&size=100" width="100px" height="100px" alt="Romain Brucker"/><br /><sub><b>Romain Brucker</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=romainrbr" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://heonheo.com"><img src="https://avatars.githubusercontent.com/u/76820291?v=4&size=100" width="100px" height="100px" alt="Heon Heo"/><br /><sub><b>Heon Heo</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=HeonHeo23" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Drewski2222"><img src="https://avatars.githubusercontent.com/u/39228951?v=4&size=100" width="100px" height="100px" alt="Drew Reisner"/><br /><sub><b>Drew Reisner</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Drewski2222" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://speakerdeck.com/eltociear"><img src="https://avatars.githubusercontent.com/u/22633385?v=4&size=100" width="100px" height="100px" alt="Ikko Eltociear Ashimine"/><br /><sub><b>Ikko Eltociear Ashimine</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=eltociear" title="Documentation">📖</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/vishalvanpariya"><img src="https://avatars.githubusercontent.com/u/27823328?v=4&size=100" width="100px" height="100px" alt="Vishal Vanpariya"/><br /><sub><b>Vishal Vanpariya</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=vishalvanpariya" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/youcefs21"><img src="https://avatars.githubusercontent.com/u/34604972?v=4&size=100" width="100px" height="100px" alt="Youcef Boumar"/><br /><sub><b>Youcef Boumar</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=youcefs21" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/LucasTrg"><img src="https://avatars.githubusercontent.com/u/47852577?v=4&size=100" width="100px" height="100px" alt="LucasTrg"/><br /><sub><b>LucasTrg</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=LucasTrg" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/issues?q=author%3ALucasTrg" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://ashrafchowdury.me"><img src="https://avatars.githubusercontent.com/u/87828904?v=4&size=100" width="100px" height="100px" alt="Ashraf Chowdury"/><br /><sub><b>Ashraf Chowdury</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Aashrafchowdury" title="Bug reports">🐛</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=ashrafchowdury" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/jp-agenta"><img src="https://avatars.githubusercontent.com/u/174311389?v=4&size=100" width="100px" height="100px" alt="jp-agenta"/><br /><sub><b>jp-agenta</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=jp-agenta" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Ajp-agenta" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://mrunhap.github.io"><img src="https://avatars.githubusercontent.com/u/24653356?v=4&size=100" width="100px" height="100px" alt="Mr Unhappy"/><br /><sub><b>Mr Unhappy</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Amrunhap" title="Bug reports">🐛</a> <a href="#infra-mrunhap" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/morenobonaventura"><img src="https://avatars.githubusercontent.com/u/2118854?v=4&size=100" width="100px" height="100px" alt="Moreno Bonaventura"/><br /><sub><b>Moreno Bonaventura</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Amorenobonaventura" title="Bug reports">🐛</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://ikazoy.me/"><img src="https://avatars.githubusercontent.com/u/385109?v=4&size=100" width="100px" height="100px" alt="Yoshiki Ozaki"/><br /><sub><b>Yoshiki Ozaki</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Aikazoy" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/ahmed-agenta"><img src="https://avatars.githubusercontent.com/u/194256084?v=4&size=100" width="100px" height="100px" alt="ahmed-agenta"/><br /><sub><b>ahmed-agenta</b></sub></a><br /><a href="#design-ahmed-agenta" title="Design">🎨</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/VahantSharma"><img src="https://avatars.githubusercontent.com/u/172914890?v=4&size=100" width="100px" height="100px" alt="Vahant Sharma"/><br /><sub><b>Vahant Sharma</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=VahantSharma" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/muzman123"><img src="https://avatars.githubusercontent.com/u/66068301?v=4&size=100" width="100px" height="100px" alt="Muhammad Muzammil"/><br /><sub><b>Muhammad Muzammil</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=muzman123" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/CyrusNamjoo"><img src="https://avatars.githubusercontent.com/u/209579763?v=4&size=100" width="100px" height="100px" alt="Sirous Namjoo"/><br /><sub><b>Sirous Namjoo</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=CyrusNamjoo" title="Documentation">📖</a> <a href="#example-CyrusNamjoo" title="Examples">💡</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/adityadewan22-hub"><img src="https://avatars.githubusercontent.com/u/225586510?v=4&size=100" width="100px" height="100px" alt="adityadewan22-hub"/><br /><sub><b>adityadewan22-hub</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=adityadewan22-hub" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/majiayu000"><img src="https://avatars.githubusercontent.com/u/19658300?v=4&size=100" width="100px" height="100px" alt="lif"/><br /><sub><b>lif</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=majiayu000" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="http://karimkohel.com"><img src="https://avatars.githubusercontent.com/u/46066647?v=4&size=100" width="100px" height="100px" alt="karim kohel"/><br /><sub><b>karim kohel</b></sub></a><br /><a href="#example-karimkohel" title="Examples">💡</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=karimkohel" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Vishesh-Paliwal"><img src="https://avatars.githubusercontent.com/u/142072830?v=4&size=100" width="100px" height="100px" alt="Vishesh Paliwal"/><br /><sub><b>Vishesh Paliwal</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Vishesh-Paliwal" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/aviu16"><img src="https://avatars.githubusercontent.com/u/162624394?v=4&size=100" width="100px" height="100px" alt="Eve"/><br /><sub><b>Eve</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=aviu16" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://endoze.github.io"><img src="https://avatars.githubusercontent.com/u/997161?v=4&size=100" width="100px" height="100px" alt="Endoze"/><br /><sub><b>Endoze</b></sub></a><br /><a href="#infra-endoze" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=endoze" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/anshk8"><img src="https://avatars.githubusercontent.com/u/141085661?v=4&size=100" width="100px" height="100px" alt="Ansh Kakkar"/><br /><sub><b>Ansh Kakkar</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Aanshk8" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Devarsh05"><img src="https://avatars.githubusercontent.com/u/116822773?v=4&size=100" width="100px" height="100px" alt="Devarsh Prajapati"/><br /><sub><b>Devarsh Prajapati</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3ADevarsh05" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/axelray-dev"><img src="https://avatars.githubusercontent.com/u/110029405?v=4&size=100" width="100px" height="100px" alt="AxelRay"/><br /><sub><b>AxelRay</b></sub></a><br /><a href="#platform-axelray-dev" title="Packaging/porting to new platform">📦</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=axelray-dev" title="Documentation">📖</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Sanket2329"><img src="https://avatars.githubusercontent.com/u/196506711?v=4&size=100" width="100px" height="100px" alt="Sanket Shakya"/><br /><sub><b>Sanket Shakya</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Sanket2329" title="Code">💻</a> <a href="#platform-Sanket2329" title="Packaging/porting to new platform">📦</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=Sanket2329" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/unfitcoder101"><img src="https://avatars.githubusercontent.com/u/175036458?v=4&size=100" width="100px" height="100px" alt="unfitcoder101"/><br /><sub><b>unfitcoder101</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Aunfitcoder101" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Shunmuka"><img src="https://avatars.githubusercontent.com/u/137101604?v=4&size=100" width="100px" height="100px" alt="Shunmuka Valsa"/><br /><sub><b>Shunmuka Valsa</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Shunmuka" title="Code">💻</a> <a href="#platform-Shunmuka" title="Packaging/porting to new platform">📦</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/NamHT4Devlop"><img src="https://avatars.githubusercontent.com/u/122743792?v=4&size=100" width="100px" height="100px" alt="Hồ Trung Nam"/><br /><sub><b>Hồ Trung Nam</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=NamHT4Devlop" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Koushik-Salammagari"><img src="https://avatars.githubusercontent.com/u/138836560?v=4&size=100" width="100px" height="100px" alt="Koushik-Salammagari"/><br /><sub><b>Koushik-Salammagari</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3AKoushik-Salammagari" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/truecallerabreham"><img src="https://avatars.githubusercontent.com/u/180291642?v=4&size=100" width="100px" height="100px" alt="Abreham Melese"/><br /><sub><b>Abreham Melese</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3Atruecallerabreham" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://kunaal-portfolio.vercel.app"><img src="https://avatars.githubusercontent.com/u/126342173?v=4&size=100" width="100px" height="100px" alt="Boggavarapu Yuva Satya Kunaal"/><br /><sub><b>Boggavarapu Yuva Satya Kunaal</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Yuvakunaal" title="Tests">⚠️</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/MarceloAdan73"><img src="https://avatars.githubusercontent.com/u/112431764?v=4&size=100" width="100px" height="100px" alt="Marcelo-Palma"/><br /><sub><b>Marcelo-Palma</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=MarceloAdan73" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="http://adekolamanasseh-tech.vercel.app"><img src="https://avatars.githubusercontent.com/u/221562541?v=4&size=100" width="100px" height="100px" alt="MannieTech"/><br /><sub><b>MannieTech</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=mannietech15" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/moataz-hjaiji"><img src="https://avatars.githubusercontent.com/u/74058655?v=4&size=100" width="100px" height="100px" alt="moataz hjaiji"/><br /><sub><b>moataz hjaiji</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=moataz-hjaiji" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/iamhaseebn"><img src="https://avatars.githubusercontent.com/u/36381672?v=4&size=100" width="100px" height="100px" alt="Haseeb Nazir"/><br /><sub><b>Haseeb Nazir</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=iamhaseebn" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://cormid.xyz/"><img src="https://avatars.githubusercontent.com/u/107045341?v=4&size=100" width="100px" height="100px" alt="cormid"/><br /><sub><b>cormid</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Kirtofu" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/mdsiddiqjuber"><img src="https://avatars.githubusercontent.com/u/234624433?v=4&size=100" width="100px" height="100px" alt="mdsiddiqjuber"/><br /><sub><b>mdsiddiqjuber</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=mdsiddiqjuber" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/SJY051"><img src="https://avatars.githubusercontent.com/u/68188784?v=4&size=100" width="100px" height="100px" alt="Seojin Yoon"/><br /><sub><b>Seojin Yoon</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=SJY051" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=SJY051" title="Tests">⚠️</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/shafeeq27edu-ai"><img src="https://avatars.githubusercontent.com/u/234775624?v=4&size=100" width="100px" height="100px" alt="Shafeeq"/><br /><sub><b>Shafeeq</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=shafeeq27edu-ai" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://www.abdelkader.work/"><img src="https://avatars.githubusercontent.com/u/108610803?v=4&size=100" width="100px" height="100px" alt="Abdelkaderbzz"/><br /><sub><b>Abdelkaderbzz</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3AAbdelkaderbzz" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/panshularora"><img src="https://avatars.githubusercontent.com/u/170356171?v=4&size=100" width="100px" height="100px" alt="panshularora"/><br /><sub><b>panshularora</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=panshularora" title="Tests">⚠️</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://neokit.app/"><img src="https://avatars.githubusercontent.com/u/185078340?v=4&size=100" width="100px" height="100px" alt="Ankit"/><br /><sub><b>Ankit</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/issues?q=author%3AWhoamiI00" title="Bug reports">🐛</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Aman-goel-04"><img src="https://avatars.githubusercontent.com/u/216227649?v=4&size=100" width="100px" height="100px" alt="Aman"/><br /><sub><b>Aman</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=aman-goel-04" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/AJ-ing"><img src="https://avatars.githubusercontent.com/u/226107146?v=4&size=100" width="100px" height="100px" alt="Aayush Jain"/><br /><sub><b>Aayush Jain</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=AJ-ing" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/MFA-G"><img src="https://avatars.githubusercontent.com/u/136257088?v=4&size=100" width="100px" height="100px" alt="Mochammad Fadhlan Al-Ghiffari"/><br /><sub><b>Mochammad Fadhlan Al-Ghiffari</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=MFA-G" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://www.heysuraj.dev/"><img src="https://avatars.githubusercontent.com/u/46050946?v=4&size=100" width="100px" height="100px" alt="suraj ✨ "/><br /><sub><b>suraj ✨ </b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=uchiha-suraj" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://oforiwaasam.github.io/portfolio/"><img src="https://avatars.githubusercontent.com/u/41793292?v=4&size=100" width="100px" height="100px" alt="Lily Sam"/><br /><sub><b>Lily Sam</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=oforiwaasam" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://christiansidak.com"><img src="https://avatars.githubusercontent.com/u/61099993?v=4&size=100" width="100px" height="100px" alt="Christian Sidak"/><br /><sub><b>Christian Sidak</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Christian-Sidak" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/XixianWasTaken"><img src="https://avatars.githubusercontent.com/u/74043034?v=4&size=100" width="100px" height="100px" alt="XixianWasTaken"/><br /><sub><b>XixianWasTaken</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=XixianWasTaken" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Sanchar127"><img src="https://avatars.githubusercontent.com/u/143952019?v=4&size=100" width="100px" height="100px" alt="Sanchar panthi"/><br /><sub><b>Sanchar panthi</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Sanchar127" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/insuffer"><img src="https://avatars.githubusercontent.com/u/237025162?v=4&size=100" width="100px" height="100px" alt="Cabeza"/><br /><sub><b>Cabeza</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=insuffer" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/deepanshupal"><img src="https://avatars.githubusercontent.com/u/40927968?v=4&size=100" width="100px" height="100px" alt="Deepanshu Pal"/><br /><sub><b>Deepanshu Pal</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=deepanshupal" title="Code">💻</a> <a href="https://github.com/Agenta-AI/agenta/commits?author=deepanshupal" title="Tests">⚠️</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Mahaboob-Ashraf"><img src="https://avatars.githubusercontent.com/u/200949257?v=4&size=100" width="100px" height="100px" alt="Mohammad Mahaboob Ashraf"/><br /><sub><b>Mohammad Mahaboob Ashraf</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Mahaboob-Ashraf" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Twiink"><img src="https://avatars.githubusercontent.com/u/154496350?v=4&size=100" width="100px" height="100px" alt="Twiink"/><br /><sub><b>Twiink</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Twiink" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/adityasingh345"><img src="https://avatars.githubusercontent.com/u/159435863?v=4&size=100" width="100px" height="100px" alt="Aditya Kumar singh"/><br /><sub><b>Aditya Kumar singh</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=adityasingh345" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/DerrickJc"><img src="https://avatars.githubusercontent.com/u/78075015?v=4&size=100" width="100px" height="100px" alt="derrickLzw"/><br /><sub><b>derrickLzw</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=DerrickJc" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/XonkelX"><img src="https://avatars.githubusercontent.com/u/197416079?v=4&size=100" width="100px" height="100px" alt="Oniel Alejo Feliz"/><br /><sub><b>Oniel Alejo Feliz</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=XonkelX" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/LykenL"><img src="https://avatars.githubusercontent.com/u/206323895?v=4&size=100" width="100px" height="100px" alt="Junxian Lyken Lin"/><br /><sub><b>Junxian Lyken Lin</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=LykenL" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/LinghaoLiOfficial"><img src="https://avatars.githubusercontent.com/u/231870551?v=4&size=100" width="100px" height="100px" alt="LeonLee"/><br /><sub><b>LeonLee</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=LinghaoLiOfficial" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/demonroute1"><img src="https://avatars.githubusercontent.com/u/340640589?v=4&size=100" width="100px" height="100px" alt="Demon Route "/><br /><sub><b>Demon Route </b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=demonroute1" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/mosifu"><img src="https://avatars.githubusercontent.com/u/256577176?v=4&size=100" width="100px" height="100px" alt="mosifu"/><br /><sub><b>mosifu</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=mosifu" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/yunusarda-sudo"><img src="https://avatars.githubusercontent.com/u/64425746?v=4&size=100" width="100px" height="100px" alt="Yunus Arda Güney"/><br /><sub><b>Yunus Arda Güney</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=yunusarda-sudo" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/itsgintoki"><img src="https://avatars.githubusercontent.com/u/237295543?v=4&size=100" width="100px" height="100px" alt="Gin"/><br /><sub><b>Gin</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=itsgintoki" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://wahidsaeed.github.io"><img src="https://avatars.githubusercontent.com/u/26499932?v=4&size=100" width="100px" height="100px" alt="Abdul Wahid"/><br /><sub><b>Abdul Wahid</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=WahidSaeed" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/TPSJASPER"><img src="https://avatars.githubusercontent.com/u/204532137?v=4&size=100" width="100px" height="100px" alt="Jasper"/><br /><sub><b>Jasper</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=TPSJASPER" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/abrahamguo"><img src="https://avatars.githubusercontent.com/u/7842684?v=4&size=100" width="100px" height="100px" alt="Abraham Guo"/><br /><sub><b>Abraham Guo</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=abrahamguo" title="Code">💻</a></td>
    </tr>
    <tr>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/TbhVishal"><img src="https://avatars.githubusercontent.com/u/146272351?v=4&size=100" width="100px" height="100px" alt="Vishal Sharma"/><br /><sub><b>Vishal Sharma</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=TbhVishal" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/Tkrechet"><img src="https://avatars.githubusercontent.com/u/84284166?v=4&size=100" width="100px" height="100px" alt="Anatoly Krechetnikov"/><br /><sub><b>Anatoly Krechetnikov</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Tkrechet" title="Documentation">📖</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://www.linkedin.com/in/muzaqil-hesenli"><img src="https://avatars.githubusercontent.com/u/229985354?v=4&size=100" width="100px" height="100px" alt="Muzaqil Hesenli"/><br /><sub><b>Muzaqil Hesenli</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=Muzaqil555" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/mvanhorn"><img src="https://avatars.githubusercontent.com/u/455140?v=4&size=100" width="100px" height="100px" alt="Matt Van Horn"/><br /><sub><b>Matt Van Horn</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=mvanhorn" title="Code">💻</a></td>
      <td align="center" valign="top" width="14.28%"><a href="https://github.com/DivyamTalwar"><img src="https://avatars.githubusercontent.com/u/194859478?v=4&size=100" width="100px" height="100px" alt="Divyam Talwar"/><br /><sub><b>Divyam Talwar</b></sub></a><br /><a href="https://github.com/Agenta-AI/agenta/commits?author=DivyamTalwar" title="Code">💻</a></td>
    </tr>
  </tbody>
</table>






This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind are welcome!

---

### README (`docs/README.md`)

# Agenta Documentation

This documentation is powered by [Docusaurus](https://docusaurus.io/), a modern and efficient static site generator.

## Getting Started

To set up the documentation locally, follow these steps:

1. **Install Dependencies**  
   First, install the required packages:

   ```bash
   npm install
   ```

2. **Start the Local Development Server**  
   Spin up the server to start working locally:

   ```bash
   npm run start
   ```

   Open your browser and go to `localhost:5000` to view the development site.

3. **Build the Project**  
   Ensure everything is working by building the project:

   ```bash
   npm run build
   ```

4. **Preview the Production Environment**  
   Run the production build server to see how your site will look in production:
   ```bash
   npm run serve
   ```
   Visit `localhost:3000` to explore the production build.

## Deployment

The docs build to Cloudflare Workers Static Assets. Two workers serve the site:

| Worker | Config | What it serves |
| --- | --- | --- |
| `agenta-docs` | `wrangler.production.jsonc` | the production build, on its own `workers.dev` URL |
| `agenta-docs-preview` | `wrangler.jsonc` | one version per pull request |

`https://agenta.ai/docs` and all paths below it route directly to
`agenta-docs`. The retired `new-docs-router` worker no longer proxies these
requests to Vercel. The production routes are declared in
`wrangler.production.jsonc` so later deployments preserve the cutover.

Two GitHub Actions workflows drive them:

- `.github/workflows/18-docs-preview.yml` builds every pull request that touches
  `docs/**`, uploads it as a new version of the preview worker under the alias
  `pr-<number>`, and posts the preview URL as a comment on the pull request. Pull
  requests from forks are skipped, because they cannot read the deploy secrets.
- `.github/workflows/19-docs-production.yml` builds and deploys on every merge to
  `main` that touches `docs/**`.

Both run `pnpm run build:worker`, which writes the site into `dist/docs` rather than
`build`. The nested directory makes the file tree match the public `/docs/` URL
prefix, so Cloudflare serves the site with no rewrite rule. `scripts/stage-worker-assets.mjs`
then copies `worker-assets/_headers` and `worker-assets/_redirects` to `dist/`, where
Cloudflare reads them.

To build and serve the exact production artifact locally:

```bash
pnpm run build:worker
npx wrangler dev --config wrangler.jsonc   # http://localhost:8787/docs
```

`scripts/check-parity.mjs` requests every URL in the live sitemap against another
host, which is how a preview or a new production deploy is checked before traffic
moves to it:

```bash
node scripts/check-parity.mjs https://pr-1234-agenta-docs-preview.<subdomain>.workers.dev
```

`scripts/monitor-production.mjs` is the smaller production health check. GitHub
Actions runs it every 15 minutes against the sitemap and representative current,
versioned, security, and API-reference pages. It checks normal, Googlebot, and
Bingbot requests and rejects any Vercel challenge response or unexpectedly
cacheable error.

## Changelog Guidelines

When working on the changelog page, following specific formatting rules are important to ensure the page's layout remains intact. Failure to follow these guidelines may result in broken UI elements.

### Key Guidelines for Editing the Changelog Page

1. **Avoid using italic (`**`) formatting** except when specifying the **publishing date\*\*.
2. **Use Heading 3 (`###`)** for all changelog section titles.
3. **Always insert a horizontal rule (`----`)** before beginning a new section of the changelog.
4. **Ensure all content is written within** the `<section class="changelog">...</section>` **elements**. Writing outside of this structure will break the UI.

By inserting to these formatting conventions, you'll maintain the integrity and readability of the changelog page.

## Notes

- Do not update any libraries or packages as this could disrupt the template structure and cause it to break.
- Please use kebab-case (this-way) instead of snake_case for naming files and folders

---

### Design README (`docs/design/README.md`)

# Design docs

Each folder here holds the design, plan or research for one piece of work, written when that work
was done. The docs are a dated record: they are not updated when the code changes later.

Many of them name `web/oss` and `web/ee`, the desktop web app that was removed in favor of
`web/mobile` (served at `/m`). Those paths are history. The desktop app no longer exists, so read
them as "the old desktop app" and look for the live code in `web/mobile` and `web/packages`.

`docs/design/testing/` is the exception: it describes how tests run today and is kept current.
`scripts/check-no-desktop-app-refs.sh` enforces that split in CI.

---

### .Agents Docs Code Review README (`.agents/docs/code-review/README.md`)

# Code Review Artifact Structure

This document defines the structure of files and folders used by a code‑review agent.  Each artifact has a clear role in the lifecycle of a review, from the fixed harness through working memory and finally to the user‑facing outputs.  The descriptions below explain when to use each artifact, why it is a file or a folder, whether it is optional, and whether it is mutable or append‑only.  A summary table at the end provides a quick reference.

## 1 Harness (fixed reference files)

These files and folders define **how** reviews should be performed and what file structure to use.  They live outside of any individual run and change infrequently.

### `guidelines.md`  – Global file structure overview

* **Purpose:** Provides an overview of the entire code‑review file structure.  It explains the roles of each file and folder, how they fit together, and offers a quick reference for new users.
* **When to use:** Consult this file when setting up a new review process or onboarding a team member.  It is the first place to look to understand where to place information and where to find specific artifacts.
* **When not to use:** Do not use it to store actual review content or instructions; those belong in the other harness files.  Avoid duplicating detailed instructions or rubrics here.
* **Why a file:** A single guidelines document centralises the structure description and makes it easy to discover.  It provides a human‑readable entry point without requiring multiple documents.
* **Optional?** Recommended.  While not strictly required for a review to function, a guidelines file improves discoverability and onboarding.
* **Mutable?** Mutable but updated infrequently.  Edit it when the file structure evolves.

### `instructions.md`  – Review guidelines

* **Purpose:** Contains general review procedures, best practices, and common checks.  It sets expectations for reviewers and ensures consistency across runs.
* **When to use:** Always consult this file at the start of a review to understand the process and rubric.  Agents should reference it when deciding what constitutes a finding or how to classify severities.
* **When not to use:** Do not store run‑specific notes or scope here.  It should not be modified by an agent during a review.
* **Why a file:** Instructions are relatively stable and apply globally across projects; storing them in a single file simplifies maintenance.
* **Optional?** Required – a review should not start without knowing the instructions.
* **Mutable?** Mutable but rarely edited.  Updates are made centrally to refine the review process, not within individual runs.

### `deliverables.md`  – Output requirements

* **Purpose:** Defines the required and optional outputs of a review (e.g., findings, summary, patch).  It describes formats, severity levels, and acceptance criteria.
* **When to use:** Read at the beginning of a project to know what artifacts must be produced.  Agents can check this file to ensure all mandatory outputs are generated.
* **When not to use:** It is not used to store actual deliverables or findings.
* **Why a file:** Deliverable definitions are stable across runs and are most useful as a single reference document.
* **Optional?** Required.  This file ensures the agent understands what it must produce.
* **Mutable?** Mutable but updated only by administrators when deliverable requirements change.

### `templates/`  – Template folder

* **Purpose:** Holds reusable templates for different artifacts (e.g., issue format, summary layout, scorecard skeleton).  Templates ensure consistent formatting across reviews.
* **When to use:** When creating a new artifact, agents should start from the appropriate template file in this folder.
* **When not to use:** Do not store run‑specific content here.  Templates should not be edited during a review.
* **Why a folder:** Multiple template files may exist (one per artifact), so a folder keeps them organised.
* **Optional?** Optional.  If templates are not provided, agents may build the artifacts manually, but consistency may suffer.
* **Mutable?** Template files can be updated centrally but should remain static during a run.

### `rubrics/`  – Rubric folder

* **Purpose:** Contains one file per review type (e.g., security, performance, migration) specifying criteria, scoring ranges, and domain‑specific checks.
* **When to use:** Select the appropriate rubric(s) before planning a review.  Agents may consult them when scoring issues or deciding risk levels.
* **When not to use:** Do not mix rubrics with findings or run notes; rubrics describe evaluation standards only.
* **Why a folder:** Each review type can have its own rubric file, and new types can be added without modifying existing ones.
* **Optional?** Optional.  If your organisation does not use detailed rubrics, this folder may be empty.
* **Mutable?** Mutable at the administrative level; rubric files should not be altered mid‑review.

## 2 Per‑run input

These artifacts define **what** is being reviewed and why.  They originate from the user or requester.

### `scope.md`  – Scope definition

* **Purpose:** Describes the scope of the current review, including the codebase/branch, modules included or excluded, the goals of the review, and any constraints or context provided by the requestor.
* **When to use:** Created at the beginning of each review run.  The agent uses it to understand boundaries and to avoid analysing unrelated parts of the codebase.
* **When not to use:** Do not edit this file during the review to record progress or findings.  It is the baseline contract of the review.
* **Why a file:** The scope is a single, definitive statement for the run.  A file suffices because scope is typically concise and does not require multiple subdocuments.
* **Optional?** Required.  A review cannot start without a defined scope.
* **Mutable?** Immutable during the run; once defined, it should not change unless the requester updates the review brief.

## 3 Per‑run execution

These files track **how** the agent intends to conduct the review and what the current state is.

### `plan.md`  – Review plan

* **Purpose:** Outlines the agent’s planned approach: which files or modules to review first, hypotheses about risk areas, prioritisation of checks, and planned passes.
* **When to use:** Generated at the outset of the review based on the scope, instructions and rubric.  It should be updated only if the plan needs to adapt significantly.
* **When not to use:** Do not record progress or actual findings here.  Keep it high‑level and forward‑looking.
* **Why a file:** The plan is a single, coherent narrative; storing it in one file makes it easy to read and update.
* **Optional?** Required.  A clear plan helps ensure structured reviews and repeatability.
* **Mutable?** Mutable.  It may be updated as the agent adjusts its strategy, but such changes should be rare and well‑justified.

### `progress.md`  – Review progress

* **Purpose:** Records the current execution state: which files have been reviewed, which checks are complete, outstanding tasks, and any blockers or time estimates.
* **When to use:** Update this file regularly during the review to reflect progress and provide transparency.  It complements the plan by showing actual execution.
* **When not to use:** Do not include findings, evidence or reasoning here.  It is strictly about status.
* **Why a file:** Progress can be tracked as a checklist or table in a single file.  One file suffices to keep all tasks and their statuses together.
* **Optional?** Required for long or complex reviews.  Optional for trivial reviews with a single pass.
* **Mutable?** Mutable.  Entries and statuses can be updated as tasks progress; you can mark items complete, adjust estimates or reorder rows.  Append new entries when needed but do not be afraid to update existing ones.

## 4 Per‑run working memory

These artifacts capture **thinking** and **evidence** during the review.  They are internal to the agent and not part of the final deliverables.

### `notes/`  – Scratchpad folder

* **Purpose:** Serves as the reviewers’ scratchpad.  Each agent, pass or concern area can have its own file within this folder to record hypotheses, tentative observations and questions that are not yet promoted to findings.
* **When to use:** Write to this folder during the analysis phase.  Use separate files to avoid conflicts when multiple agents or passes run concurrently.  Reviewers can later revisit these notes when formulating findings.
* **When not to use:** Do not store definitive evidence or final findings here.  Notes are provisional and may contain false positives.
* **Why a folder:** A folder supports parallel work streams (by agent, pass or module).  It prevents a single file from becoming cluttered.
* **Optional?** Optional for simple reviews but highly recommended when multiple agents collaborate or when reviews are complex.
* **Mutable?** Mutable.  Files within this folder are freely edited during a review; they may be appended, reorganised or removed as needed.

### `evidence/`  – Evidence folder

* **Purpose:** Stores concrete proof for each issue or hypothesis, such as code snippets, line ranges, reproduction steps, logs or command outputs.  Each evidence file can correspond to a specific finding or a reviewed file.
* **When to use:** Whenever you identify something notable, create or update an evidence file to capture the supporting material.  Link to these evidence files from findings.
* **When not to use:** Do not use evidence files for narrative explanations; save that for the notes or findings.  Also avoid duplicating entire source files.
* **Why a folder:** Evidence is modular; splitting it into multiple files avoids an unwieldy monolith and makes cross‑referencing easier.
* **Optional?** Required for any non‑trivial finding.  Optional in reviews that yield no issues.
* **Mutable?** Mutable.  Evidence files may be updated or reorganised as new information emerges.  You can refine sections, add clarifications or extend snippets; try to avoid deleting useful context.

### `metadata.json`  – Structured state

* **Purpose:** Stores machine‑readable metadata about the review.  Fields might include the review ID, timestamps, list of reviewed files, counts of findings by severity, and completion flags.
* **When to use:** The agent updates this file programmatically as the review progresses.  It can be read by orchestration tools or dashboards to track status.
* **When not to use:** Do not include human‑readable notes or evidence; keep it structured for consumption by software.
* **Why a file:** JSON is well suited for structured data and can be easily parsed by tools.  A single file suffices because metadata is centrally maintained.
* **Optional?** Optional but recommended when automation or dashboards are used.
* **Mutable?** Mutable.  Fields may be updated or added as the review evolves.

## 5 Per‑run promoted outputs

These artifacts contain **conclusions** drawn from the working memory and are intended for consumption by stakeholders.

### `findings.md`  – Confirmed issues

* **Purpose:** Lists all confirmed issues discovered during the review.  Each entry includes its severity, location, a clear description, an explanation of why it matters, references to relevant evidence, and a recommended remediation.  Remediation should present one or more options to address the issue, with optional code changes or patch snippets where applicable.  Entries are typically organised as rows of a table with columns for each attribute, making it easy to scan and update.  Alternatively, each finding can be documented as its own subsection with subheadings for each column attribute (e.g., Issue ID, Description, Evidence, Remediation), giving a table‑list structure that scales when entries are verbose.
* **When to use:** Populate this file throughout or at the end of the review when provisional notes are promoted to findings.  When adding an issue, include its supporting evidence and remediation options.
* **When not to use:** Do not include unverified suspicions or non‑issues.  Keep it concise and focused on actionable defects.
* **Why a file:** Findings need to be presented in a single coherent list to stakeholders.  A file allows sequential organisation and easy referencing.
* **Optional?** Required when issues are found.  If no issues are found, this file may be empty or omitted.
* **Mutable?** Mutable.  The table of findings can be expanded with new entries or updated with clarifications, improved explanations or remediation options.  Avoid deleting entries unless they are duplicates; mark resolved items clearly.

### `risks.md`  – Broader concerns

* **Purpose:** Captures high‑level risks that might not be direct defects, such as maintainability concerns, architectural weaknesses or potential performance bottlenecks.  Each risk entry should include a description, an explanation of the potential impact, references to relevant evidence, and recommended mitigation options.  Mitigation should present one or more approaches, with optional code snippets or patch guidance where applicable.  Risks should be presented as a table with columns for category, description, impact, evidence references and mitigation options.  Alternatively, each risk can be written as its own subsection with subheadings for these attributes, creating a table‑list layout that improves readability when entries are lengthy.
* **When to use:** Use this file when you identify system‑wide or non‑blocking issues that stakeholders should be aware of.  When adding a risk, include supporting evidence and multiple mitigation options if there are different ways to address it.
* **When not to use:** Do not duplicate confirmed defects here; those belong in `findings.md`.  Avoid speculating without evidence.
* **Why a file:** A separate file helps distinguish general risks from actionable defects, aiding prioritisation.
* **Optional?** Optional.  Include it only when such risks are identified.
* **Mutable?** Mutable.  Risk entries can be added or updated as your understanding of the system evolves.  If a risk is resolved or mitigated, note the outcome rather than deleting the row.

### `questions.md`  – Clarifications needed

* **Purpose:** Lists questions for the code author or requestor that block understanding or prevent conclusions.  Each question should be clear and reference the related code or context.  Entries should also provide a brief explanation of why the question matters, refer to relevant evidence, and, where possible, propose potential directions or provisional suggestions (which may include more than one option) to explore once the question is answered.  Questions should be captured in table form with columns for the question, explanation, evidence references, provisional suggestions, and status (e.g., open, resolved).  Alternatively, each question may be organised as its own subsection with subheadings for these attributes, giving a table‑list structure that is easier to read when the answers or explanations are long.
* **When to use:** Whenever ambiguity arises that cannot be resolved internally.  Early recording of questions helps avoid delays.  Include supporting evidence and any provisional suggestions or options that may help once the question is addressed.
* **When not to use:** Do not store rhetorical questions or brainstorming here; those belong in `notes/`.  Only include questions that need external answers.
* **Why a file:** A single list of unanswered questions helps facilitate efficient communication with stakeholders.
* **Optional?** Optional.  Omit if no clarifications are needed.
* **Mutable?** Mutable.  Questions may be added, updated, marked as resolved, or expanded with additional context.  Retain the history of asked questions for transparency.

## 7 Per‑run synthesis

These artifacts summarise the review for quick consumption by decision‑makers.

### `summary.md`  – Narrative summary

* **Purpose:** Provides a human‑readable overview of the review: overall health, key issues, risk posture, and next steps.  It should reference the main findings and recommendations without duplicating all details.
* **When to use:** Generate at the end of the review after findings and recommendations are finalised.  Use it when communicating results to stakeholders who may not read the full findings file.
* **When not to use:** Do not insert new findings or recommendations here; the summary should only draw from existing files.
* **Why a file:** It stands as the primary document for executive stakeholders.  A single markdown file keeps the narrative cohesive.
* **Optional?** Required for most reviews.  Exceptions may include internal or ad‑hoc checks where a formal summary is unnecessary.
* **Mutable?** Mutable until the review concludes; once delivered, treat as final.

### `scorecard.md`  – Structured report card

* **Purpose:** Offers a concise, structured overview of the review, often as a table or list: number of findings by severity, risk scores, confidence levels, review coverage and readiness recommendation.
* **When to use:** Use alongside the summary for stakeholders who prefer quick metrics.  Scorecards help in comparing multiple reviews or tracking improvement over time.
* **When not to use:** Avoid narrative explanations here; those belong in the summary.  Do not overload the scorecard with long descriptions.
* **Why a file:** Separating metrics from narrative improves readability and allows automated tooling to parse scorecards easily.
* **Optional?** Optional but recommended.  It is particularly useful when multiple reviews need to be aggregated or when managers require at‑a‑glance status.
* **Mutable?** Mutable until the review is finalised; afterwards, treat it as static.

## 8 Summary timeline / sequence

The artifacts above follow a typical sequence:

1. **Harness (fixed)** – `guidelines.md`, `instructions.md`, `deliverables.md`, `templates/`, and `rubrics/` are prepared by administrators and read before starting a review.
2. **Define scope** – Create `scope.md` based on the requester’s brief.
3. **Plan** – Draft `plan.md` using scope and rubrics.
4. **Execute and record progress** – Update `progress.md` as you work, and use `notes/` and `evidence/` to capture thoughts and proof.  Maintain `metadata.json` if automation is needed.
5. **Promote outputs** – When ready, consolidate confirmed issues in `findings.md`, broader concerns in `risks.md`, and unresolved questions in `questions.md`.  For each entry, include its explanation, references to evidence, and recommended remediation.  Remediation should offer one or more possible options and may include code or diff snippets where appropriate.
6. **Synthesize** – Produce `summary.md` and `scorecard.md` at the end of the review for stakeholders.

## 9 Quick reference table

The table below summarises the key properties of each artifact.  It uses short phrases rather than full sentences to remain concise.

| Artifact | Type (file/folder) | Required? | Mutability |
|---|---|---|---|
| `instructions.md` | File | Yes | Mutable, rarely edited |
| `guidelines.md` | File | Recommended | Mutable, rarely edited |
| `deliverables.md` | File | Yes | Mutable, rarely edited |
| `templates/` | Folder | No | Static during run |
| `rubrics/` | Folder | No | Static during run |
| `scope.md` | File | Yes | Immutable during run |
| `plan.md` | File | Yes | Mutable |
| `progress.md` | File | Usually | Mutable (checklist) |
| `notes/` | Folder | Optional | Mutable |
| `evidence/` | Folder | Optional* | Mutable |
| `metadata.json` | File | Optional | Mutable |
| `findings.md` | File | If issues | Mutable (table) |
| `risks.md` | File | Optional | Mutable (table) |
| `questions.md` | File | Optional | Mutable (table) |
| `summary.md` | File | Usually | Mutable until final |
| `scorecard.md` | File | Optional | Mutable until final |

\*Evidence is not needed if the review uncovers no issues or if the scope is extremely small.

---

### Design Advanced Auth README (`docs/design/advanced-auth/README.md`)

# Authentication & Authorization

This directory contains specifications for the authentication and authorization system.

---

## Quick Reference

### Core Specifications

| Document | Description |
|----------|-------------|
| [auth.flags.specs.md](auth.flags.specs.md) | Organization flags, defaults, enforcement rules, safety mechanisms |
| [auth.domains.specs.md](auth.domains.specs.md) | Domain verification, DNS TXT, governance model |
| [auth.sso.specs.md](auth.sso.specs.md) | SSO providers, OIDC configuration, secrets, lifecycle |
| [auth.sessions.specs.md](auth.sessions.specs.md) | Session model, identity accumulation |
| [auth.flows.specs.md](auth.flows.specs.md) | Discovery, login, org switching, error handling |
| [auth.realms.specs.md](auth.realms.specs.md) | URL routing, multi-tenant realm configuration |

### Supporting Documents

| Document | Description |
|----------|-------------|
| [auth.supertokens.specs.md](auth.supertokens.specs.md) | SuperTokens runtime configuration model |
| [auth.oss-ee.specs.md](auth.oss-ee.specs.md) | OSS vs Commercial License feature matrix |
| [auth.migrations.specs.md](auth.migrations.specs.md) | Personal/collaborative org migration spec |
| [auth.testing.plans.md](auth.testing.plans.md) | Manual E2E test plan |

---

## Schema Overview

### `organizations`

| Column | Type | Purpose |
|--------|------|---------|
| `id` | UUID | Identifier |
| `slug` | TEXT | URL-visible identifier |
| `name` | TEXT | Human label |
| `flags` | JSONB | Authentication and access policies |

### `organization_domains`

| Column | Type | Purpose |
|--------|------|---------|
| `id` | UUID | Identifier |
| `organization_id` | UUID FK | Owning org |
| `slug` | TEXT | Domain name (e.g., `acme.com`) |
| `token` | TEXT | DNS TXT verification token |
| `flags` | JSONB | Contains `is_verified` |

### `organization_providers`

| Column | Type | Purpose |
|--------|------|---------|
| `id` | UUID | Identifier |
| `organization_id` | UUID FK | Owning org |
| `slug` | TEXT | Provider identifier (e.g., `okta`) |
| `name` | TEXT | User-facing label |
| `type` | TEXT | Provider type (e.g., `oidc`) |
| `flags` | JSONB | Contains `is_active`, `is_valid` |
| `secret_id` | UUID FK | Encrypted configuration |

### `users`

| Column | Type | Purpose |
|--------|------|---------|
| `id` | UUID | Identifier |
| `email` | TEXT | Unique email |
| `is_active` | BOOLEAN | Account enabled |

### `identities`

| Column | Type | Purpose |
|--------|------|---------|
| `id` | UUID | Identifier |
| `user_id` | UUID FK | Link to user |
| `method` | ENUM | `email`, `social`, `sso` |
| `provider` | TEXT | e.g., `email:otp`, `social:google`, `sso:acme:okta` |
| `subject` | TEXT | Stable identifier from provider |

---

## Organization Flags

All stored in `organizations.flags` JSONB:

| Flag | Default | Purpose |
|------|---------|---------|
| `is_demo` | `false` | Demo organization |
| `allow_email` | `env.auth.email_enabled` | Allow email/OTP authentication |
| `allow_social` | `env.auth.oidc_enabled` | Allow social authentication |
| `allow_sso` | `false` | Allow SSO authentication |
| `allow_root` | `false` | Owner bypasses all auth restrictions |
| `domains_only` | `false` | Restrict to verified email domains |
| `auto_join` | `false` | Auto-add users with verified domains |

> **Note:** The `is_personal` flag has been removed. All organizations are collaborative by default.

---

## Error Codes

| Code | Trigger | User Action |
|------|---------|-------------|
| `AUTH_UPGRADE_REQUIRED` | Auth method not in allowed list | Re-authenticate with allowed method |
| `AUTH_SSO_DENIED` | SSO disabled or provider inactive | Contact admin |
| `AUTH_DOMAIN_DENIED` | Email domain not in verified list | Contact admin or use verified domain |

---

## Authorization Flow

```
Request → Middleware → check_organization_access()
                            │
                            ├─ Owner bypass (allow_root)
                            │
                            ├─ Build allowed methods from flags
                            │
                            ├─ Match session identities
                            │   └─ No match → AUTH_UPGRADE_REQUIRED
                            │   └─ SSO mismatch → AUTH_SSO_DENIED
                            │
                            └─ Check domains_only
                                └─ Domain not verified → AUTH_DOMAIN_DENIED
```

---

## One-Sentence Summary

> Organizations control access via flags stored in JSONB; domain verification establishes governance authority; SSO providers enable enterprise authentication; and sessions accumulate identity proofs that are validated against org policies on each request.

---

### Design Agent Chat Turn Continuation README (`docs/design/agent-chat-turn-continuation/README.md`)

# agent-chat-turn-continuation

Fix for the duplicated turn blocks in the agent playground: after every tool
approval, the whole previous assistant turn stacks again as a new block. Root cause:
the AI SDK client continues the last assistant message on a resume, but our server
mints a fresh `msg-{trace_id}` per HTTP request, so the client's identity check fails
and it pushes a full clone instead of replacing in place.

Design-only workspace (2026-07-06). No product code changed here.

## Files

| File | What it holds |
|---|---|
| `context.md` | The symptom, why it happens (one paragraph), goals and non-goals |
| `research.md` | The full verified flow: message-id lifecycle, why the client clones, frontend decision points, wire frames for normal/pause/resume, before/after playground mock. Read this to understand the system. |
| `fix-options.md` | Options A/B/C evaluated, interface-role review, the trace-per-message implications, recommendation (A: server echoes the continuation id) |
| `plan.md` | Implementation slices, unit + manual test plan, rollout |
| `trace-continuation.md` | Follow-up design: propagate trace context across a turn's resumes so one turn = one trace (fixes the multi-trace trade-off v1 accepts). Decision pending. |
| `status.md` | Current progress and decisions |

## Related

- Original investigation:
  `docs/design/agent-workflows/scratch/approval-turn-duplication-findings.md`
  (this workspace verifies and extends its root cause 1; root cause 2, the phantom
  tool failure, is out of scope here).
- Key code: `sdks/python/agenta/sdk/decorators/routing.py` (fix site),
  `sdks/python/agenta/sdk/agents/adapters/vercel/stream.py` (id minting),
  `web/oss/src/components/AgentChatSlice/` (playground UI),
  `web/packages/agenta-playground/src/state/execution/` (resume predicate, request
  builder).

---

### Design Agent Config Editing README (`docs/design/agent-config-editing/README.md`)

# Agent config editing

An agent in the Agenta playground can edit its own configuration. Today every edit must
resend the full content, which wastes tokens, breaks above ~4.8 KB, and silently replaces
whole lists. This project replaces that with targeted operations, and refactors the runner
so small configuration changes stop forcing a full sandbox rebuild.

## Reading order

| File | Answers |
|---|---|
| `context.md` | Why this work exists. Goals, non-goals, user stories. |
| `plan.md` | The execution plan: slices, order, QA gates. |
| `status.md` | Where the work stands right now. Decisions and blockers. |
| `contracts/change-set.md` | The change-set engine, decided. Where any other document disagrees with it, this one wins. |
| `contracts/execution-authorization.md` | Execution authorization for workspace file references, decided. |
| `contracts/workspace-import.md` | The workspace import boundary, decided. |
| `contracts/adapter-matrix.md` | The harness reconciliation matrix, decided. |
| `contracts/commit-transaction.md` | The atomic commit transaction and its wire response, decided. |
| `contracts/read-config.md` | `read_config`, the editable scope, and the call description, decided. |
| `research.md` | What the codebase research found, with file references. |
| `research/rfc.html` | The original RFC: requirements, design questions. Historical context; the `contracts/` files carry the decided answers. |
| `research/change-set-interface-codex.md` | The pre-consolidation change-set interface spec. Historical; superseded by `contracts/change-set.md`. |
| `research/runner-lifecycle-codex.md` | The pre-consolidation runner lifecycle architecture. Historical; superseded by `contracts/adapter-matrix.md`. |
| `spikes/engine-spike.md` | Findings from the change-set engine prototype. Historical. |
| `spikes/runner-spike.md` | Findings from the runner-side spikes. Historical. |

The `contracts/` files are the implementation source of truth. `research/` and `spikes/`
record how we got there; read them for context, not for the current behavior.

## Glossary

- **Configuration**: the JSON object at `parameters.agent` in a revision. It holds the
  instructions, the model, the tools, the skills, the MCP servers, the harness, and the
  permissions.
- **Revision**: one committed version of the configuration. Revisions are immutable.
- **Harness**: the coding agent that runs inside the sandbox (Pi, Claude Code, or Codex).
- **Runner**: the TypeScript service (`services/runner`) that creates sandboxes, writes
  workspace files, opens harness sessions, and executes turns.
- **Sandbox**: the isolated machine (local process or Daytona VM) the harness runs in.
- **Warm session**: a sandbox plus harness session the runner keeps alive between turns.
- **Fingerprint**: today, one checksum over all configuration values. The runner compares
  it to decide whether a parked warm session can be reused.
- **Builder tools**: platform tools (commit_revision and others) injected into playground
  runs only, never stored in the configuration.
- **Change set / delta**: the payload of a commit: what to change relative to a base.

---

### Design Agent Custom Secrets README (`docs/design/agent-custom-secrets/README.md`)

# Custom secrets for agent runs

Agent variants can attach text secrets from the project vault to their sandbox as environment variables. An agent can also pause a conversation with `request_secret`, let the user configure the binding, and continue on the committed revision.

## Reading order

1. [Context](context.md): problem, intended outcome, and milestone boundary.
2. [Contracts](contracts.md): shipped configuration, runtime, and tool interfaces.
3. [Plan](plan.md): implementation sequence and interaction lifecycle.
4. [Simplification](simplification.md): V1 scope decisions and deferred V2 work.
5. [QA](qa.md): automated and runtime acceptance criteria.
6. [Browser checklist](qa-browser-checklist.md): release checks for the user-facing transaction.
7. [Status](status.md): implementation and validation state.

## Shipped V1

V1 includes text custom secrets, environment-variable bindings, project-scoped resolution, runner injection and redaction, shared create and attach UI, an Advanced agent configuration section, and the `request_secret` conversation flow. Bindings persist on an ordinary agent variant revision.

The vault owns secret content. The variant stores only the secret slug and environment binding. The run transport carries resolved values to the runner over the existing protected channel and registers them with existing diagnostic redaction. The [QA notes](qa.md) describe the limits of readable delivery and short-value redaction.

V1 has no service presets, secret templates, session-only grants, delivery-mode picker, host allowlist, or advanced secret metadata. Host-restricted and opaque delivery remain V2 work.

## Terms

A **vault secret** is encrypted project data. A **binding** maps a saved secret to one environment-variable name. A **variant revision** is a saved version of the agent configuration. A **paused turn** waits for a user interaction before the harness continues.

## Tracking

[Issue #5703](https://github.com/Agenta-AI/agenta/issues/5703), also [AGE-4067](https://linear.app/agenta/issue/AGE-4067), tracks custom-secret delivery. The implementation builds on the shared platform-instruction path introduced by [PR #6365](https://github.com/Agenta-AI/agenta/pull/6365).

---

### Design Agent Permission Defaults README (`docs/design/agent-permission-defaults/README.md`)

# Agent permission defaults

New agents should run ordinary work without approval. The playground build kit should
set explicit approval policies for its platform operations. Settings should expose a
general permission dropdown without harness or sandbox implementation details.

## Reading order

- [Context](context.md): goals, scope, and agreed behavior.
- [Plan](plan.md): implementation slices and acceptance checks.
- [Research](research.md): current code and policy ownership.
- [Spikes](spikes.md): Claude and Codex questions and evidence requirements.
- [Claude findings](claude-spike.md) and [Codex findings](codex-spike.md): executed
  tests, native settings observations, and blocked live checks.
- [Validation](validation.md): implementation checks and desktop/mobile coverage.
- [Deployed QA](qa.md): real-app results and screenshots from the release-based stack.
- [Status](status.md): implementation and verification progress.

## Terms

A **harness** is the agent engine: Pi, Claude, or Codex. The **runner** executes that
engine and handles tool delivery and approval requests. An **execution environment**
is where it runs, such as local or Daytona. The **build kit** is a temporary set of
tools and guidance added to playground runs, not saved in the agent configuration.

Tool availability, approval policy, API access, and environment isolation are separate.
An explicit tool policy overrides the general permission fallback.

---

### Design Agent Platform Instructions README (`docs/design/agent-platform-instructions/README.md`)

# Agent platform instructions

Keep Agenta's shared instructions in one SDK module and deliver them through the
runner's existing instruction paths. This cleanup adds a short common base, moves
gateway guidance out of the bundled skills module, and removes the SDK's
delivery-choice wrapper. Author configuration stays separate from generated text.

- [Context](./context.md): problem and scope.
- [Plan](./plan.md): implementation, rollout, and checks.
- [Research](./research.md): existing implementation.
- [Status](./status.md): progress and verification.

---

### Design Agent Self Naming Tools README (`docs/design/agent-self-naming-tools/README.md`)

# Agent self-naming tools

Two new platform tools that let an agent name and describe the session it is running in
(`rename_session`) and name and describe itself (`rename_agent`), plus the live-refresh
mechanism that makes those renames show up in an open browser tab.

## Reading order

| File | The question it answers |
| --- | --- |
| [context.md](context.md) | Why this work exists, what counts as done, what is out of scope, and which decisions are already made. |
| [research.md](research.md) | How agent tools, sessions, workflow artifacts, and the live-update relay work in the code today, and the two hazards found while reading them. |
| [api-design.md](api-design.md) | The exact contract of both tools, the tool descriptions the model reads, and the watch-event payload. |
| [plan.md](plan.md) | The implementation steps, in dependency order, with files per step. |
| [qa.md](qa.md) | Tests, the one-shot benchmark scenarios, and the live verification script. |
| [status.md](status.md) | Current progress, open decisions, and history. |

## Glossary

Terms used across these files, defined once here.

- **Agent**: what a user builds and talks to in the product. It is stored as a **workflow
  artifact** (the row the agents list reads) with variants and revisions under it. Its display
  name lives on the artifact.
- **Session**: one conversation. Stored as a `session_streams` row carrying `name` and
  `description`. `name` is the session title; there is no separate title column.
- **Runner**: the Node service that drives a turn, dispatches tool calls from the host, and holds
  the run's credential. The sandbox never holds a credential.
- **Sandbox**: the isolated process the harness runs in. It sends a tool name plus arguments and
  nothing else.
- **Harness**: the coding-agent program the runner drives (Claude Code, Pi, Codex).
- **Platform tool**: an Agenta endpoint exposed to the model as a tool. The author writes
  `{"type": "platform", "op": "<op>"}`; the description, schema, endpoint, and hidden bindings all
  come from a code-defined catalog.
- **Run context**: a blob of the run's own identity (project, workflow, trace) delivered on the
  `/run` request. A tool binds a field from it server-side so the model never sees or sets that
  field.
- **Context binding**: a map from a request-body path to a `$ctx.<dotted.path>` token. The runner
  fills it at dispatch, after the model's arguments, so a bound field always wins.
- **Build kit**: the tool set injected into every playground agent by default
  (`DEFAULT_BUILD_KIT_OPS`).
- **Watch relay**: a server-to-browser notification path. The server publishes a small frame on
  Redis, an endpoint streams it as Server-Sent Events, and the browser refetches through its
  normal endpoints. The frame carries ids only, never entity data.

---

### Design Agent Workflows README (`docs/design/agent-workflows/README.md`)

# Agent Workflows

This workspace documents the agent-workflows feature: running a coding harness as an
Agenta workflow. It is organized into five layers so the living design docs stay separate
from in-flight project notes and historical archaeology.

## Layout

- **[documentation/](documentation/)** — the living design docs, kept current with the
  code. Start here.
- **[interfaces/](interfaces/)** - interface inventory for reviews: public edge
  contracts, cross-service contracts, and in-service ports/DTOs.
- **[projects/](projects/)** — active, self-contained workstreams. Each has its own
  `README.md`/`status.md`. These graduate into `documentation/` or fold into the code as
  they land.
- **[scratch/](scratch/)** — transient coordination: status, open issues, PR/branch
  cleanup reports. These drop off and move to `archive/` over time.
- **[archive/](archive/)** — superseded notes, old RFCs, and finished work-package
  spikes. Kept for archaeology only; not design truth.
- **trash/** — truly disposable items, safe to delete.

## documentation/ (read in this order)

1. [Ground Truth](documentation/ground-truth.md): what the code does, what is wired, and
   what is still missing.
2. [Architecture](documentation/architecture.md): the service, agent runner sidecar,
   harnesses, and sandboxes.
3. [Protocol](documentation/protocol.md): `/invoke`, `/messages`, and the
   runner `/run` wire contract.
4. [Ports and Adapters](documentation/ports-and-adapters.md): the SDK runtime ports,
   backend adapters, harness adapters, and browser protocol adapter.
5. [Agent Template](documentation/agent-template.md): the split between generic agent
   identity, harness-specific config, and runtime infrastructure.
6. [Sessions](documentation/sessions.md): cold replay, streaming, session ids, and the
   missing session store.
7. [Triggers](documentation/triggers.md): planned trigger/event integration.
8. [Tools](documentation/tools.md): the tool taxonomy and executor model.
9. Adapters: [Pi](documentation/adapters/pi.md),
   [Claude Code](documentation/adapters/claude-code.md),
   [Agenta](documentation/adapters/agenta.md).
10. [Skills](documentation/skills.md): the development-workflow skills (plan, implement,
    debug, test, document, branch) and how they chain across a feature's life.

## projects/

- [agent-plugin-templates](projects/agent-plugin-templates/) - Single-agent template loading specs, existing build-kit reuse, and deferred multi-agent requirements.
- [code-tool-sandbox](projects/code-tool-sandbox/) — sandboxed code-tool execution.
- [harness-capabilities](projects/harness-capabilities/) — per-harness capability model.
- [model-config](projects/model-config/) — model selection config.
- [provider-model-auth](projects/provider-model-auth/) — provider/model/credential
  injection.
- [qa](projects/qa/) — manual QA matrix, findings, and regression-test skills.
- [runner-interface](projects/runner-interface/) — runner `/run` interface notes.
- [sdk-local-tools](projects/sdk-local-tools/) — standalone SDK tool resolution.
- [sidecar-deployment-proposal](projects/sidecar-deployment-proposal/) — sidecar to
  k8s/Helm + prod compose + Railway.
- [skills-config](projects/skills-config/) — skills configuration.
- [tool-resolution-layering](projects/tool-resolution-layering/) — SDK tool-resolution
  layering.
- [typescript-structure](projects/typescript-structure/) — TS runner structure and tests.
- [sandbox-agent-refactor](projects/sandbox-agent-refactor/) — sandbox-agent runner
  refactor plan.
- [research](projects/research/) — external-architecture research (e.g. OpenCode).

## scratch/

Status, open issues, PR-stack and branch-cleanup reports, meeting-alignment, the
implementation review, and the feature-matrix test report. Transient by design.

---

### Design Agenta Mobile README (`docs/design/agenta-mobile/README.md`)

# Agenta Mobile — project index & handoff

**Status: WAVE-1 COMPLETE (2026-07-25)** — WP1 (mobile foundation), WP0 (sessions backend
residual), and WP3a (`@agenta/chat` headless package, copy-extraction mode with OSS
byte-untouched) all built and dual-reviewed on `feat/agenta-mobile-wave-1`, which sits on
**PR #5479's tip (`3c78268700`)**. 35 commits, final coherence sweep clean, not pushed.
Next: wave-2 planning (WP2 auth/drawer → WP3b mobile chat skin → WP4 pages → WP5 gate).
This file is the entry point: what exists, what's done, what's next.

## What this is

A minimal mobile web experience: a **sessions list** (searchable/filterable) + a **chat view**
with playground-identical behavior — nothing else. Served as a separate greenfield Next.js app
at `/m`, doubling as the modernization vehicle for the OSS/EE frontend (shadcn instead of antd,
headless chat core shared between desktop and mobile skins).

### Locked decisions (see design.md for rationale)

| # | Decision |
|---|----------|
| a | Separate `web/mobile` app (Pages Router), not pages in the existing app |
| b | Path mount `/m` behind Traefik (`basePath: "/m"`, no stripprefix) |
| c | Session list is project-wide (not per-user) |
| d | Continue-session uses the latest config used (latest `session_turns.references`) |
| e | Backend residual owned here; no external dependency |
| f | Greenfield design system: shadcn/ui + AI Elements + Tailwind v4 + `motion`; no antd/Lexical, lint-enforced |
| g | Chat = headless core (`@agenta/chat`: hooks/view-models/registries, zero markup) + per-app skins |

## Document map

| Doc | What it is |
|-----|-----------|
| [design.md](./design.md) | The spec (v3). Backend section REVISED 2026-07-18 to the as-built sessions-extensions architecture |
| [chat-headless-contract.md](./chat-headless-contract.md) | Line-level dissection of the chat slice: engine/behavior/presentation classification, the four type leaks, hook APIs, slot contract, WP3a extraction order |
| [plans/2026-07-12-wp1-mobile-foundation.md](./plans/2026-07-12-wp1-mobile-foundation.md) | WP1 plan — **EXECUTED** (see banner in file for deviations) |
| [plans/2026-07-12-wp0-sessions-query-and-stamping.md](./plans/2026-07-12-wp0-sessions-query-and-stamping.md) | WP0 residual plan — **EXECUTED** (see banner: re-audit corrections + execution deltas) |
| [plans/2026-07-12-wp3a-chat-headless-core.md](./plans/2026-07-12-wp3a-chat-headless-core.md) | WP3a plan — **EXECUTED under copy-extraction** (see banners: strategy change + task mapping) |
| [plans/2026-07-25-wp1-infra-tail.md](./plans/2026-07-25-wp1-infra-tail.md) | WP1 infra tail (prod image CI, compose, run.sh) — **EXECUTED** (Tasks 1-5, 7); fixed the latent entrypoint crash in the unbuilt mobile image. Only the first `workflow_dispatch` publish (Task 7 runbook) is still pending, and it's post-merge by design |
| [plans/2026-07-26-wp5-device-gate.md](./plans/2026-07-26-wp5-device-gate.md) | WP5 device gate (flag-gated middleware, both directions) — **EXECUTED** (Tasks T1-T7); default-off, T8 banner-retirement deferred to flag-flip |

Remaining wave-2 plans (WP2 auth + project drawer, WP3b mobile chat skin, WP4 product pages) are
**deliberately unwritten** — they must be planned against the real wave-1 code and the finalized
sessions surface. WP5 is no longer among them: its plan was written and executed (row above).

## Execution state

Branch **`feat/agenta-mobile-wave-1`** (off `feat/sessions-continuity-fixes`, worktree
`.claude/worktrees/big-agents-sessions`). Not pushed. Executed subagent-driven: every task got a
fresh implementer + spec-compliance review + code-quality review; fix rounds were re-reviewed.

### WP1 — foundation (COMPLETE, 8 commits)

| Commit | Content | Review outcome |
|--------|---------|----------------|
| `d0f5c1c0` | `web/mobile/AGENTS.md` + CLAUDE.md symlink; 3 skills (`mobile-app-structure`, `mobile-shadcn-conventions`, `mobile-motion-patterns`) + `.claude/skills` symlinks | spec ✅ (byte-identical to plan) |
| `c914e333` | `@agenta/mobile` scaffold: workspace/turbo wiring, Next 15.5.18, `basePath /m`, standalone output, minimal `_app`/`_document` (shared `agenta-theme` init script), proof-of-life page. Live-verified: `/m`→200, `/`→404 | spec ✅ quality ✅ |
| `629d6e51` | shadcn (components.json/cn/globals.css Tailwind-v4 CSS-first), palette→shadcn token bridge (`scripts/generate-shadcn-tokens.ts` → committed `theme.generated.css`), motion presets, CLI-installed button+skeleton. Tokens verified in compiled CSS | spec ✅ quality **fix-first** |
| `b53094b5` | Review fixes: dark `--accent` olive→`#2a2a2a` (zinc[2]), token **drift guard** (`--check` mode, chained into mobile `lint` AND web `generate:tailwind-tokens`; tamper-tested), `--destructive-foreground` dark→`#141414`, new-token warning, `useMemo`, transitions exposed reduced-aware | re-review ✅ |
| `342cacef` | `eslint.config.mjs`: flat config + hard bans (antd/`@ant-design/*`/app-layer), canary-proven; first full `build-mobile` + standalone check | spec ✅ (byte-identical) quality: 2 plan gaps |
| `54a404c4` | Plan-gap fixes: `react-hooks/rules-of-hooks: error` (+`exhaustive-deps: warn`), lexical ban. All 4 canaries proven | ✅ |
| `bd4671ad` | Dev deployment: entrypoint `__env.js` mirror (guarded), mobile COPY layers in both dev Dockerfiles, `web-mobile` compose service (OSS+EE) behind Traefik `` PathPrefix(`/m`) `` + cache volumes. `docker compose config` validated both editions | spec ✅ quality ✅ |
| `b44cbee4` | Prod `web/mobile/docker/Dockerfile.gh` (mirrors oss gh image; baked `CMD` justified — no compose gh wiring yet). **Image build deferred to a gh CI run** | ✅ |

What works right now: `cd web && pnpm dev-mobile` → http://localhost:3000/m renders the themed
shell (light+dark from the bridged palette); `pnpm build-mobile` produces a standalone server;
`pnpm --filter @agenta/mobile lint` enforces the bans + token sync; the dev compose stacks have
a routable `web-mobile` service (needs a dev-image rebuild to pick up the Dockerfile changes).
Since v0.113.0 the dev stack starts it by default, from the repo root (swap `--oss` for `--ee`
to match the loaded env file): `bash ./hosting/docker-compose/run.sh --oss --dev`. It was opt-in
(`--with-mobile`) for one release because a live dev run showed the second Next dev server pushes
an 8GB Docker VM into OOM-killing the main web app's first big Turbopack compile — dmesg-confirmed
`next-server` kills at ~4.5GB RSS. Running both dev servers comfortably wants a 12GB+ VM, so on a
small VM pass `--no-mobile`.

### WP0 residual — COMPLETE (2026-07-25, 9 commits, all dual-reviewed)

Executed after the rebase onto PR #5479, re-audited first (all four tasks were still needed; the
plan banner carries the corrections). Commits, in order:

| Commit | Content |
|--------|---------|
| `117cd6e4` | R1: `apply_windowing` learns `updated_at`; sessions query + FE wrapper cursor params |
| `11b722f8` | R1 fix: order/cursor ride `coalesce(updated_at, created_at)` (NULL-safe; matches FE `activity()`) |
| `c2ad2393` | R1 fix: **direction-matched id tiebreak in shared windowing** — fixes a latent dup/skip pagination bug for ALL 18 `apply_windowing` call sites (cursor predicates always assumed DESC) |
| `dc7d8499` | R2: `search` (escaped `ilike` on `session_streams.name`) threaded request→core→service→stream-query→DAO; FE param w/ TODO(fern-regen) cast |
| `0afb4125` | R2 polish: trim search term (whitespace ⇒ no filter), tightened tests |
| `c757ca9d` | R3: latest-turn `references` batch-hydrated onto `/sessions/query` rows (new `latest_turn_per_session` DISTINCT-ON helper; core `SessionListItem` DTO; FE `sessionReferenceSchema`) |
| `a159baae` | R3 polish: `.get()` enrichment loop, full-field test pin, IN-list docstring |
| `0c906849` | R4: `session-query-schema.test.ts` — 8-case zod wire pin (stamped/minimal/ended/archived/no-refs/envelope/2 drift-guards) |
| `ab7b09ad` | R4 fix: fixture made server-faithful (phantom `status` removed; reference id → UUID string) |

The mobile list's backend needs are now fully served: true last-activity ordering with working
keyset pagination, title search, agent-labeled rows (references echoed, one batch query per
page), and a drift-pinned wire contract. Suites at close: api sessions 152 passed;
`@agenta/entities` 928 passed; entities typecheck clean.

### WP3a `@agenta/chat` — COMPLETE (2026-07-25, COPY-EXTRACTION mode, 18 commits, all reviewed)

**Mid-execution strategy pivot (Arda's direction):** too many in-flight FE PRs + a local
antd→shadcn branch overlap the OSS `AgentChatSlice`, so the original move-extraction (same-commit
OSS re-imports) was replaced by **copy-extraction: the package copies behavior verbatim
(byte-parity-audited, copy-headers with declared adaptations) and OSS is byte-untouched** — the
branch's only non-package files are the T1 wiring five. Three early move-mode commits were
rewound off the branch after the pivot. The desktop re-plumb (OSS consuming the package,
deleting its local copies) is a follow-up PR sequenced after the FE queue drains.

| Commits | Content |
|---------|---------|
| `3984282642` | T1 scaffold: package + forbidden-deps contract test + workspace/turbo wiring |
| `1d0721e9` `21dee91e` `259e7de1` | C1: neutral types (PendingAttachment, MessageAction) + parts predicates/toolIdentity/partToolName + parseAgentRunError |
| `a1dffc2e` `367af807` `7c369789` `6537a379` `88e4cd88` | C2/C3: toolSummary, approvals, turnStatus, renderModel (predicate-injected), grouping + sessionStatus |
| `2d622f48` `ccc77f4a` `eda687d7` | C4a: asset chain (toolFormat/trace/attachmentRules/files/rewind; transcriptToMessages/loadSession/transport) + state stores (expandState; sessionEphemera — PendingAttachment-based, windowed-list map omitted) |
| `1230499b` `707910d1` `cd341019` | C4b: queue+model-key hooks (verbatim); useComposerAttachments/useApprovalDock; **useAgentConversation** host (+ sessionMessages store copy, turnViewModel with per-mount identity cache). 5 real integration tests: real useChat + real transport over mocked SSE |
| `f9a6155d` | C5: skin registration (registerChatSkin) + resolvers mirroring OSS precedence/fallback chains |
| `f3a50772` `032b125b` | Review polish (updater purity, kind-override header note) + mobile-skills gitignore allowlist |

Package at close: **190 tests / 27 files green**, `pnpm run check` clean, banned-literals grep
empty (no antd/ant-design/virtuoso/lexical/app-layer strings anywhere in src/ incl. comments),
zero-OSS-edit gate proven. The C4/C5 review ran FULL byte-parity diffs (copies differ from OSS
only by headers) and found no undeclared behavioral divergence; the localStorage message key,
quota eviction, throttle, and persist ordering are identical to OSS — no history fork.

### ⚠️ WP3b (mobile skin) gotchas — from the C4/C5 review, read before building the skin

1. **Mount `useAgentConversation` with `key={sessionId}`** — initialMessages, stopped-state,
   hydration flags, and the executed-identity cache seed once per mount; prop-switching the
   sessionId without a remount leaves them stale.
2. **Call `attachments.clear()` after a successful send** — the host clears the draft, not the
   attachment stage (documented in the hook).
3. **Trace-side error refinement is skin-side** — `turns[].status` derives with
   `traceError: null`; layer the per-turn trace summary in the skin (matches where OSS does it).
4. **`useApprovalDock` returns no renderer** — resolve friendly bodies via
   `resolveApprovalBody(toolName)` and names via `resolveToolDisplay` from `./skin`.
5. **The model-key composer gate is not composed into the host** — wire
   `useAgentModelKeyStatus` in the skin's composer.

### WP1 infra tail — EXECUTED (2026-07-26, 3 commits)

Closed the deferred items from WP1's "Chores pending" (prod image CI, compose wiring,
`run.sh` awareness); see
[plans/2026-07-25-wp1-infra-tail.md](./plans/2026-07-25-wp1-infra-tail.md) for the full task
breakdown and grounding facts.

| Commit | Content |
|--------|---------|
| `b93b936bc5` | Fix the mobile gh image's entrypoint env-dir crash (G8): pre-create+chown `/app/oss/public` and `/app/ee/public` so the shared `web/entrypoint.sh` can write `__env.js` as the non-root runtime user |
| `af93751a16` | New `.github/workflows/17-check-mobile.yml`: `@agenta/mobile` typecheck job + per-arch (amd64/arm64) `agenta-web-mobile` image build with PR smoke (`/m`, `/m/__env.js`, non-root check) and `workflow_dispatch` push/merge-manifest/`:latest` publication |
| `03b16ae45a` | `web-mobile` service in all five prod/gh compose files (oss gh/ssl/local, ee gh/local) behind the opt-in `with-web-mobile` profile + `run.sh --with-mobile` |

The image's **first-ever build+serve smoke passed**: ~500MB standalone image, `/m` and
`/m/__env.js` both 200, `/` 404 (basePath), runs as the non-root `agenta` user — all checks
green. Task 5 re-verified (didn't re-add) that mobile lint and `@agenta/chat` unit tests were
already reached by the existing generic CI mechanisms (workflows 11 and 12); only the mobile
image build and `@agenta/mobile` typecheck needed a new job.

### WP5 device gate — EXECUTED (2026-07-26, 5 commits)

> **STATUS UPDATE (2026-08-22, v0.113.0):** the gate now ships **DEFAULT ON**, and the
> `web-mobile` compose service starts with every stack (the `with-web-mobile` profile is
> gone). Both keys became opt-OUTs: only the exact value `false` turns a gate off, and
> `AGENTA_MOBILE_ENABLED=false` (or `run.sh --no-mobile`) holds the service back and forces
> the desktop gate off; `--no-web` implies the same opt-out. The Helm chart deploys `web-mobile`
> and routes `/m` by default; `webMobile.enabled=false` removes both and disables the desktop gate.
> v0.113.0 shipped to production without `/m` because no deployment set the keys — that is what the
> flip fixes. The section below records the original default-off design; read it as history.

Ships the mobile device gate (design.md "Gate and routing") behind a runtime flag,
`AGENTA_MOBILE_GATE`, **default off** (see the status update above): with the flag off, request behavior is byte-identical to
today. A second flag, `AGENTA_MOBILE_REVERSE_GATE` (**default on**, mobile app only), turns off
the reverse direction alone: mobile devices still get sent to `/m`, but nothing is bounced back
out of `/m`. Set it to `false` to test `/m` from a tablet or a desktop browser — iPadOS Safari
sends the macOS desktop UA and Chromium tablets send `sec-ch-ua-mobile: ?0`, so both read as
non-mobile and would otherwise be bounced.
`NoMobilePageWrapper` retirement (T8) is specified but deliberately **not executed** —
it ships only in the deployment window where the flag is actually flipped on. See
[plans/2026-07-26-wp5-device-gate.md](./plans/2026-07-26-wp5-device-gate.md) for the full task
breakdown and grounding facts.

| Commit | Content |
|--------|---------|
| `cf272e1227` | T1: `@agenta/shared/utils/mobileGate` — pure, framework-free decision core (detection, deep-link maps, cookie semantics, documented exceptions); 27 unit tests in the package's vitest harness |
| `6b3aaf5654` | T2: `web/oss/src/middleware.ts` + `web/ee/src/middleware.ts` — twin desktop forward-gate adapters (byte-identical, both NEW files) wrapping the shared core |
| `2df5e4d2a1` | T3: `web/mobile/src/middleware.ts` — reverse-gate middleware carrying a declared verbatim copy of the reverse-gate subset (mobile has zero workspace deps until WP2), new minimal mobile vitest harness, and the "View desktop site" `?view=desktop` escape link on the placeholder page |
| `7be0b8d528` | T4: plumb `AGENTA_MOBILE_GATE` through dev + gh compose files (default `false`), documented in both dev env examples |
| `9ac651525f` | T6: self-skipping Playwright UA-emulation smoke (`web/oss/tests/playwright/acceptance/mobile-gate/gate.spec.ts`), 6 tests, skips unless the runner asserts `AGENTA_MOBILE_GATE=true` |

**Verification highlights:**

- Build proof: all three apps (`oss`, `ee`, `mobile`) print a `ƒ Middleware` row after adding
  their respective `src/middleware.ts`, confirming Next 15.5.18 picks up the placement.
- Zero new tsc signatures in `@agenta/oss` or `@agenta/ee` after wiring the middleware (T2).
  Scope note from the combined post-execution review: the T6 Playwright spec itself adds 9
  signatures to the `@agenta/oss` tsc run (TS2307 `@playwright/test` + implicit-any bindings) —
  the same error class every existing acceptance spec under `tests/playwright/` already
  produces, because playwright specs are type-checked by the `web/tests` harness, not oss tsc.
  Accepted as precedented noise; the clean fix (excluding `tests/playwright` in
  `web/oss/tsconfig.json`) is a separate cleanup, not part of this WP.
- Combined review verdict across the five commits above plus the T7 documentation commit:
  **approve**. Every code block landed byte-identical to
  the plan, the desktop matcher regex was independently confirmed correct against the compiled
  middleware manifest (`/m` and `/m/*` excluded; `/models`-style paths still gated), and the
  middleware bundle carries only the gate core (no transitive leaks). Two deferred hardening
  notes for the agenta_cloud PR: make the gate cookies `secure` conditional on the forwarded
  proto and add `httpOnly` (safe — nothing client-side reads them), and note that EE's first
  deploy with these commits is the first live `ƒ Middleware` proof for EE (its local build
  predates the middleware; the file is a byte-twin of the verified OSS one).
- **T5 live proof** (the load-bearing verification): same standalone binary, two runs, no
  rebuild between them. Flag on (`AGENTA_MOBILE_GATE=true`): mobile UA on `/w` → `307` to `/m/`,
  desktop UA on `/w` → `200`. Same binary, flag unset: mobile UA on `/w` → `200`, no redirect —
  proving `process.env` in middleware is read at request time on the pinned standalone server,
  not build-inlined. Also surfaced a **basePath-stripping observation**: at runtime Next strips
  the `/m` basePath from `nextUrl.pathname` before the mobile middleware handler runs, but the
  handler normalizes defensively either way (needed for unit tests, which construct
  `NextRequest` directly and still see the `/m` prefix).
- **Live QA found two gate defects the review missed (both fixed):** (1) Turbopack's DEV
  middleware sandbox exposes only `.env`-file vars, not the container's process env, so
  `AGENTA_MOBILE_GATE` read `undefined` in `next dev` even with the container env set — dev
  compose commands now mirror the flag into `.env.development.local` at container start
  (prod standalone is unaffected; T5's runtime-read proof stands). (2) With `basePath`, the
  bare root `/m` never matched the `"/((?!...).*)"` matcher (the root strips to an empty
  string), leaving the landing page ungated in BOTH dev and prod — the matcher now carries an
  explicit `"/"` entry. Unit tests construct `NextRequest` directly and bypass Next's matcher
  layer entirely, which is why 27+8 green tests missed it; only a live end-to-end probe
  caught both. Desktop twins are unaffected (no basePath; `/` 308s into gated `/w`).
- **T6 spec self-skip.** `--list` (which does not invoke `global-setup`) confirms the spec
  discovers exactly the expected 6 tests. A real (non-`--list`) run against this worktree with
  no stack running was attempted to observe the runtime skip directly, but `global-setup`
  unconditionally authenticates against `AGENTA_WEB_URL` before any per-test `test.skip` logic
  runs, so it fails with `ERR_CONNECTION_REFUSED` rather than reporting `6 skipped` — exactly the
  fallback the plan anticipated. With the flag confirmed unset in the runner env (the CI
  default), the `test.skip(!gateEnabled, ...)` predicate is proven to evaluate `true`, so the
  6-skipped outcome is correct by construction; observing it as a live Playwright report is an
  operator step against a running stack (flag-on run is likewise an operator step — see Open
  items below).

## Flows-lite + auth-lite + approvals (2026-07-26/27) — EXECUTED

The postponed-fidelity phase Arda redirected into ("keep ui look basic / raw … focus on
navigation / flows / logic"). All raw-UI; the radix-primitives track re-skins later.

- **Flows-lite** ([plan](./plans/2026-07-26-mobile-flows-lite.md), 6 tasks + review fixes,
  commits `cf2792299f…9137760079`): @agenta/* packages wired into the mobile app + both
  container layers; AppProviders (default-store jotai + queryClientAtom + sdk host) +
  route→projectIdAtom ContextSync; root workspace/project resolution (stored → single →
  desktop-continuity → raw picker); sessions list (querySessions windowed cursor, debounced
  search, `includeArchived:false`); read-only transcript replay (loadSessionMessages +
  buildTurnViewModels). Reviewed: approve after 4 fixes. **Live-verified by Arda.**
- **Auth-lite** (commits `2a2f91af61…f0809ee1c4`): gate maps `/auth`→`/m/auth`
  (`/auth/callback` stays desktop — OAuth must land there); headless supertokens-web-js
  (desktop-identical appInfo); refresh-before-verdict + the **provider-scope
  `ensureAuthInit()`** (the SuperTokens fetch interceptor must install before ANY API call —
  live QA caught the sessions query 401ing without it); raw email/password `/m/auth` page
  (OTP/SSO → "use desktop" notice).
- **Approvals** ([plan](./plans/2026-07-27-mobile-approvals-steering.md) — read §1: there is
  NO server-side session SSE; approval answers are fresh `/invoke` POSTs; §4b decisions;
  9 commits `53e1fa427f…2a2ba33f2a` + review fixes `02c36566aa`): M0 badges/polls, M1
  approve/deny/approve-all via the references-only lite resume builder (fire-and-forget) +
  Stop, runner warm-park TTL 5→30min, M2 detached respond composition (api). Reviewed:
  approve; both high-risk contracts traced end-to-end. **Live-unverified:** warm-vs-cold on a
  detached respond (probe: answer via `/respond`, check runner logs `resume key=` vs
  `approval-mismatch`); runner process restart required to activate the TTL.
- **⚠️ Standing follow-ups (Arda: do not forget):** M3 live relay (desktop live-updating a
  phone-resumed turn) and steer-lite (M1.5 specced+unbuilt, gated on runner
  reject-with-feedback #5444; Arda may request next).

## Resume runbook (from here)

1. **Plan wave-2** against the real code (WP2 auth/drawer → WP3b skin → WP4 pages → WP5 gate).
   Planning inputs: the WP0 plan banner (archived_at client filter, auto-title lift into
   `@agenta/entities`, delete-vs-kill swipe semantics, Fern regen for search/include_ended) +
   the WP3b gotchas above + the WP1 gotcha (mobile compose/Dockerfile need `@agenta/*` wiring
   the moment WP2 adds package imports).
2. **Follow-up track (separate, after the FE PR queue + shadcn branch):** desktop re-plumb —
   OSS consumes `@agenta/chat`, deletes its local copies; the copy-headers mark every site.

### Verify-the-foundation smoke (run after any rebase)

```bash
cd web && pnpm install
pnpm --filter @agenta/mobile lint            # bans + tokens:check
pnpm --filter @agenta/mobile types:check
pnpm build-mobile && test -f mobile/.next/standalone/mobile/server.js
pnpm dev-mobile   # → http://localhost:3000/m, check light+dark
```

## Open items & gotchas (do not relearn these)

- **`@agenta/*` deps are deliberately unwired for mobile.** The `web-mobile` compose service has
  **no `web/packages` mount**, and `Dockerfile.gh` copies **no package manifests** — correct
  today (mobile has zero workspace deps) but MUST be added the moment WP2+ imports
  `@agenta/entities`/`@agenta/shared`/`@agenta/chat` (compose volumes + Dockerfile manifest
  copies + turbo `dependsOn` for `@agenta/mobile#build`).
- **Token workflow:** palette changes go through `web/oss/src/styles/theme/palette.ts` → the
  chained `generate:tailwind-tokens` now also regenerates mobile; `theme.generated.css` is
  committed and lint fails if stale. Never hand-edit it. Installing a shadcn component that
  references a NEW token requires extending the VARS role map + `@theme inline` first.
- **shadcn CLI** emits the consolidated `radix-ui` package (not `@radix-ui/react-slot`) — expected.
- **`exhaustive-deps` is `warn`** by choice (rules-of-hooks is the error-class check).
- **Dev `__env.js`:** the entrypoint mirrors it into the bind-mounted `web/mobile/public/` on
  container start (gitignored). Until the dev image is rebuilt with the P5 Dockerfile changes,
  `/m/__env.js` 404s — harmless console noise.
- **Chores:** the `.gitignore` allowlist entries for the `mobile-*` skills are **done** (see
  `.gitignore` — both the `.agents/skills/` and `.claude/skills/` blocks). Still pending: Fern
  regen so the FE `include_ended` param stops being a runtime cast.
- **Mobile image CI + publication runbook** (WP1 infra tail, EXECUTED —
  [plans/2026-07-25-wp1-infra-tail.md](./plans/2026-07-25-wp1-infra-tail.md)):
  `.github/workflows/17-check-mobile.yml` build-verifies + smoke-tests the `agenta-web-mobile`
  image (both arches) on mobile-path PRs and typechecks `@agenta/mobile`; lint (`turbo run lint`
  in workflow 11) and `@agenta/chat` unit tests (recursive package discovery in workflow 12)
  were already covered by their generic mechanisms — verified, not changed. **First publication
  ordering:** `17 - check mobile` no longer publishes `latest` — there is no `push_latest` input,
  and `image_tag=latest` is rejected outright. Publication is owned by `43 - Release to GHCR` in
  the private `agenta_cloud` repo, the same as api, web, services and runner; only after that
  pipeline has published `agenta-web-mobile` once can operators start it from
  `bash ./hosting/docker-compose/run.sh --oss --gh` (or `--ee`). That first publication happened
  (the image starts at v0.111.0), so the opt-in `with-web-mobile` profile was removed in
  v0.113.0 and `web-mobile` now starts with every stack; `run.sh --no-mobile` holds it back.
- **Design-doc staleness:** `docs/design/sessions/**` predates the streams-merge/turns model;
  don't trust it over the code. The memory file `project_agenta_mobile_discovery` (assistant
  memory) mirrors this handoff.
- **WP5 device gate flag-flip runbook (SUPERSEDED — the gate is default-on since v0.113.0, so
  there is nothing to flip):** once WP2 (mobile auth) and WP4 (product
  pages) are live, per deployment: set `AGENTA_MOBILE_GATE=true` in that deployment's env file,
  recreate the `web`/`web-mobile` services, run the T6 Playwright smoke
  (`web/oss/tests/playwright/acceptance/mobile-gate/gate.spec.ts`) against it to confirm 6
  passed, then land T8 (the prepared, not-yet-executed `NoMobilePageWrapper` retirement commit)
  from [plans/2026-07-26-wp5-device-gate.md](./plans/2026-07-26-wp5-device-gate.md). T8 remains
  **specified but unexecuted** in that plan by design — it is coupled to this flip, not to WP5
  landing.

## Follow-up tracks (post-wave-1, explicitly out of scope for now)

- Desktop playground re-plumb onto `useAgentConversation` (the contract's acceptance test),
  then incremental antd→shadcn skin swaps in OSS/EE.
- Scroll-hook extraction (`useConversationScroll`) — desktop-only, deferred from WP3a.
- Next 16 pilot on `web/mobile`.
- Subdomain (`m.`) mounting option for cloud; session-rename UX coordination (PR #5202).

---

### Design Ai Actions README (`docs/design/ai-actions/README.md`)

# AI Services (Tool Calls)

This workspace specifies a REST API for "tool call"-shaped AI services.

Chapter 1 implements a single tool:

- Refine Prompt (`tools.agenta.api.refine_prompt`)

The backend calls a deployed prompt in an internal Agenta org (Bedrock credentials live in the Agenta app config, not backend env vars).

## Files

- `docs/design/ai-actions/context.md` - Problem statement, goals/non-goals, constraints
- `docs/design/ai-actions/spec.md` - API + tool contract (request/response schemas)
- `docs/design/ai-actions/plan.md` - Implementation plan (Chapter 1)
- `docs/design/ai-actions/research.md` - Codebase findings and relevant reference points
- `docs/design/ai-actions/status.md` - Living decisions, open questions, and progress log
- `docs/design/ai-actions/frontend-spec.md` - Frontend implementation specification (UI, components, state, flows)

---

### Design Align Evaluator Interface README (`docs/design/align-evaluator-interface/README.md`)

# Align Built-in Code Evaluator Interface with SDK Evaluators

**Issue:** [#3591](https://github.com/Agenta-AI/agenta/issues/3591)
**Branch:** `feat/align-evaluator-interface`

## Summary

Migrate the built-in code evaluator from the legacy `(app_params, inputs, output, correct_answer)` signature to a new `(inputs, outputs, trace)` signature, aligned with what SDK `@ag.evaluator` receives via `WorkflowServiceRequestData`. Also update evaluator documentation to fill gaps around template variables, nesting, and data sources.

## Settled Interface

```python
# v1 (legacy, existing evaluators keep working)
def evaluate(app_params, inputs, output, correct_answer) -> float

# v2 (new default for new evaluators)
def evaluate(inputs, outputs, trace) -> float
```

## Workspace Files

| File | Description |
|------|-------------|
| [context.md](./context.md) | Problem statement, design decisions, rationale |
| [research.md](./research.md) | Codebase analysis: execution pipeline, data flow, template nesting, key files |
| [plan.md](./plan.md) | Implementation plan: 5 phases (SDK, API, Frontend, Docs, Examples) |
| [qa.md](./qa.md) | QA protocol: backward compatibility + new interface testing |
| [status.md](./status.md) | Living progress tracker |

---

### Design Annotation Queue V2 README (`docs/design/annotation-queue-v2/README.md`)

# Annotation Queue v2

A redesign of the annotation queue system to make human annotation a first-class capability across multiple data sources.

## Problem Statement

The current `EvaluationQueue` implementation is tightly coupled to evaluation runs (`run_id` is required). This works for human evaluation within eval runs but creates friction for other annotation use cases like annotating traces, test sets, or programmatically submitted items.

## Documents

| Document | Description |
|----------|-------------|
| [context.md](./context.md) | Background, motivation, current state analysis |
| [prd.md](./prd.md) | Product requirements, user stories, acceptance criteria |
| [rfc.md](./rfc.md) | Original technical proposal with three solution options (A, B, C) |
| [rfc-v2.md](./rfc-v2.md) | **Current RFC**: Simplified interface over existing evaluation entities (based on Feb 24 discussion) |
| [research.md](./research.md) | Analysis of current EvaluationQueue implementation, code references |
| [research-human-eval-implementation.md](./research-human-eval-implementation.md) | How human evaluation works today: frontend components, state, API calls, annotation storage |
| [competitive-analysis.md](./competitive-analysis.md) | Analysis of competitor's metadata-based approach |

## Current Direction

Use existing `EvaluationRun` + `EvaluationQueue` entities as the backbone. Build a **convenience API layer** that hides evaluation run machinery from annotation consumers. No new domain entities.

See [rfc-v2.md](./rfc-v2.md) for the full proposal.

## Status

- **Phase**: Design (RFC v2 ready for review)
- **Created**: 2026-02-12
- **Last Updated**: 2026-02-24

## Quick Links

- Current implementation: `api/oss/src/core/evaluations/` (queue-related code)
- API endpoints: `POST /evaluations/queues/`
- Database: `evaluation_queues` table

---

### Design Api Rate Limiting README (`docs/design/api-rate-limiting/README.md`)

# API Rate Limiting

Redis-based rate limiting for API protection with support for multiple algorithms and flexible policy definitions.

## Overview

This system provides distributed rate limiting using Redis with:
- **Two algorithms**: TBRA (Token Bucket) and GCRA (Generic Cell Rate Algorithm)
- **PAR(C) policies**: Principal, Action, Resource, Condition model
- **Three-layer architecture**: Scripts → Library → Middleware
- **Fail-safe modes**: Open or closed on Redis failure

## Documentation

| Document | Description |
|----------|-------------|
| [throttling.concepts.specs.md](throttling.concepts.specs.md) | Core vocabulary: principals, categories, plans, enforcement |
| [throttling.policies.specs.md](throttling.policies.specs.md) | PAR(C) policy model, scoping modes, examples |
| [throttling.algorithms.specs.md](throttling.algorithms.specs.md) | TBRA vs GCRA algorithms, trade-offs, parameters |
| [throttling.implementation.specs.md](throttling.implementation.specs.md) | Three-layer architecture, Lua scripts, Python API |
| [throttling.middleware.specs.md](throttling.middleware.specs.md) | Middleware design, entitlements integration, plan-based limits |

## Quick Start

```python
from oss.src.utils.throttling import check_throttle, Algorithm

# Simple usage
result = await check_throttle("global", max_capacity=100, refill_rate=60)

# With dict key
result = await check_throttle({"org": org_id}, max_capacity=100, refill_rate=60)

# With GCRA algorithm (default)
result = await check_throttle(
    {"org": org_id, "policy": "cats:standard"},
    max_capacity=50,
    refill_rate=30,
    algorithm=Algorithm.GCRA,
)

if not result.allow:
    # Return 429 with Retry-After header
    retry_after = result.retry_after_seconds
```

## Key Concepts

**Principal**: Who is being limited (organization_id; IP not yet implemented)

**Categories**: Named endpoint groups (STANDARD, CORE_FAST, TRACING_SLOW, etc.)

**Plan**: Subscription tier that determines limits (HOBBY, PRO, BUSINESS)

**Policy**: PAR(C) rule mapping principal + plan + categories → bucket parameters

## Bucket Key Format

```
throttle:organization:{org_id}:plan:{plan}:policy:{slug}
```

Examples:
- `throttle:organization:org_abc123:plan:cloud_v0_pro:policy:cats:standard`
- `throttle:organization:org_abc123:plan:cloud_v0_hobby:policy:cats:core_fast,services_fast,tracing_fast`

## Response Headers

On 429 response:
```
Retry-After: 2
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
```

## Design Principles

1. **Redis is enforcement, not billing** — billing-grade quotas exist elsewhere
2. **Organization-first** — primary identifier is org_id, not user_id
3. **Fail-open by default** — allow requests when Redis is unavailable
4. **Atomic operations** — Lua scripts ensure correctness under concurrency
5. **GCRA by default** — smooth scheduling, minimal state, predictable behavior

---

### Design Automations Ux Rework README (`docs/design/automations-ux-rework/README.md`)

# Automations UX Rework

**Branch:** `fix/shady-webhooks`
**Status:** Planning

## Problem

The current automations flow requires users to create a webhook, then separately test it from the table before it becomes active. Users don't discover this requirement, leading to confusion when their automations silently do nothing.

## Goal

Make automations work like GitHub/Stripe webhooks: create = active. Testing is diagnostic, not a gate.

## Documents

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, motivation, problem statement, goals/non-goals |
| [plan.md](./plan.md) | Detailed execution plan for Checkpoints 1 and 2 |
| [research.md](./research.md) | Codebase analysis, architecture notes, caveats |
| [status.md](./status.md) | Living progress tracker |

---

### Design Best Effort Ingestion README (`docs/design/best-effort-ingestion/README.md`)

# Best-Effort OTLP Ingestion

## Overview

This project improves the resilience of Agenta's OTLP trace ingestion pipeline. The goal is to ensure that a single bad field, span, or transient error doesn't cause cascading loss of unrelated good data.

## Origin

This work originated from fixing the TypeScript/Node.js OpenTelemetry examples in the docs. We discovered that OTel JS SDKs send structured data as JSON strings because `setAttribute()` only accepts primitives. The backend then failed strict validation and **silently dropped entire spans**.

Further investigation revealed multiple places in the pipeline where a single failure can cause disproportionate data loss.

## Documents

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, motivation, problem statement, goals, non-goals |
| [plan.md](./plan.md) | High-level execution plan with phases and implementation details |
| [research.md](./research.md) | Pipeline failure analysis and external strategy comparison |
| [status.md](./status.md) | Living document with progress updates and decisions |

## Quick Links

- **Worktree deployment**: `http://<dev-host>:8480`
- **Branch**: `feat/otlp-best-effort-hardening`
- **Key files modified**:
  - `api/oss/src/apis/fastapi/tracing/utils.py`
  - `api/oss/src/apis/fastapi/otlp/router.py`
  - `api/oss/src/apis/fastapi/otlp/opentelemetry/otlp.py`
  - `api/oss/src/apis/fastapi/otlp/extractors/adapter_registry.py`
  - `api/oss/tests/pytest/unit/otlp/*`
  - `api/oss/tests/pytest/unit/tracing/test_utils.py`

---

### Design Browser Page Titles README (`docs/design/browser-page-titles/README.md`)

# Browser page titles

This workspace plans a frontend-only change that makes the browser tab describe the page or chat session a user is viewing.

## Reading order

1. [context.md](context.md) explains the user-visible behavior and scope.
2. [research.md](research.md) records the relevant frontend ownership and routing facts.
3. [plan.md](plan.md) defines the implementation slice and its acceptance checks.
4. [status.md](status.md) is the current source of truth for progress and blockers.

## Terms

- **Page title**: the text shown in the browser tab and written through `next/head`.
- **Project page**: a page scoped to a project but not to one agent.
- **Agent page**: a page scoped to one workflow artifact. The artifact provides the agent's display name.
- **Empty session**: an agent chat session before the user sends its first message.
- **Session title**: the persisted title derived from the first user message, capped at 60 characters by the existing chat state.

---

### Design Build Kit Overlay Delivery README (`docs/design/build-kit-overlay-delivery/README.md`)

# Build-kit overlay delivery — make the playground build kit reliably visible on every agent

**Status:** DESIGN DRAFT (see [status.md](./status.md))
**Owner:** onboarding / agent-workflows
**Created:** 2026-07-07

## The one-paragraph problem

The playground's Advanced section shows a read-only "Playground build kit" overlay on
agent configs — 16 platform ops, the read/bash builtins, `request_connection`, the
build-an-agent skill, and the sandbox permissions the assistant uses to build and revise
an agent. It is **missing** on agents created through the new template-builder /
playground-native onboarding flow, both before the agent is committed AND after. Today
the overlay is delivered by riding on a single application-fetch response
(`GET /simple/applications/{id}` → `additional_context`) and resolved on the frontend
through a fragile three-hop atom chain keyed on the open revision. The overlay content,
however, is a **static function of the platform catalog** — `build_agent_template_overlay()`
takes no application argument. Coupling it to a per-application fetch is the root of this
whole bug class.

## The fix in three sentences

Make the build kit the reserved static workflow **`__ag__build_kit`** in the existing
`StaticWorkflowCatalog` — a **plain agent config** whose `parameters.agent` carries the
tools, skills, and sandbox elevation — and have the frontend resolve it **by slug** through
the workflow retrieve path that already serves the other `__ag__*` constants, **once per
project/session**. Merge it **client-side onto any agent-typed entity** open in the
playground — ephemeral `local-*` drafts, onboarding-committed agents, classic template
apps, and SDK-created apps alike — gated only by the target entity's type
(`flags.is_agent`), never by a workflow/application id. Retire the per-application
`additional_context` attachment once the frontend migrates.

**Decision: Option F (Mahmoud, 2026-07-07).** No new endpoint and no new id — one namespace
and one mental model shared with the other static constants, embed-ability left open as a
future product choice. This supersedes the earlier "dedicated route" (A) and "rider on the
catalog-template response" (B) doors. See
[context.md](./context.md#delivery-door--decision-option-f-reserved-static-workflow) and
[status.md](./status.md).

## Why this matters now (the gate)

This fix **gates the flags-default-on re-flip**. Mahmoud's requirement is that the new
agent experience ship default-on with zero env configuration; the parked default work
lives on the PR #5121 lane. We should not flip the new onboarding on by default while its
signature affordance (the build kit) is invisible on the agents it creates. See
[context.md](./context.md#the-gate-flags-default-on).

## File index

| File | What's in it |
|------|--------------|
| [context.md](./context.md) | Problem statement, background, the flag-default gate, constraints, the Option-F decision (with A–E for the record), glossary |
| [research.md](./research.md) | Root-cause with live evidence, the old atom chain, the disproven "missing application row" theory, the Option-F verify-item findings, file/line map |
| [plan.md](./plan.md) | Phased implementation sized for narrow subagents (catalog entry, FE slug retrieve, retire the rider, tests, live QA) |
| [status.md](./status.md) | The Option-F decision, the parked lane's fate, root-cause verdict, what needs Mahmoud's confirmation, next steps |

## TL;DR of the root cause

The server is healthy for **every** creation path. Live-verified: an agent created the
onboarding way (`POST /workflows/` + variant + two commits) resolves as a full simple
application, and `GET /simple/applications/{workflow_id}` returns the identical 16-tool
overlay that the classic path returns. **The "onboarding commits a bare workflow with no
application row" theory is disproven.** The gap is entirely in the delivery/resolution
coupling on the frontend: the overlay is only reachable through
`revisionId → workflow_id → applicationId → app fetch`, and that chain short-circuits for
ephemeral drafts (no `workflow_id`) and is identity/timing-fragile for the in-place
onboarding swap. Because the overlay is catalog-static, the entire chain is unnecessary.

---

### Design Chat Interface Rfc README (`docs/design/chat-interface-rfc/README.md`)

# Chat Interface for Custom Workflows RFC

This workspace contains the planning and implementation documentation for enabling custom workflows to work as chat applications in Agenta.

## Files

- **[context.md](./context.md)** - Background, motivation, and goals
- **[rfc.md](./rfc.md)** - The full RFC document (as provided)
- **[research.md](./research.md)** - Codebase analysis and technical findings
- **[plan.md](./plan.md)** - Implementation plan with phases
- **[status.md](./status.md)** - Current progress and decisions

## Quick Summary

**Goal:** Enable custom workflows to declare `is_chat: true` so Agenta can treat them as chat applications.

**Approach:** Add `flags` support to legacy `@ag.route`/`@ag.entrypoint`, emit `x-agenta.flags.is_chat` in the legacy OpenAPI operation(s), and have the frontend prefer that signal for chat detection (with heuristics as fallback). Also align the new `@ag.route` to accept `flags` for consistency.

**Current Phase:** Phase 1 - SDK Changes

---

### Design Cleanup Evaluators Endpoints README (`docs/design/cleanup-evaluators-endpoints/README.md`)

# Evaluators Endpoints Cleanup Research

## Summary

This document provides comprehensive research on the legacy evaluators endpoints to determine which can be safely removed or deprecated.

**Key Findings:**
1. `GET /evaluators` - **Still actively used** for fetching evaluator templates, needs migration
2. `POST /evaluators/{key}/run` - **Dead code**, can be removed immediately
3. `POST /evaluators/map` - **Dead code**, can be removed immediately
4. `GET/POST/PUT/DELETE /evaluators/configs/*` - **Dead code**, can be removed immediately

## File Index

| File | Description |
|------|-------------|
| [endpoint-analysis.md](./endpoint-analysis.md) | Detailed endpoint-by-endpoint analysis |
| [migration-plan.md](./migration-plan.md) | Proposed migration strategy |
| [frontend-usage.md](./frontend-usage.md) | Frontend code that calls these endpoints |

## Quick Decision Matrix

| Endpoint | Status | Action | Risk |
|----------|--------|--------|------|
| `GET /evaluators` | Active | Migrate to new endpoint | Low |
| `POST /evaluators/{key}/run` | **Dead code** | Remove | None |
| `POST /evaluators/map` | **Dead code** | Remove | None |
| `GET /evaluators/configs/` | **Dead code** | Remove | None |
| `POST /evaluators/configs/` | **Dead code** | Remove | None |
| `PUT /evaluators/configs/{id}/` | **Dead code** | Remove | None |
| `DELETE /evaluators/configs/{id}/` | **Dead code** | Remove | None |

### Summary

The **entire legacy `/evaluators/*` router can be removed** except for `GET /evaluators/` which needs migration first.

Frontend only uses:
- `GET /evaluators` → Evaluator templates (needs migration)
- `POST /simple/evaluators/*` → All config CRUD operations
- `POST /workflows/invoke` → Evaluator execution

## Architecture Overview

```
/* Detailed source-code truncated for AI context efficiency. */
```

---

### Design Client Tool Interaction Lifecycle README (`docs/design/client-tool-interaction-lifecycle/README.md`)

# Interaction cards: research and fix plan

An agent can ask the user for something in the middle of a run. The chat then shows a
card. The user acts on the card. The run continues.

We have three kinds of cards:

| Card | What it asks | Example |
|---|---|---|
| Form card | Fill in some fields | "Pick a time and a timezone" |
| Connect card | Connect an external account | "Connect Telegram" |
| Approval card | Allow or deny a tool call | "Allow the agent to create a schedule?" |

On 2026-08-10, Mahmoud hit many bugs with these cards in one session. Cards came back
after he answered them. Dead cards blocked the screen. A warning strip accused his own
tab. This folder explains why, and what we will change.

## Read in this order

1. [context.md](context.md) — what the user saw, in his words.
2. [research.md](research.md) — how the system really works, and where it lies.
3. [plan.md](plan.md) — the four changes we will make.
4. [qa.md](qa.md) — the tests that will catch this class of bug forever.
5. [status.md](status.md) — where the work stands.

## The words we use (same words in every file)

- **Card**: the widget the user sees and acts on.
- **Interaction row**: one database row per card. It stores the card's state:
  `pending` (waiting), `resolved` (answered), or `cancelled` (closed without an answer).
- **Record list**: the server's saved history of the conversation. The browser can
  rebuild the whole chat from it. We call that rebuild **replay**.
- **Adoption**: the browser throws away its own copy of the chat and takes the server's
  replay instead.
- **The sweep**: a cleanup job. At the start of each new turn, it closes old `pending`
  rows by setting them to `cancelled`.
- **Park**: the run stops and waits for the user to act on a card.
- **Resume**: the run continues after the user acted.
- **Runner**: the service that runs the agent.

## Fixes already merged on 2026-08-10 (before this plan)

- [#5904](https://github.com/Agenta-AI/agenta/pull/5904): the agent no longer guesses
  file paths for its skills.
- [#5909](https://github.com/Agenta-AI/agenta/pull/5909): Telegram connect uses the
  right login type, errors show on screen, and "Not now" really declines.
- [#5910](https://github.com/Agenta-AI/agenta/pull/5910): the runner no longer loses
  the result of an approved tool call.
- [#5912](https://github.com/Agenta-AI/agenta/pull/5912): cancelled cards come back
  dead, not alive.
- [#5913](https://github.com/Agenta-AI/agenta/pull/5913): the "running somewhere else"
  strip no longer shows in the tab that owns the run.

Open issues: [#5907](https://github.com/Agenta-AI/agenta/issues/5907) (runner race),
[#5911](https://github.com/Agenta-AI/agenta/issues/5911) (reuse an existing connection).

---

### Design Code Evaluator Rich Outputs README (`docs/design/code-evaluator-rich-outputs/README.md`)

# Rich Outputs for Code Evaluators

**Status:** Implemented (interface version "3"), verified on the dev stack, in review as [PR #4626](https://github.com/Agenta-AI/agenta/pull/4626)
**Related workspace:** [align-evaluator-interface](../align-evaluator-interface/README.md) (settled the v2 signature, kept `-> float`)

## Summary

Code evaluators in the playground can only return a float. Returning a dict fails with
`Error during code execution: Result is not a float after conversion: <class 'dict'>`.

The goal is to let code evaluators return dicts (multiple metrics or feedback per
evaluator), and to make the same evaluator runnable from the SDK, locally or remotely,
without changes.

The surprising finding: almost the entire pipeline already supports dict outputs.
Other evaluators (LLM-as-a-judge with a JSON schema, multi-field JSON match) return
dicts today, and the metrics and UI layers handle them. The float restriction lives in
exactly one layer: the sandbox runners, plus a pinned output schema in the catalog.

## Workspace Files

| File | Description |
|------|-------------|
| [context.md](./context.md) | Why this work exists, goals, non-goals |
| [research.md](./research.md) | How code evaluators flow through frontend, backend, and SDK; where float is enforced; what already supports dicts |
| [plan.md](./plan.md) | Possible directions with a recommendation, and a draft phase plan |
| [status.md](./status.md) | Living progress tracker |

---

### Design Codex Harness README (`docs/design/codex-harness/README.md`)

# Codex harness

This workspace plans and tracks adding OpenAI Codex as a first-class agent harness in
Agenta, next to the existing Claude and Pi harnesses.

## Glossary

These terms appear across every file here. Each is defined once, in this list.

- **Harness**: the coding-agent program Agenta runs on behalf of a user (Claude Code,
  Pi, and soon Codex). The user picks a harness per agent.
- **Runner**: Agenta's Node service (`services/runner`) that executes a harness inside a
  sandbox and streams its events back to the platform.
- **Sandbox-agent daemon**: the pinned npm package the runner talks to. It spawns the
  harness process and speaks ACP with it.
- **ACP (Agent Client Protocol)**: the JSON-RPC protocol between the daemon and a
  harness. Claude and Codex do not speak ACP natively; each sits behind a bridge
  process from Zed (`claude-acp`, `codex-acp`) that translates.
- **Park**: what the runner does when a harness asks permission for a tool call and a
  human must answer. The run pauses, the question surfaces in the UI, and the run
  resumes with the answer.
- **agenta-tools (loopback MCP server)**: the runner's internal MCP server. It is how
  Agenta-defined tools (callback tools, code tools, connected integrations) are
  delivered into a harness that has no native Agenta tool support.
- **Managed key / subscription auth**: the two credential modes. Managed means Agenta
  holds a provider API key in its vault and injects it. Subscription means the harness
  authenticates from the operator's own login state (OAuth tokens) on a mounted
  directory; the subscription sidecar performs that login.

## Reading order

1. `context.md`: why this project exists, what exists today, goals and non-goals.
2. `research.md`: the factual map of the current code on main that the design builds on.
3. `spike/findings.md`: empirical answers from the Milestone 0 spike (approvals,
   config, MCP tools, auth modes).
4. `design.md`: the proposed design (written after the spike).
5. `decisions.md`: the decision register. Every choice that is not an obvious copy of
   the existing Claude pattern is recorded here with its status (proposed / approved by
   Mahmoud / rejected). Nothing ships on a proposed-only decision.
6. `plan.md`: milestones, deliverables, and checks.
7. `status.md`: current progress and blockers. Always the latest truth.
8. `reports/`: one written report per milestone, for Mahmoud's review.

---

### Design Commit Loading Stall README (`docs/design/commit-loading-stall/README.md`)

# Commit Loading Stall Investigation

Tracks research into a frontend issue where commit actions stay in a loading state even though the API responds quickly.

## Files
- context.md: Background, problem statement, goals, and non-goals.
- plan.md: High-level execution plan and milestones.
- status.md: Current progress, blockers, and decisions.
- research.md: Codebase findings, hypotheses, and references.

---

### Design Composio Tools Rework README (`docs/design/composio-tools-rework/README.md`)

# Gateway connection rework

An agent can use tools from an outside product, for example GitHub or Slack. Today each
tool is one saved entry in the agent configuration. This project replaces those per-tool
entries with one entry per connection, gives the model two runtime tools instead of many,
and moves permission from a routing string into structured private data.

## Reading order

Start with [handoff.md](handoff.md): the current status, what was done, every open item,
and the links to the pull requests, issues, and evidence. It is the entry point for
anyone joining after 2026-08-27.

Then read the three design documents. They are decided. The plan implements them and does
not change them.

1. [data-model.md](data-model.md). The saved `gateway_connection` entry, the four
   permission values, validation, and migration from the per-tool format.
2. [runtime-tools.md](runtime-tools.md). The two model-facing tools `search_tools` and
   `run_tool`, their input and output shapes, and the prompt guidance.
3. [permission-layers.md](permission-layers.md). Who stores policy, who compiles it, who
   enforces it, and how a call reaches the provider.

Then read the working documents.

4. [context.md](context.md). Why this work exists and what it does not cover.
5. [contracts.md](contracts.md). The exact shared shapes between Python, TypeScript, and
   the API. Every slice reads this file before it writes a field name.
6. [plan.md](plan.md). Seven implementation slices in dependency order.
7. [research.md](research.md). What the current code does, with file and line references.
8. [qa.md](qa.md). Every test this project must pass, each with an ID. The plan's slices
   point at those IDs instead of restating them.
9. [release-gate-changes.md](release-gate-changes.md). How the standing agent release gate
   should change to cover gateway tools.
10. [status.md](status.md). Progress and the decisions taken during review.

The authoring surface has its own specification, copied into this workspace so it is
versioned on this branch: [ui-handoff.md](ui-handoff.md) and the design board
[ui-handoff-board.html](ui-handoff-board.html). Section 2a of the board is the specification.

## Words used in these documents

**Gateway.** The part of the platform that reaches outside products. Composio is the only
gateway provider today.

**Provider.** The company or service that fronts many outside products. Value: `composio`.

**Integration.** One outside product behind the provider. Values: `github`, `slack`,
`gmail`. Composio calls this a toolkit.

**Connection.** One authenticated account for one integration, saved on the project. It has
a slug, for example `github-work`. Several agents can share one connection.

**Tool key.** The stable Agenta name for one action of an integration, for example
`GET_ISSUE`. The saved permission map uses tool keys.

**Provider action ID.** The provider's own name for the same action, for example
`GITHUB_GET_ISSUE`. It stays inside the API.

**Catalog.** The list of integrations and their tools, read from the provider and cached by
the API.

**Runner.** The TypeScript service at `services/runner`. It drives the model turn, enforces
permission, and asks a person for approval.

**Harness.** The coding agent the runner drives inside the sandbox. Claude Code, Codex, and
Pi are harnesses.

**Sandbox.** The isolated machine the harness runs in. It never holds credentials.

**Resolver.** The Python code that turns saved configuration into runner-ready tool
specifications at run start.

**Compiler.** The new pure Python function that turns saved permission policy plus catalog
metadata into one `allow`, `ask`, or `deny` value per tool.

## Rules for this project

- Touch as few files as possible.
- Reuse what exists. The Sessions interaction machinery, the `ConnectDrawer` connect flow,
  the API catalog cache, and the `CatalogChooser` component all stay.
- Do not add an abstraction for a case the design does not describe.
- Do not put policy in a name or a routing string.

---

### Design Connect Model Drawer README (`docs/design/connect-model-drawer/README.md`)

# Connect a Model drawer redesign

Planning workspace for redesigning the agent playground's "Model & harness" section
drawer after the claude.design prototype "Connect a Model Flow", with the product
owner's final decisions applied (three sections, a "Use API key" / "Use subscription"
credentials toggle, inline custom providers, an unsaved-changes guard, and a readable
selection style for the shared SectionRail).

Status: **implemented (slices 1-6), pending review and live verification**. See
status.md for details.

## Files

| File | What it holds |
| --- | --- |
| [context.md](context.md) | Why the work exists, the owner's locked decisions, scope, and constraints (uncommitted in-flight changes, package layering, dark mode). Read this first. |
| [research.md](research.md) | Verified code map with file/line citations, the confirmed `--ag-colorPrimaryBg` root cause, SectionRail blast radius, the extracted design prototype, and the hex → theme-token mapping. |
| [design.md](design.md) | Component-level design: drawer structure, the SectionRail restyle, the ProviderCredentialsSection and its props, the CustomProviderForm extraction (with required package moves), the unsaved-changes guard, Advanced-tab removal, gating matrix, and final copy strings. |
| [plan.md](plan.md) | Six implementation slices sized for Sonnet subagents, in dependency order, plus the dev-stack verification plan (light + dark). |
| [status.md](status.md) | Source of truth for progress, the open decisions D1-D6, locked decisions, and next steps. Keep it updated. |

## Quick orientation

- Drawer host: `web/packages/agenta-entity-ui/src/DrillInView/SchemaControls/AgentTemplateControl.tsx`
- Stateful core: `.../SchemaControls/agentTemplate/useModelHarness.tsx`
- Shared rail: `web/packages/agenta-entity-ui/src/drawers/shared/SectionRail.tsx`
- Secrets: `web/packages/agenta-entities/src/secret/`
- Custom-provider form (extraction source): `web/oss/src/components/ModelRegistry/Drawers/ConfigureProviderDrawer/`
- Design prototype: `Agenta onboarding flow redesign (1)/Connect a Model Flow.dc.html`

---

### Design Data Optimizations README (`docs/design/data-optimizations/README.md`)

# Data & render optimizations — branch summary

Branch: `fe-refactor/data-optimizations`
Status: **built and profiler/HAR-verified** (not yet merged)
Scope: warm-reload and cold-load cost of the web app, with the **agent playground** as the
reference route.

**Out of scope for this branch:** the drive / file / mount surfaces (virtualization, the unified
Files drawer, the paged listing endpoint). That work ships separately in
[PR #5400](https://github.com/Agenta-AI/agenta/pull/5400), which this branch is stacked on. No
commit here touches `Drives/`, `mounts`, or `/files`.

Companion docs (deeper detail on two sub-efforts):

- [app-boot-optimizations/plan.md](../app-boot-optimizations/plan.md) — the serial boot gate chain
- [app-boot-optimizations/gates.md](../app-boot-optimizations/gates.md) — render-gate ladder audit
- [playground-query-persistence/plan.md](../playground-query-persistence/plan.md) — the IndexedDB layer

---

## What we tackled

### 1. Per-query IndexedDB persistence (paint-from-disk)

A per-query persister layer over TanStack Query, backed by one IndexedDB database
(`agenta-query-cache` / store `queries`), with four classes:

| persister | prefix | maxAge | on restore | used for |
|---|---|---|---|---|
| `immutablePersister` | `agenta-imm` | ∞ | never refetch | immutable-by-key bodies (workflow revisions, trace summaries) |
| `catalogPersister` | `agenta-cat` | 14d | one revalidate if stale | catalogs/schemas/profile/projects/workflow detail |
| `recordsPersister` | `agenta-rec` | 7d | **always** revalidate | session record logs (append-only, disk never authoritative) |
| `vaultSecretsPersister` | `agenta-vault` | — | **always** revalidate | LLM provider rows, **redacted** before write |

Everything not on that list is memory-only and refetched per cold load.

### 2. Cold-load request reduction

HAR-driven removal of redundant and head-of-line requests: duplicate by-id workflow fetches,
an eager revisions-list fetch, a per-reload-rotating inspect persist key, session records
fetched 3×, and null-fetch stragglers. Secondary reads demoted to `priority: "low"`.

### 3. Boot render-gate hygiene

Latching the protected-route gate, prewarming the boot atom graph and the serialized boot chunks,
un-gating org detail from `/profile`, config-accordion render hygiene, naming anonymous
`forwardRef`s, and skipping the Tooltip wrapper on tooltip-less buttons. Detail in the
companion docs.

### 4. Session-UI boot render cost (`e3495d2292`)

Three fixes on the session rail/tab surfaces, all profiler-confirmed:

- **Latch-mount `SessionRail`.** It lives in a `size={0}` + `inert` splitter panel until the chat is
  maximized, but was rendered unconditionally — mounting the whole session list (~1000 renders,
  **10–15% of all boot React work**) plus fetching its lazy chunk, into a zero-width panel. Now
  mounted on first open and kept mounted after.
- **Hover-gate the rename/delete/close clusters.** Each button drags a Tooltip + Trigger + icon
  subtree; a full history of rows paid all of it on boot behind `opacity-0` — **984 renders,
  7.8–12.3% of React work**, for pixels nobody sees. Now mounted on hover/focus, with keyboard
  access preserved via the focusable row plus a focus-leave guard.
- **Memoize the rows** (`SessionRailRow`, `SessionTag`) with id-taking callbacks and hoisted static
  icon elements, so a streamed token or liveness poll no longer re-renders every row.

Measured (same session, baseline → after): `Button` 375 → 87 renders, `Tooltip` 439 → 177,
`IconBase` 538 → 258, `SessionStatusDot` 176 → 50. Both row components went from ~2 re-renders per
mount to **0**, reproducible across three independent captures.

### 5. Request dedup + stop cancelling boot queries (`7f4905a0df`)

- `revalidateSessionRecordsAtom` invalidated with TanStack's default `cancelRefetch: true`, killing
  an in-flight records fetch and restarting an identical one. It fires from `onFinish` when the SDK
  auto-resumes the restored last turn on reload — i.e. every warm boot. Now `cancelRefetch: false`,
  matching `revalidateSessionMountsAtom`, whose comment documents the same hazard.
- `workflowDetailQueryAtomFamily` and `workflowArtifactScopedQueryAtomFamily` issue the **same**
  `POST /workflows/query` (same body) under two cache keys. They now cross-prime each other, so
  whichever runs first satisfies the other.

### 6. Latest-revision persistence — "Phase 1" (`96b7f1363f`)

The revision *body* was already disk-served, but a warm reload still blocked on the latest-revision
round-trip (1.7–5 s on a slow backend) to resolve the fallback selector, the "latest" tag, and the
dirty/commit affordance. Now `catalogPersister` is attached to
`workflowLatestRevisionQueryAtomFamily`, **plus** the two `setQueryData` prime paths mirror to IDB
via `persistQueryByKey` — without that, a session that only ever *primed* the latest (dedicated
query disabled) would leave nothing on disk to restore.

Verified: the blocking `workflows/revisions/query` is **absent** from the warm-reload HAR.

### 7. Removed the persistence kill switch (`f19395f798`)

See *Learnings* — this is the one that made everything else actually work.

---

## What we deliberately did **not** tackle

- **Phase 2 — persisting the variant/revision *list* queries.** Scoped and gated, then parked. Two
  reasons: once Phase 1 landed, the lists were no longer on the critical path (they're fast,
  Low-priority background fetches), and the gate test proved it is *not* a clean persister-add — see
  the `isFetched` learning below. Revisit only if the switcher is measurably slow.
- **The sidebar `Menu` churn.** Attempted and **reverted**. Memoizing inside `SidebarMenu` was a
  no-op because the inputs are unstable upstream (`menuProps` is a fresh object literal per render;
  `section.items` comes from `scope.useSections()`, which rebuilds every render). A real fix means
  refactoring the sidebar scope engine — its churn is also partly legitimate (route/`openKeys`
  resolving during boot). Not worth the risk/value.
- **Deep config-panel work** (`AgentTemplateControl`, `ConfigAccordionSection`,
  `SchemaPropertyRenderer` — still the largest React cost). `sections` is a ~20-dependency inline
  array; wholesale `useMemo` is a real stale-UI risk on core config code. We verified the collapsed
  bodies aren't the prize either (the heavy sections are drawer-openers that render `children` as
  `null`). Squeezing further means structural work, not pattern-reuse.
- **Persisting `organizations` / `organizations/{id}`.** High-priority and unpersisted, so they're
  candidates — but org data drives workspace/permissions, so stale-then-revalidate has a real
  correctness surface. Deferred pending evidence it's a felt cost.
- **The `billing/subscription` 502.** Investigated, no code change needed. The FE already handles it
  deliberately: never retries 502/503/504, deferred to browser idle at Low priority, degrades to
  hobby/free, and is config-gated behind `isBillingEnabled()`. The 502 is a **local EE dev artifact**
  (billing flagged on via `NEXT_PUBLIC_AGENTA_BILLING_ENABLED` while Stripe/the billing service
  isn't configured); the handler itself returns a clean 404 for "no subscription".
- **The serial boot gate chain** (`profile → organizations → project-scoped queries → mounts`). This
  is the single biggest remaining lever, but it belongs to the app-boot workstream, not the data
  layer. Partly addressed (org detail un-gated from `/profile`); the rest is a separate project.
- **`sessions/mounts` + `sessions/records` cancelled pair (unmount variant).** The
  *invalidate*-triggered cancel is fixed. A second variant — both queries aborted mid-flight by a
  component unmount, then cleanly refired — appeared in slow-backend captures but not in the healthy
  warm one. Not root-caused.

---

## Important learnings

### A silent kill switch disabled the entire persistence layer

**This cost the most time by far.** The layer was built but never live-verified, and a stale
`localStorage["agenta:persist:disable"] = "1"` flag (from earlier A/B debugging) made every
IndexedDB read and write a silent no-op. The failure was invisible because:

- `getItem`/`setItem` **early-returned before logging**, so the debug output showed nothing.
- `entries()` (used by GC) **did not check the flag**, so GC kept happily reporting
  `[persist] GC 17 entries` — proving data existed on disk while nothing could read it.

Every "warm" reload was therefore cold, and every measurement of the persistence work read as
"it does nothing." The fix was to **remove the kill switch entirely** — persistence is now
unconditional, and removing the *check* (not just the flag) self-heals any browser that still has
the stale flag set.

**Takeaway:** a debug kill switch that fails silently is worse than no kill switch. If one must
exist, it has to be loud.

### Verify the layer runs before optimizing on top of it

We shipped Phase 1 and measured it against captures where persistence wasn't executing at all —
and nearly concluded the work was ineffective. Confirm the foundation is live (one `[persist] HIT`
line would have done it) before attributing results to changes built on it.

### `isPending` vs `isFetching` — most consumers were already SWR-safe

The worry that paint-from-disk would be undone by components blanking to skeletons on the background
revalidate turned out to be **mostly unfounded**. TanStack v5's `isPending` is `false` whenever data
exists, including mid-revalidate, and the codebase gates on `isPending` almost everywhere
(`isFetching` appears once, off the reload path). `PlaygroundConfigSection` even belt-and-suspenders
it: `schemaQuery.isPending && !hasRenderableConfigSections(activeData)`.

The audit was worth doing — but the correct outcome was **"change 2 selection hooks, not 30
components."**

### `isFetched` is `true` after a persister restore — even for an empty list

The Phase 2 gate test ([persist.test.ts](../../../web/packages/agenta-shared/tests/unit/persist.test.ts),
[autoSelectLatestChild.restore.test.ts](../../../web/packages/agenta-entity-ui/tests/unit/autoSelectLatestChild.restore.test.ts))
pinned this: a restored query reports `isPending: false` (good) but `isFetched: true` — because the
persisted state carries `dataUpdateCount: 1`. That bypasses `resolveAutoSelectLatestChild`'s
`isFetched === false` wait-guard, so an **empty** restore returns `"complete"` with no selection
instead of waiting for the revalidate that brings the real revision. This is a *correctness* hazard,
not a visual one, and it's why Phase 2 is not a blind persister-add.

### `setQueryData` bypasses the persister

Anything primed imperatively never reaches disk. Both the revision-body cache and the
latest-revision cache need an explicit `persistQueryByKey` mirror alongside their `setQueryData`
calls, or the disk copy silently never exists.

### Measure render *counts*, not self-time, across runs

Per-render self time moved 1.25–2.3× between captures purely from backend/machine contention, which
twice led to a wrong conclusion (once "Button regressed 2x" — it hadn't). Render **counts** and
**re-renders-per-mount** are contention-independent and were the only reliable cross-run metric.
Normalizing self-time against a global mean is *not* valid: the global mean is dominated by trivial
fibers that inflate differently than heavy components.

### Hidden UI is not free

Two of the largest wins were subtrees that were never visible: a whole session rail mounted into a
zero-width panel, and ~106 hover-action buttons rendered behind `opacity-0`. CSS-hiding
(`opacity-0`, `width: 0`, `inert`) still costs full mount + reconciliation. Gate on *mount*, not on
*paint*.

### Don't memoize without verifying the inputs are stable

The reverted sidebar change: a `useMemo`/`useCallback` whose dependencies change every render is
dead weight. Always confirm the upstream props are referentially stable first — the profiler will
show it (`changed props: {menuProps, items, …}` every commit).

### Tooling notes

- **React DevTools profiler exports** use variable-length opcodes in the `operations` stream that
  break naive parsers. A tolerant decoder (resync by trying candidate skips and validating a
  lookahead) is needed to recover fiber names — without it, everything reads as `#1234`.
- **Never `rm -rf node_modules/.pnpm` alone.** It empties the virtual store but leaves pnpm's state
  file, after which every `pnpm install` reports "Already up to date" and refuses to rematerialize,
  leaving all binaries as dangling symlinks. Use `pnpm install --force`, or remove all of
  `node_modules`.
- A **duplicated `@tanstack/query-core`** would put the persister and the app's QueryClient on
  different instances and silently break restore. `pnpm-workspace.yaml` pins it to a single version;
  keep it in lockstep with `@tanstack/react-query`.

---

## Verification status

| area | status |
|---|---|
| Session-UI render hygiene | **Verified** — 5 profiler captures, reproducible |
| Request dedup / cancel fix | **Verified** — cancelled pair absent from warm HAR |
| Phase 1 latest-revision persistence | **Verified** — `[persist] HIT` logs + blocking request gone |
| Persistence layer end-to-end | **Verified** — HITs for profile, projects, detail, body, records, vault |
| Phase 2 | Not built (gate tests only) |

Known pre-existing failure on the base PR, not from this branch: `session-mounts-store.test.ts`
(2 tests) fails identically on `origin/fe-refactor/drive-surfaces`.

---

### Design Data Retention README (`docs/design/data-retention/README.md`)

# Data Retention

## Overview
Data retention defines how long trace data is kept per plan. Retention windows are
enforced by a scheduled job that deletes traces older than the configured window
for each plan.

## Goals
- Enforce plan-based retention windows for traces.
- Keep deletion workloads bounded with batching.
- Provide a safe administrative endpoint for on-demand retention runs.

## Architecture
- Retention windows are configured in plan entitlements.
- A tracing DAO deletes root traces and their spans before a cutoff.
- A cron triggers the retention job via the admin billing endpoint.

## Runtime flow

Spans and events are independent retention domains; each has its own admin
endpoint, its own cron, and its own Redis lock so the two flushes never block
each other.

Spans:

1. Cron calls the admin endpoint `/admin/spans/flush`.
2. The tracing service enumerates plans with finite `Counter.TRACES_INGESTED.retention`.
3. For each plan, it batches projects and deletes traces older than the cutoff.
4. Logs include per-plan and total deletion counts.

Events:

1. Cron calls the admin endpoint `/admin/events/flush`.
2. The events retention service enumerates plans with finite `Counter.EVENTS_INGESTED.retention`.
3. For each plan, it batches projects and deletes events older than the cutoff.
4. Logs include per-plan and total deletion counts.

## Operational notes
- Retention runs should be idempotent and safe to re-run.
- Deletions are limited per batch to keep runtime bounded.

---

### Design Daytona Secret Propagation README (`docs/design/daytona-secret-propagation/README.md`)

# Daytona Secret propagation: the placeholder-401 incident and its instruments

Working notes for the 2026-08-29 finding on EU cloud production: a fresh sandbox's first
model call sometimes carries the raw `dtn_secret_<id>` placeholder instead of the real key,
because Daytona applies a new Secret's substitution rule asynchronously and gives no
completion signal. The model proxy refuses the placeholder with a 401, and the user used to
read "model authentication failed — add the project's OpenAI key", which was wrong on every
count.

## The measured facts (72h window, EU cloud prod)

- 7 placeholder 401s at the LiteLLM proxy (`Virtual Key expected. Received=dtn_****…`),
  each matching a failed runner turn, across 5 organizations.
- Every one was the FIRST outbound model call of a freshly created sandbox, 10–24 seconds
  after its Secrets were created. Substitution never failed mid-session.
- 4 of 7 had a destroy-plus-delete of the previous same-host Secret 14–61 seconds earlier
  (the eviction ordering: destroy sandbox → delete its Secrets → allocate new → create).
- Successful cold starts sit in the same age range (6–22s), so the lag is stochastic, not a
  fixed delay. Sibling measurement from 2026-08-09: value UPDATES on an existing Secret take
  15–18s to reach a running sandbox against the docs' "within seconds".

## The two hypotheses

- **H1, create lag**: the substitution rule for a new Secret + sandbox pair converges
  per-node in Daytona's egress layer, and the first call sometimes lands on a node that has
  not converged.
- **H2, delete interference**: deleting an older Secret for the same host while the new
  one propagates widens the window.

## Probe results (2026-08-30, production org, target eu) — CORRECTED

The first probe run concluded substitution was host-dependent ("a never-used host never
substitutes"). That was a measurement artifact: Daytona's egress proxy also performs
RESPONSE SCRUBBING — real values in responses are rewritten back to placeholders before
they reach the sandbox — so an echo service shows `dtn_...` whether or not substitution
happened. Proven by sending the literal real value in the header: the echo still read
`dtn_secret_...`. The correct instrument is a provider whose error body echoes a MASKED
key (api.openai.com: "Incorrect API key provided: sk-probe*****"), which scrubbing does
not rewrite.

With that instrument (20 fresh-Secret first-sandbox samples, production create shape,
target eu, 28 sandboxes total, all cleaned up):

- **15 of 20 sandboxes substituted on their FIRST request**, +1.5s to +2.9s after Secret
  creation — including brand-new hosts. Creation order and the delete-then-create eviction
  ordering do not matter.
- **5 of 20 never substituted at all** (raw placeholder for the full 90-180s watched, from
  the first request onward). The distribution is bimodal: no sample landed between 3s and
  180s. A twin sandbox created against the SAME Secret substituted at its first request
  while the stuck one stayed raw; stop+start did not repair it. One stuck sandbox returned
  an Envoy "upstream connect error or disconnect/reset before headers".

**Mechanism read:** a per-sandbox registration failure at create time, with no
reconciliation — not a propagation delay. Production's "10-24s after creation" was merely
when the first call happened; "only first calls fail" is survivorship (the 401 kills the
run and the sandbox is rebuilt). Today's stuck rate (~25%) is far above the ~3% in the
production log window, so the rate varies or the eu fleet was degraded on 2026-08-30.

Consequence for the runner: waiting does not help a stuck sandbox. The preflight must
REBUILD instead of waiting (see the instruments below).

## The instruments

- The stuck-sandbox rate was measured with a throwaway probe script, not tracked here: it
  created sandboxes through the runner's own Daytona SDK calls and read the masked-echo
  instrument (api.openai.com's 401 body, which names the credential it received). An echo
  service cannot serve as the instrument — Daytona scrubs real credential values out of
  responses, so an echo of a HEALTHY credential comes back looking like a placeholder. A
  variant that deleted the previous Secret first tested the eviction ordering, which the
  2026-08-30 runs showed is NOT a factor. Each run costs about one sandbox-minute and needs
  an environment holding the runner's Daytona credentials.
- The runner now logs `[daytona-secrets] allocated/deleted n=… hosts=[…] ms=…` (counts,
  hosts, and timing only — never ids, names, placeholders, or values), so future incidents
  carry their own create/delete timeline instead of needing it reconstructed from eviction
  lines.
- A placeholder-shaped 401 classifies as `credential_delivery_failed`
  (`services/runner/src/engines/sandbox_agent/errors.ts`), with retry-flavored user copy.

## Daytona's answer (2026-08-31, their support; a fix PR is in progress on their side)

They confirmed the reproduction and gave operating guidance:

- "Substitution is not guaranteed on the first call. Some sandboxes never get wired;
  restart does not fix those. A new sandbox on the same Secret does."
- "If the provider logs dtn_secret_…, throw that sandbox away and create a new one.
  Retrying or restarting the same one will not help."
- "If a retry on the same sandbox starts working within ~30s, you can keep it. If the
  placeholder is still going out after that, recreate." (We deliberately convict at 10s,
  below their bound: every healthy sandbox we measured answered on its first probe, their
  fix is imminent, and waiting 30s only holds a stuck user turn. Product-owner decision,
  2026-08-31.)
- "Keep one long-lived Secret; you don't need a new Secret per run." (DECLINED for
  compliance, and told to them: we hold users' secrets for the sandboxes and must delete
  them as soon as the sandbox is thrown away. A TTL-based garbage collector would be a big
  lifecycle change, and their fix is imminent, so we keep per-run Secrets.)
- They marked the wiring failure as priority and will report when their fix lands.

## The guard that does not wait for Daytona

The preflight (#6370): probe the fresh sandbox concurrently with acquire; convict as
stuck when the raw placeholder still echoes at the 10s grace; destroy and rebuild once. Tracked in the session todo list beside this
workspace.

---

### Design Ee Self Hosting README (`docs/design/ee-self-hosting/README.md`)

# EE Self-Hosting

## Overview

Decouple the Enterprise Edition from cloud-only concerns (billing, Stripe, reverse trials) so that self-hosted customers get enterprise features (RBAC, entitlements, org management) without cloud dependencies.

## Problem

Today "EE" ≈ "Cloud". It bundles:
- Features needed for self-hosting (RBAC, entitlements, org management)
- Features only relevant to cloud (billing, Stripe integration, reverse trials, metering)

Self-hosted enterprise customers need the first set but not the second. There is also missing functionality for self-hosting scenarios: configuring org entitlements, default entitlements, and controlling who can create organizations.

## Documents

| File | Description |
|------|-------------|
| `context.md` | Background, motivation, goals, and non-goals |
| `research.md` | Comprehensive analysis of the current EE codebase: plans, entitlements, billing, RBAC, org lifecycle, meters, throttling, frontend gating, env vars, and identified gaps |
| `rfc-0.md` | RFC: Self-hosted EE — Stripe as differentiator, enterprise plan, billing UI hidden |
| `rfc-1.md` | RFC: Org creation restriction — `AGENTA_ORG_CREATORS` allowlist |
| `plan.md` | Execution plan with milestones and stacked PRs |
| `doc-0.md` | Draft: documentation changes needed for self-hosted EE |
| `doc-1.md` | Draft: documentation changes needed for org creation restriction |
| `status.md` | Living progress tracker — current state, decisions, blockers |

---

### Design Empty States README (`docs/design/empty-states/README.md`)

# Empty States Design System

This workspace documents the design and implementation of empty state components across Agenta.

## Files

- **context.md** - Background, motivation, and goals
- **plan.md** - Implementation roadmap and phases
- **status.md** - Current progress and decisions
- **research.md** - Codebase analysis, patterns found, and technical notes
- **components.md** - Component API and usage examples

## Quick Links

- POC Implementation: `web/oss/src/components/EmptyState/`
- Auto Evaluation Empty State: `web/oss/src/components/pages/evaluations/autoEvaluation/EmptyStateEvaluation/`
- Assets: `web/ee/public/assets/eval.mp4`

---

### Design Eval Metric Type Filtering README (`docs/design/eval-metric-type-filtering/README.md`)

# Evaluation Metric Type Filtering

Text metrics like `reason` are incorrectly showing in aggregation views (overview table, histograms, spider chart). This workspace documents the root cause and fix.

## Files

- **context.md**: Problem statement, goals, non-goals
- **research.md**: Technical investigation findings
- **plan.md**: Implementation plan with phases
- **status.md**: Progress updates

---

### Design Evaluation Runtime Heartbeats README (`docs/design/evaluation-runtime-heartbeats/README.md`)

# Evaluation Runtime Heartbeats And Step Mutation

This document captures the current evaluation execution loops and a concrete proposal for:

- runtime heartbeats / liveness detection
- Redis execution locks / leases
- step mutation semantics for `add` and `archive`
- loop-specific consistency rules

See also:

- [plan.md](./plan.md) for the concrete implementation plan across all phases

## Goals

- Make "is this evaluation currently executing?" answerable from runtime state rather than only persisted run flags.
- Keep `run.flags.is_active` as the control-plane flag for "should this run be active".
- Prevent stale worker ownership after application crashes.
- Support step evolution safely without destroying historical evaluation data.
- Make loop behavior consistent where possible.

## Current Loops

### SDK local loop

The SDK creates a persisted evaluation run and then executes the loop locally in the client process.

- create/persist run: `sdk/agenta/sdk/evaluations/runs.py`
- local execution loop: `sdk/agenta/sdk/evaluations/evaluate.py`

Important property:

- the API does not own execution for this loop once the run is created

### Live query evaluation

Live evaluations are discovered periodically and dispatched as Taskiq jobs.

- live refresh dispatcher: `api/oss/src/core/evaluations/service.py`
- fetch active live runs: `api/oss/src/dbs/postgres/evaluations/dao.py`
- task registration: `api/oss/src/tasks/taskiq/evaluations/worker.py`
- executor: `api/oss/src/core/evaluations/tasks/live.py`

Important property:

- a run can remain logically active for a long time
- execution happens in periodic bursts, not as one continuous attached worker

### Batch query evaluation

This is a one-shot Taskiq run over traces selected by a query.

- dispatch: `api/oss/src/core/evaluations/service.py`
- task registration: `api/oss/src/tasks/taskiq/evaluations/worker.py`
- executor: `api/oss/src/core/evaluations/tasks/live.py`

Important property:

- one worker task executes a finite batch for a single run

### Batch testset evaluation

This is the legacy offline testset loop.

- dispatch: `api/oss/src/core/evaluations/service.py`
- task registration: `api/oss/src/tasks/taskiq/evaluations/worker.py`
- executor: `api/oss/src/core/evaluations/tasks/legacy.py`

Important property:

- one worker task usually owns the full run execution

### Batch invocation

This is the testset + application path without evaluator steps.

- dispatch: `api/oss/src/core/evaluations/service.py`
- task registration: `api/oss/src/tasks/taskiq/evaluations/worker.py`
- executor: `api/oss/src/core/evaluations/tasks/legacy.py`

Important property:

- same runtime concerns as batch testset, but no annotation/evaluator work

### Trace queue

Trace queues create a queue-backed run and then append work in batches.

- queue creation: `api/oss/src/core/evaluations/service.py`
- batch append: `api/oss/src/core/evaluations/service.py`
- task registration: `api/oss/src/tasks/taskiq/evaluations/worker.py`
- executor: `api/oss/src/core/evaluations/tasks/legacy.py`

Important property:

- many batch tasks can belong to the same run over time

### Testcase queue

This mirrors trace queue behavior but the source items are testcase ids.

- queue creation: `api/oss/src/core/evaluations/service.py`
- batch append: `api/oss/src/core/evaluations/service.py`
- task registration: `api/oss/src/tasks/taskiq/evaluations/worker.py`
- executor: `api/oss/src/core/evaluations/tasks/legacy.py`

Important property:

- many batch tasks can belong to the same run over time

## Current Liveness Model

Today, liveness is approximated from persisted run state:

- `run.flags.is_active`
- `run.status`

This is useful as control-plane state, but it is not a reliable execution heartbeat.

Current behavior:

- runs are activated by setting `flags.is_active = True`
- runs are stopped by setting `flags.is_active = False`
- live refresh selects runs with `is_live = true`, `is_active = true`, `status = running`
- there is no per-run worker heartbeat or ownership lease

Consequences:

- worker crashes can leave runs looking active
- batch tasks can appear "running" even when no worker is alive
- there is no authoritative way to block edits only while real execution is in flight

## Proposed Runtime Model

Separate control-plane state from execution-plane state.

### Control plane

Keep existing persisted run state:

- `run.flags.is_active`: the run is enabled / eligible for execution
- `run.status`: lifecycle state shown in UI and APIs

### Execution plane

Add Redis-based leases with heartbeats.

Use leases, not a one-shot lock. The execution owner must refresh a TTL while work is still running.

Implementation note:

- runtime locks reuse the existing `oss.src.utils.caching` lock helpers
- actual Redis keys therefore start with the existing cache lock prefix
- the examples below show the logical suffix after `cache:p:{project}:u:{user}:lock:`

Recommended Redis records:

- worker heartbeat key
- one run mutation lock key
- one execution lock key per run job

## Redis Keys

### Worker heartbeat

Key:

```text
eval:worker:{worker_id}:heartbeat
```

Value:

```json
{
  "worker_id": "...",
  "created_at": "...",
  "updated_at": "..."
}
```

Purpose:

- answer "is worker X alive?"
- support diagnostics
- not sufficient by itself to prove a specific run is executing

### Run mutation lock

Key:

```text
eval:run:{run_id}:lock
```

Allowed `job_type` values: `api`, `web`, `sdk`

Example value:

```json
{
  "job_type": "api",
  "job_id": "2e2d3c2e-3d79-45f8-bec5-fc9af9e6d223",
  "job_token": "some-token",
  "created_at": "2026-03-24T09:30:00Z",
  "updated_at": "2026-03-24T09:30:30Z"
}
```

Purpose:

- ensures only one mutation operation edits a run definition at a time
- blocks execution jobs from starting while a run mutation is in progress
- gives run edits a clear coordination point

### Run job execution lock

Key:

```text
eval:run:{run_id}:job:{job_id}:lock
```

Allowed `job_type` values: `api`, `web`, `sdk`

Example value:

```json
{
  "job_type": "sdk",
  "job_id": "3fdcc012-7e17-42ef-9f3d-985ffb15329d",
  "job_token": "some-token",
  "created_at": "2026-03-24T09:30:00Z",
  "updated_at": "2026-03-24T09:30:30Z"
}
```

Purpose:

- authoritative ownership for one concrete execution running under a run
- supports safe cleanup with compare-and-delete semantics

Meaning:

- a run may have one or more active jobs
- non-queue loops use a reserved singleton lock slot, so they have at most one active job
- queue loops may have multiple active jobs at once

## Locking Semantics

### Lease, not mutex

Do not treat this as a permanent state flag. It is a run job lease with TTL and heartbeat.

Rules:

- the owner gets a `job_token`
- only the owner may renew the lease
- only the owner may delete the lease
- renew/delete should use compare-and-set semantics
- use Lua or an equivalent atomic compare-and-renew / compare-and-delete operation
- one lock belongs to exactly one run job
- wildcard lock discovery must use Redis `SCAN` or a dedicated index/set, never `KEYS`

### Mutation lock semantics

Use a separate run-level mutation lock:

```text
eval:run:{run_id}:lock
```

Rules:

- mutation acquires the run mutation lock before changing run steps or mappings
- mutation checks that there are no active job locks under the run before proceeding
- mutation releases the run mutation lock in `finally`
- execution jobs must check for the run mutation lock before starting
- if the mutation lock exists, execution must wait, retry later, or fail fast depending on the loop contract

This separation matters:

- `eval:run:{run_id}:lock` protects the mutable run definition
- `eval:run:{run_id}:job:{job_id}:lock` protects one concrete execution

### TTL and heartbeat cadence

Use a time-based heartbeat, not a scenario-based heartbeat.

Recommended defaults:

- worker heartbeat TTL: 5 minutes
- worker heartbeat refresh: 30 seconds
- run job lock TTL: 5 minutes
- run job lock refresh: 30 seconds

Why not heartbeat per scenario:

- a single scenario can be slow
- different loops do not have a consistent "scenario boundary"
- long model calls and retries would make progress-based heartbeats too coarse

## How Heartbeat Should Work Per Loop

### SDK local loop

The API cannot own this heartbeat unless the SDK participates.

Recommendation:

- do not infer SDK execution from backend worker state
- expose an SDK heartbeat endpoint that acquires and renews a run job lock
- until then, `is_active` and `status` remain best-effort only for SDK runs

Practical rule:

- SDK runs become authoritative for runtime edit gating once they participate in run job locks

Suggested endpoints:

- `POST /simple/evaluations/{run_id}/heartbeat`
- `DELETE /simple/evaluations/{run_id}/heartbeat`

Note: `{run_id}` here is the evaluation run id (`run.id`). In `SimpleEvaluationsService` this is also referred to as `evaluation_id`.

Behavior:

- `POST` acquires or renews `eval:run:{run_id}:job:{job_id}:lock` with `job_type = "sdk"`
- `DELETE` releases the lock if the caller owns it

### Live query evaluation

This loop should use a run job lock only while a refresh execution is actually running.

Reason:

- a live run is logically active for a long time
- work happens in periodic refresh jobs
- there may be minutes between jobs

Proposal:

- keep `run.flags.is_active = true` for enabled live runs
- before dispatch or at task start, check whether `eval:run:{run_id}:lock` exists
- each dispatched refresh job acquires `eval:run:{run_id}:job:{job_id}:lock`
- if overlapping live refresh jobs are not allowed, check whether another active lock already exists for the run before dispatch or at task start

Result:

- `is_active` means the live run is enabled
- the Redis lock means a live refresh job is executing right now

### Batch query evaluation

Use one run job lock for the duration of the batch execution.

Proposal:

- check whether `eval:run:{run_id}:lock` exists before starting
- acquire `eval:run:{run_id}:job:{job_id}:lock` on task start
- heartbeat periodically until task exit
- clear on success/failure in `finally`

### Batch testset evaluation

This should behave the same as batch query.

Proposal:

- check whether `eval:run:{run_id}:lock` exists before starting
- acquire `eval:run:{run_id}:job:{job_id}:lock` on task start
- task heartbeat every 30 to 60 seconds

This is one of the best candidates for edit gating:

- if any active lock exists under the run, edits should be blocked or converted into stop-and-restart behavior

### Batch invocation

Use the same mechanism as batch testset.

Proposal:

- check whether `eval:run:{run_id}:lock` exists before starting
- acquire `eval:run:{run_id}:job:{job_id}:lock` on task start
- heartbeat until completion, then release

### Trace queue

Use one run job lock per appended batch.

Proposal:

- check whether `eval:run:{run_id}:lock` exists before starting
- each appended batch task acquires `eval:run:{run_id}:job:{job_id}:lock`
- multiple queue batch jobs may run concurrently for the same run

Implication:

- queue execution remains concurrent
- run mutation must check whether any active locks exist under the run

### Testcase queue

Same as trace queue.

Proposal:

- check whether `eval:run:{run_id}:lock` exists before starting
- each appended batch task acquires `eval:run:{run_id}:job:{job_id}:lock`
- multiple queue batch jobs may run concurrently for the same run

## Taskiq Integration

The cleanest integration point is middleware or a task wrapper around the registered evaluation tasks.

Responsibilities:

- resolve `job_id`
- check the run mutation lock
- acquire the run job lock on task start
- start a background heartbeat coroutine
- stop the heartbeat and release the lock in `finally`

This handles:

- normal completion
- exceptions in task code
- most application-level crashes where cleanup still runs

This does not fully handle:

- host crash
- container kill with no graceful shutdown
- `SIGKILL`

That is why TTL expiry is still required.

For API-owned Taskiq executions:

- `job_type = "api"`
- `job_id` should be the concrete Taskiq execution id
- non-queue loops may still use a reserved singleton lock slot in the key while storing the concrete Taskiq execution id in the payload

For SDK-owned executions:

- `job_type = "sdk"`
- `job_id` should be the SDK execution or session id

For web-owned executions if needed later:

- `job_type = "web"`
- `job_id` should be the browser/session execution id

## Step Mutation Model

Hard delete is the wrong default for steps.

Recommended model:

- allow `add`
- allow `archive`
- model `edit` as `archive + add`
- do not physically remove historical step definitions or results by default

Suggested step lifecycle:

- `active`
- `archived`
- optionally `superseded_by`

Backward-compatibility rule:

- absence of `archived` means the step is active / not archived
- do not persist `archived: false`
- only write archival state when a step is actually archived

Benefits:

- preserves historical results
- avoids orphaning in-flight writes
- keeps audits and old metrics reproducible
- lets UI hide archived steps by default without destroying history

## Evaluator Step Rules

Evaluator origins:

- `auto`
- `human`
- `custom`

Execution rule:

- scenarios are always created regardless of evaluator origin
- only `auto` evaluators are executed by backend workers
- `human` and `custom` steps remain pending until fulfilled by another mechanism

### Add evaluator step

#### Live query loops

Default rule:

- apply only to future scenarios

#### Non-live loops

Default rule:

- backfill all existing scenarios in the run

Applies to:

- batch query
- batch testset
- trace queue
- testcase queue

Operational requirement:

- schedule a separate backfill job for the newly added step
- do not rebuild or invalidate unrelated results

Backfill behavior:

- backfill runs as a separate execution, not inline with the mutation request
- mutation updates the run definition and then enqueues backfill work
- backfill acquires its own `eval:run:{run_id}:job:{job_id}:lock`
- backfill heartbeats like any other run job
- backfill should be loop-specific rather than one generic opaque job type
- evaluator-step backfill is only enqueued for newly added `auto` evaluators
- newly added `human` and `custom` evaluators do not trigger execution backfill

Likely job families:

- `evaluations.backfill.batch_query`
- `evaluations.backfill.batch_testset`
- `evaluations.backfill.trace_queue`
- `evaluations.backfill.testcase_queue`

### Archive evaluator step

Rule:

- do not schedule future executions for that step
- preserve historical results
- hide archived steps from default "current" views

If a step is archived while tasks are in flight:

- the executor should check step state before writing new results
- if archived, skip writing new result records for that step

## Input Step Rules

Input steps should support `auto` and `custom`.

The semantics are different from evaluator steps because they redefine the corpus.

### Live query loops

Input edits are feasible.

Rules:

- add query/input step: affects future windows only
- archive query/input step: stop generating new scenarios from it
- preserve historical scenarios already produced by that step

### Batch query

Possible, but this is close to redefining the run.

Rules:

- add input step: create new scenarios for newly included traces
- archive input step: stop including it in current aggregate views, preserve historical scenarios

This uses addition and archival semantics, not run revisioning.

### Batch testset

Most sensitive loop.

Rules:

- add input step: create scenarios for all new testcases from that source
- archive input step: preserve old scenarios and exclude archived source from current views

Recommendation:

- use addition and archival semantics, not run revisioning
- for active runs, block mutation while execution locks exist or stop execution first and then mutate

### Trace queue and testcase queue

These do not naturally have editable input-step graphs. The queue source is the appended items.

Recommendation:

- do not expose input-step editing for queue loops

## Metrics Rules

Metrics are stored per evaluation metrics entry, but the payload is keyed by `step_key`.

Implication:

- the backend refresh path builds `EvaluationMetrics.data` as a map of `step_key -> metrics`
- metric computation remains step-scoped even when stored in one run-level or scenario-level metrics row
- archiving a step does not change previously computed metrics for that step
- archived-step metrics remain available through the same step-keyed metric data

What changes after archival:

- default views can hide archived steps
- execution stops producing new results for that step
- the underlying metric records do not need a separate historical mode

What does not change after archival:

- metric aggregation remains per step
- existing archived-step metrics can continue to participate in aggregated views
- metric computation does not need special archived-step filtering

## Edit Gating And Data Integrity

Edits should not mutate a run blindly just because `flags.is_active` is false or true.

Recommended gating:

- mutation must first acquire `eval:run:{run_id}:lock`
- if any `eval:run:{run_id}:job:*:lock` exists for the run, treat the run as executing now (enumerate with Redis `SCAN` / `scan_iter` — never `KEYS` — to avoid blocking Redis under load)
- for batch testset and batch query, block mutation or convert it to stop-and-restart
- for live runs, allow plan mutation for future dispatches even while the run remains logically active
- for queue runs, allow mutation if the semantics are "applies to future batches" or if the system can safely backfill all existing scenarios

## Recommended First Implementation

### Phase 1

- add a run mutation lock
- add Redis run job locks with heartbeat
- add worker heartbeats
- expose "run currently executing" by checking whether any active locks exist under the run
- do not overload `is_active`

### Phase 2

- introduce step lifecycle with `active` and `archived`
- change evaluator edits to `archive + add`
- preserve historical results

### Phase 3

- implement evaluator-step backfill for non-live loops
- keep live-loop additions future-only by default

### Phase 4

- define how aggregate views include or exclude archived steps
- add explicit product semantics for input-step mutation

## Decisions Captured Here

- Queue batches are allowed to execute concurrently for the same run.
- Live-loop edits are future-only. Live loops do not backfill historical scenarios.
- Batch query and batch testset input-step changes use addition and archival semantics, not run revisioning.
- Archived-step results should remain queryable, ideally behind an `include_archived` style flag.

## Summary

The shortest safe path is:

- use Redis run job locks with heartbeats for runtime truth
- use a separate run mutation lock for step/input edits
- keep `is_active` as control-plane state
- use `archive`, not destructive `remove`
- model `edit` as `archive + add`
- backfill evaluator additions for non-live loops
- keep live-loop additions future-only unless explicitly backfilled

---

### Design Fern Sdk Update README (`docs/design/fern-sdk-update/README.md`)

# Fern SDK Update

Update the Fern SDK generation process and regenerate the Python SDK client.

## Files
- `context.md` - Background and problem statement
- `plan.md` - Execution plan with phases
- `status.md` - Current progress and next steps

---

### Design Fix Evaluation Workflow Revision Lookup README (`docs/design/fix-evaluation-workflow-revision-lookup/README.md`)

# Fix: Evaluation Workflow Revision Lookup

Bug fix for [#3661](https://github.com/Agenta-AI/agenta/issues/3661) - Chat app evaluations return empty runs and never start.

## Files

- **context.md** - Problem statement, root cause analysis
- **research.md** - Code analysis, adapter pattern findings  
- **plan.md** - Implementation approach
- **status.md** - Current progress
- **missed-migration-paths.md** - Comprehensive list of all code paths missed during v0.84.0 migration (for future work and QA)

## Summary

The v0.84.0 migration moved application storage from legacy tables to workflow tables but missed updating the evaluation code paths. This fix updates `_resolve_app_info()` in `legacy.py` to use `LegacyApplicationsAdapter` (the same pattern as migrated routers).

---

### Design Fix Input Keys README (`docs/design/fix-input-keys/README.md`)

# Fix: input_keys Not Saved on Commit

**Customer Issue:** When a user has 2 prompts in an app, fetching the API only returns the `input_keys` of the first configuration. The second prompt's `input_keys` are missing.

**Root Cause:** The `input_keys` field inside each prompt config (e.g., `ag_config.prompt.input_keys`) is not being updated/computed before commit. A refactoring removed the `syncInputKeysInPrompts` mechanism without replacing it.

## Files

| File | Description |
|------|-------------|
| `context.md` | Background, problem statement, and goals |
| `research.md` | Detailed codebase analysis and git archaeology |
| `plan.md` | Proposed fix with specific code changes |
| `status.md` | Current progress tracker |
| `legacy-entities-usage.md` | Notes on where old entities are still used |

---

### Design Fix Sts Mount Expiry README (`docs/design/fix-sts-mount-expiry/README.md`)

# Fix: agent mounts return EACCES after STS credentials expire

Planning workspace for GitHub issue Agenta-AI/agenta#5516. Agent file mounts go
"Permission denied" for many minutes at a time because the temporary store credentials
behind them expire and nothing reacts. This workspace holds the investigation and the
proposed fix.

## What each file answers

| File | Question it answers |
| --- | --- |
| [context.md](context.md) | What breaks for the user today, and why this work exists. |
| [research.md](research.md) | How credentials flow end to end, what actually expires and when, where credentials are installed into mounts, which refresh mechanisms geesefs supports, and why the fix is safe on both SeaweedFS and real AWS. |
| [plan.md](plan.md) | The chosen fix, the exact code changes per file, the test plan, and the live QA plan. |
| [decisions.md](decisions.md) | Every decision the fix embeds, its trade-off, and how to back it out. |
| [status.md](status.md) | Where this work stands right now. |

## Domain nouns, one sentence each

- **Runner**: the Node sidecar (`services/runner/`) that executes one agent turn per
  HTTP `/run` request.
- **Sandbox**: the isolated environment a turn runs in; "local" means the runner's own
  host, "remote" means a Daytona cloud VM.
- **Turn**: one user-message-to-agent-reply exchange; the runner's unit of work.
- **Turn boundary**: the moment between two turns, when the runner decides whether to
  reuse a live environment or build a fresh one.
- **Session pool**: the runner's in-memory table of live environments parked between
  turns so the next turn can continue without a rebuild.
- **Mount**: a directory in the sandbox whose contents live in the object store, so
  files survive sandbox teardown.
- **Durable agent volume**: the per-agent mount (`agent-files/`) shared across all
  sessions of one agent; long-lived by design.
- **Session scratch**: the per-session working directory mount (`cwd`); re-signed at
  every turn boundary.
- **Mount credentials**: the temporary, prefix-scoped S3 key, secret, and session
  token a mount's geesefs daemon holds; they carry an expiry and cannot be renewed
  in place.
- **Installed lease**: the expiry of the credentials a live environment's daemons
  are actually running on, as opposed to the expiry of credentials signed later and
  never given to them.
- **geesefs**: the FUSE filesystem binary that presents an S3 prefix as a local
  directory; each mount is one geesefs daemon process.
- **S3**: the object-storage HTTP protocol; Agenta speaks it to whichever store backs
  the deployment.
- **SeaweedFS**: the S3-compatible store bundled with self-hosted Agenta.
- **STS**: the "Security Token Service" protocol for minting temporary, scoped
  S3 credentials; both SeaweedFS and AWS implement it.
- **EACCES**: the "Permission denied" error code; geesefs returns it for every file
  operation once the store answers 403.
- **ENOTCONN**: the "Transport endpoint is not connected" error code; the kernel
  returns it when a FUSE daemon has died but its mount point is still registered.

## Related work

- `docs/design/mount-file-viewer/`: the mounts file-listing UI; shares the same sign
  endpoints, no credential-lifetime logic.
- Draft PR #5247 and design issue #5215 introduced the durable agent mount this bug
  hits hardest; its design workspace lives on that PR's branch, not on main.

---

### Design Folders README (`docs/design/folders/README.md`)

# Folders Design Docs

This folder captures the design for introducing folder-based organization while the codebase is in a hybrid state:

- New entity: `folders`
- Legacy entity still in use on this branch: `app_db`
- Mainline extension (already on `origin/main`): artifact-based application model

## Why These Docs Exist

The current branch introduces folders and integrates them with legacy applications (`app_db.folder_id`).  
At the same time, `origin/main` has moved applications onto workflow/artifact primitives, and folder support is being extended there via artifact-level `folder_id`.

These docs align both realities so we can iterate without losing migration intent.

## Documents

- [PRD.md](PRD.md): Product requirements, user goals, constraints, success metrics, and open product questions.
- [RFC.md](RFC.md): Technical architecture, APIs, data model, migration strategy, and open technical questions.
- [PR.md](PR.md): PR-style summary for reviewers, including risks and validation guidance.

## Snapshot: Current Branch vs Main

- Current branch:
  - `folders` domain and API exist (`/folders` CRUD + query).
  - `app_db.folder_id` links applications to folders.
  - Prompts UI uses folders for browsing/moving/creating.
- `origin/main`:
  - Applications are represented via workflow artifacts (application alias on artifact model).
  - `folder_id` has been added to artifact tables (`workflow_artifacts`, `testset_artifacts`, `query_artifacts`) via migration `f6a7b8c9d0e1`.
  - Legacy applications are migrated to the workflow model via migration `a7b8c9d0e1f2`.

## Open Questions (Cross-Cutting)

1. What should be the canonical owner of folder assignment for applications long-term (`app_db`, artifacts, or both during transition)?
2. Do we want one shared folder tree across entity types or separate trees by `FolderKind`?
3. What compatibility contract should clients rely on during migration (dual-read, dual-write, versioned endpoints)?

---

### Design Gateway Tool Rendering README (`docs/design/gateway-tool-rendering/README.md`)

# Canonical gateway tool rendering in the playground

Design workspace for fixing the playground read path so it renders connected-app
(gateway) tools written in the **canonical persisted shape**, not just the legacy
function-name encoding the UI itself writes.

This is a **frontend-only, read-path** design. No backend or SDK wire changes: both
tool encodings are already equivalent server-side (the SDK compat layer converts
legacy → canonical, and the resolve path enriches description + schema from the live
catalog at run time). Per the standing rule, we normalize on the frontend.

## The one-line symptom

A builder agent authored three Slack tools in the canonical shape
(`{"type":"gateway","provider":"composio","integration":"slack","action":"OPEN_DM",…}`).
The playground showed all three as **"gateway · built-in"** rows under a BUILT-IN
header, each opening a raw JSON editor — instead of "Connected app tool" rows grouped
under a Slack card with a humanized action name.

## Files

| File | What it holds |
| --- | --- |
| [context.md](context.md) | Why this exists, the symptom, goals, non-goals, the standing constraints. |
| [research.md](research.md) | Verified findings: the two encodings, every consumer that keys off the legacy slug, and exactly where the canonical shape falls through. All with file:line citations. |
| [plan.md](plan.md) | The design: one shared shape-detection helper, the read-path changes per consumer, the drill-in decision, the removal/dedupe fix, phasing, and the open questions for Mahmoud. |
| [status.md](status.md) | Current state, decisions taken, and what's blocked on Mahmoud. |

## Live repro

`:8280` dev stack — app `019f3d51-1f93-7452-8133-dff2f0d91385`, revision
`019f3d56-90f3-7870-b1c4-bd67f4313e18` ("Support triage") shows the three misrendered
tools.

## Status at a glance

Design only, approved with Mahmoud's review round folded in (2026-07-07). Both open
questions are closed (see [plan.md § Decisions](plan.md#decisions-resolved-2026-07-07-mahmoud)
and [context.md § Review round](context.md#review-round--2026-07-07-decider-mahmoud)):

1. **Drill-in: Option B.** Fetch the catalog action detail and populate the **existing**
   gateway view — no new component. An unresolvable tool fails safe to raw JSON with a
   warning. This is the only place a canonical tool may look different from a legacy one.
2. **Convergence: deferred.** The drawer keeps writing the legacy shape on add; read-side
   canonical support is unaffected.

The governing product invariant: a connected-app tool looks the same regardless of who
authored it.

---

### Design Gateway Tools README (`docs/design/gateway-tools/README.md`)

# Gateway Tools Design Workspace

This folder captures design, implementation notes, and ongoing remediation work for the gateway-tools feature (third-party tool integrations and playground tooling UX).

## Index

- `prd-ui-improvements.md` — Product requirements for current UI/UX improvements in settings and playground.
- `plan.md` — Active remediation plan based on code review findings and implementation sequencing.
- `status.md` — Living execution log for progress, decisions, and blockers.
- `implementation-spec.md` — Technical implementation details and architecture decisions.
- `specs.md` — Functional/API specifications.
- `PR.md` — High-level scope and implementation summary for the feature.
- `api-reference.md` — API endpoint and payload reference for tools/gateway flows.
- `composio-integration.md` — Composio integration details and behavior.
- `CONNECTION_FLOWS.md` — Connection lifecycle and auth flow notes.
- `providers.md` — Provider model and assumptions.
- `TOOLS_IMPLEMENTATION.md` — Additional implementation notes.
- `summary.up-to-this-point.md` — Historical summary of work completed.

---

### Design Gateways Research README (`docs/design/gateways-research/README.md`)

# Gateways research

Design for two gateways — an **LLM gateway** and an **MCP gateway** — treated as one problem
with two protocol surfaces.

**Status: v1, in progress.** [`v1/`](v1/) is the design; its `README.md` carries the posture,
the reading order, and the scope. Documents there are structured but not complete — each
states what it must establish and what is still missing.

There is no v2 and there should not be one until v1 is superseded rather than merely extended.

## Why the two are one design

They are the same shape. A run has exactly two kinds of outbound dependency needing a
credential we hold: the **model** it calls, and the **tools** it calls. Today both are
resolved and shipped outward as secrets. The runner wire already models them as two consumers
of one pattern — a route, a credential, a policy — and describes a gateway MCP server as "an
HTTP MCP server whose URL happens to be ours."

Governance, identity, authorization, compliance, metering and routing are **the same six
concerns over different nouns**. Designing the two gateways separately means building that
plane twice and having it disagree with itself. That is the failure mode this research exists
to avoid.

## Layout

- **[`v1/`](v1/)** — the design. Start at its `README.md`.
- **[`v1/raw/`](v1/raw/)** — the research behind it: the codebase surveys, the protocol
  findings, and the framing documents the design grew out of. Read these when you want to know
  *why* a document says what it says.
- **`v1/notes.md`** — positions that were taken and reversed, with the reasoning. Read it when
  a shape in the design looks wrong and you want to know whether it was already tried.
- **`v1/open-designs.md`** and **`v1/open-reviews.md`** — working documents: what is still
  undecided, and what to verify against the code when the ports are implemented.

## Relationship to the earlier tool-gateway research

A prior docs-only effort covered the **tool/MCP** half: the provider landscape, why no
open-source equivalent of the incumbent catalog exists, the two auth layers, and a recommended
direction of "be an MCP client/gateway rather than clone a catalog vendor."

That work is input, not a duplicate. This design keeps its conclusions on the tool side and
asks the question it did not: what happens when the model plane gets the same treatment, and
what do the two share. It also postdates that research on one material point — the protocol
revision it assumed has since been replaced, and `v1/mcp.md` covers what changed.

## Scope

In: the outbound plane for every caller — model calls and tool/MCP calls — and the identity,
policy, audit and metering both need. The credential model, including user-level credentials
designed but not scheduled. The self-hosted posture, since it is the reason this work exists
rather than adopting a hosted provider.

Out: the tool **catalog** question, settled earlier as "do not become a catalog vendor."
Trigger delivery, a separate subsystem for structural reasons — the protocol is
request/response and carries no inbound events. Prompt and response transformation. The
internal first-party tool-delivery channel, which is a different concern and deliberately not
modelled here.

---

### Design Gemini Native Door README (`docs/design/gemini-native-door/README.md`)

# Built-in Gemini over Google's native protocol

Status: approved by Mahmoud on 25 October 2026 (no feature flag; the gateway translator is
dropped). Implementation follows the workflow in "Workflow" below.

## Why

Pi drives the built-in Gemini models (`builtin/agenta`: `google/gemini-3.8-flash`,
`google/gemini-3.7-flash`, `google/gemini-4-argon`) with its `openai-completions` client. The
gateway relays those calls to Vertex's OpenAI-compatible endpoint
(`.../endpoints/openapi/chat/completions`).

That endpoint stalls. On staging (25 October 2026), 120 follow-up calls carrying two tool calls
with thought signatures and their results stalled 56 times on the OpenAI-compatible stream. The
same conversations stalled 0 times in 120 on Vertex's native `streamGenerateContent`, and 0
times without streaming. Some requests stayed stuck for minutes. v0.124.2 (PR #7795) limits the
damage: a 90 s first-byte cut, two retries, a changed retry body. It does not remove the cause.

The OpenAI client also loses data Gemini needs. It drops the `extra_content` that carries
thought signatures, so the gateway hides them in tool call ids (`__thought__`). It drops the
signatures on text parts entirely, which Pi's own code says makes Gemini "intermittently end
mid-task". And because the built-in model is registered in Pi with only an `id`, Pi never sends
a thinking level at all.

Pi already ships a native Gemini client, `google-generative-ai` (built on `@google/genai`). It
accepts a custom base URL and custom headers, stores thought signatures natively in its session
records, and sends thinking levels. So the fix is to let Pi speak native Gemini to the gateway,
and let the gateway relay native bytes to Vertex.

Rejected: translating OpenAI chat completions to native Gemini inside the gateway. Only Pi uses
the built-in models (`BUILTIN_CHAT_COMPLETIONS_HARNESSES = {pi_core}` in
`web/packages/agenta-entities/src/secret/core/agentModelCandidates.ts`), so a translator would
add a permanent body-conversion layer (an exception to D34) for no caller that needs it. The
draft and its comparison with LiteLLM, the Vercel AI SDK and Portkey are kept outside the repo
as reference.

## The call after the change

```
Pi google-generative-ai
  POST {gw}/gateways/llms/builtin/agenta/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse
  X-AG-Credentials: Secret ...        (from models.json headers, as today)
  x-goog-api-key: agenta-gateway      (Pi requires a key; a placeholder, never forwarded)
  body: native GenerateContentRequest (contents, systemInstruction, tools, generationConfig)
        |
gateway (new native door, protocol GEMINI)
  auth, built-in guard, allowlist (google/<model>), capability guard, wallet admission,
  default thinking level, stall rules, relay
        |
Vertex  POST https://aiplatform.googleapis.com/v1/projects/{p}/locations/global/
             publishers/google/models/gemini-3.8-flash:streamGenerateContent?alt=sse
        |
answer relayed as received; usage read from usageMetadata; errors rebuilt in Google's shape
```

## Components

### 1. API: the native door

- `LLMProtocol` gains `GEMINI = "gemini"` (`api/oss/src/core/gateways/llms/dtos.py`).
- One route in `api/oss/src/apis/fastapi/gateways/llms/proxy.py`, built-in only:
  `POST /builtin/{provider}/v1beta/models/{model}:streamGenerateContent`. Pi's Google client
  calls only `generateContentStream` (no `countTokens`, no `generateContent`, no file upload),
  so no other native operation is served. The model comes from the path and must be a bare
  Gemini id (no slash); the door names it `google/<model>` so the existing allowlist and rate
  card apply unchanged. Caller query parameters (`key`, `alt`) are never forwarded; the
  upstream URL sets `alt=sse` itself.
- The door builds the `LLMCallContext` itself and passes it to the service; the service skips
  `_parse_call_context` for `GEMINI`. Everything else in `relay_chat_completion` runs as today:
  policy, wallet admission, platform secret, retries, drain and record.
- Capability guard for `GEMINI` (`_check_builtin_capabilities`) is an allowlist, not a
  denylist, because the native request has many fields that select another model or a priced
  feature (`generationConfig.routingConfig`, `modelConfig`, `responseModalities`,
  `speechConfig`, `imageConfig`, `modelArmorConfig`, hosted tools, `cachedContent`). Top level:
  `contents`, `systemInstruction`, `tools`, `toolConfig`, `generationConfig`, `safetySettings`.
  Each tool object holds only `functionDeclarations`. `generationConfig`: `temperature`,
  `topP`, `topK`, `maxOutputTokens`, `stopSequences`, `seed`, `presencePenalty`,
  `frequencyPenalty`, `responseMimeType`, `responseSchema`, `responseJsonSchema`,
  `thinkingConfig`, and `candidateCount` only when 1. Parts in `contents` and
  `systemInstruction` may carry `text`, `inlineData`, `functionCall`, `functionResponse`,
  `thought`, `thoughtSignature`; `fileData` is refused (Vertex would fetch a URL on the
  platform's account). Exact camelCase keys, so snake_case aliases are refused too.
- Ceilings: not applied on the native door. Only the built-in endpoint serves it, and the
  built-in endpoint configures no `max_output_tokens` ceiling; `_enforce_ceilings` returns the
  body unchanged for `GEMINI`. A ceiling there would need a nested `generationConfig` path.
- Thinking: the door normalizes `generationConfig.thinkingConfig` for the built-in models,
  so every request carries a level these models accept. No thinking setting at all,
  `thinkingBudget: 0`, or `thinkingLevel: MINIMAL` become `thinkingLevel: LOW` (thinking off).
  Any other `thinkingBudget` is dropped, so Vertex uses its default level (MEDIUM). `LOW`,
  `MEDIUM`, `HIGH` and `includeThoughts` pass unchanged. Reason (Pi 0.99.1,
  `google-shared.js`): Pi's Google client sends `thinkingBudget: 0` for thinking "off", and a
  budget of `-1` for any level on `gemini-4-argon` (its level-model check is a regex on
  `gemini-3`); Gemini 4 refuses `thinkingBudget` (400), and 3.7, 3.8 and 4 refuse `MINIMAL`.
  Same "off means LOW" rule as v0.124.2 on the OpenAI door.
- Old sessions: no gateway rewrite. Pi treats the old OpenAI-route messages as another model's
  (different model id and API), drops their signatures and normalizes their tool call ids
  before they reach the gateway (`transform-messages.js`), so a gateway split would see
  truncated ids. Gemini validates signatures only on the current turn, so an old session works
  from its next turn; only a turn in flight during the switch can fail once. Checked in the
  end-to-end step.
- Stall rules stay: `response_headers_timeout_seconds` (90 s) and two retries; a stalled retry
  appends one newline per stall to the last text part of `systemInstruction`.
- Routing: `routing.vertex_gemini_native_url(route, stream)` builds the publisher URL.
- Usage: `_usage_from_payload` gains a `GEMINI` branch over `usageMetadata`, explicit
  counters only: `input = max(promptTokenCount + toolUsePromptTokenCount -
  cachedContentTokenCount, 0)`, `cache_read = cachedContentTokenCount`,
  `output = candidatesTokenCount + thoughtsTokenCount`. No `totalTokenCount` fallback (it
  would count tool-use input as output). Usage arrives on the last event; a stream cut before
  it records no usage, as on the OpenAI door today.
- Errors: an error answered before the stream starts (status body, domain refusal) uses
  Google's shape, `{"error": {"code": <http status>, "message": <marked sentence>, "status":
  <canonical status>}}`. `@google/genai` raises that, and the runner still finds the
  `⟦agenta_code:…⟧` marker. Built-in errors stay unquoted (Vertex names the project). An error
  after the stream started cannot reach Pi as a marked error: `@google/genai` 2.21.0 does not
  raise `data: {"error": ...}` events and Pi reports "Google stream ended without a finish
  reason" (Codex, mocked fetch). The runner classifies that sentence as a lost connection.
- Terminal detection: a native stream has no `[DONE]`. The relay treats a stream as finished
  when an event's `candidates[0].finishReason` is set (parsed per event, `GEMINI` only), so a
  clean end is not reported as a lost connection.
- Caller headers: the door must not forward `x-goog-api-key` or `?key=`. The egress boundary
  admits only allowlisted caller headers; a unit test pins that the placeholder never reaches
  Vertex.

### 2. API: the resolve hint

`LLMGatewayConnectionResolution` gains `protocol: Optional[LLMProtocol]`. For a `builtin`
Vertex endpoint it is `GEMINI`; for everything else it is absent. `provider_key` and
`deployment_kind` stay `openai` / `custom`, so an older SDK or runner that ignores the field
keeps today's OpenAI route.

### 3. SDK (agent service)

- `platform/connections.py` reads `protocol` from the resolution.
- `ResolvedConnection` gains `protocol: Optional[str]`.
- `endpoint.base_url` stays the `/v1` route, as today (see "Version skew").
- The run request to the runner carries the hint as `modelConnection.protocol`.

### 4. Runner

- `pi-model-config.ts`: `PiProviderApi` widens to include `"google-generative-ai"`. When
  `modelConnection.protocol === "gemini"`, the plan uses that API, the connection's base URL
  with its trailing `/v1` replaced by `/v1beta` (`@google/genai` appends
  `/models/{model}:...` and is told the base already carries the version), the same
  placeholder key and the same `X-AG-Credentials` header. The model id is
  the bare Gemini id (`gemini-3.8-flash`); Pi's catalog id stays `<slug>/<id>`.
- The model entry is NOT marked `reasoning: true`. Pi's default thinking level is "medium"
  (`pi-coding-agent` `DEFAULT_THINKING_LEVEL`), and the runner never sets one, so marking it
  would make every built-in turn think at MEDIUM and stream its thoughts, against the product
  rule (thinking off means LOW, gemini-3.8-flash at LOW by default). Unmarked, Pi sends no
  thinking setting, exactly as on the OpenAI route today, and the gateway applies LOW. Letting
  an agent choose its thinking level is a separate change.
- The runtime identity (`session-identity.ts`, `lifecycle/desired-state.ts`) includes the
  protocol, so a warm runtime is rebuilt when a connection switches between the two routes.
- Error classifier (`errors.ts`, `gateway-error.ts`): map the strings Pi's Google client
  produces: our marked error from a status body, "Google stream ended without a finish reason"
  (lost connection), "Provider stopped with: MALFORMED_FUNCTION_CALL" (today's regex expects
  `finish_reason: malformed_function_call`), and the client's timeout and 429 wording.

## Version skew

API, agent service (SDK) and runner deploy apart. Each new field is optional and ignored by
older readers, so every order is safe:

| API | SDK | Runner | Result |
|---|---|---|---|
| old | any | any | no `protocol`; OpenAI route |
| new | old | any | SDK drops `protocol`; OpenAI route |
| new | new | old | runner ignores `protocol` and uses the unchanged `/v1` base; OpenAI route |
| new | new | new | native route |

The SDK never changes the base URL; only the runner that understands `protocol` derives the
native base from it. That is what keeps the third row safe. The OpenAI door for `builtin`
stays, for every row but the last.

Accepted window (Mahmoud's "fewest rollout steps" rule): during a rolling API deploy a new
replica can advertise `protocol` while the run's next call lands on an old replica, which
answers 404 for the native route. That lasts as long as the rollout (minutes) and fails at
most the affected turns once. The alternative, shipping the route one release before the
advertisement, doubles the rollout. Rollback is safe: an old API stops advertising, and a warm
runtime is rebuilt because the protocol is part of its identity.

## Thinking

Pi sends no thinking setting for the built-in models (they are not marked as reasoning), so the
gateway's normalization gives every call `thinkingLevel: LOW`, the same as v0.124.2 on the OpenAI
route. The normalization also covers clients that do send a setting: `thinkingBudget: 0` and
`MINIMAL` become LOW (3.7, 3.8 and 4 refuse `MINIMAL`), any other budget is dropped (Gemini 4
refuses budgets), and `LOW`, `MEDIUM`, `HIGH` pass. Retries: Pi retries the initial request once
(`GATEWAY_PI_RETRY`) and the gateway twice, so a call can reach Vertex up to six times.

## Security

- The platform's Vertex credential stays in the API, as today.
- The placeholder `x-goog-api-key` is dropped at the door and never forwarded.
- The built-in guard (`_refuse_builtin_outside_agent_run`) applies to the new routes.
- The capability guard refuses everything the rate card does not price.

## Tests

- API unit (`test_gateways_gemini_native_door.py`): route matching for the path Google's SDK
  calls, context from the path, bare model ids, malformed bodies; the allowlist at every depth
  (top level, tools, tool config, safety settings, generation and thinking config, parts in
  contents, system instruction and function responses, inline data), with zero upstream calls
  on a refusal; opaque arguments, responses and schemas pass; thinking normalization; usage
  from `usageMetadata`; the stall nudge; Google error shapes with the marker; terminal detection;
  the placeholder key never reaches Vertex; wallet admitted once and charged once; the resolve
  hint.
- SDK unit: resolution with and without `protocol`; a shared golden for the native route's
  model connection.
- Runner unit: models.json for `protocol: "gemini"` (API, base, headers, bare id, no reasoning
  flag) and without it (unchanged); identities pinned to their pre-change values; a mocked
  fetch of Pi's Google client (URL, headers, no thinking setting); classifier strings.
- End to end (local stack and staging, staging's Vertex account): tools across turns, parallel
  bash, long tool chains with approvals, three models, a session started on the OpenAI route,
  wallet charges, live UI QA.
- Stall A/B: direct to Vertex, 120 follow-ups per endpoint; through the product, 15 two-turn
  tool sessions per route.

## Workflow

1. This design, reviewed by Codex (gpt-6-astra, medium).
2. API slice, unit tests, Codex review.
3. SDK and runner slice, unit tests, Codex review.
4. Local end to end on a worktree stack with staging's Vertex account.
5. Stall A/B on staging's Vertex account.
6. Live QA as a real user, recordings in the PR comment.
7. Staging deploy, release gate with the new cell.
8. Stacked PRs (API, then SDK and runner) into the next release branch.

## Design review (Codex, gpt-6-astra medium, 25 October 2026)

Applied: streamed errors are classified in the runner instead of relying on a marked SSE event;
the gateway signature split was dropped (ineffective after Pi's id normalization); the
capability guard became an allowlist; thinking is normalized for what Pi actually sends,
including Argon; the protocol joins the runtime identity; usage uses explicit counters with
tool-use input as input; terminal detection parses events; only `streamGenerateContent` is
served. Accepted with reason: the rolling-deploy window (see "Version skew").

---

### Design Gemini Thought Signatures README (`docs/design/gemini-thought-signatures/README.md`)

# Gemini thought signatures in the tool call id

This folder plans one change that moves Gemini thought signatures into the Agenta LLM
gateway. Today a Pi extension in the runner keeps signatures, and the gateway fills the gaps
with a value that turns off Google's check. After the change, the gateway carries each
signature inside the tool call id on the way back to the client, and it puts the signature
back where Gemini reads it on the next request. The skip value and the runner extension are
deleted in the same PR. This is an architecture change, and it is not expected to fix the
`malformed_function_call` seen in production.

The code baseline is `origin/release/v0.122.6` at `090e8bd81b`. The local workspace checkout
is older and does not have the code this plan changes.

## Reading order

| File | Answers |
| --- | --- |
| [context.md](context.md) | What goes wrong today, and why we are changing it. |
| [design.md](design.md) | The wire shape, the code change in each file, the costs, the tests, and the open questions. Read this one first if you read only one. |
| [research.md](research.md) | What we found in the code, in Pi, and in LiteLLM, with file and line references. |
| [plan.md](plan.md) | The order of work and how to check it on a live stack. |
| [status.md](status.md) | Where the work stands. |

## Terms used in every file

- **Gateway**: the Agenta LLM gateway in `api/oss/src/core/gateways/llms/`. It relays a
  chat completions request to the provider and relays the response back.
- **Pi**: the agent harness the runner (`services/runner`) drives. Pi talks to the gateway
  in the OpenAI chat completions format.
- **Thought signature**: an opaque base64 string Gemini 3 returns with a tool call. Gemini
  wants it back, unchanged, when the next request sends that tool call in its history.
- **Google's OpenAI-compatible endpoint**: the chat completions API that Google serves for
  Gemini, on Vertex (deployment kind `VERTEX`) and directly (provider key `gemini`). The
  gateway reaches Gemini only through this endpoint.
- **Skip value**: `skip_thought_signature_validator`, a fixed string that Google accepts in
  place of a signature. Google documents that it costs reasoning quality.
- **Current turn**: Google's term for every message after the latest user message that is not
  a tool result. Google checks signatures only on tool calls in the current turn.

---

### Design Hosted Subscription Connections README (`docs/design/hosted-subscription-connections/README.md`)

# Hosted subscription connections

Build a working exploratory implementation while investigating authentication and concurrent
refresh. There is no timebox; a recommendation alone is not the intended result. Architecture
choices remain open, and experiments can change the implementation.

## Reading order

1. [Requirements](requirements.md): Mahmoud's product requirements, edited only for clarity.
2. [Working research](working-research.md): current direction, architecture experiments, parallel
   implementation tracks, and validation.
3. [Fable prompt](fable-prompt.md): editable handoff for Mahmoud to send.
4. [Communication log](communication-log.md): asynchronous updates, feedback, and handoffs.
5. [Status](status.md): current workspace, ownership, and next work.
6. [Technical inferences](technical-inferences.md) and [design questions](design-questions.md):
   explicitly labeled AI analysis. Consult working research for the current exploration direction.
7. [v0](v0/README.md): original plan, context, research, status, and walkthrough. It is a good
   starting point, but it may miss important requirements and design questions.

## Terms

A harness is the coding client, such as Codex or Pi. A runner starts and manages the harness. A
session holds one conversation. Authentication state contains credentials used and renewed by the
client. A mount exposes storage as a directory; its behavior depends on the storage and filesystem
adapter. A coordination component can share credential changes without owning provider refresh.

The v0 assumptions about one active run, private owner-only use, and Grok in the first release do
not define the current scope. Existing research needs verification against the versions and cloud
runtime used for these experiments.

---

### Design Kubernetes Oss Ee Self Hosting README (`docs/design/kubernetes-oss-ee-self-hosting/README.md`)

# Kubernetes OSS/EE self-hosting

This workspace tracks the work needed to make Agenta's Kubernetes self-hosting path support both OSS and EE cleanly.

## Goal

Provide a simple, non-hacky Kubernetes setup path for:

- OSS users
- self-hosted EE users

while preserving the existing Docker Compose deployment flow.

## Files

- `context.md` — problem statement, goals, non-goals, and constraints
- `plan.md` — agreed multi-PR execution plan
- `research.md` — current chart/runtime findings and EE-vs-OSS differences
- `status.md` — current status, branch/workstream tracking, blockers, and next steps

---

### Design Legacy Adapter Migration README (`docs/design/legacy-adapter-migration/README.md`)

# Legacy Adapter Migration

This document scopes the migration away from the legacy adapter-backed routers:

- `/apps`
- `/variants`
- `/configs`
- `/environments` (legacy deploy RPC)

The goal is to replace those router families with the new entity routers:

- `/applications`
- `/workflows`
- `/evaluators`
- `/environments`
- `/simple/environments`

## Summary

The new entity routers already cover almost all of the old CRUD and revision history surface:

- apps/applications CRUD
- variants CRUD
- revision create, fetch, query, commit, log
- evaluator config CRUD
- environment CRUD

What is still missing is not generic storage capability. The gap is mostly a set of old RPC-style deployment and config convenience endpoints.

## Main Findings

### 1. The real gap is deployment convenience, not data capability

The old routers expose one-call deploy/retrieve/revert flows:

- `POST /environments/deploy`
- `GET /apps/get_variant_by_env`
- `GET /apps/{app_id}/environments`
- `GET /apps/{app_id}/revisions/{environment_name}`
- `GET /configs/deployment/{deployment_revision_id}`
- `POST /configs/deployment/{deployment_revision_id}/revert`
- `POST /variants/configs/deploy`
- `POST /variants/configs/fetch` when used with `environment_ref`

The new entity routers can represent the same state through environment revisions and application/workflow revisions, but callers have to orchestrate several steps themselves.

### 2. Some old endpoints are only thin convenience wrappers now

These legacy endpoints are already conceptually covered by generic entity operations:

- `POST /variants/from-base`
- `PUT /variants/{variant_id}/parameters`
- `PUT /variants/{variant_id}/service`
- `GET /variants/{variant_id}/revisions`
- `GET /variants/{variant_id}/revisions/{revision_number}`
- `POST /variants/revisions/query`
- `POST /variants/configs/add`
- `POST /variants/configs/commit`
- `POST /variants/configs/history`
- `POST /variants/configs/list`
- `POST /variants/configs/query`

The new DTOs already support revision `data.url`, `data.parameters`, and even the temporary legacy `data.service` / `data.configuration` fields during migration.

### 3. A few legacy concepts should not be carried forward as first-class APIs

These should stay deprecated:

- `template_key`-driven app creation
- `base_id` and `config_name` as primary API concepts
- legacy `ConfigDTO` as the canonical public contract

### 4. SDK migration is required

The remaining migration work is mainly in the managed SDK/client layer, not in Fern-generated clients:

- replace legacy config/deploy helpers with entity-router calls
- move evaluator execution to workflow invocation where needed
- normalize on the new entity DTOs instead of legacy adapter DTOs

## Recommendation

Do both:

1. Add a small set of explicit deployment/retrieval RPCs to the new routers.
2. Migrate the SDK to those new endpoints instead of keeping the legacy adapters alive.

That is cleaner than preserving `/apps`, `/variants`, `/configs`, and the old `/environments` deploy route as permanent compatibility surface.

## Proposed API Additions

### On environments

Add RPCs that operate on environment deployment state directly:

- `POST /environments/deploy`
- `POST /environments/retrieve`
- `POST /environments/revert`

Suggested semantics:

- `deploy`: write a revision reference into a new environment revision
- `retrieve`: resolve the currently deployed application/workflow revision for a key or artifact
- `revert`: replay a historical environment revision as a new deployment commit

These endpoints are the closest replacement for the old deployment-oriented adapter surface.

### On workflows or applications

Optional thin wrappers can improve ergonomics:

- `POST /workflows/deploy`
- `POST /workflows/retrieve`

or equivalently on applications:

- `POST /applications/deploy`
- `POST /applications/retrieve`

If we only add one family, environments should win. Deployment state belongs to environments.

## SDK Scope

The SDK should migrate away from legacy adapter routes in this order:

1. Deploy/retrieve/revert helpers
2. Config fetch/list/history helpers
3. Variant shorthand helpers

The Fern clients do not need to drive this migration. This is primarily SDK manager and handwritten helper logic.

## Detailed Audit

See [route-gap-analysis.md](./route-gap-analysis.md).

---

### Design Lifecycle Cold Warm Audit README (`docs/design/lifecycle-cold-warm-audit/README.md`)

# Cold/warm lifecycle audit — 2026-08-29

A fresh-context audit of the session lifecycle code, commissioned after the harnessKind
wire-spelling bug (#6364) to find more of its class. Method: read
`reconciliation-router.ts`, `desired-state.ts`, `session-coordinator.ts`,
`session-identity.ts`, `session-pool.ts`, `engine.ts`, `run-plan.ts` and their tests;
cross-check every wire literal against `protocol.ts` and the Python SDK; confirm each
behavioral claim with a throwaway probe built on the `lifecycle-live-routes.test.ts`
harness.

## Findings, most severe first

1. **FIXED (#6372). The live route cleared every mismatch reason.** The coordinator's
   else-if chain found only the FIRST reason, and a successful live model apply set
   `mismatch = undefined` wholesale. A model switch riding an edited transcript, a rotated
   credential, an expiring mount lease, or a stale tail continued warm past the skipped
   checks (all four proven warm with the probe). Fixed by re-asking the ordered checks
   after each repair; four pinned tests.

   Review found a second half of the same finding: re-asking returned the FIRST unresolved
   reason, and that reason alone chose the teardown. `history` sorts ahead of the credential
   checks, so a model switch carrying both an edited transcript and an undeliverable
   rotation evicted as `history`, mapped to `continuity-invalid`, and PARKED a sandbox whose
   daemon still held the old key. The eviction is now NAMED by the first reason and DISPOSED
   by all of them, strictest wins; pinned with the three-way combination.

2. **`modelCapabilities` defeats the live model route across modality changes.** It is
   per-turn data (read only by the attachment-delivery chain) but sits in the fingerprint
   and the `harnessSession` facet, and it CHANGES WITH THE MODEL (resolved input
   modalities). Switching between a vision model and a text-only model moves two facets,
   the mixed plan rebuilds, and the one live route works only when the two models agree on
   modalities. Fix: move it to the per-turn-volatile list (the `workflowRevision` /
   `isDraft` precedent), pinned in `lifecycle-desired-state.test.ts`.

3. **FIXED (#6399, with 6). `harnessMode` is normalized in the fingerprint but raw in the facet.** The two views
   can disagree (measured: fingerprint equal while `harnessSession` moves), which poisons
   later plans into rebuilding. Reachable today only through a direct runner caller.
   Fix: normalize in one place; add the reverse-direction "no input drift" assertion (a
   change that moves a facet must move the fingerprint).

4. **FIXED (#6398). The agent-mount artifact id is in no fingerprint and no facet (under-eviction).**
   `runContext.workflow.artifact.id` signs the agent mount, sets its env var, and appends
   its guidance — all baked at acquire — yet a changed or newly present id reuses the warm
   sandbox (measured). Fix: add the id alone to the `sandbox` facet + fingerprint, with an
   eviction test.

5. **FIXED (#6400). `toolCallback.endpoint` is fingerprinted but consumed per-turn (over-eviction).** Low
   reachability (stable per-deployment URL); same fix class as 2.

6. **FIXED (#6399). `configFingerprint` matches `codex` on a bare wire literal inline.** Correct today,
   but the exact shape of the #6364 bug (a literal plus a silent fall-through). Fix:
   one exported harness normalizer used by `configFingerprint`, `run-plan.ts`, and
   `reconciliation-router.ts`, with a round-trip test over the SDK enum.

7. **FIXED (#6400). `applyReconcilePlan` treats every `apply-live` action as a model change** (ignores
   `action.facet`). Unreachable today; becomes real the moment the credential plan routes
   through the applier. Fix: switch on the facet, refuse the rest, one test.

8. **DECLINED. `connection` `{mode, slug}` evicts on every harness but only Pi consumes it.** Very
   low reachability; listed for completeness. Declined on review: design Decision 7 pins that a
   custom provider identity change cold-starts on EVERY harness, and its test covers non-Pi.
   The decline is recorded beside the field in `session-identity.ts` (#6400).

Verified clean: the harness wire spellings after #6364 (both normalizers agree, with a
plan-build assertion), and the shadow-router's decision scoping.

## Standing checks born from this

- Gate: L1's model case is blocking on claude AND pi_core (#6371).
- New Relic: alert policy "Runner lifecycle audit" (policy 1731651) pages the operator
  Slack webhook on any `DISAGREE` or `harness=unknown` runner log line.
- Unit: the repair-scoping pinned tests in `lifecycle-live-routes.test.ts` (#6372).

Every finding is now fixed or declined; each fix landed with its pin (see the PR on each row).

---

### Design Litellm Client Closed Retry README (`docs/design/litellm-client-closed-retry/README.md`)

# LiteLLM Client Closed Retry Workaround

## Problem

Production chat endpoint intermittently fails with "OpenAIException - Connection error" when the underlying httpx client is closed mid-request due to LiteLLM's cache eviction.

## Workspace Contents

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, problem statement, root cause analysis |
| [research.md](./research.md) | Code analysis, LiteLLM internals, findings |
| [plan.md](./plan.md) | Execution plan for the workaround |
| [status.md](./status.md) | Current progress and decisions |

## Quick Summary

- **Issue**: Chat endpoint returns 500 with "Cannot send a request, as the client has been closed"
- **Root Cause**: LiteLLM caches OpenAI clients; when evicted mid-request, GC closes the httpx client
- **Workaround**: Detect error in exception chain, flush cache, retry once
- **Affected**: Only OpenAI models, only in production (high concurrency)

---

### Design Loops README (`docs/design/loops/README.md`)

# Trace Reuse via Hashing

## What Hashing Does

Hashing assigns a stable identity to a trace node from:

- the references that define the node from which the trace was generated
- the links that describe the nodes before it in the execution chain

The goal is to identify whether a node that is about to run is logically the same node as one that has already been traced.

The references can include identities such as:

- `testset`
- `testcase`
- workflow lineage
- application lineage
- evaluator lineage

For artifact-based entities, that lineage may be expressed at the artifact, variant, or revision level.

The hash is not derived from the entire trace payload. It is derived from the canonical identity of the node in context.

## Scope Of The Hash

The hash is built from:

- canonical references for the node
- canonical upstream links for the node

For trace reuse, `testset_variant` and `testset_revision` are excluded from hashing so that the same testcase can reuse traces across testset variants and revisions.

## How To Use It

In an evaluation loop, when a workflow, application, or evaluator is about to be invoked, first compute the expected hash for that node and try to fetch an existing trace by that hash.

Flow:

1. Compute the expected hash from the node's references and upstream links.
2. Query existing traces by that hash.
3. If a matching trace is found, reuse its `trace_id` instead of invoking the runnable.
4. If no matching trace is found, invoke the runnable normally.

Persistence does not need a separate step here, because traces are already persisted automatically when the runnable executes.

Operationally, the switch is only:

- fetch and reuse
- fetch, miss, and invoke

## Required Utilities And Components

The core primitive utilities are:

- `make_hash(...)`
- `fetch_traces_by_hash(...)`

`fetch_traces_by_hash(...)` should be plural by default.

This is necessary because reuse depends on cardinality:

- application-step fan-out may need up to `repeats` traces
- evaluator-step fan-out may need up to `repeats` traces
- partial cache hits need all matching traces, not just one

On top of those primitives, the runtime also needs:

- `select_traces_for_reuse(...)`
- `plan_missing_traces(...)`
- a repeat-aware fan-out planner
- a repeat-aware result-slot planner
- a reuse resolver that decides, for each result slot, whether to bind an existing trace or invoke execution

### Responsibility Split

- `make_hash(...)`
  - compute the canonical identity for the node in context
- `fetch_traces_by_hash(...)`
  - fetch all candidate traces for that identity
- `select_traces_for_reuse(...)`
  - choose which fetched traces satisfy the current repeat demand
- `plan_missing_traces(...)`
  - determine how many additional executions are still required

At execution time, this must be applied at the runnable step boundary:

- workflow step
- application step
- evaluator step

## When To Use It

Hash-based trace reuse must be explicit.

The run should opt into reuse through a dedicated flag, for example:

- `is_cached=true`

This avoids implicit behavior changes and makes reuse a deliberate execution choice.

When `repeats > 1`, the run should also explicitly declare where fan-out happens through:

- `is_split`

Semantics:

- `is_split=false` by default
- if `repeats > 1` and `is_split=true`, fan-out happens at the application step
- if `repeats > 1` and `is_split=false`, fan-out happens at the evaluator step

Hash-based trace reuse may be used for:

- workflow steps
- application steps
- evaluator steps

Hash-based trace reuse must also be coherent with repeat fan-out.

### Repeats Fan Out At Application Steps

If repeats fan out at application steps and `is_cached` is true:

- fetch traces by hash for the application step
- if the number of matching traces is greater than or equal to the number of repeats, reuse them
- if the number of matching traces is smaller than the number of repeats, reuse the traces that exist and generate the missing traces
- the newly generated traces will carry the same hash

### Repeats Fan Out At Evaluator Steps

If repeats fan out at evaluator steps and `is_cached` is true:

- for evaluator steps, fetch traces by hash for the evaluator step
- if the number of matching traces is greater than or equal to the number of repeats, reuse them
- if the number of matching traces is smaller than the number of repeats, reuse the traces that exist and generate the missing traces
- the newly generated traces will carry the same hash

There is also a cross-step optimization when repeats fan out at evaluator steps:

- for application steps, fetch traces by hash
- if there is at least one matching application trace, reuse the latest matching application trace for all evaluator repeats
- only invoke the application step when there is no matching application trace

## When Not To Use It

- if `is_cached=false`, do not use hashes
- if `is_cached=true` and repeats fan out at the application step, but the number of traces with the hash is smaller than the number of repeats, some traces must still be generated
- if `is_cached=true` and repeats fan out at the evaluator step, but the number of traces with the hash is smaller than the number of repeats, some traces must still be generated

## Summary

Hashing gives us a stable identity for a trace node so we can tell whether we have already generated the same logical node before.

That identity is computed from:

- references, which describe what node this trace came from
- links, which describe the upstream nodes before it in the execution chain

So the hash is not "hash the whole trace payload." It is "hash the canonical identity of this node in context."

We use that in evaluation loops to avoid unnecessary execution. Before invoking a runnable, we compute the expected hash and try to fetch an existing trace with that hash.

This applies to runnable steps such as:

- workflow
- application
- evaluator

The runtime flow is:

1. Compute the expected hash for the node.
2. Query traces by hash.
3. If a matching trace exists, reuse its `trace_id`.
4. If no matching trace exists, invoke normally.

There is no extra persistence step to think about. If we do invoke, trace persistence already happens automatically.

So the decision is always:

- fetch and reuse
- fetch, miss, and invoke

One important correction we made is that `testset_variant` and `testset_revision` should not affect the hash. If they do, the same testcase ends up with different hashes across testset revisions or variants, which breaks reuse for something that is logically the same testcase input.

When should hashes be used?
Only when explicitly enabled, for example with `is_cached=true`. Reuse should never be implicit.

Then fan-out behavior has to stay coherent for the step where repeats happen.

When `repeats > 1`, that fan-out location should be explicit:

- `is_split=true` means application-step fan-out
- `is_split=false` means evaluator-step fan-out

If repeats fan out at the application step and `is_cached=true`:

- fetch traces for that application-step hash
- if matching traces are greater than or equal to repeats, reuse them
- if matching traces are fewer than repeats, reuse what exists and generate the missing traces

If repeats fan out at the evaluator step and `is_cached=true`, the same rule applies at the evaluator step:

- fetch traces for that evaluator-step hash
- if matching traces are greater than or equal to repeats, reuse them
- if matching traces are fewer than repeats, reuse what exists and generate the missing traces

There is also a cross-step case.

If repeats fan out at evaluator steps, then at the application step there is no need to regenerate identical application traces for each evaluator repeat. In that case:

- if at least one matching application trace exists, reuse the latest one for all evaluator repeats
- only invoke the application if there is no matching trace at all

When not to use hashes:

- if `is_cached=false`
- if `is_cached=true` but the number of matching traces is smaller than the repeat demand for the step that actually fans out, missing traces still must be generated

The mental model is:

- hashes define logical node identity
- reuse is an explicit opt-in
- `is_split` defines where fan-out happens when `repeats > 1`
- workflow, application, and evaluator steps can all use hashes
- the reuse policy depends on where repeats fan out
- hashes reduce duplicate work, but they do not eliminate the need to generate missing traces when repeat cardinality requires them

---

### Design Managed Secrets README (`docs/design/managed-secrets/README.md`)

# Managed secrets

Managed secrets are vault rows provisioned and owned by a platform component. Their
management policy is separate from whether their value is write-only.

The internal contract stores a structured `management` object in the encrypted vault
JSON:

```json
{
  "management": {
    "manager": "starter-credits-bridge",
    "policy": "manager_only"
  }
}
```

This requires no database migration. There is deliberately no compatibility fallback for
the former flat `managed_by` experiment.

Public create and update payloads do not accept management fields. Trusted components use
`VaultService.create_managed_secret` and provide `SecretManagementDTO` separately. Public
responses expose only `management.policy`; the manager identity remains internal.

`manager_only` means public update and delete operations are rejected after the DAO locks
the current row. There is no owner bypass in the general vault service. A future manager
workflow that needs reconciliation should use a dedicated manager-specific operation.

Management and value visibility are independent. A managed secret may explicitly be
readable when its product flow requires that behavior, while write-only managed secrets
continue to use the normal runtime grant and redaction rules.

---

### Design Migrate Evaluator Playground README (`docs/design/migrate-evaluator-playground/README.md`)

# Migrate Evaluator Playground to New Evaluator Endpoints

## Overview

This planning workspace documents the migration of the Evaluator Playground frontend to use the new workflow-based evaluator endpoints. The backend team has migrated evaluators from the old `EvaluatorConfig` model to the new `SimpleEvaluator` (workflow-based) model.

## Migration Strategy

**Direct migration (no adapters)** split into two PRs:

| PR | Scope | Description |
|----|-------|-------------|
| **PR 1** | CRUD | Migrate to `/simple/evaluators/*`, change internal types to `SimpleEvaluator` |
| **PR 2** | Run | Migrate to `/workflows/invoke`, add workflow service types |

See [plan.md](./plan.md) for detailed implementation steps.

## Context

- **PR #3527**: Backend migration that introduces new evaluator endpoints
- **Goal**: Full migration to new endpoints, no legacy code remaining

## Documents

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, motivation, problem statement, goals, and non-goals |
| [current-system.md](./current-system.md) | Detailed map of current Evaluator Playground implementation |
| [new-endpoints.md](./new-endpoints.md) | New evaluator endpoint shapes and differences from legacy |
| [research.md](./research.md) | Deep dive into evaluator execution architecture and URI-based handlers |
| [migration-options.md](./migration-options.md) | Why we chose direct migration over adapters |
| [risk-analysis.md](./risk-analysis.md) | Coupling points and risk areas for the migration |
| [plan.md](./plan.md) | **Main plan** - PR 1 (CRUD) and PR 2 (Run) implementation details |
| [status.md](./status.md) | Living document for progress updates and decisions |

## Key Mapping Changes

| Legacy | New |
|--------|-----|
| `EvaluatorConfig` | `SimpleEvaluator` |
| `evaluator_key` | derived from `data.uri` |
| `settings_values` | `data.parameters` |
| `GET /evaluators/configs/` | `POST /simple/evaluators/query` |
| `POST /evaluators/configs/` | `POST /simple/evaluators/` |
| `PUT /evaluators/configs/{id}/` | `PUT /simple/evaluators/{id}` |
| `DELETE /evaluators/configs/{id}/` | `POST /simple/evaluators/{id}/archive` |
| `POST /evaluators/{key}/run/` | `POST /workflows/invoke` |

## Files Affected

### PR 1: CRUD Migration

| Area | Files |
|------|-------|
| Types | `web/oss/src/lib/Types.ts` |
| Services | `web/oss/src/services/evaluators/index.ts` |
| State | `web/oss/src/state/evaluators/atoms.ts` |
| Playground State | `web/oss/src/components/.../ConfigureEvaluator/state/atoms.ts` |
| Playground UI | `web/oss/src/components/.../ConfigureEvaluator/index.tsx` |
| Registry | `web/oss/src/components/Evaluators/index.tsx` |
| Registry Hook | `web/oss/src/components/Evaluators/hooks/useEvaluatorsRegistryData.ts` |
| Columns | `web/oss/src/components/Evaluators/assets/getColumns.tsx` |

### PR 2: Run Migration

| Area | Files |
|------|-------|
| Types | `web/oss/src/lib/Types.ts` (add workflow types) |
| Invoke Service | `web/oss/src/services/workflows/invoke.ts` (new) |
| Debug Section | `web/oss/src/components/.../ConfigureEvaluator/DebugSection.tsx` |

### Backend Reference (PR #3527)
- `api/oss/src/routers/evaluators_router.py` - Legacy endpoints (kept temporarily)
- `api/oss/src/apis/fastapi/evaluators/router.py` - New `SimpleEvaluators` router
- `api/oss/src/apis/fastapi/workflows/router.py` - Workflow invoke endpoint
- `api/oss/src/core/evaluators/dtos.py` - New data transfer objects

## Effort Estimate

| PR | Effort |
|----|--------|
| PR 1: CRUD | 4-5 days |
| PR 2: Run | 3-4 days |
| **Total** | **7-9 days** |

---

### Design Mount Credential Refresh README (`docs/design/mount-credential-refresh/README.md`)

# Mount credential refresh: swap fresh credentials into a running mount

Planning workspace for the long-term fix behind a v0.112.3 release finding. Mount
credentials cannot be renewed inside a running geesefs mount today, so the runner
rebuilds sandboxes at turn boundaries to install fresh ones, and a turn that outlives
its lease loses file access mid-run. This project teaches the mount to pick up fresh
credentials while running, so a run of any length keeps live files and warm sessions
never need a credential-driven rebuild.

Predecessor: [docs/design/fix-sts-mount-expiry/](../fix-sts-mount-expiry/) made the
credential lifetime real and made the runner rebuild before expiry. This project
removes the need to rebuild at all.

## What each file answers

| File | Question it answers |
| --- | --- |
| [context.md](context.md) | What still breaks or costs us today, and why this work exists now. |
| [research.md](research.md) | How credentials enter a mount today, what the pinned geesefs SDK actually supports for refresh (verified against its source), why the push model keeps the security boundary intact, and what happens to in-flight file operations at rotation. |
| [plan.md](plan.md) | The chosen mechanism, the changes per file, the slice order, the test plan, and the live QA plan. |
| [decisions.md](decisions.md) | Every decision this design embeds, its trade-off, and how to back it out. |
| [status.md](status.md) | Where this work stands right now. |

## Domain nouns, one sentence each

- **Runner**: the Node sidecar (`services/runner/`) that executes one agent turn per
  HTTP `/run` request.
- **Sandbox**: the isolated environment a turn runs in; "local" means the runner's own
  container, "remote" means a Daytona cloud sandbox.
- **Turn**: one user-message-to-agent-reply exchange; the runner's unit of work.
- **Session pool**: the runner's in-memory table of live environments parked between
  turns so the next turn continues warm instead of rebuilding.
- **Mount**: a directory in the sandbox whose contents live in the object store; each
  mount is one geesefs daemon holding one set of store credentials.
- **Mount credentials / lease**: the temporary, prefix-scoped S3 key, secret, and
  session token a mount's daemon uses; signed by the API, they expire at a TTL.
- **geesefs**: the FUSE filesystem binary (pinned v0.43.0) that presents an S3 prefix
  as a local directory; it vendors a fork of aws-sdk-go v1 for credentials.
- **credential_process**: an AWS SDK config-file directive that names a command the
  SDK re-runs to obtain credentials whenever the previous ones expire.
- **Lease file**: the JSON file, written by the runner, that the credential_process
  command reads; rewriting it is how fresh credentials reach a running daemon.
- **Refresher**: the runner-side loop that re-signs leases before they expire and
  rewrites the lease files, locally by direct write, remotely by pushing into the
  sandbox.
- **Installed lease / credential epoch**: the session pool's record of when the
  credentials actually installed in an environment's daemons expire; today it drives
  evict-before-expiry, after this project it advances on every refresh.
- **STS**: the "Security Token Service" protocol for minting temporary scoped S3
  credentials; both SeaweedFS (bundled store) and AWS implement it.
- **EACCES**: "Permission denied"; what every file operation returns once the store
  answers 403 to an expired lease.
- **ENOTCONN**: "Transport endpoint is not connected"; what the kernel returns when a
  FUSE daemon has died. A different failure, already handled, untouched here.

## Related work

- [docs/design/fix-sts-mount-expiry/](../fix-sts-mount-expiry/): the predecessor.
  Its research.md section 3 is the mechanism catalog this project extends, and its
  decisions.md item 2 is the deferral this project resolves.
- The v0.112.3 patch-release mitigation (shipped separately, on its own lane):
  balances the run deadline (11 h) under the lease TTL (12 h) so no turn can outlive
  its lease. It is a numbers truce, not a fix; this project is the fix.
- The lifecycle migration (`services/runner/src/lifecycle/`): moved the session
  decision logic into `session-coordinator.ts` and introduced live routes that
  reconfigure a running environment instead of rebuilding it. This project adds the
  mount-lease equivalent of that idea.

---

### Design Mount File Viewer README (`docs/design/mount-file-viewer/README.md`)

# Mount file viewer in the SessionInspector

Let users browse a session mount's files in the playground SessionInspector drawer and
click a file to preview it (text, markdown, images), instead of seeing only the mount's
name and id.

- Scope: frontend only. The backend endpoints already exist.
- Surface: `web/oss/src/components/SessionInspector/` (Mounts tab).
- Status: see `status.md`. Plan: `plan.md`. Findings: `research.md`.

---

### Design Onboarding Connect Step README (`docs/design/onboarding-connect-step/README.md`)

# Onboarding connect step

Issue [#6043](https://github.com/Agenta-AI/agenta/issues/6043) / AGE-4134.

Agent onboarding creates the agent first and asks for accounts later — mid-run, several
turns in, through the builder's `request_connection` client tool. This workspace adds a
**setup step before create**: identify the accounts the agent will need, connect them, and
carry the result into the created agent.

## Files

- `context.md` — why this exists, what today actually does (including a correction to the
  issue's premise), goals, non-goals, and the locked decisions D1–D7.
- `research.md` — verified findings from the tree: the two onboarding paths, the flag
  matrix, the connect machinery that already exists, and what the frontend can and cannot
  infer.
- `design.md` — the step's anatomy, the gating rule, detection strategy, the two new
  questions, carry-through mechanisms, and copy.
- `plan.md` — WP-1…WP-6, sized to land independently, plus the verification plan.
- `qa.md` — the live browser matrix. Not yet run.
- `status.md` — where things stand. Source of truth for progress.

## Mockups

Design iteration 1 (three variants, state matrix, decisions) is published as an artifact:
<https://claude.ai/code/artifact/df1e9483-6da8-43b9-82ca-0c8fbd0da82d>

Iteration B ("inline reveal") was chosen. A ("setup drawer") survives only as the flag-off
template arm; C ("the agent asks first") is parked until the builder can plan pre-commit
server-side — its copy voice is borrowed for B.

## Quick orientation

- Free-text path: `web/oss/src/components/pages/agent-home/StripHome.tsx` →
  `hooks/useAgentHomeActions.ts` → `hooks/useCreateAgent.ts`.
- Playground-native path: `agent-home/PlaygroundOnboarding/useAgentOnboarding.ts` (`commit`).
- Template path: `agent-home/hooks/useCreateAgentFromTemplate.ts` (default) and
  `hooks/useTemplateSelect.ts` + `components/TemplateSetupDrawer/` (flag-off only).
- Connect machinery, reused as-is: `@agenta/entities/gatewayTool` (connections, catalog),
  `@agenta/entity-ui/gatewayTool` (`ConnectDrawer`),
  `@agenta/entity-ui/clientTools/useConnectFlow.ts` (the OAuth flow).
- Template registry + provider catalog: `web/packages/agenta-entities/src/workflow/agentTemplates.ts`.
- Flag pattern: `web/oss/src/components/pages/agent-home/assets/constants.ts`.

---

### Design Openapi Cleanup README (`docs/design/openapi-cleanup/README.md`)

# OpenAPI Cleanup

Working notes and tooling for keeping the FastAPI surface, the OpenAPI spec, the Fern-generated clients, and the Docusaurus API reference in sync.

## Files

- [`endpoints.md`](endpoints.md) — generated table mapping every static FastAPI route to its operation_id, generated client method, and handler.
- [`summary.md`](summary.md) — high-level summary of the cleanup that just shipped (canonical surface, deprecations, follow-ups).
- [`tracing-cleanup.md`](tracing-cleanup.md) — design + scope of the tracing-API cleanup.
- [`generate.py`](generate.py) — regenerates `endpoints.md` by walking `application/api/` routers and cross-referencing the Fern clients.
- [`research.md`](research.md) — design / cleanup notes.

## Commands

Run from the repo root.

### 1. Regenerate the Fern clients (Python + TypeScript)

```bash
bash ./clients/scripts/generate.sh
# or
bash ./clients/scripts/generate.sh --language python
bash ./clients/scripts/generate.sh --language typescript
bash ./clients/scripts/generate.sh --live   # use cloud OpenAPI instead of localhost
```

Strips operations tagged `Deprecated`, `Admin`, or `OpenTelemetry` before generation. Outputs:
- Python → [`clients/python/agenta_client/`](../../../clients/python/agenta_client/)
- TypeScript → [`web/packages/agenta-api-client/src/generated/`](../../../web/packages/agenta-api-client/src/generated/)

### 2. Regenerate the API reference docs

```bash
bash ./docs/scripts/update-api-docs.sh
# or
bash ./docs/scripts/update-api-docs.sh --local
bash ./docs/scripts/update-api-docs.sh --file /path/to/openapi.json
```

Pulls the OpenAPI spec, drops it at [`docs/docs/reference/openapi.json`](../../docs/reference/openapi.json), and runs the Docusaurus `gen-api-docs` plugin.

### 3. Regenerate this directory's routes-and-endpoints table

```bash
python3 ./docs/design/openapi-cleanup/generate.py
```

Reads:
- routers under `application/api/oss/src/apis/fastapi/*/router.py`, `application/api/oss/src/routers/*.py`, and `application/api/ee/src/apis/fastapi/*/router.py`
- the generated Fern clients in [`clients/python/agenta_client/`](../../../clients/python/agenta_client/) and [`web/packages/agenta-api-client/src/generated/`](../../../web/packages/agenta-api-client/src/generated/)

Writes [`endpoints.md`](endpoints.md). Routes are split into a *mapped* table (operation_id resolves to a generated client method) and an *unmapped* table (admin-stripped or hidden from the public OpenAPI spec).

## Typical workflow

```bash
# Update the API → regenerate clients → regenerate reference docs → refresh the table
bash ./clients/scripts/generate.sh --local
bash ./docs/scripts/update-api-docs.sh --local
python3 ./docs/design/openapi-cleanup/generate.py
```

Run the table generator last — it inspects the freshly generated clients to fill in the TS/Python columns.

---

### Design Parallel Approval Gates README (`docs/design/parallel-approval-gates/README.md`)

# Parallel approval gates: phantom "failed" tool in the playground

Planning workspace for issue 2 of the 2026-07-06 approval-flow investigation: when the
model calls two approval-gated tools in one turn, the runner's one-pause-per-turn latch
drops the second gate, the client is left with an orphaned tool part, and the frontend
fabricates a `This app can't handle the ... request.` failure for a tool that never
ran. The user then pays two sequential approval round-trips.

**TL;DR of the recommendation** (details in [options.md](options.md)): fix it in the
runner, in two layers. Option A (small, ship now): at pause time, settle every
announced-but-unresolved sibling tool call with a deterministic "not executed, paused
for another approval" result before tearing the session down. Option B (follow-up,
medium): additionally synthesize approval requests for gated siblings whose args are
trustworthy, so the user approves everything in one dock pass and the cold replay
executes all of it in one resume. B contains A as its fallback; nothing is thrown
away. No frontend tool-name lists anywhere (hard constraint).

## Files

| File | What it holds |
|---|---|
| [context.md](context.md) | The bug, the framing decisions from Mahmoud, goals, non-goals. |
| [research.md](research.md) | Verified mechanics with file:line for every claim: the ACP wire trace, the CLI's serial gate scheduling, teardown cancellation, the FE orphan path, the resume machinery, corrections to the earlier findings doc. |
| [flows.md](flows.md) | Mermaid sequence diagrams and example frames: today's broken flow, Option A, Option B, each at the wire / stream / user level. |
| [options.md](options.md) | Both remedies with honest complexity assessments, why A is a stepping stone to B, the recommendation, and one independent flag about the FE force-settle pattern. |
| [plan.md](plan.md) | Phased implementation: files to change, tests (runner unit, FE unit, replay regression), live-stack verification, docs sync, open questions. |
| [status.md](status.md) | Current state and next steps. Source of truth for progress. |

## Prior art

- `docs/design/agent-workflows/scratch/approval-turn-duplication-findings.md`: the
  original investigation (both issues). Issue 1 (duplicate turn blocks from message-id
  churn) is out of scope here.
- F-040 pause contract: `services/runner/src/engines/sandbox_agent/pause.ts:1-27`.

---

### Design Playground Eval Button Changes README (`docs/design/playground-eval-button-changes/README.md`)

# Playground Evaluation Button Changes

Rename, restyle, and add tooltips to evaluation-related buttons in the playground header, execution header, and sidebar.

## Files

- **context.md** — Background, motivation, and goals
- **status.md** — Implementation progress and decisions

---

### Design Playground Keep Drafts On Testset Connect README (`docs/design/playground-keep-drafts-on-testset-connect/README.md`)

# Keep playground draft rows when connecting a test set

Planning workspace for fixing the UX where draft test cases in the playground
(opened from a trace, or created manually) are silently destroyed when the user
connects a test set.

## Files

- [context.md](context.md): why this work exists, the reported UX issue, goals
  and non-goals.
- [research.md](research.md): codebase findings. The full data flow from trace
  to playground, the exact root cause of the silent data loss, the existing
  building blocks we can reuse, and the caveats (chat mode, empty initial row,
  column mismatches).
- [plan.md](plan.md): proposed fix, UX flow, implementation phases, and test
  plan.
- [status.md](status.md): current progress and open decisions. Source of truth
  for where the work stands.

## TL;DR

When the playground is in local mode (not connected to a test set) and holds
draft rows, "Connect test set" replaces those rows with the selected test set
with no warning. The guard modal that exists for "Change test set" never fires
because (a) the not-connected menu path skips it and (b) the `hasLocalChanges`
selector returns `false` by design when not connected.

The fix: detect meaningful local draft rows at connect time, ask the user
whether to keep them, and on "keep" connect to the test set then re-import the
captured rows as unsaved additions. The existing `importRows` + `commitChanges`
machinery already supports "unsaved rows on top of a connected test set, then
sync back", so no new persistence logic is needed.

---

### Design Playground Mode Switch README (`docs/design/playground-mode-switch/README.md`)

# Playground mode switch (chat ⇄ completion)

Working docs for letting users switch a chat app's playground between chat
mode (multi-turn conversation) and completion mode (single-turn, N test
cases) at runtime, without losing data in either direction.

Design source: the handoff bundle at `design_handoff_playground_mode_switch/`
in the repo root (open `Mode Switch Exploration.html` for the boards; its
`README.md` is the visual spec). Where this plan deviates from the handoff,
[context.md](context.md) records the deviation and the reason.

## Files

| File | Purpose |
|---|---|
| [context.md](context.md) | What we build and why, scope decisions, product rules (the invariants) |
| [research.md](research.md) | Codebase map: mode derivation and its consumers, the chat working copy and its adapter, sync state, reusable UI |
| [plan.md](plan.md) | The PR stack with tasks and test strategy |
| [status.md](status.md) | Progress, decisions, next steps. Read this first in a new session |

## TL;DR

- `is_chat` does two jobs today: it says the app accepts a messages input
  (a capability) and it picks the playground UI (a behavior). We split
  them. The behavior becomes a playground-level override atom, persisted
  per app, never versioned. Scope: chat apps only, so every run stays an
  ordinary chat request and the backend never changes.
- The conversation already lives in the test case row's `messages` column;
  a bidirectional adapter keeps it in sync with the chat UI in real time.
  We reuse that column as the frozen history. No new `history` column.
- Chat → completion: move the last assistant reply from `messages` into
  the row's result slot; runs then regenerate that reply per row.
  Completion → chat: `messages` plus the latest result become the
  conversation again (picker when several rows are loaded; tabs come in a
  later PR).
- A sync gate blocks switching while test cases have unsynced changes
  (with a quiet "Switch without syncing" escape hatch). The toggle is
  disabled in compare mode and stays behind a flag until both directions
  work (end of PR3).

---

### Design Playground Shortcut Discoverability README (`docs/design/playground-shortcut-discoverability/README.md`)

# Playground shortcut discoverability

The agent playground binds forty-three keyboard shortcuts across six files. Six of them name a
key on screen. The rest are unreachable unless you read the source.

This project gives every shortcut a place where a user can find it, adds two that were missing,
and moves three Alt letters off keys that browsers claim on Windows and Linux.

## The files here

| File                         | What it holds                                                        |
| ---------------------------- | -------------------------------------------------------------------- |
| [context.md](context.md)     | What shipped before this project, and what the user asked for        |
| [research.md](research.md)   | The full inventory, the browser key conflicts, and what Linear does  |
| [decisions.md](decisions.md) | **Why each key is what it is. Read this before changing a binding.** |
| [plan.md](plan.md)           | The slices and their acceptance checks                               |
| [status.md](status.md)       | What is done, what is left                                           |

## The short version

- One registry, `web/packages/agenta-shared/src/utils/shortcuts.ts`, owns every binding's keys
  and label. Tooltips, keycaps and the shortcuts sheet all read it, so a label can never drift
  away from the handler.
- Keys appear on the control that already does the job: a tooltip, or a keycap on the button.
- The eleven shortcuts that answer no control live in a sheet, opened with `?` or from a
  keyboard button at the right edge of the playground top bar.
- The Alt letters avoid every browser menu key. A unit test fails if one is ever bound again.

---

### Design Playwright Oss Stabilization README (`docs/design/playwright-oss-stabilization/README.md`)

# Playwright OSS Stabilization

Tracks the stabilization of frontend Playwright tests for OSS deployed environments and their integration into CI.

## Current State

The branch improves the OSS Playwright harness, but the suite is not fully stabilized yet.

- The two reviewed harness regressions are now fixed on this branch: Playground now starts its response wait before clicking Run, and cached-auth setup now recreates the ephemeral project with stored auth.
- Several specs are still skipped or conditionally skipped, so the suite should not be described as "10 pass, 2 skip" right now.
- The latest CI run on this branch reported `5 passed`, `4 skipped`, `1 failed`, and `2 flaky`.
- The design docs in this folder track the real pass/skip state instead of the earlier optimistic claim.

## Files

- `context.md` - Problem statement, what was done, goals, and constraints.
- `research.md` - Test architecture, suite inventory, and key patterns discovered.
- `plan.md` - Execution phases and next steps.
- `status.md` - Test results, how to run, known issues, and key patterns.
- `qa.md` - QA profile, environment contract, and coverage map.
- `backlog.md` - Remaining work items (P1/P2).

## Quick Links

- OSS acceptance specs: `web/oss/tests/playwright/acceptance/`
- BDD feature specs: `web/oss/tests/playwright/acceptance/features/`
- Playwright config: `web/tests/playwright.config.ts`
- Run instructions: see `status.md`

---

### Design Preview Route Normalization README (`docs/design/preview-route-normalization/README.md`)

# Preview Route Normalization

This workspace tracks the plan to keep legacy `/*` endpoints working while introducing canonical non-preview mounts and exposing only canonical paths in OpenAPI.

## Prompt

Create a migration plan for preview route cleanup, identify which routes are safe vs open risk, and track migration status for frontend and SDK consumers.

## Documents

- `context.md` - Why this change exists, goals, and constraints.
- `research.md` - Current route inventory, usage findings, and risk notes.
- `route-matrix.md` - Per-route safety and migration status (API + frontend + SDK).
- `plan.md` - Phased rollout plan with exit criteria.
- `status.md` - Current execution status, decisions, and next actions.

## Current headline

- Feasible approach: dual-mount routes, hide preview mounts from schema (`include_in_schema=False`), then migrate clients.
- Most domains are safe to add now.
- `environments` remains open/risky due existing legacy `/environments` router also mounted.

---

### Design Prompt Runtime Unification README (`docs/design/prompt-runtime-unification/README.md`)

# RFC: Prompt Variables, JSON Values, and LLM Runtime Unification

## Context

Agenta runs several LLM-backed services that share most of their lifecycle but were built separately:

- Completion prompts.
- Chat prompts.
- LLM-as-a-judge evaluators.
- Future agent-style services.

Each can be invoked from multiple surfaces — direct API, SDK (including local evaluation workflows), the normal playground, the evaluator playground, and the evaluation service jobs that run app and evaluator revisions over stored testsets.

The same conceptual operation appears in all of them: take structured inputs, expose variables to a prompt, render message templates, resolve provider/model settings, call an LLM, and normalize outputs. Today those steps differ enough that users and developers cannot rely on one consistent mental model.

## Problem Statement

Users need a consistent answer to these questions:

- What variables can I use in a prompt?
- Are variables strings, JSON objects, arrays, or messages?
- If a testset cell contains JSON, can I access nested fields?
- Which template formats are supported, and how do I escape special characters?
- Why does the same variable behave differently in completion, chat, evaluator playground, and evaluation runs?
- Why can chat/completion use some configured models while LLM-as-a-judge cannot?

The current system makes those answers difficult because runtime behavior and frontend transport behavior are not fully aligned.

## Current State

### Runtime services

**Chat and completion** share the same prompt runtime.

- Config lives under `parameters.prompt`: `messages`, `template_format`, `input_keys`, and `llm_config`.
- Rendering goes through `PromptTemplate.format(**inputs)` in `sdk/agenta/sdk/utils/types.py`, which supports `curly`, `fstring`, and `jinja2`.
- Completion exposes top-level `inputs` keys as variables. Chat exposes the same keys except `messages`, which is appended as typed messages after rendering (not exposed as a template variable).

**LLM-as-a-judge** is close in behavior but uses a separate runtime path.

- Config is a flat evaluator shape: `prompt_template`, `model`, `response_type`, `json_schema`, `correct_answer_key`, `threshold`, `version`, optional `template_format`.
- Renders messages through `_format_with_template` in `sdk/agenta/sdk/engines/running/handlers.py`. It supports the same three formats as `PromptTemplate.format`; the default depends on evaluator `version` — `fstring` for v2, `curly` for v3+.
- Render context combines the testcase row, app outputs, ground-truth aliases, trace, and evaluator parameters. See [Variable Matrix](#variable-matrix) for the full list with types and availability.

### Runtime gaps

All three services should share the same building blocks but currently don't:

- **Provider/model resolution.** Chat and completion use workflow provider settings; the judge manually extracts a fixed provider-key set and therefore cannot reliably use custom or self-hosted models configured in the UI.
- **Rendering.** The services now share more renderer infrastructure than before, but they still differ in configuration shape and runtime entrypoint. Chat and completion render from `parameters.prompt`, while the judge still uses its flat evaluator config and separate handler path.
- **Config.** The judge does not allow configuring `temperature`. It currently sends a hard-coded `temperature=0.01`, which some models reject as an unsupported optional parameter.
- **Output.** Completion, chat, and judge return different output shapes. Shared runtime code should stop before handler-specific output normalization.

### Invocation surfaces

**Direct API and SDK calls.** The caller sends `data.inputs` as JSON; the runtime receives native JSON values. For chat, `messages` arrives as a typed message list.

**Evaluation service.**

- For chat / completion, `parse_legacy_inputs(...)` selects configured `input_keys` from `testcase.data` (or copies the row), preserving native objects and arrays. For chat, it reads `messages` or `chat`; native lists are preserved and string values are parsed as message JSON only for that special field.
- For evaluator invocation, the request sends `inputs=testcase.data`, `outputs=...`, `trace=...`, so evaluator runs already receive native testcase JSON.

**Normal playground.**

- Completion path: testcase values can start as native JSON in the UI state, but request construction stringifies object and array values before invoking the runtime. As a result, whole-value insertion (`{{profile}}`) appears to work; nested access (`{{profile.name}}`) breaks.
- Chat path: chat history is normalized into typed `messages`, but other variables follow the same stringifying input construction.

**Evaluator playground.** Combines testcase data, upstream app output, traces, evaluator settings, and evaluator input schema. Like the normal playground, it stringifies object and array testcase values via `normalizeCompact` in `web/packages/agenta-entities/src/runnable/utils.ts`; the inputs reach the evaluator runtime as JSON-encoded strings rather than native objects. Types in play: testcase columns (any JSON), `prediction` / upstream output (any JSON, currently sent as a string), evaluator parameters (object).

### Playground transport

The playground discovers variables from prompt templates and configuration, then builds input rows from testcase data or manual entry. It also extracts variables from response formats and tools in some prompt configurations.

The problematic part is execution payload construction:

- For completion, object and array testcase values are converted to strings before being sent.
- For chat, `messages` is normalized as chat history, while non-message variables follow the same stringifying input construction path.
- The evaluator playground does the same.
- Testcase editing already has utilities to detect object, array, string, boolean, number, null, and messages — but that type information is not consistently preserved through execution.

The basic rule should be: **native JSON stays native until template rendering.**

Transport should preserve type. Rendering should decide how a value becomes text. A JSON object should be sent as an object, not as a JSON-encoded string. If a user stores JSON text in a string field, it should remain a string.

In the playground, this means:

- Send testcase data as-is when it is JSON in the testset.
- Allow the user to switch between data types (string ↔ JSON) explicitly.

Today the UI can display JSON, the evaluation service preserves JSON, but normal playground execution may still send that JSON as a string. This RFC closes that gap.

Example.

```json
{"profile": {"name": "Ada"}}
```

`profile` is a JSON object. The runtime can access `{{profile.name}}`, `{{$.profile.tags[0]}}`, or `{{profile}}` (renders as compact JSON text).

```json
{"profile": "{\"name\":\"Ada\"}"}
```

`profile` is a string whose text happens to contain JSON. The runtime treats it as a string. It does not silently parse the value — that would make strings ambiguous and break users who intentionally store JSON text.

## Solution Requirements

### 1. Preserve native value types

- Playground execution must preserve native JSON objects and arrays when the stored testcase value is an object or array.

### 2. Make field types visible and editable

- Show the field type wherever testcase or trace values are edited or inspected: `string`, `object`, `array`, `number`, `boolean`, `null`, `messages`.
- Use the same type-display pattern in the playground, testset views, and observability views.
- Allow users to create and edit JSON object/array variables directly in the playground.
- Allow users to intentionally convert a field between string and JSON.
- Preserve the selected type when saving or invoking.

### 3. Template rendering semantics

Three substitution formats plus one full templating engine:

- **`mustache`** — Mustache rendering for new apps. **The default for new apps.** Tags that start with `{{$` are resolved as JSONPath expressions against the render context and substituted into the rendered output last, as inert data (never re-parsed) — they are shielded from the Mustache engine, not fed back through it. Ordinary Mustache behavior handles plain tags such as `{{name}}`, dotted names such as `{{profile.name}}`, and standard Mustache sections. Partials are not supported in Agenta runtime and must fail clearly if present. JSON objects and arrays render as compact JSON text when inserted as whole values into a string template.

- **`curly`** — `{{variable}}` substitution. **Deprecated.** Same syntax as `mustache`, but the resolver applies literal-key-first lookup: if a top-level key is literally named `foo.bar`, `{{foo.bar}}` returns that key's value before nested traversal is attempted. This is what keeps old apps that have variables with literal dots in their names working. Not surfaced in the playground for new apps; existing apps keep their declared format.

- **`fstring`** — `{variable}` substitution. Backward compatibility only. Not recommended for nested JSON because of brace-escaping conflicts. Not extended.

- **`jinja2`** — full sandboxed Jinja2. The format to pick when conditionals, loops, filters, or other logic are required.

### 4. Variable by service

- Provide a variable matrix for each service and invocation surface (see [Variable Matrix](#variable-matrix) below).
- Document variable name, type, source, and when the variable is available.
- Add tests for the render context each service exposes.

### 5. Align model and provider resolution

- LLM-as-a-judge must resolve provider settings using the same path as chat/completion.
- LLM-as-a-judge must support custom/self-hosted models configured in the UI.
- LLM-as-a-judge must not inject unsupported optional parameters such as `temperature`.
- The existing judge flat config and output shape must remain compatible.

### 6. Playground UX

- Field type is visible: string, JSON object, JSON array, number, boolean, null, messages.
- Users can edit JSON values without losing their type.
- Users can intentionally convert a field between string and JSON.
- The variables panel (right side of the playground) shows:
  - variables discovered from the prompt
  - variables available from the current testcase or trace context, labeled with source and type
- The prompt editor provides autocomplete for available variables — top-level only, no nesting.

### 7. Documentation

The shipped documentation must include:

- Template formats with examples.
- Escaping rules for literal braces and special characters in each format.
- JSON vs. stringified JSON examples.
- Variable availability by service.
- SDK examples for local usage of completion, chat, and LLM-as-a-judge.
- Evaluation service examples showing app invocation and evaluator invocation.

## Variable Matrix

What variables are exposed to prompt rendering, by service. Surface availability is described after the per-service lists.

### Completion

| Variable | Type | Source |
|---|---|---|
| top-level keys from `data.inputs` | any JSON | the request payload |

No special variables. Whatever keys the caller puts into `inputs` become available to the prompt template, with their native types.

### Chat

| Variable | Type | Source |
|---|---|---|
| top-level keys from `data.inputs` (excluding `messages`) | any JSON | the request payload |
| `messages` | message list | the request payload, typed special field |

`messages` is **not** a regular template variable. It is removed from the render context, then appended as chat history after the prompt template renders. The evaluation service preserves native message-list values; for legacy rows that store a JSON-encoded string, it parses the string into a list — that is the only place the system converts string-encoded messages to a list.

### LLM-as-a-judge

| Variable | Type | Source |
|---|---|---|
| `inputs` | object | dict spread into the render context; source depends on interface (see below) |
| top-level testcase / trace-input keys | any JSON | spread from `inputs` |
| `outputs` / `prediction` | any JSON | upstream app output (offline) or trace output (online) |
| `ground_truth` / `correct_answer` / `reference` | any JSON | resolved as `inputs[correct_answer_key]` at runtime |
| `trace` | dict | the full trace, dumped via `trace.model_dump(mode="json")` |
| `parameters` | object | evaluator configuration |

Notes on the judge variables:

- **`inputs`** — In **offline evaluation**, `inputs` is the testcase row (`testcase.data` is passed directly to the handler, including any columns that aren't declared as evaluator inputs — ground-truth column, metadata, etc.). In **online evaluation**, there is no stored testcase row, so `inputs` is sourced from the trace's recorded inputs (the root span's `ag.data.inputs`). The handler treats both paths the same way once `inputs` is built: it spreads top-level keys into the render context, so `{{question}}` and `{{inputs.question}}` both work. Native JSON values are preserved through the spread — `{{profile.name}}` and `{{tags.0}}` resolve against the native dict / list, with stringification happening only at the final substitution into the rendered text.

- **`outputs` / `prediction`** — Populated when an upstream app result is available. Offline: the output of the upstream app run over the testcase. Online: sourced from the trace's recorded outputs. Same native-JSON handling as `inputs`.

- **`ground_truth` / `correct_answer` / `reference`** — `correct_answer_key` is still part of the evaluator parameters (default: `"correct_answer"`); the runtime reads it from `parameters` and resolves the value as `inputs[correct_answer_key]`. The aliases are populated only when that key resolves — in practice, offline evaluation where the testset includes the configured ground-truth column. Not typically populated in online evaluation, since traces don't carry ground-truth columns.

- **`trace`** — A plain dict (the result of `trace.model_dump(mode="json")` on the trace passed in by the evaluation service). Prompt authors can dot-traverse it; the structure follows the trace schema (root span, spans, attributes including `ag.data.*` and `ag.meta.*`). Populated when the judge runs in a context that produced a trace — primarily online evaluation.

- **`parameters`** — The evaluator's own configuration object. Useful when a prompt needs to reference its own settings (rare).

### Variable population by interface

#### Direct API / SDK

All variables come from the request payload — caller decides what's there. Native JSON values arrive intact.

#### Evaluator playground

- `inputs`: from the testcase row.
- `outputs` / `prediction`: from the chained app run, when present.
- `ground_truth`: from `inputs[correct_answer_key]` when configured and the column is present.
- `trace`: from the chained app run, when present.

The evaluator playground currently stringifies object and array values before transport via `normalizeCompact` in `web/packages/agenta-entities/src/runnable/utils.ts`. Same fix as WP2 needs to apply here so JSON arrives native.

#### Evaluation service — offline (testset-driven)

Reference: `api/oss/src/core/evaluations/tasks/legacy.py`.

- `inputs`: `testcase.data`, the full testset row. Includes any columns that aren't declared as evaluator inputs (ground-truth column, metadata, etc.).
- `outputs` / `prediction`: from the upstream app run over the testcase.
- `ground_truth`: from `inputs[correct_answer_key]` when configured and the column is present.
- `trace`: from the upstream app run, when produced. Usually not central to offline judge prompts.

Native JSON preserved end to end (this is the reference behavior the playground paths should match).

#### Evaluation service — online (trace-driven)

Reference: `api/oss/src/core/evaluations/tasks/live.py`.

- No stored testcase row exists. `inputs` is taken from the trace's recorded inputs (`root_span_attributes_ag_data.get("inputs")`).
- `outputs` / `prediction`: from the trace's recorded outputs.
- `ground_truth`: typically not present — traces don't carry ground-truth columns.
- `trace`: the trace itself.

## Work Packages

The work falls into three layers: backend service alignment, frontend UX, documentation. Within each layer the order matters because later packages build on earlier ones.

### Backend

#### WP-B1 — Secret handling and low-level rendering helper

- Patch `auto_ai_critique_v0` to use the shared provider/secret resolution path. Custom and self-hosted models configured in the UI become available to the judge.
- Stop sending hard-coded `temperature=0.01` from the judge LLM call.
- Extract a low-level rendering helper with signature roughly `(template_string, mode, context) -> rendered_string`. Pure, unit-testable, no service knowledge. The substitution modes (`mustache`, `curly`, `fstring`) and `jinja2` all funnel through it.

#### WP-B2 — Message and JSON-return rendering on top of the helper

Builds on WP-B1.

- Build a message renderer on top of the low-level helper, used by completion, chat, and judge.
- Build a JSON-return renderer on top of the low-level helper. It renders variables inside `response_format` (chat/completion) and `json_schema` (judge) the same way. The judge's `json_schema` is no longer a special case.
- Align Jinja error behavior on **raise** across all services. The judge's silent-return-on-error is removed.
- Keep handler-specific output parsing in the handlers (judge keeps its output normalization).

#### WP-B3 — Add `mustache` template format

Builds on WP-B1.

- Add `mustache` as a new template-format option in the runtime. Semantics: tags that start with `{{$` are resolved as JSONPath expressions and substituted as inert data after rendering (never re-parsed); all other tags render through a Mustache engine. Partials are unsupported and fail clearly.
- `mustache` becomes the default rendering format for newly created apps / prompt configs. Existing apps continue to use the format they declared.
- See [appendix-rendering-edge-cases.md](appendix-rendering-edge-cases.md) for the current escape behavior of every mode.

### Frontend

#### WP-F1 — JSON ↔ string switching, applied everywhere

The same UX pattern lives in playground inputs, the testset editor, observability/trace views, and evaluation result views.

- Type indicator next to each value: `string`, `object`, `array`, `number`, `boolean`, `null`, `messages`.
- Convert action between `string` and `JSON`. The user's choice is preserved.
- The selected type round-trips through save/load and through invocation.

#### WP-F2 — Playground execution with native JSON and dotless variable handling

Depends on WP-B3 (`mustache` available) and WP-F1 (type switching available).

- Send testcase data as native JSON when the stored type is JSON. No `JSON.stringify` in request construction.
- In `mustache` mode, `{{$.a.b}}` is the explicit JSONPath escape hatch. Plain Mustache tags such as `{{a}}` or `{{profile.name}}` follow ordinary Mustache rendering behavior. The playground's variable discovery for nested JSON is still a frontend concern.
- The frontend honors the WP-B3 `mustache` default and hides `curly` from the format list unless the current old app already has `curly` selected. Existing apps still on `curly` continue to work — the literal-key-first behavior is preserved for them.

#### WP-F3 — Variable discovery (autocomplete)

A nicety on top of WP-F2.

- Autocomplete in the prompt editor surfaces top-level variables only — no nesting. Combines variables referenced in the prompt template with variables available from the testcase, trace, or evaluator context, labeled with source and type.
- The variables panel (right side of the playground) shows the same set, plus expandable nested fields.

### Documentation

#### WP-D1 — Documentation and SDK examples

- Publish prompt templating docs covering `mustache` (default for new apps), `curly` (legacy compat), `fstring`, and `jinja2`. Spell out the JSONPath shield-and-substitute rule for `mustache` and the literal-key-first distinction of `curly`.
- Publish the variable matrix by service and interface.
- Add SDK / local examples for completion, chat, and LLM-as-a-judge.
- Document escaping rules, JSON vs. stringified JSON, and JSONPath. Document JSON Pointer only for legacy `curly` semantics if it remains supported there.

Reference template examples:

```text
Hello {{name}}
Profile JSON: {{profile}}
Profile name: {{profile.name}}
First tag: {{$.profile.tags[0]}}
JSONPath: {{$.profile.name}}
```

Reference JSON-vs-stringified-JSON examples:

```json
{"profile": {"name": "Ada"}}
```

This is an object and supports nested lookup.

```json
{"profile": "{\"name\":\"Ada\"}"}
```

This is a string. It does not support nested lookup unless the user explicitly parses it elsewhere.

## Rollout Plan

The work packages have a natural order:

1. **WP-B1** unblocks judge model coverage and creates the rendering helper everything builds on.
2. **WP-B2** stands up message and JSON-return rendering on the helper, and aligns Jinja error behavior.
3. **WP-B3** adds `mustache` as a new format.
4. **WP-F1** lands the same JSON/string switching pattern in playground / testset / observability / evaluation.
5. **WP-F2** flips playground execution to send native JSON and hides `curly` from new-app format selection. Curly stays visible for legacy apps that already use it.
6. **WP-F3** adds autocomplete on top.
7. **WP-D1** publishes the templating docs, variable matrix, and SDK examples.

## Test Plan

### Backend runtime

- The low-level rendering helper keeps current `curly` behavior and adds `mustache` support.
- In `mustache` mode, only tags that start with `{{$` are resolved through JSONPath (shielded from the engine and substituted last as inert data); other tags render through the Mustache engine.
- `curly` preserves literal-key-first behavior on dotted keys.
- Whole-object insertion renders as compact JSON text in both modes.
- `fstring` and `jinja2` behavior is preserved.
- Stringified JSON inputs are treated as strings (no auto-parse).
- Chat removes `messages` from template inputs and appends them as chat history.
- LLM-as-a-judge exposes the variables in the variable matrix.
- LLM-as-a-judge resolves custom provider settings via the shared resolver.
- LLM-as-a-judge does not send `temperature` in the LLM call.
- Variables inside `json_schema` (judge) and `response_format` (chat/completion) render via the shared renderer.
- Jinja errors raise consistently across all services.

### Frontend

- Playground completion request body preserves object testcase fields.
- Playground completion request body preserves array testcase fields.
- Playground keeps string testcase fields as strings, even if their text contains JSON.
- Chat request body sends `messages` as an array of message objects.
- Evaluator playground sends testcase `inputs` as an object and upstream output as `outputs` / `prediction`.
- New apps default to `mustache`; existing apps keep their declared `template_format`.
- In `mustache` mode, a prompt containing `{{a.b}}` causes the playground to discover one variable `a` of type object.
- Type switch (string ↔ JSON) round-trips through save/load and through invocation, in playground / testset / observability / evaluation views.

### Evaluation service

- `parse_legacy_inputs(...)` preserves object and array testcase values.
- Chat evaluation parses stringified `messages` for legacy rows.
- Evaluator workflow request uses `testcase.data` as `inputs`.

### Documentation

- Examples cover string, JSON object, array, JSONPath, Mustache dotted names, messages, and brace escaping in each format.
- Variable matrix covers completion, chat, judge, and the four interfaces (Direct API/SDK, evaluator playground, evaluation service offline, evaluation service online).

## Future Directions

Sketches for follow-up work. None of this is part of the present RFC.

### Sharing the prompt template across services

Today, chat and completion store their prompt config under `parameters.prompt`. The judge has a flat config with `prompt_template`, `model`, `response_type`, `json_schema`, `correct_answer_key`, `threshold`, `version`. The follow-up is to give the judge a `prompt` field with the same shape as chat/completion (messages, template format, input keys, llm_config), and keep judge-specific fields alongside it — rather than try to invent one structure that fits every service.

```yaml
# chat / completion
prompt:
  messages: [...]
  template_format: mustache | curly | fstring | jinja2
  input_keys: [...]
  llm_config:
    model: ...
    response_format: ...

# judge — same prompt block, plus judge-specific fields alongside it
prompt:
  messages: [...]
  template_format: ...
  input_keys: [...]
  llm_config:
    model: ...
    response_format: ...   # absorbs response_type + json_schema
correct_answer_key: ...
threshold: ...
version: ...
```

Notes:

- Open question: `response_type` and `json_schema` in today's judge config describe the same thing chat/completion's `response_format` does — the response shape. The unification collapses them into a single `response_format` (e.g. `{type: "json_schema", json_schema: ...}`).
- Open question: A migration adapter at the API boundary translates legacy judge flat config into the unified shape. The old shape stays valid until usage drops to zero, then is deprecated.

## Implementation tracking

Each work package gets its own subfolder with research, plan, implementation notes, QA, and status:

- [`wp-b1-runtime-foundation/`](wp-b1-runtime-foundation/README.md) — judge backend patch (provider/secret resolution + temperature removal) and the low-level rendering helper extraction.
- [`wp-b2-rendering-unification/`](wp-b2-rendering-unification/README.md) - shared message rendering, JSON-return rendering, judge `json_schema` rendering, and Jinja error alignment.
- [`wp-b3-mustache-rendering/`](wp-b3-mustache-rendering/README.md) - `mustache` runtime format, `{{$...}}` JSONPath shield-and-substitute resolution, `mystace` rendering, and clear partial failures.

Subfolders for the remaining work packages will be added as each is picked up.

## Appendices

- [`appendix-rendering-edge-cases.md`](appendix-rendering-edge-cases.md) — operational reference for special characters, escape sequences, ambiguous placeholders, and the template/value boundary across all four modes (`curly`, `fstring`, `jinja2`, `mustache`).

---

### Design Provider Connections Models README (`docs/design/provider-connections-models/README.md`)

# Provider connections and model lists

> AGENT-GENERATED, low weight. This is a draft. Mahmoud must approve product and interface decisions.

This folder plans how Agenta can treat standard provider keys and custom providers as provider
connections with the same optional model and harness settings. The user-facing surface is called
"AI providers" everywhere. The founder reviewed the first draft on pull request 5987 on
2026-08-12; this revision addresses every review comment, and [status.md](status.md) records
which decisions the review resolved.

A provider connection is one configured way to reach a model provider. It has an identity,
credentials, optional endpoint settings, models shown to users, and compatible harnesses. A harness
is the program that communicates with a model and uses tools, such as Pi, Codex, or Claude Code.

Subscription status is separate. It is runtime state detected by the runner and is planned under
`../runner-subscription-status/`. A later frontend can display subscriptions and stored provider
connections in one menu without storing them as the same object.

## Reading order

1. [context.md](context.md) explains the user experience, goal, and scope.
2. [experience.md](experience.md) records the founder-provided interface design. The clickable
   prototype [`model-providers-ux-prototype.html`](model-providers-ux-prototype.html) sits beside
   it.
3. [research.md](research.md) explains the current data and code constraints.
4. [provider-discovery.md](provider-discovery.md) separates credential testing, model refresh, and
   default models.
5. [data-model.md](data-model.md) defines the compatibility-first connection shape.
6. [plan.md](plan.md) splits the work into four dependent pull requests, ending with the wiring of
   prompts, completion, chat, and LLM-as-a-judge.
7. [status.md](status.md) records resolved decisions, decisions taken for review, and open
   decisions.

---

### Design Railway Gateway Header Buffers README (`docs/design/railway-gateway-header-buffers/README.md`)

# Railway Gateway Header Buffers

This workspace tracks the fix for Railway preview and test failures caused by the gateway returning `upstream sent too big header while reading response header from upstream` during auth session refresh.

Files:
- `context.md` - background, problem statement, goals, and non-goals
- `research.md` - findings from code and workflow inspection
- `plan.md` - execution plan for the fix and verification
- `status.md` - current progress, decisions, and follow-ups

---

### Design Railway Preview Environments README (`docs/design/railway-preview-environments/README.md`)

# Railway Preview Environments

Create a fully programmatic Railway deployment workflow for Agenta, starting with OSS baseline deployment and evolving to per-PR preview environments.

## User Request

"Create a plan for this how to do it. The goal is to reach the point where we can have preview environments using railways, but maybe the first step is to deploy oss version programmatically."

## Scope

- Phase 1: programmatic OSS deployment on Railway (no manual UI configuration after token setup)
- Phase 2: harden CI/CD and config-as-code
- Phase 3: automated per-PR preview environments (create/update/delete lifecycle)

## Files

- **[context.md](./context.md)** - Problem statement, goals, non-goals, constraints
- **[research.md](./research.md)** - Findings from Agenta and Railway docs/codebase
- **[plan.md](./plan.md)** - Execution phases, milestones, and deliverables
- **[status.md](./status.md)** - Current progress, decisions, and next actions
- **[qa.md](./qa.md)** - Validation strategy and smoke checks for each phase
- **[deployment-notes.md](./deployment-notes.md)** - What we changed on Railway, why we changed it, and how to operate upgrades

## Quick References

- Agenta compose baseline: `hosting/docker-compose/oss/docker-compose.gh.yml`
- Agenta env template: `hosting/docker-compose/oss/env.oss.gh.example`
- API root path: `api/entrypoints/routers.py:174`
- API CORS defaults: `api/entrypoints/routers.py:192`
- Services health endpoint: `services/entrypoints/main.py:20`
- Railway CLI docs: project/service/environment/variable/volume/domain/deployment

---

### Design Registry Commit Fix README (`docs/design/registry-commit-fix/README.md`)

# Registry Commit Fix

**Problem:** Committing a new revision from the registry page fails after a hard refresh with `"badly formed hexadecimal UUID string"`. The frontend incorrectly routes the commit through the legacy `PUT /variants/{variantId}/parameters` endpoint instead of the workflow `POST /workflows/revisions/commit` endpoint.

**Scope:** Frontend only. Make the registry commit flow always use the workflow commit path.

The current implementation plan is intentionally narrow: fix the commit path now, and treat create/delete as separate follow-ups unless we reproduce the same cold-refresh bug there.

## Files

- `context.md` — Background, root cause analysis, the two bugs
- `plan.md` — Step-by-step execution plan
- `research.md` — Code paths, data flow, key file references
- `status.md` — Progress tracker

---

### Design Revision Query Grouping README (`docs/design/revision-query-grouping/README.md`)

# Per-parent grouping on revision queries

This folder defines one change to the Agenta API. The change lets a caller group
revisions by parent and explicitly get the latest revision from every group.

## Reading order

| File | Question it answers |
| --- | --- |
| `context.md` | What breaks today, and why we want to change it. |
| `research.md` | What the code does now, with measurements. |
| `api-design.md` | The interface we propose, and the shapes we rejected. |
| `plan.md` | What to build, in what order. |
| `status.md` | Where the work stands, and what is still open. |

## Words used in this folder

- **artifact**: the parent entity that owns a line of history. A workflow, a testset, an
  evaluator, an environment, an application, or a query.
- **variant**: a branch of an artifact.
- **revision**: one committed version of a variant. An artifact has many revisions.
- **git DAO**: the shared database layer at `api/oss/src/dbs/postgres/git/dao.py`. Six
  entity families store their artifacts, variants, and revisions through it.
- **windowing**: the shared request object that says which slice of an ordered result to
  return. It carries a time range, a cursor, a limit, and a sort order.
- **event loop**: the single thread inside each API worker that serves every request on
  that worker. Work that does not yield blocks every other request on the same worker.

---

### Design Runnables README (`docs/design/runnables/README.md`)

# Runnables (Workflows) — Initial Exploration

> Status: exploration / audit
> Date: 2026-03-05

> Note: this document is the exploration snapshot. The current target design is defined by
> [plan.md](./plan.md),
> [gap-analysis.md](./gap-analysis.md),
> [simple-traces-unification.md](./simple-traces-unification.md),
> [runnables-system-layer.md](./runnables-system-layer.md),
> [runnables-subsystem-layer.md](./runnables-subsystem-layer.md),
> [runnables-component-layer.md](./runnables-component-layer.md),
> and [runnables-function-layer.md](./runnables-function-layer.md).
> Where this document records earlier hypotheses or only the current-state code, the newer layer docs win.
> The canonical discovery contract is: persisted revision/query truth first, `/inspect` only when no local revision truth exists yet or explicit live discovery is needed.

## Companion Documents

- [gap-analysis.md](./gap-analysis.md)
- [gap.migrations.md](./gap.migrations.md)
- [gap.catalog.md](./gap.catalog.md)
- [plan.md](./plan.md)
- [design-review.md](./design-review.md)
- [simple-traces-unification.md](./simple-traces-unification.md)
- [taxonomy.md](./taxonomy.md)
- [runnables-system-layer.md](./runnables-system-layer.md)
- [runnables-subsystem-layer.md](./runnables-subsystem-layer.md)
- [runnables-component-layer.md](./runnables-component-layer.md)
- [runnables-function-layer.md](./runnables-function-layer.md)

## 1. Conceptual Model

A **runnable** is a black box with:

- A **predefined interface** — input schema, output schema, parameter schema
- **Predefined expectations about its runtime** — capability flags, execution mode
- **Side-effects** — primarily tracing

In the backend the term used is **workflow**. The SDK exposes `workflow`, `application`, and `evaluator` as decorator classes that all share the same underlying `workflow` machinery.

### 1.1 Hierarchy

```
workflow (base)
├── application   (is_evaluator=False)
└── evaluator     (is_evaluator=True)
```

Both `application` and `evaluator` are thin subclasses that preset flags and reference namespaces. See `sdk/agenta/sdk/decorators/running.py:563-706`.

---

## 2. Two Parallel Systems

There are **two coexisting systems** for serving workflows over HTTP. They share some types but have distinct execution paths.

### 2.1 Legacy Serving System (`serving.py`)

**File:** `sdk/agenta/sdk/decorators/serving.py`

Uses the `@ag.route()` / `@ag.entrypoint` decorators. Creates FastAPI endpoints directly:

| Endpoint | Purpose |
|----------|---------|
| `POST {prefix}/run` | Deployed invoke (config from API) |
| `POST {prefix}/test` | Playground invoke (inline config) |
| `POST {prefix}/generate` | Legacy alias for `/test` |
| `POST {prefix}/generate_deployed` | Legacy alias for `/run` |
| `GET {prefix}/openapi.json` | OpenAPI spec with `x-agenta` extensions |
| `GET {prefix}/health` | Health check |

**Key characteristics:**
- Function signature IS the schema (parameters extracted from Python signature)
- Config schema derived from Pydantic model passed to `config_schema=`
- Middleware stack: CORS -> OTel -> Auth -> Config -> Vault -> Inline -> Mock
- Flags exposed in OpenAPI via `x-agenta.flags` extension on each path operation (`serving.py:904-935`)
- Streaming support: detects `AsyncGenerator`/`Generator` return types and returns SSE

### 2.2 New Running System (`running.py` + `routing.py`)

**Files:**
- `sdk/agenta/sdk/decorators/running.py` — core workflow/invoke/inspect logic
- `sdk/agenta/sdk/decorators/routing.py` — HTTP endpoint creation

Uses `@ag.workflow()` / `@ag.application()` / `@ag.evaluator()` decorator classes for the core logic, plus `route` from `routing.py` for HTTP exposure:

| Layer | Method | Signature |
|-------|--------|-----------|
| Programmatic | `invoke(request=...)` | `WorkflowServiceRequest` -> `WorkflowServiceBatchResponse \| WorkflowServiceStreamResponse` |
| Programmatic | `inspect()` | `() -> WorkflowServiceRequest` |
| HTTP | `POST {path}/invoke` | JSON body as `WorkflowServiceRequest` -> JSON or NDJSON/SSE stream |
| HTTP | `POST {path}/inspect` | -> `WorkflowServiceRequest` as JSON |

**HTTP routing details** (`routing.py`):
- `route` class creates a FastAPI app with middleware: CORS -> Vault -> Auth -> OTel
- Stream format negotiation: checks `Accept` header for `text/event-stream` (SSE) vs default (NDJSON)
- Response headers: `x-ag-version`, `x-ag-trace-id`, `x-ag-span-id`
- Error handling: domain `ErrorStatus` -> `WorkflowServiceStatus` with type URL, code, stacktrace

**Key characteristics:**
- Schema comes from `WorkflowServiceInterface.schemas` (explicit JSON Schema)
- Handler registered in `HANDLER_REGISTRY` by URI (`provider:kind:key:version`)
- Running middleware pipeline: Vault -> Resolver -> Normalizer
- Flags passed as `dict` in `WorkflowServiceRequest.flags`

### 2.3 How They Relate

| Aspect | Legacy (`serving.py`) | New (`running.py` + `routing.py`) |
|--------|----------------------|----------------------------------|
| HTTP endpoints | `/run`, `/test`, `/generate`, `/generate_deployed` | `{path}/invoke`, `{path}/inspect` |
| Schema source | Python function signature + Pydantic model | Explicit JSON Schema in `WorkflowServiceInterface` |
| OpenAPI discovery | Legacy `/openapi.json` with `x-agenta` extensions | Not in new system; use persisted revision/query truth first and `POST /inspect` as the live fallback |
| Streaming | Detected from return type | `WorkflowServiceStreamResponse` + Accept header negotiation (SSE/NDJSON) |
| Tracing | OTel middleware + `TracingContext` | `TracingContext` via context manager |
| Config resolution | Middleware chain (Config -> request.state) | Resolver middleware |
| Error model | HTTPException with detail dict | `WorkflowServiceStatus` with type URL, code, stacktrace |

---

## 3. Types & Contracts

### 3.1 Core Types (`sdk/agenta/sdk/models/workflows.py`)

```
/* Detailed source-code truncated for AI context efficiency. */
```

### 3.2 Domain Aliases

The SDK provides typed aliases to give domain-specific names:

| Base | Application Alias | Evaluator Alias |
|------|------------------|-----------------|
| `Workflow` | `Application` | `Evaluator` |
| `WorkflowVariant` | `ApplicationVariant` | — |
| `WorkflowRevision` | `ApplicationRevision` | `SimpleEvaluatorRevision` |
| `WorkflowRevisionData` | `ApplicationRevisionData` | `EvaluatorRevisionData` |
| `WorkflowFlags` | `ApplicationFlags` (is_evaluator=False) | `EvaluatorFlags` (is_evaluator=True) |
| `WorkflowServiceRequest` | `ApplicationServiceRequest` | `EvaluatorServiceRequest` |
| `WorkflowServiceBatchResponse` | `ApplicationServiceBatchResponse` | `EvaluatorServiceBatchResponse` |

### 3.3 Legacy Types (`sdk/agenta/sdk/types.py`)

Used by the legacy serving system:

- `BaseResponse` — wrapper with `data`, `trace_id`, `tree_id`
- `StreamResponse` — SSE streaming wrapper
- `FuncResponse` — `{message, usage, cost, latency}`
- `MessagesInput` — `List[Dict[str, str]]` (triggers `is_chat=True`)
- `TextParam`, `FloatParam`, `BinaryParam`, `MultipleChoiceParam` — typed config params

---

## 4. Handler Registry

**File:** `sdk/agenta/sdk/workflows/utils.py`

Handlers are registered by URI: `provider:kind:key:version`

```
HANDLER_REGISTRY[provider][kind][key][version] = callable
INTERFACE_REGISTRY[provider][kind][key][version] = WorkflowServiceInterface
CONFIGURATION_REGISTRY[provider][kind][key][version] = WorkflowServiceConfiguration
```

Builtin handlers (under `agenta:builtin:*:v0`):
- **Evaluators:** exact_match, regex_test, field_match_test, json_multi_field_match, webhook_test, custom_code_run, ai_critique, starts_with, ends_with, contains, contains_any, contains_all, contains_json, json_diff, levenshtein_distance, similarity_match, semantic_similarity
- **Applications:** echo, hook, completion, chat

Each builtin has a triple: handler function, interface definition (JSON Schemas), and default configuration.

Custom handlers are registered as `user:custom:{module}.{name}:latest`.

---

## 5. API Layer (Backend)

### 5.1 Workflow CRUD (`api/oss/src/apis/fastapi/workflows/`)

Standard Git-pattern CRUD. **Dual mounted** under both `/workflows` and `/workflows` (preview hidden from OpenAPI — migration seam):

**Workflow Management:**

| Method | Path | Purpose |
|--------|------|---------|
| POST | `/workflows/` | Create workflow |
| GET | `/workflows/{id}` | Fetch workflow |
| PUT | `/workflows/{id}` | Edit workflow |
| POST | `/workflows/{id}/archive` | Soft delete |
| POST | `/workflows/{id}/unarchive` | Restore |
| POST | `/workflows/query` | Filter/search workflows |

**Variants:** CRUD + fork under `/workflows/variants/`

**Revisions:** CRUD + commit/log under `/workflows/revisions/`

**Execution Services:**

| Method | Path | Purpose |
|--------|------|---------|
| POST | `/workflows/invoke` | Invoke a workflow (delegates to SDK `invoke_workflow`) |
| POST | `/workflows/inspect` | Inspect a workflow (delegates to SDK `inspect_workflow`) |

### 5.2 Service & DAO

- **Service:** `api/oss/src/core/workflows/service.py` — delegates to shared `GitDAO`
- **DTOs:** `api/oss/src/core/workflows/dtos.py` — `Workflow`, `WorkflowVariant`, `WorkflowRevision`
- **DBEs:** `api/oss/src/dbs/postgres/workflows/dbes.py` — `WorkflowArtifactDBE`, `WorkflowVariantDBE`, `WorkflowRevisionDBE` (has `data` JSONB)
- **DAO:** No dedicated DAO file — uses shared `GitDAO` from `api/oss/src/dbs/postgres/git/dao.py`, wired in `api/entrypoints/routers.py`

**Wiring in entrypoints** (`routers.py`):
- `WorkflowsService` is shared — injected into both `ApplicationsService` and `EvaluatorsService`
- These all reuse the same Git DAO with different DBE types

**Architectural implication for the migration plan:**
- workflows are the canonical runnable API family
- applications and evaluators are filtered workflow projections, not separate execution systems
- do not assume application/evaluator API router families get their own runnable invoke/inspect endpoints; runtime execution/discovery belongs to `/services`
- at the subsystem boundary, the target direction is for the API to act as a control plane and hand runnable execution/discovery toward runtime services rather than keeping execution inside the API container

### 5.3 Invoke & Inspect (New System)

The workflows router has **both invoke and inspect** endpoints:

This is the current implementation shape, not necessarily the target subsystem boundary.

**`POST /workflows/invoke`** (router.py lines 1114-1139):
```
Client -> WorkflowsRouter.invoke_workflow()
  -> WorkflowsService.invoke_workflow()
    -> sign_secret_token(user_id, project_id, workspace_id, org_id)
    -> SDK's invoke_workflow(request, credentials=f"Secret {token}")
      -> workflow().invoke(request, secrets, credentials)
        -> Vault -> Resolver -> Normalizer middleware chain
        -> execute handler
      -> WorkflowServiceBatchResponse or WorkflowServiceStreamResponse
    -> handle_invoke_success(req, response) -> JSON or SSE/NDJSON stream
```

**`POST /workflows/inspect`** (router.py lines 1143-1168):
```
Client -> WorkflowsRouter.inspect_workflow()
  -> WorkflowsService.inspect_workflow()
    -> SDK's inspect_workflow(request)
      -> workflow().inspect(credentials)
      -> resolve interface + configuration
      -> WorkflowServiceRequest with schemas populated
    -> handle_inspect_success(request) -> JSON
```

**EE permissions:** `RUN_WORKFLOWS` for invoke, `VIEW_WORKFLOWS` for inspect.

### 5.4 Legacy Invoke (Proxy Pattern)

The legacy invoke path (still active) goes through a different flow:

- `api/oss/src/core/invocations/service.py` — resolves variant -> deployment -> URL, makes HTTP call to SDK service
- Legacy: `api/oss/src/routers/app_router.py` — `POST /api/app/{app_id}/generate`

```
Client -> API (resolve variant -> deployment URL) -> SDK HTTP Service (/run or /test) -> execute handler -> response back
```

---

## 6. Capability Flags

### 6.1 Current State

| Flag | Defined In | Set By | Exposed Via |
|------|-----------|--------|-------------|
| `is_custom` | `WorkflowFlags` | SDK auto-detection (`is_user_custom_uri`) + `WorkflowDBE.is_custom` | Persisted in DB |
| `is_evaluator` | `WorkflowFlags` | `@ag.evaluator()` sets True, `@ag.application()` sets False | OpenAPI `x-agenta.flags`, `inspect()` |
| `is_feedback` | `WorkflowFlags` | Not set anywhere currently | — |
| `is_chat` | `WorkflowFlags` | `@ag.route(flags={"is_chat": True})` or auto-detect from `MessagesInput` | OpenAPI `x-agenta.flags`, `inspect()` |

### 6.2 How Flags Are Exposed

There are two different flag types in this migration discussion:

- `WorkflowFlags`: static workflow flags used for identity/capability discovery
- `WorkflowRequestFlags`: per-invocation flags carried on `WorkflowServiceRequest.flags`

**Legacy serving** (`serving.py:904-935`):
```json
// In OpenAPI spec, on each path operation:
{
  "post": {
    "x-agenta": {
      "flags": {
        "is_evaluator": true,
        "is_chat": false
      }
    }
  }
}
```

**New running** (`running.py:420-447`):
```python
# inspect() returns WorkflowServiceRequest which includes:
WorkflowServiceRequest(
    flags=self.flags,   # dict with is_evaluator, is_chat, etc.
    ...
)
```

### 6.3 Persistence & Adapter Layer

The API has its own `WorkflowFlags` in `api/oss/src/core/workflows/dtos.py` (mirrors SDK's), plus `WorkflowQueryFlags` with optional fields for filtering. Flags flow through the revision system into the DB via the `data` JSONB column on `WorkflowRevisionDBE`. The `WorkflowDBE` itself only has `is_custom` as a first-class column.

**Legacy adapter** (`api/oss/src/services/legacy_adapter.py`):
- `_template_key_to_flags()` — maps old template types to flags (e.g. `CHAT_SERVICE` -> `is_chat=True`, `SDK_CUSTOM` -> `is_custom=True`)
- `_flags_to_app_type()` — reverse mapping for backward compat

### 6.4 Frontend Flag Reading

**File:** `web/packages/agenta-entities/src/appRevision/api/schema.ts`

The frontend reads flags with a priority chain:
1. Read `x-agenta.flags.is_chat` from OpenAPI spec (explicit SDK flag)
2. Heuristic fallback: check if endpoint has a `messages` schema property

Result stored in `RevisionSchemaState.isChatVariant`, used to toggle chat vs completion UI.

### 6.5 Missing Flags

| Flag | Status | Description |
|------|--------|-------------|
| `can_stream` / `is_streaming` | Missing | Whether the workflow supports streaming output |
| `can_evaluate` | Missing | Whether the workflow can be used for evaluation at the product/API contract level |
| `can_chat` | Missing | Whether the workflow can also accept chat-style input when it is not chat-only |
| `can_verbose` | Missing | Whether the workflow can switch between concise and verbose response modes |

### 6.6 Missing Workflow Request Flag Semantics

The invoke request currently has no way to specify runtime behavior. There's no mechanism like:
```python
# Hypothetical request flags in request:
WorkflowServiceRequest(
    flags={
        "stream": True,
        "evaluate": True,
        "chat": True,
        "verbose": True,
    }
)
```

The `aggregate` and `annotate` params on the `workflow` decorator hint at this direction but aren't exposed as clearly defined request-level flags yet. In the target contract, the request-time flag should be `evaluate`, even if the lower-level implementation still uses `annotate`. The important distinction is that these flags should live on a separate `WorkflowRequestFlags` type, not on `WorkflowFlags`.

---

## 7. Tracing

### 7.1 SDK Tracing

**Files:**
- `sdk/agenta/sdk/tracing/main.py` — `Tracing` class, span lifecycle
- `sdk/agenta/sdk/tracing/conventions.py` — attribute naming (`ag.type`, `ag.data.inputs`, etc.)
- `sdk/agenta/sdk/tracing/processors.py` — span batching/processing
- `sdk/agenta/sdk/tracing/exporters.py` — HTTP export to API

**Span attributes:** `ag.type` (workflow/evaluator/task/agent/tool/...), `ag.node.name`, `ag.data.inputs`, `ag.data.outputs`, `ag.internals`, `ag.refs`, `ag.meta`, `ag.metrics`, `ag.tokens.*`, `ag.cost`

### 7.2 API Tracing

**File:** `api/oss/src/apis/fastapi/tracing/router.py`

Endpoints:
- `POST /observability/v1/otlp/traces` — ingest (OTel-compatible)
- `POST /observability/v1/traces/query` — query
- Various span query endpoints

### 7.3 Trace Context Scope for This Plan

The only trace-related concern relevant to this runnable plan is narrower than the API-level flow above:

- SDK routing/running should be able to honor incoming parent trace context when it is already present
- this matters primarily for workflow-to-workflow execution
- this plan does **not** imply adding new API-to-SDK trace propagation behavior

---

## 8. Builtin Interface Definitions

**File:** `sdk/agenta/sdk/workflows/interfaces.py`

Each builtin handler has a `WorkflowServiceInterface` with explicit `JsonSchemas` defining:
- `schemas.parameters` — JSON Schema for configuration
- `schemas.inputs` — JSON Schema for inputs
- `schemas.outputs` — JSON Schema for outputs

This is the richest schema definition in the system, but it only covers builtins. Custom workflows rely on the legacy serving system to extract schemas from Python function signatures.

---

## 9. Key File Map

### SDK

| File | Role |
|------|------|
| `sdk/agenta/sdk/decorators/running.py` | New workflow/application/evaluator decorators, invoke/inspect logic |
| `sdk/agenta/sdk/decorators/routing.py` | New HTTP routing: `/invoke`, `/inspect` endpoints, stream format negotiation |
| `sdk/agenta/sdk/decorators/serving.py` | Legacy HTTP serving, OpenAPI generation, flag injection |
| `sdk/agenta/sdk/models/workflows.py` | All workflow types: flags, request/response, schemas, aliases |
| `sdk/agenta/sdk/models/shared.py` | Shared base types (Identifier, Slug, Lifecycle, etc.) |
| `sdk/agenta/sdk/workflows/utils.py` | Handler/interface/configuration registries, URI parsing |
| `sdk/agenta/sdk/workflows/interfaces.py` | Builtin handler interface definitions (JSON Schemas) |
| `sdk/agenta/sdk/workflows/configurations.py` | Builtin handler default configurations |
| `sdk/agenta/sdk/workflows/handlers.py` | Builtin handler implementations |
| `sdk/agenta/sdk/tracing/main.py` | Tracing engine, span lifecycle |
| `sdk/agenta/sdk/tracing/conventions.py` | Attribute naming conventions |
| `sdk/agenta/sdk/router.py` | FastAPI router (health endpoint only) |
| `sdk/agenta/sdk/types.py` | Legacy types (FuncResponse, MessagesInput, etc.) |

### API

| File | Role |
|------|------|
| `api/oss/src/apis/fastapi/workflows/router.py` | Workflow CRUD routes |
| `api/oss/src/apis/fastapi/workflows/models.py` | Request/response schemas |
| `api/oss/src/core/workflows/service.py` | Business logic |
| `api/oss/src/core/workflows/dtos.py` | Domain objects |
| `api/oss/src/core/workflows/interfaces.py` | DAO contracts |
| `api/oss/src/dbs/postgres/workflows/dbes.py` | SQLAlchemy entities |
| `api/oss/src/dbs/postgres/workflows/dao.py` | Postgres DAO |
| `api/oss/src/core/invocations/service.py` | Invoke orchestration (proxy) |
| `api/oss/src/core/applications/service.py` | Legacy bridge |
| `api/oss/src/services/legacy_adapter.py` | Flag <-> template type mapping |
| `api/oss/src/services/llm_apps_service.py` | Flag usage in invocation |
| `api/entrypoints/routers.py` | Route mounting |

### Web

| File | Role |
|------|------|
| `web/packages/agenta-entities/src/appRevision/api/schema.ts` | Flag reading from `x-agenta` in OpenAPI |

---

## 10. Summary of Gaps

| # | Gap | Impact |
|---|-----|--------|
| 1 | **Two parallel HTTP serving systems** (serving.py vs running.py) | Confusion about which path is canonical |
| 2 | **API inspect exists but doesn't cache** | `POST /workflows/inspect` delegates to SDK but doesn't persist/cache results |
| 3 | **No OpenAPI-compatible endpoint in new system** | Legacy serving has `/openapi.json` with `x-agenta.flags`; new system has `/inspect` but not OpenAPI-formatted |
| 4 | **Flags not persisted in DB** | Only `is_custom` stored; `is_evaluator`, `is_chat`, `is_feedback` are runtime-only |
| 5 | **Missing capability flags** | `can_stream`, `can_evaluate`, `can_chat`, `can_verbose` not defined |
| 6 | **Request flags in invoke are underspecified** | The request model has `flags`, but invocation-mode semantics are not clearly defined on it |
| 7 | **Trace scope is easy to overstate** | The plan should stay limited to passive incoming trace-context support inside SDK routing/running |
| 8 | **Identity vs capability still conflated** | `is_*` and `can_*` are not cleanly separated today |
| 9 | **Custom workflow schemas** | Custom workflows rely on Python signature extraction (legacy) rather than explicit JSON Schema (new) |
| 10 | **`aggregate` and `annotate` params** | Exist on `workflow` decorator but aren't connected to the external evaluate request-flag contract |

---

### Design Runner Owned Pi Trace Export README (`docs/design/runner-owned-pi-trace-export/README.md`)

# Runner-owned Pi trace export

This workspace plans a replacement for the token-lifetime fix in
[PR #6135](https://github.com/Agenta-AI/agenta/pull/6135).

See [review.md](review.md) for the review and the decisions taken.

The invariant is simple:

- Pi still creates the Pi-native agent, turn, LLM, and tool spans.
- The runner is the only component that sends spans over the network.
- Local and Daytona Pi runs use the same file-spool protocol and lifecycle.
- Export credentials and export routing never enter the Pi process or sandbox. The runner may put
  sandbox-visible mount credential values in the per-turn control file only so Pi can redact them;
  those values do not authorize telemetry export.

The runner does not reconstruct Pi spans from ACP events. Pi keeps its richer in-process view of
provider calls, messages, tools, token counts, and cost. It serializes that span tree as a standard
OTLP protobuf batch and publishes the bytes to a bounded per-turn spool. The runner picks up those
exact bytes and exports them with a renewable runner-owned credential.

```mermaid
flowchart LR
    SDK[SDK and middleware] -->|run request and general credential| Runner
    Runner -->|turn control file| Pi[Pi extension]
    Pi -->|native spans as OTLP protobuf| Spool[Ephemeral telemetry spool]
    Spool -->|same host interface| Runner
    Runner -->|OTLP POST with current credential| API[Agenta OTLP ingest]

    Local[Local filesystem] -. implements .-> Spool
    Daytona[Daytona filesystem API] -. implements .-> Spool
```

This removes the need for a two-hour telemetry token, a token scope field, and a second
`exportAuthorization` DTO field. A 12-hour session remains safe because the runner renews its own
credential while the run is active. No fixed export-token lifetime defines how long tracing works.

## Glossary

| Term | Meaning in this plan |
|---|---|
| Pi extension | Code loaded inside Pi that observes native Pi lifecycle events and creates spans. |
| Runner | The trusted runner service that owns session orchestration, platform calls, and external trace export. |
| Harness | The coding-agent runtime driven by the runner. Pi is one harness. |
| Turn | One `/run` request and one prompt execution. A warm session can contain many turns. |
| OTLP batch | A standard `ExportTraceServiceRequest` protobuf body containing spans. |
| Telemetry spool | An ephemeral directory where Pi atomically publishes an OTLP batch for the runner. |
| Runtime file host | The runner abstraction that reads and writes runtime files either locally or through Daytona's filesystem API. |
| Credential lease | A runner-owned object that keeps the caller's platform credential valid and exposes the current value without giving it to Pi. |

## Documents

| File | Purpose |
|---|---|
| [context.md](context.md) | Current behavior, problem statement, goals, constraints, and non-goals. |
| [research.md](research.md) | Verified repository facts and why the existing relay is the right transport precedent. |
| [architecture.md](architecture.md) | Proposed components, local and Daytona flow, security boundary, and failure behavior. |
| [interfaces.md](interfaces.md) | Field roles, wire contract, spool protocol, and internal interfaces. |
| [plan.md](plan.md) | Phased implementation with concrete files and migration steps. |
| [qa.md](qa.md) | Unit, integration, and live verification matrix. |
| [status.md](status.md) | Decisions, open questions, progress, and next action. |

## Recommendation

Implement this as a replacement for PR #6135 if that PR has not merged. If it has merged, make the
runner-owned exporter a follow-up and remove the extra scoped-token contract after the new path is
proven. Keep the diagnostics from PR #6109 in either case.

---

### Design Runner Subscription Status README (`docs/design/runner-subscription-status/README.md`)

# Runner subscription status

> AGENT-GENERATED, low weight. This is a draft. Mahmoud must approve product and interface decisions.

This folder plans how Agenta shows whether a runner can use a model subscription.

The runner is the private Node service that starts Codex, Pi, or Claude Code. A harness is the
program that communicates with the model and uses tools. The frontend is the Agenta web application.

## Reading order

1. [context.md](context.md) explains the user problem and the limits.
2. [research.md](research.md) shows the current code path and the code evidence.
3. [api-design.md](api-design.md) defines the proposed response and the new path.
4. [plan.md](plan.md) lists the implementation work in dependency order.
5. [qa.md](qa.md) defines the test cases.
6. [status.md](status.md) records the current state and open decisions.

## Proposed path

```text
Mounted login folder
        ↓
Node runner: inspect local login files
        ↓  authenticated private HTTP
Python agent service: remove private details and return status
        ↓  authenticated public HTTP
Frontend query: cache status for a short time
        ↓
Subscription card: show connected, not found, or unavailable
```

The browser must not contact the runner. The browser must not receive the runner token, file paths,
login tokens, account names, or token contents.

---

### Design Sdk Evaluator Metrics Bug README (`docs/design/sdk-evaluator-metrics-bug/README.md`)

# SDK Evaluator Metrics Bug

## Summary

SDK custom evaluators defined with `@ag.evaluator` show evaluator columns, but their
results are empty. LLM judge evaluators work. The root cause is missing
`schemas.outputs` in evaluator revisions created by the SDK. Metrics aggregation needs
that schema to extract `score` and `success`.

## What is fixed now

- Backend metrics refresh can infer missing evaluator schemas from trace data.
- Run mappings are repaired so the scenario drill in table can render evaluator outputs.
- UI drill in panel can render outputs even when evaluator schemas or slugs are missing.

## What is planned

- SDK first scenario deferral to create evaluator revisions with schemas up front.

## How to read this folder

Start here and move in order:

1. `context.md` for symptoms and evidence
2. `research.md` for the SDK and backend flow analysis
3. `backend-fix.md` for the metrics refresh and run mapping updates
4. `ui-fix.md` for scenario drill in behavior and UI fallbacks
5. `plan.md` for the SDK long term fix
6. `status.md` for current progress

### Communication drafts

`slack-message.md` and `message-to-colleague.md` are drafts for internal updates.

## Repro guidance

Use your local environment. Do not store tokens or API keys in this repo.

---

### Design Self Serve Account Deletion README (`docs/design/self-serve-account-deletion/README.md`)

# Self-serve account deletion

Planning workspace for letting users delete their own Agenta account from Settings,
without asking support to do it for them.

## Why this exists

Users regularly ask us on chat to delete their accounts. Today an admin has to run the
deletion by hand. We want a self-serve button in Settings that removes the account
cleanly across every system that holds the user's data: our database, SuperTokens,
Stripe, and Loops.

## The short version

A logged-in user opens Settings, confirms by typing their email, and clicks delete. The
backend cancels their Stripe subscription, deletes their SuperTokens login, hard-deletes
their user and the organizations they solely own, and removes them from Loops. The
frontend then signs them out. Scope for v1 is cloud and self-hosted EE. OSS singleton
instances do not get the button.

## Files in this folder

| File | What it holds |
| --- | --- |
| [context.md](context.md) | Why the work exists, goals, non-goals, the demand behind it |
| [research.md](research.md) | What the codebase already has, with exact file paths and line numbers |
| [plan.md](plan.md) | The proposed design and the phased implementation plan |
| [decisions.md](decisions.md) | Open design decisions with a recommendation for each |
| [status.md](status.md) | Source of truth for current progress and next steps |

## Start here

Read [context.md](context.md) for the goal, then [decisions.md](decisions.md) for the
choices that need sign-off, then [plan.md](plan.md) for how to build it. [research.md](research.md)
is the reference for every existing function we reuse.

---

### Design Session Control And Live Events README (`docs/design/session-control-and-live-events/README.md`)

# Session control and live events

> AGENT-GENERATED, low weight. Draft for discussion. Mahmoud makes final decisions.

This folder holds the design work for session execution control, shared live output,
durable event replay, and durable commands.

## Reading order

1. [Context](context.md) explains the user problems and the current system boundary.
2. [Requirements](requirements.md) lists the open issues and draft system requirements.
3. [Decisions](decisions.md) separates confirmed decisions from proposals and open questions.
4. [Plan](plan.md) defines the design tracks and the order of discussion.
5. [Research](research.md) records verified repository findings and external dependency checks.
6. [Record properties](records-invariants.md) evaluates the existing record model before storage
   options are compared.
7. [RFC](rfc.md) is the living architecture proposal. It remains incomplete until each track is discussed.
8. [Status](status.md) records current progress and the next discussion.
9. [Tonight handoff](tonight-handoff.md) contains independent spike and implementation briefs.

## Terms under review

- **Session:** One durable conversation and its workspace.
- **Execution:** One runner attempt that can start, pause, complete, fail, or be cancelled.
- **Conversation turn:** One user message and the resulting agent response. One conversation turn
  can contain several executions when an approval pauses and resumes work.
- **Runner:** The service that starts a sandbox and drives the coding harness.
- **Harness:** The coding-agent program inside the sandbox, such as Pi or Claude Code.
- **Live frame:** A temporary output update, such as a text delta or tool progress update.
- **Durable event:** An append-only saved fact used for replay and recovery.
- **Command:** A saved request to send, cancel, approve, queue, or steer.
- **Lease:** Temporary proof that one runner owns a session or execution.

The names are provisional. The contract discussion must settle how these terms map to the
existing `turn_id` and `turn_index` fields.

---

### Design Session Ux Interface README (`docs/design/session-ux-interface/README.md`)

# Session UX interface redesign

This workspace records the completed revision of the session-list interfaces introduced by the
v0.112 sessions UX stack.

## Reading order

1. [`context.md`](context.md) explains the user experience, goals, decisions, and non-goals.
2. [`implementation.md`](implementation.md) gives reviewers a concise code and runtime handoff.
3. [`qa-handoff.md`](qa-handoff.md) records verification evidence and remaining QA work.
4. [`research.md`](research.md) compares the proposed design with PR #5767 and records costs and
   regression risks.
5. [`plan.md`](plan.md) records the implementation phases, files, tests, and rollout order.
6. [`status.md`](status.md) records the implementation outcome and residual verification work.

The detailed interface review remains at
[`../session-ux-interface-review.md`](../session-ux-interface-review.md).

## Terms

- **Session:** The conversation or work container shown in session lists.
- **Turn:** One agent execution inside a session.
- **Automation:** A schedule or event subscription that invokes an agent.
- **Delivery:** The audit record for one automation firing. Every successful claim has a unique
  delivery ID.
- **Origin:** Who or what created a session. The current automated value is `trigger`; an absent
  value means unknown, not manual.
- **Expansion:** Optional response data that the caller requests because it costs another lookup,
  such as a message preview or current automation name.
- **Session attribution:** The stable relationship from a session to its origin, automation, and
  exact delivery.

## Implementation record

Implementation started from GitButler target `origin/release/v0.112.0` at `965851e15d`. No stacks
were applied at the start.

The implementation is complete and organized as a stacked review set. See `implementation.md` for
the review split and `qa-handoff.md` for verification evidence and residual risks.

---

### Design Sessions README (`docs/design/sessions/README.md`)

# Sessions — design index

The `sessions` domain is the durable + coordination layer for agent sessions. It is composed
of sub-domains that mirror the code layout (`core/sessions/<sub>`, `dbs/postgres/sessions/<sub>`,
one `apis/fastapi/sessions` router), plus the standalone `mounts` domain it delegates to.

| Sub-domain | What it owns | DB | Design |
|---|---|---|---|
| **states** | Durable SDK `SessionRecord` + sandbox resume pointer (1:1 per session) | core DB `session_states` | [states/](./states/) |
| **streams** | Live control/ownership handle for a session's ACP stream — invoke (DATA/FORCE matrix), heartbeat, attach/detach, liveness; Redis coordination plane | core DB `session_streams` + Redis | [streams/](./streams/) |
| **records** | Append-only persisted contents of a session's stream (events) | tracing DB `records` | [records/](./records/) |
| **interactions** | Human-in-the-loop requests raised by running agents (approvals, inputs, tool confirmations) | core DB `interactions` | [interactions/](./interactions/) |
| **mounts** (standalone) | Durable object-store mounts for agent working directories; `sessions/mounts` is a thin session-scoped layer over it | core DB `mounts` | [../mounts/](../mounts/) |

## Frontend

- [frontend-integration.md](./frontend-integration.md) — status + follow-ups for the agent-chat
  FE integration (records-replay, liveness badge, SWR cache, request priority). **Read its
  "Blocked / waiting" and "Follow-ups" tables before picking up remaining FE work.**

## Cross-cutting

- **RBAC**: one permission family `VIEW_SESSIONS` / `EDIT_SESSIONS` / `RUN_SESSIONS` across all
  sub-domains (granted mirroring the workflow roles). Runner-internal writes (stream
  heartbeat/detach, interaction state transitions) sit behind admin auth, not these.
- **Detached invoke**: interactions (respond) and triggers fire the runner's detached
  `/sessions/streams/invoke` — fire-and-forget, no held connection. See
  [interactions/cross-cutting-review.md](./interactions/cross-cutting-review.md) and the
  detached-invoke design.
- **`replica_id`** (which container owns a stream) is ephemeral routing state — Redis
  owner-lock only, never persisted.

---

### Design Simplify Nav New Users README (`docs/design/simplify-nav-new-users/README.md`)

# Simplify navigation for new signup users

**Status:** Implemented
**Date:** 2026-07-27

New signup users land on the full platform sidebar, which is noise when their only goal is
building an agent. This workspace plans a nav-only simplification in two phases. **Phase 1**
hides the advanced pages (Prompts, the Evaluation group, Overview, Registry, Evaluations) for
new signups. **Phase 2** adds a per-user **"Classic mode"** switch in Settings →
Feature flags so anyone can switch back to the full view to use the LLM-app pages. Existing and
returning users default to the full view throughout.

## Decisions

- Two phases: Phase 1 = hide-for-new-signups; Phase 2 = the Settings → Feature flags switch
  (additive — touches no Phase-1 file except one derived atom).
- Nav-only — hide sidebar entries; no route guards, no in-app link changes.
- Hide when simplified: Prompts, Evaluation group (project); Overview, Registry, Evaluations (app).
- Keep always: Home, Agents, Observability, app Playground.
- Default mode seeded by a fresh forward-only key `navSimplifiedDefaultAtom`, written at signup
  (new signups → simplified); everyone else → full. Deliberately **not** `isNewUserAtom`, which
  is sticky-true for existing users and would strip their advanced nav.
- Stable seam: the sidebar reads one derived atom `advancedNavHiddenAtom` (in `state/onboarding`
  selectors) — Phase 1 `= navSimplifiedDefault`, Phase 2 `= override ?? navSimplifiedDefault`.
- No backend, no team-wide enforcement — per-user preference; an invited teammate flips the
  Phase-2 switch to match their team. A workspace-level flag is deferred, not blocked.
- Built on the sidebar's existing `isHidden` mechanism; one OSS sidebar file, both editions inherit it.

## Deliverables

- [context.md](./context.md) — problem, phased scope, out-of-scope, product language, success criteria.
- [research.md](./research.md) — how the sidebar, new-user state, and settings tabs work today, with `file:line`.
- [plan.md](./plan.md) — the phased, sliced implementation plan (Phase 1: Slice 0–4; Phase 2: Slice 5–6).
- [status.md](./status.md) — locked decisions, open questions, next action.

## Intended outcome

A user who has just signed up sees a focused, agent-first sidebar: Home, Agents, and
Observability at the project level, Playground + Observability inside an app. Anyone who wants
the complete platform — an existing LLM-app team, or an invited teammate — enables Classic mode
in Settings → Feature flags and gets it back, with the choice remembered. No one is ever stuck in the
wrong view.

---

### Design Snippets README (`docs/design/snippets/README.md`)

# Snippets Design Docs

Status: draft  
Last updated: 2026-02-11

## Purpose

This folder contains iterative design docs for the `poc/snippets-using-legacy-apps` work.  
The branch uses older naming and entities in several places; these docs focus on intent and direction rather than strict legacy naming fidelity.

## Documents

- `PRD.md`: product goals, user problems, requirements, and success criteria.
- `RFC.md`: technical contract, including snippet embed format, dereferencing, and resolver behavior.
- `PR.md`: draft pull request narrative/checklist for implementation review.

## Where To Find Snippet Format

- Canonical format and resolver contract: `RFC.md` -> `Snippet Format (Normative for This Branch)`

## Scope

- Define how "snippets" should behave as first-class artifacts.
- Preserve backward compatibility with legacy "application" terms and flows where needed.
- Capture unresolved decisions to drive follow-up iterations.

## Open Questions

- Should "snippet" eventually replace "application" in all user-visible surfaces, or remain an alias?
- Do we want a hard migration timeline away from legacy entities, or long-term dual support?
- Which compatibility guarantees are required for existing API clients and SDK users?

---

### Design Starter Credits Bridge README (`docs/design/starter-credits-bridge/README.md`)

# Starter-credits bridge

> Status: removed. The bridge code is gone from the API. Its signup mint policy lives on
> as the wallet signup grant policy in `api/ee/src/core/wallets/signup_policy.py`. This
> page records the original design.

A new organization signs up with no model provider key, so nothing runs until someone
pastes one in. The starter-credits bridge closes that gap. At signup the platform mints a
budget-capped key on a proxy the operator runs, and writes it into the new organization's
vault as a ready-to-use provider connection. The first run then works with no key form and
no configuration.

The bridge is deliberately small and deliberately temporary. It is EE only, inert unless a
deployment configures it, and it reuses the connection path that already ships instead of
adding a funded route of its own. When a first-class gateway owns funded traffic, the
bridge is removed.

## The path, end to end

1. **Signup.** A person signs up. The signup path creates their organization and its
   default project, then calls the EE hook `provision_signup_subscription`
   (`api/ee/src/core/organizations/service.py`), which calls
   `seed_starter_credits_bridge_safely`.
2. **Gates.** Seeding runs only when the deployment is armed (see
   [Configuration](#configuration)), the mint policy resolves, the proxy team's budget
   ceiling verifies, the organization has no seeded row already, and the mint policy
   allows this signup.
3. **Mint.** The service asks the proxy for one virtual key: a credential the proxy itself
   issues, carrying a spend ceiling, an allowlist of exactly one model, and per-key
   concurrency and throughput caps. The key's alias is the organization id, so a retried
   signup cannot mint twice.
4. **Seed.** The same call writes the key into the default project's vault as a custom
   provider connection, created `managed_by` the bridge and `write_only`. The connection
   stores the proxy's public base URL and the one model id.
5. **First run.** The SDK resolves the connection like any other custom provider, the
   runner pins that one model at that base URL, and the harness in the sandbox calls the
   proxy. The proxy checks the key, checks the budget, attaches the operator's upstream
   credential, and forwards the call.
6. **Exhaustion.** Once the organization's spend reaches the ceiling, the proxy refuses at
   admission. The runner classifies the refusal from the response body and returns a
   stable error code with a plain message, so the chat can tell the user to add their own
   key.

## The pieces

| Piece | Where | What it does |
| --- | --- | --- |
| Seeding service | `api/ee/src/core/starter_credits_bridge/service.py` | The gates, the mint, the vault write, the velocity counters, the operator alert |
| Proxy admin client | `api/ee/src/core/starter_credits_bridge/client.py` | The master-keyed calls: generate a key, block a key, read team info |
| Mint policy and errors | `api/ee/src/core/starter_credits_bridge/types.py` | The `MintPolicy` model, the free-mail domain list, the development policy, the proxy error types |
| Signup hook | `api/ee/src/core/organizations/service.py` | The one call site, bounded and swallow-all |
| Configuration | `api/oss/src/utils/env.py` (`StarterCreditsBridgeConfig`) | The env contract and the `armed` predicate |
| Write-only secrets | `api/oss/src/core/secrets/redaction.py`, `api/oss/src/middlewares/auth.py` | Values a user can replace but never read back; the runtime reads plaintext through the `secret-resolve` grant |
| Managed secrets | `api/oss/src/core/secrets/managed.py` | Rows the platform owns, which users cannot edit or delete |
| SDK resolution | `sdks/python/agenta/sdk/agents/platform/connections.py`, `connections/errors.py` | Turns the connection into a provider configuration; raises `WriteOnlySecretError` when a caller without the grant gets a redacted key and no environment fallback |
| Endpoint validation | `sdks/python/agenta/sdk/agents/connections/endpoints.py` | Rejects any connection base URL that is not absolute HTTPS |
| Runner error classes | `services/runner/src/engines/sandbox_agent/errors.ts` | `RunErrorCode`, including `starter_credits_exhausted`, `starter_credits_program_paused`, `starter_credits_unavailable`, and `rate_limited` |

## Configuration

Every variable is read once into `StarterCreditsBridgeConfig`
(`api/oss/src/utils/env.py`). The bridge is `armed` only when `ENABLED` is true and both
proxy addresses, the master key, and the team id are all present. An unarmed deployment
returns from the seeding call immediately, which is what every OSS and self-hosted
deployment does.

| Variable (`AGENTA_STARTER_CREDITS_BRIDGE_` prefix) | Required to arm | What it holds |
| --- | --- | --- |
| `ENABLED` | yes | The opt-in switch. Defaults to false. Changing it takes a redeploy |
| `PROXY_PUBLIC_URL` | yes | The base URL stored on the seeded connection. A sandboxed run dials it from outside the deployment's network, so only the proxy's inference paths are published there |
| `PROXY_ADMIN_URL` | yes | The proxy's address on the private network. The minting client dials it, so the master key never crosses the public edge |
| `MASTER_KEY` | yes | The proxy's admin credential. It mints and blocks keys |
| `TEAM_ID` | yes | The proxy team every minted key joins. The team's own budget ceiling bounds total exposure, so seeding refuses to run without one |
| `MODEL_ID` | no | The single model id the minted key allowlists and the seeded connection publishes. Defaults to `vertex_ai/gemini-3.7-flash` |
| `POLICY_FLAG` | no | The name of the PostHog feature flag whose payload carries the mint policy. Defaults to `starter-credits-bridge-policy` |
| `ALERT_WEBHOOK` | no | An operator webhook. The service posts `{"text": ...}` to it on refusals and failures |

No policy value (grant size, velocity caps, per-key limits, domain rules) is configured
here. Those arrive in the policy payload. See
[Mint policy](design.md#the-mint-policy-comes-from-the-operator-not-from-source).

## Documents

| File | Answers |
| --- | --- |
| [design.md](design.md) | Every decision, the options it was chosen against, and why |
| [write-only-secrets.md](write-only-secrets.md) | The vault contract the seeded row depends on: write-only values and managed rows |
| [proxy-and-deployment.md](proxy-and-deployment.md) | What the proxy must look like, how it is routed, and what that constrains |

---

### Design Starter Credits Seeding README (`docs/design/starter-credits-seeding/README.md`)

# Starter credits seeding

This document records the production contract for the starter-credits connection created for a
new organization's default project.

## Seeding flow

The EE signup hook calls the starter-credits bridge. The bridge:

1. Confirms the bridge configuration and `AGENTA_SERVICES_INTERNAL_KEY` are configured.
2. Resolves the mint policy and verifies the proxy team budget ceiling.
3. Loads the organization's default project and checks the `starter-credits` Vault slug.
4. Applies the signup and velocity policy.
5. Mints one budget-capped proxy key for the organization.
6. Creates one managed Vault connection through `VaultService.create_managed_secret`.

The proxy alias and the project-plus-slug unique constraint make duplicate signup attempts
idempotent. If the Vault write fails after minting, the bridge blocks the orphaned proxy key.

## Vault connection contract

The bridge creates a custom-provider connection with these independent properties:

| Property | Value | Purpose |
| --- | --- | --- |
| Slug | `starter-credits` | Stable Vault identity |
| Name | `Agenta` | User-facing connection name and model-key namespace |
| Description | `Provided and managed by Agenta.` | User-facing explanation |
| Provider URL | `AGENTA_STARTER_CREDITS_BRIDGE_PROXY_PUBLIC_URL` | Endpoint used by model runs |
| `write_only` | `true` | Prevents ordinary API and UI callers from reading the virtual key |
| Manager | `SecretManager.STARTER_CREDITS_BRIDGE` | Identifies the trusted lifecycle owner internally |
| Management policy | `SecretManagementPolicy.MANAGER_ONLY` | Prevents general update and delete operations |

Management and value visibility are separate policies. The bridge selects both explicitly. The
general Vault layer does not infer `write_only` from management.

The public Vault response exposes the management policy, not the internal manager identity.

## Names with different roles

The bridge keeps these values separate even when two serialized values happen to match:

- `PROXY_ORIGIN` is proxy audit metadata attached to the minted key.
- `AGENTA_STARTER_CREDITS_BRIDGE_PROXY_ADMIN_URL` routes administrative mint and block calls.
- `AGENTA_STARTER_CREDITS_BRIDGE_PROXY_PUBLIC_URL` is stored as the connection endpoint.
- `STARTER_CREDITS_DESCRIPTION` is human-facing copy stored in the Vault header.

Do not reuse the proxy origin or either URL as the user-facing description.

## Cache ownership

`VaultService.create_managed_secret` owns Vault list-cache invalidation. The bridge does not call
the cache helper directly. This keeps HTTP and in-process Vault writers on the same invalidation
path.

## Runtime key requirement

The bridge refuses to mint when `AGENTA_SERVICES_INTERNAL_KEY` is absent, blank, or the
`replace-me` placeholder. It does not fall back to `AGENTA_AUTH_KEY`. Without the dedicated key,
the runtime cannot obtain the grant required to resolve the write-only connection.

---

### Design Stateless Playground README (`docs/design/stateless-playground/README.md`)

# Stateless Playground

Create a project level Playground page that is not bound to any app. It always runs against the shared completion service (and later chat). It treats everything as a draft and never allows saving.

Key constraint: reuse the existing Playground UI by swapping bindings (adapter) rather than rewriting components.

## User Request

"A playground page at the same level as evaluation or prompts (project level) that is bound to no app. Always uses the same URL for the service (the completion service). All variants/revisions are drafts and you cannot save anything. Allows creating a prompt, running it, and adding test cases. It is the usual playground experience, but it is not connected to a prompt."

## Files

- **[context.md](./context.md)** - Background, motivation, goals, non-goals
- **[research.md](./research.md)** - Codebase analysis and key findings
- **[rfc.md](./rfc.md)** - Technical proposal for the adapter based approach
- **[plan.md](./plan.md)** - Implementation plan with phases
- **[status.md](./status.md)** - Current progress, blockers, and decisions
- **[api-design.md](./api-design.md)** - Data flow and API contracts
- **[qa.md](./qa.md)** - QA plan and test scenarios

## Quick Links

- Current Playground UI and atoms: `web/oss/src/components/Playground/`
- Completion service: `services/oss/src/completion.py`
- Service schema fetching: `web/packages/agenta-entities/src/appRevision/api/schema.ts`
- Loadable bridge (local mode testcases): `web/packages/agenta-entities/src/loadable/`

---

### Design String Comparison Operators README (`docs/design/string-comparison-operators/README.md`)

# String Comparison Operators for Tracing Filters

Add lexicographic comparison operators (`>`, `<`, `>=`, `<=`) to string attributes in the tracing/observability filter system.

## Problem

Users store datetime strings in custom attributes (e.g., `tags.created_at = "2024-01-15T10:30:00Z"`) and want to query ranges. Before this work:

- The UI did not expose `gt`/`lt`/`gte`/`lte` for string custom fields
- String field parsing in core did not allow numeric comparison operators
- DAO string-field handling did not route numeric operators for plain string columns

## Solution

Reuse existing `NumericOperator` values (`gt`, `lt`, `gte`, `lte`) for strings by allowing them in string parsing and routing them in DAO handling. PostgreSQL naturally supports lexicographic comparison on text, so ISO8601 datetime strings sort correctly.

## Files

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, motivation, user request |
| [plan.md](./plan.md) | Execution plan with phases |
| [research.md](./research.md) | Code analysis and implementation details |
| [status.md](./status.md) | Current progress |

## Effort Estimate

**Low complexity** - ~2-3 hours total

- Backend: ~1 hour (parser + handler routing changes)
- Frontend: ~1 hour (registry + field config changes)
- Testing: ~30 min

---

### Design Tags README (`docs/design/tags/README.md`)

# Tags Design Docs (Draft)

This folder contains draft design artifacts for a Tags feature on a legacy branch.
The docs are intentionally lightweight and use current assumptions only as placeholders.

## Documents

- `PRD.md`: product goals, user value, scope, and success criteria.
- `RFC.md`: technical approach, architecture, data model, API, and rollout plan.
- `PR.md`: pull request draft summary and reviewer checklist.

## How to use these docs

- Treat all details as a starting point for iteration.
- Prefer decisions that are easy to migrate when legacy entities are replaced.
- Capture unresolved decisions in the open-questions sections.

## Open Questions

1. Which existing "entity" types should be supported first in this old branch?
2. Should tags be globally unique, workspace-scoped, or entity-scoped?
3. Do we want free-form tag creation or constrained vocabulary in v1?
4. What migration path is acceptable if naming and IDs change later?

---

### Design Template Strip Onboarding README (`docs/design/template-strip-onboarding/README.md`)

# Template strip onboarding

One shared "template strip" component replaces the current template presentation on the
home page and in the playground. The strip is a fixed-height, horizontally paged row of
template cards with category tabs. Clicking a card fills the composer with the template's
message and attaches a provenance chip. The whole experience sits behind a new
environment flag; the current flows stay intact when the flag is off.

The high-fidelity design lives at `design_handoff_template_strip/` at the repo root
(interactive HTML prototypes plus written notes). Light mode is final and should be
recreated pixel-perfectly with AntD + Tailwind. Dark mode needs deliberate token
translation, covered in `design.md`.

## Files

- `context.md` - why this work exists, goals, non-goals, owner decisions, flag matrix.
- `research.md` - verified findings from the design handoff and the existing codebase:
  what exists today, what the prototype specifies, what is uncommitted in the tree.
- `design.md` - the TemplateStrip component design (props, state, pager math, chip),
  per-surface integration, env-flag wiring, the hex-to-token mapping table with dark
  values, the copy action and toast, the Usage card restyle, and analytics parity.
- `plan.md` - implementation slices sized for Sonnet subagents, plus the dev-stack
  verification plan.
- `status.md` - current progress, blockers, and the open decisions list. Source of truth
  for where the project stands.

## Quick orientation

- Design handoff: `design_handoff_template_strip/` at the repo root
  (`Template Strip Prototype.dc.html` is the real component with template data and logic
  in a `text/x-dc` script block; `README.md` and
  `Template Strip - Implementation Notes.md` are the notes; `_ds/.../colors_and_type.css`
  is the token sheet).
- Template registry (reused as-is): `web/oss/src/components/pages/agent-home/assets/templates.ts`.
- Flag pattern to follow: `web/oss/src/components/pages/agent-home/assets/constants.ts`
  plus `web/oss/src/lib/helpers/dynamicEnv.ts`.
- Theme source of truth: `web/oss/src/styles/theme/palette.ts` (edit, then
  `pnpm generate:tailwind-tokens`; never hand-edit generated files).

---

### Design Testing README (`docs/design/testing/README.md`)

# Testing

This directory specifies the testing strategy for the Agenta monorepo, covering all system interfaces: API, SDK, Web, Services, and Docs. The strategy uses orthogonal documents: principles describe the philosophy, boundaries describe architectural layers, dimensions describe filtering, structure describes folder layout, and interface documents describe per-component specifics.

**The folder decides the layer, and the rule is about RUNTIME dependencies.** It
applies to every part of the repo — api, sdks, services, runner, web, packages —
in both Python and TypeScript.

The distinction is runtime, not code. Importing a module, a package, or another
workspace's library is a **code** dependency and stays unit — import as much as
you like. What moves a test out of `unit/` is needing something **running**: a
database, an object store, a broker, an HTTP server, a browser, a spawned
process, a container. Reading `POSTGRES_HOST` from the environment is fine;
connecting to it is not. One runtime dependency, still exercising a single unit →
`integration/`. Point-like or flow-like end to end → `acceptance/`.

**That includes the part's own server.** An api unit test must not need the api
running, a web unit test must not need the web app served, and the same holds for
the runner, services and workers. Import the code and call it; do not boot your
own process and talk to it over a socket. This is the case that slips through
most often, because the dependency looks internal — it is not, it is a running
thing.

In-process is the dividing line, not the protocol. Constructing an app object in
the test and driving it through an in-memory transport — FastAPI's `TestClient`,
`httpx.ASGITransport`, a React render — starts no server and stays **unit**, as
long as everything below is faked. The check that settles it: **stop the
deployment and run the test.** If it still passes, it was a unit test.

A runtime dependency is **relative to the part you are testing**, so the same
thing changes layer depending on which side of it you sit. Postgres is a runtime
dep of the api; the api is a runtime dep of web and of the sdks; a sandbox
provider is one of the runner. A web test that calls a running api is not a unit
test even though it opens no database, and an sdk test hitting a live endpoint is
not a unit test even though it is one function call. Conversely a web test that
imports `@agenta/entities` and drives it with fixtures is a unit test, however
many packages it pulls in.

This is not stylistic. A unit test that reaches a shared running resource becomes
order-dependent — green alone, red in a full-layer run once another test mutates
state it assumed — and that failure reads as a regression in whatever branch is
checked out.

---

## Quick Reference

### Core Specifications

| Document | Description |
|----------|-------------|
| [testing.principles.specs.md](testing.principles.specs.md) | Philosophy, test pyramid, tradeoffs, mocking approach |
| [testing.boundaries.specs.md](testing.boundaries.specs.md) | Architectural test layers and what to test at each |
| [testing.dimensions.specs.md](testing.dimensions.specs.md) | Unified marker/tag taxonomy across all runners |
| [testing.structure.specs.md](testing.structure.specs.md) | Folder layout, file types, naming conventions |

### Interface Specifications

| Document | Description |
|----------|-------------|
| [testing.interfaces.specs.md](testing.interfaces.specs.md) | Overview of all system interfaces and testing matrix |
| [testing.interface.api.specs.md](testing.interface.api.specs.md) | API testing: current state, targets, mocking guidance |
| [testing.interface.sdk.specs.md](testing.interface.sdk.specs.md) | SDK testing: unit, integration, smoke |
| [testing.interface.web.specs.md](testing.interface.web.specs.md) | Web testing: Playwright E2E, data layer, component unit |

### Supporting Documents

| Document | Description |
|----------|-------------|
| [testing.fixtures.specs.md](testing.fixtures.specs.md) | Shared test infrastructure, accounts, helpers, scoping |
| [testing.running.specs.md](testing.running.specs.md) | How to run tests: local, cloud, CI |
| [testing.initial.specs.md](testing.initial.specs.md) | Original discussion-format spec (preserved as reference) |
| [rtm/web-acceptance-rtm.md](rtm/web-acceptance-rtm.md) | Web acceptance requirements traceability matrix for the current OSS Playwright suite |

---

## Which layer a test belongs to

**The folder decides the layer, not a marker**, and the question is what must be
**running** — not what is imported.

| Layer | May use | Needs running |
| ----- | ------- | ------------- |
| `unit/` | any import; env values; fixtures, fakes, in-memory doubles | **nothing** |
| `integration/` | one or more runtime deps, still exercising a single unit | e.g. Postgres, Redis, the api, a browser |
| `acceptance/` | a deployment, point-like or flow-like end to end | the stack |

A code dependency never moves a test out of `unit/`; a runtime dependency always
does — **including the part's own server.** An api unit test must not need the
api running; a web unit test must not need the web app served; the same for the
runner, services and workers. Call the function, construct the class, drive the
component — do not boot the thing you are testing and talk to it over a socket.
If a test needs its own process up, it is `integration/` at least.

What counts as a runtime dep is relative to the part under test — its own server
first, then whatever it calls:

| Part | Typical runtime deps |
| ---- | -------------------- |
| `api/` | Postgres, Redis, object store, the workers |
| `sdks/` | a running api |
| `services/` | the api, plus whatever the service brokers |
| `services/runner/` | sandbox providers, spawned agent processes, the api |
| `web/` | the api; a browser for Playwright |
| `web/packages/` | the api, for the packages that reach it (e.g. `agenta-entities`, `agenta-annotation` both have `tests/integration/`); nothing for pure-logic and component tests |

A package having its own `integration/` folder is normal, not a smell:
`web/packages/agenta-entities/tests/` holds both, with the integration side
gated on `AGENTA_API_URL` + `AGENTA_AUTH_KEY` and skipping when they are absent.
That is the shape to copy — split by what must be running, in the same package.

**An empty `unit/`, `integration/` or `acceptance/` folder means the setup is
incomplete — not that the layer does not apply.** Every part needs all three.
A missing integration layer usually means its tests were filed as unit tests
(where they fail intermittently, see above) or as acceptance tests (where they
are skipped on any machine without a full stack). If a layer is empty, the
question is what is missing from it, not whether it is needed.

## Status Matrix

Test folder structure is now **standardized** across all components with `manual/`, `legacy/`, and `pytest/`|`playwright/` containing `acceptance/`, `integration/`, `unit/`, and `utils/` subdirectories.

| Component | Unit Tests | Integration Tests | Acceptance Tests | Manual Tests | CI |
|-----------|-----------|------------------|-----------------|--------------|-----|
| **API** | Structure ready | Structure ready | ✅ 155 tests across 7 domains | ✅ HTTP files, scripts | Linting only |
| **SDK** | ✅ 22 tests (tracing decorators) | Structure ready | ✅ 66 tests (SDK against live API) | ✅ Workflow tests, imports | Linting only |
| **Web** | ✅ Jotai atom tests (colocated) | Structure ready | ✅ Playwright feature suites | ✅ Data layer tests (manual) | Linting only |
| **Services** | Structure ready | Structure ready | Structure ready | ✅ smoke.http | N/A |
| **Docs** | N/A | N/A | Planned (link checking, build) | N/A | N/A |

---

## Quick Start: Running Tests

### API Tests

```bash
# Run all E2E tests
cd api
AGENTA_API_URL=http://localhost:10180/api AGENTA_AUTH_KEY=change-me-auth \
  python -m pytest oss/tests/pytest/ -v

# Run smoke tests only (fast subset)
python -m pytest oss/tests/pytest/ -v -m coverage_smoke

# Run specific domain
python -m pytest oss/tests/pytest/acceptance/workflows/ -v

# Run with dimension filters
python -m pytest oss/tests/pytest/ -v -m "coverage_smoke and path_happy"
python -m pytest oss/tests/pytest/ -v -m "cost_free"  # Exclude paid tests
```

### SDK Tests

```bash
# Run all tests (unit + E2E)
cd sdk
AGENTA_API_URL=http://localhost:10180/api AGENTA_AUTH_KEY=change-me-auth \
  uv run pytest oss/tests/pytest/ -v

# Run unit tests only (no external deps)
uv run pytest oss/tests/pytest/unit/ -v

# Run acceptance tests only (requires running API)
uv run pytest oss/tests/pytest/acceptance/ -v -m acceptance

# Run with dimension filters
uv run pytest oss/tests/pytest/acceptance/ -v -m "coverage_smoke and cost_free"
```

### Web Tests

The Playwright harness in `web/tests` is disabled: it holds no specs, and no workflow runs it.
New `/m` specs go in `web/tests/specs/<layer>/` (default layer `acceptance`). Before the first one, rewrite
`playwright/global-setup.ts` to sign in through `/m`.

Unit tests for `/m` and the `@agenta/*` packages run with vitest from each app or package folder:

```bash
cd web/mobile && pnpm test
cd web/packages/agenta-chat && pnpm test
```

**Note:** Playwright specs, once added, need valid TESTMAIL credentials. See [web/tests/playwright.config.ts](../../web/tests/playwright.config.ts) for configuration details.

---

## Agent release gate (manual QA)

The agent runtime has a portable, wire-level QA harness packaged as the **`agent-release-gate`**
skill (`.agents/skills/agent-release-gate/`). It drives the same product endpoint the playground
drives and asserts on the SSE frame stream and real side effects, never on model prose, so it runs
against any deployment (cloud or self-hosted) from three env vars (`AGENTA_BASE`,
`AGENTA_PROJECT_ID`, `AGENTA_API_KEY`) that connect the driver to the deployment. Some individual
cells need more than that — a vault provider key, a custom-provider slug, or a subscription
sidecar login — documented per cell in `resources/coverage.md`. The continuity journeys (`warm`,
`cold1`, `cold2`) additionally need a **store-backed** deployment: with no object store the runner
falls back to an ephemeral working directory, so they SKIP by default and FAIL with
`--require-store`. Run the gate before an agent-workflows release, or after changing the runner,
the SDK agent adapters, or the runner images. The skill's `SKILL.md` has the run procedure; `resources/coverage.md` has the cells ×
journeys matrix.

## Related In-Tree Documentation

| Location | Description |
|----------|-------------|
| `web/tests/guides/` | Playwright E2E guides (generation, organization, fixtures, recording) |
| `sdk/tests/unit/README.md` | SDK unit test quick start |
| `sdk/tests/unit/TESTING_PATTERNS.md` | SDK testing patterns and approaches |
| `web/tests/playwright/config/testTags.ts` | Web test tag definitions |
| `api/pytest.ini` | API pytest configuration and markers |
| `sdk/pytest.ini` | SDK pytest configuration and markers |

---

### Design Tracing Trace Totals README (`docs/design/tracing-trace-totals/README.md`)

# Trace totals across OTLP requests

Status: implemented in `claude/project-thread-1g82wj-trace-totals`.
Bugs: B14 (root cost misses the agent subtree), B17 (Pi root shows no cost).

## Problem

Ingest rolls metrics (costs, tokens, errors) up from children to parents once per OTLP
request, in `TracingService.ingest_span_dtos`, and stores the result in
`ag.metrics.<metric>.cumulative` on each span.

A trace often arrives in more than one request:

- The agent runner exports its spans (`invoke_agent` → turns → `chat`) in its own
  request, under the Python SDK's workflow span, which the SDK exports separately.
- The Pi harness exports its spans from the sandbox under the caller's traceparent.
- An OpenTelemetry `BatchSpanProcessor` sends spans when they end, so children often go
  out before their root.

The trace root then misses the subtrees from other requests. The dashboard reads
`cumulative` from root spans only, so it under-reports cost.

## Design

`TracingWorker` (`api/oss/src/tasks/asyncio/tracing/worker.py`) already stores spans
asynchronously. After it writes a batch, it recomputes the totals of every trace the
batch touched, one trace at a time:

- `TracingDAO.recompute_trace_metrics` takes a transaction-scoped Postgres advisory lock
  on the trace, reads `span_id`, `parent_id`, `span_type`, times,
  `attributes->'ag'->'metrics'` and `attributes->'ag'->'flags'` of every span of the
  trace, runs the ingest roll-up (`recompute_cumulative_metrics` in `trees.py`, without
  pricing), and updates only the `cumulative` values that changed. It never writes
  `incremental` values.
- Each recompute runs after its own batch has committed, and the lock serializes
  recomputes of one trace. So the last recompute of a trace reads every span written
  before it.
- Upserts and updates lock rows in `(trace_id, span_id)` order, so they cannot deadlock.
- The HTTP ingest path is unchanged: it only publishes to the Redis stream.

Roll-up rule: a span's own usage and its children's add up. A span whose producer sets
`ag.flags.aggregate_usage` (the SDK agent handler's workflow span, stamped with the
whole run's usage) keeps the larger of the two instead, since both describe the same
model calls.

## Cost and limits

- Per worker batch: one short transaction per touched trace (an indexed read on
  `ix_project_id_trace_id` plus an `executemany` of the changed rows). Traces that
  arrived in one request usually produce no update.
- Traces over `AGENTA_OTLP_TOTALS_MAX_SPANS` (default 10 000) are skipped and keep
  their per-request totals.
- A failed recompute is retried in place, three attempts with a short backoff. After
  the last attempt it is logged and the batch is still acknowledged (a redelivery would
  meter the traces again). The trace keeps its partial totals until another batch
  touches it.
- A cumulative value that rolls up to nothing is removed, not written as 0: the
  dashboard counts any stored `errors.cumulative` as a failed trace.

## Options not taken

- Scheduling split traces in a Redis queue with a delay window, claims and leases:
  coalesces recomputes, but adds a second queue, recovery paths, and loses work when a
  worker restarts between ack and scheduling.
- Computing totals at read time: multiplies the rows the dashboard reads by the trace
  size, and the roll-up needs the tree.
- Rolling up from stored spans on the request path: adds database reads to ingest.
- One request per trace from producers: not possible across processes or for
  third-party exporters.

## Left

- An integration test against Postgres for the update statement.
- Live check of B17: confirm that Pi `chat` spans carry a cost, so the recomputed root
  shows it.

---

### Design Vault Named Secrets README (`docs/design/vault-named-secrets/README.md`)

# Vault named secrets

Add arbitrary user-named secrets to the project vault. Today the vault only stores LLM
provider keys and custom providers. This feature lets a user save any named secret (for
example `GITHUB_TOKEN`) scoped to the project, and manage it from a dedicated **Vault**
section in Settings.

Each secret declares a **format** (the AWS Secrets Manager model):

- **`text`** — an opaque string, stored verbatim (no re-serialization).
- **`json`** — a **flat** object of primitives (no nested objects, no arrays); the shape
  that maps onto environment variables. The backend rejects nesting.

How a value is displayed (raw vs prettified text; JSON editor vs key/value grid) is a UI
choice; `format` is what changes validation.

Scope for this iteration: **storage + management UI only**. We do not wire these secrets
into the agent runtime / sandbox yet. That is a separate follow-up — but `format` is
designed with that consumption in mind (`json` → env vars, `text` → file/single value).

## Files in this folder

- `context.md` — why this work exists, goals, non-goals, decisions.
- `research.md` — how the vault works today, with exact file:line references and gotchas.
- `plan.md` — the execution plan (backend, migration, frontend), phase by phase.
- `status.md` — current progress and the source of truth for what is done / next.

## Quick orientation

- Backend vault domain: `api/oss/src/core/secrets/` + `api/oss/src/dbs/postgres/secrets/`
  + router `api/oss/src/apis/fastapi/vault/router.py`.
- Frontend vault UI: `web/oss/src/components/pages/settings/Secrets/` + entity package
  `web/packages/agenta-entities/src/secret/`.
- The vault is `kind`-driven. We add one new `SecretKind` (`custom_secret`) and reuse the
  generic CRUD, encryption, DAO, and mapping layers unchanged. The `text`/`json` split is a
  `format` field **inside** the secret data, not a second kind — one kind, two validation
  rules.
- The management UI is a **new Vault Settings section**, separate from "Providers & Models"
  (which is LLM-scoped and also holds internal webhook/SSO secrets).

---

### Design Vercel Ai Adapter README (`docs/design/vercel-ai-adapter/README.md`)

# Vercel AI SDK Adapter for OTLP Ingestion

## Overview

Add a backend adapter that maps Vercel AI SDK's `ai.*` OpenTelemetry span attributes to Agenta's `ag.*` namespace. This enables the frontend's structured panels (inputs, outputs, model, tokens, costs) to display data from Vercel AI SDK traces.

## Origin

The Vercel AI SDK has built-in OTel support via `experimental_telemetry: { isEnabled: true }`. It emits `ai.*` span attributes. We verified that traces arrive in Agenta, but the structured UI panels are empty because no adapter maps `ai.*` to `ag.*`.

## Documents

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, problem, goals |
| [plan.md](./plan.md) | Implementation plan, attribute mapping, testing, docs |
| [research.md](./research.md) | Vercel AI SDK semconv reference (all attribute keys) |
| [status.md](./status.md) | Progress tracker |

## Scope

This project covers:

1. **Backend adapter** — `VercelAIAdapter` mapping `ai.*` → `ag.*`
2. **Unit tests** — First adapter unit tests in the codebase (establishes pattern)
3. **E2E tests** — Ingest Vercel AI-style spans via HTTP API, query back, verify `ag.*` mapping
4. **Integration docs** — `docs/docs/integrations/frameworks/vercel-ai-sdk/` (overview + observability pages)
5. **Example** — `examples/node/observability-vercel-ai/` (already created, will be refined)
6. **Live validation** — Send real Vercel AI SDK traces to deployed instance for visual verification

---

### Design View Improvements README (`docs/design/view-improvements/README.md`)

# View Improvements

**Status:** Research  
**Priority:** High (identified as biggest quality-of-life issue during dogfooding)  
**Sprint:** Q1 2026

## Overview

Consolidate and improve how data values (JSON, chat messages, text, inputs/outputs) are displayed across all surfaces in Agenta. Currently, the same data is rendered inconsistently across different surfaces, with some areas (especially observability) providing poor readability that makes the product "feel unusable" despite being technically functional.

## Problem Statement

From internal dogfooding and customer feedback: **"The readability, especially in traces, is unreadable. It makes the experience very, very bad."**

The core issues:
1. Chat messages appear as raw JSON strings instead of structured role-based display
2. No view mode switching (JSON/rendered/text/markdown) in many surfaces
3. Inconsistent rendering between surfaces (eval table vs observability table vs playground)
4. Missing copy functionality in key places
5. No "rendered table view" for JSON (Braintrust reference)

## Documents

| File | Description |
|------|-------------|
| [context.md](./context.md) | Background, motivation, goals, non-goals |
| [research.md](./research.md) | Codebase analysis, component inventory, gaps identified |
| [competitive-analysis.md](./competitive-analysis.md) | How competitors solve these problems |
| [chat-extraction-algorithm.md](./chat-extraction-algorithm.md) | Shared chat detection logic, preference model, and edge cases |
| [plan.md](./plan.md) | Execution plan with phases |
| [status.md](./status.md) | Current progress and decisions |

## Scope Summary

### In Scope
- Observability table cell rendering (inputs/outputs/tooltips)
- Span detail view improvements
- Playground output view switcher
- Testset view rendering
- Component consolidation where beneficial

### Out of Scope (for this iteration)
- SDK-side changes (parameters in inputs issue)
- New evaluator features
- Playground comparison mode improvements (separate track)

## Quick Links

- **Transcript Reference:** Sprint Planning Feb 10, 2026
- **Key Surfaces:** Observability table, Trace drawer, Playground outputs, Testset table
- **Main Gap:** `TruncatedTooltipTag` → `SmartCellContent` migration in observability

---

### Design Wallets Research README (`docs/design/wallets-research/README.md`)

# Wallets

Design and research for a **credit ledger** — one balance per organization, computed from
entries we never edit, so credits can be granted, bought, earned, and spent across models,
tools and sandbox time.

The **gateway** that spends against that balance is designed elsewhere, in
[docs/design/gateways-research/](../gateways-research/). That design owns the request path
(D11) and names the ledger a *caller* of it. This one owns what a caller decides.

`v1/` is the current version. Start at [v1/README.md](v1/README.md).

---

### Design Webhooks README (`docs/design/webhooks/README.md`)

# Webhooks (Current Design)

## Overview
Webhooks are project-scoped subscriptions stored in core Postgres. Delivery records are stored in core Postgres (`webhook_deliveries`).

Current flow:
1. Internal events land in `streams:events` (Redis durable stream).
2. `worker_events` ingests events into Postgres and, in the same batch loop, fans out TaskIQ tasks to `streams:webhooks` — one task per matching `(event, subscription)` pair.
3. `worker_webhooks` (TaskIQ) picks up each task and attempts HTTP delivery with automatic retries.
4. Exactly one `webhook_deliveries` row is written per `(subscription_id, event_id)` — on the **final outcome** (success or failure after retries). No intermediate records are created.

## Data Model

### `webhook_subscriptions` (core)
- `id` (UUID, PK)
- `project_id` (FK -> projects)
- `name`, `description` (header fields)
- `data` (JSON): `url`, `event_types`, `headers`
- `flags` (JSONB): `is_active`, `is_valid`
- `meta` (JSON), `tags` (JSONB)
- lifecycle: `created_at`, `updated_at`, `deleted_at`, `created_by_id`, `updated_by_id`, `deleted_by_id`
- `secret_id` (FK -> secrets): signing secret reference

### `webhook_deliveries` (core)
- `id` (UUID, PK)
- `subscription_id` (UUID)
- `event_id` (UUID)
- `status` (JSONB, shared Status shape: `{code, message}`)
- `data` (JSON): `url`, `event_type`, `payload`, `duration_ms`, `response` (code + body), `error`
- lifecycle: `created_at`, `updated_at`, `deleted_at`, `created_by_id`, `updated_by_id`, `deleted_by_id`

## Signing
- Subscription creation generates a vault secret and stores its `secret_id`.
- The resolved secret is encrypted (`HMAC-SHA256 keystream XOR`, stdlib-only) and cached in Redis alongside the subscription.
- The TaskIQ delivery task carries `encrypted_secret` inline — no vault round-trip during delivery.
- Worker decrypts the secret locally and signs the body with HMAC SHA-256:
  - `X-Agenta-Signature: t=<timestamp>,v1=<hex_digest>`
  - `X-Agenta-Event-Type`

No secret identifiers or secret values are sent to webhook receivers.

## Retry Semantics
- Retries are handled by TaskIQ (`worker_webhooks`).
- Retry count is read from `_taskiq_retry_count` in TaskIQ's internal task labels.
- **2xx** — success delivery record written, task completes.
- **1xx / 3xx / 4xx** — failure delivery record written, no retry (permanent error).
- **5xx / timeout / error** — exception raised so TaskIQ retries; on the last attempt, failure record written before re-raising.

## Workers

### `worker_events` (asyncio)
- Consumes `streams:events` (Redis durable stream, consumer group `worker-events`).
- Ingests events into Postgres.
- Runs a **dispatch parenthesis** per batch: fetches/caches subscriptions per project, enqueues one TaskIQ task per `(event, subscription)` match onto `streams:webhooks` (consumer group `worker-events-webhooks-dispatcher`).
- Acks messages after both ingestion and dispatch complete.

### `worker_webhooks` (TaskIQ)
- Consumes `streams:webhooks` (TaskIQ Redis Stream broker).
- Executes HTTP delivery with automatic retries (`max_retries` from config).
- Writes exactly one `webhook_deliveries` record per task on its final outcome.

## Worker Topology Options

Three deployment topologies were considered. **Option C is implemented.**

### Option A — Single container
The asyncio events worker and TaskIQ delivery worker share the same process/event loop.

- Simpler to deploy (one container).
- Cannot scale delivery independently from ingestion.
- Mixing asyncio and TaskIQ lifecycles is fragile.

### Option B — Two separate containers
A standalone asyncio dispatcher process reads `streams:events` and fans out to `streams:webhooks`. A separate TaskIQ worker handles HTTP delivery.

- Clean separation; each scales independently.
- More operational surface area for early-stage feature.

### Option C — Augmented events worker (implemented)
The events worker runs webhook dispatch as a parenthesis in its batch loop. Dispatch logic is isolated in `tasks/asyncio/webhooks/dispatcher.py` (`WebhooksDispatcher`), importable standalone.

- One fewer process to operate today.
- Migration to Option B requires only removing the import and standing up a second asyncio loop — no logic changes.

## API
- `/webhooks` — subscription CRUD, query, and test endpoints.
- `/events` — event query endpoints (project-scoped).

---

### Design Write Only Secrets README (`docs/design/write-only-secrets/README.md`)

# Write-only vault secrets

A write-only Vault secret can be created, replaced, and deleted, but an ordinary API or
frontend caller cannot read its value back. A trusted platform runtime can resolve the value
through a short-lived granted token so the credential remains usable for runs.

Status: implementation complete across #6164, #6165, #6138, #6195, and #6174. The backend
and frontend ship in the same release. The feature has no environment gate or compatibility
mode.

## Value visibility

`write_only` is a creation-time policy:

- New ordinary Vault secrets default to `write_only=True`.
- A create request may explicitly select `write_only=False`.
- Existing rows without the stored field resolve as `write_only=False`.
- Update requests cannot set or change `write_only`.
- Changing the policy requires deleting and recreating the secret.

The policy remains in the existing encrypted `data` JSON. This implementation requires no
database migration.

SSO and webhook secrets explicitly use `write_only=False`. Their existing settings, login,
test, signing, and verification flows continue to receive the readable value.

## Public and trusted responses

The trusted `SecretResponseDTO` contains the stored credential. The caller-facing
`PublicSecretResponseDTO` adds general value status:

```json
{
  "write_only": true,
  "value_status": {
    "configured": true,
    "preview": "sk-****9Qa"
  }
}
```

`value_status.configured` reports whether the secret contains credential material.
`value_status.preview` is optional and does not determine whether a value is configured.
The model applies to provider keys, custom secrets, compound provider credentials, SSO,
webhooks, and later secret kinds.

For an ordinary caller, the response projection removes the primary credential and every
credential-bearing provider extra when `write_only=True`. Non-secret configuration such as
URLs, regions, versions, models, and harnesses remains readable. A verified runtime token
carrying the `secret-resolve` grant receives the plaintext projection.

The credential-extra vocabulary is shared by the API redaction layer and Python SDK resolver
through `agenta.sdk.agents.connections.credentials`. The same module exposes the SDK helper
that reads `value_status.configured`, so runtime consumers use the public API contract rather
than a key-specific field.

## Vault list cache

The Vault service caches canonical trusted DTOs in Redis with the existing namespace, TTL,
invalidation, and shortened project UUID packing. Create, update, and delete invalidate the
project list namespace.

Caller-specific projection always happens after a cache read:

```text
list request
  -> read canonical SecretResponseDTO values from Redis or the DAO
  -> inspect the verified caller grant
  -> return plaintext to a granted runtime or redact for an ordinary caller
```

Redis is part of the trusted backend boundary. A redacted response is never stored in the
shared list cache.

## Updates

Credential updates use one strict contract:

- An omitted credential field means keep the stored value.
- A non-empty credential replaces the stored value.
- An explicitly supplied empty provider credential is invalid and is rejected.
- An empty JSON object remains an explicitly supplied JSON value and follows the custom-secret
  validation rules.

The frontend ships with the backend and follows the same contract. When a user edits a
write-only connection without typing a replacement credential, the frontend omits the
credential field. It never sends an empty value as the keep signal.

Carry-over is identity-local. Changing the secret kind, provider family, or custom-secret
format requires an explicit new credential. The service resolves the update against the row
loaded under `SELECT ... FOR UPDATE`, so a concurrent rotation cannot be overwritten by a
stale carried value.

## Runtime resolution

The platform uses the `secret-resolve` grant for plaintext runtime access. The grant is
project-scoped and allowlisted on the Vault read routes.

`AGENTA_SERVICES_INTERNAL_KEY` proves the trusted API-to-Services exchange. It is independent
from `AGENTA_AUTH_KEY`, has no administrator-key fallback, and must contain a non-placeholder
value. The API fails startup when it is missing or invalid.

Configure the same `AGENTA_SERVICES_INTERNAL_KEY` value on the API and trusted Services
container. Do not provide it to the web app, runner, sandbox, worker, cron, or migration
containers. The runner receives only the signed, short-lived runtime token needed to execute
the authorized workload.

A caller refreshing an already granted Secret token may carry the grant forward. The exchange
does not create the grant from a requested action alone.

## Consumer behavior

| Consumer | Behavior |
| --- | --- |
| Frontend Settings and connection forms | Read `value_status`, display configured state, and omit untouched credential fields on update. |
| Direct API callers | Receive redacted write-only values and general value status. |
| Platform runs | Resolve plaintext through the granted runtime token. |
| Standalone Python SDK | Reads `value_status`; a redacted provider connection uses only the matching provider environment credential or fails with `WriteOnlySecretError`. |
| Legacy SDK Vault middleware | Drops configured redacted entries so they cannot shadow local environment credentials. |
| Named tool secrets | Skip configured redacted values and log an error without the secret name or value. |
| SSO and webhooks | Remain explicitly readable and otherwise unchanged. |
| In-process trusted readers | Continue using the trusted DTO with plaintext. |

## Managed secrets

Managed lifecycle and value visibility are independent. A managed row stores typed internal
manager identity and policy in the encrypted JSON payload. The public response exposes only
`management.policy`.

The starter-credit bridge explicitly creates its connection with
`management.policy=manager_only` and `write_only=True`. General update, delete, and provider
probe operations reject manager-only rows against the current locked record. The frontend
hides these rows from Settings and edit surfaces but keeps them available for model selection,
agent defaults, key gating, and execution.

## Pull request order

The release chain is:

```text
release/v0.114.0
  -> #6164 write-only contract
  -> #6165 managed-secret model
  -> #6138 starter-credit seeding
  -> #6195 stored provider probe
  -> #6174 generated clients and frontend consumer
```

The five pull requests merge in this order and deploy together in the same release.

---

### Docs Contributing Overview (`docs/docs/contributing/overview.mdx`)

---
title: "Contributing to Agenta"
sidebar_label: "Overview"
description: "How to get started, find work, and open a solid first pull request"
sidebar_position: 1
---

Thanks for your interest in contributing to Agenta. We welcome bug fixes, features, docs improvements, examples, testing work, CI improvements, and clear issue reports.

If you are new to the project, start by using the product first. Create a cloud account, try a few flows, and get a feel for how Agenta works. That context will help you choose better issues and make better changes.

## Where To Start

If you want to open your first pull request, read [Creating Your First PR](/contributing/first-pr). It walks through the full path from picking an issue to opening the PR.

## What Contributions Help Most

These contributions are all useful:

- bug fixes
- clear feature requests
- documentation improvements
- examples and tutorials
- tests and CI fixes
- issue reports with steps to reproduce
- work on community-maintained deployment surfaces

## Getting Help

If you do not see an issue that fits your skills, join our [Slack community](https://join.slack.com/t/agenta-hq/shared_invite/zt-37pnbp5s6-mbBrPL863d_oLB61GSNFjw). You can ask questions there, get help with setup, and find work that is a good fit.

## Contributor Guides

The guides in this section cover local development, testing, formatting, linting, issue filing, and community projects. Use them as the source of truth when you prepare a contribution.

---

### Docs Self Host 00 Overview (`docs/docs/self-host/00-overview.mdx`)

---
title: "Self-host Agenta"
sidebar_label: "Overview"
description: "Where to start with a self-hosted Agenta deployment: deployment surfaces, agent execution, editions, and upgrades."
slug: /self-host/overview
sidebar_position: 0
---

A self-hosted deployment runs the studio, the API, the agent runner, and their datastores on your
own infrastructure. It has every feature of Agenta Cloud except the governance features listed
under [Editions](#editions).

:::tip Self-host with your coding agent
Paste this into Claude Code (or your coding agent) and it will walk you through setup and testing:

```
1. Install the Agenta self-hosting skill: npx skills add Agenta-AI/agenta-skills
2. Help me self-host Agenta with its repository.
```
:::

## Start here

- [Quick start](/self-host/quick-start) runs the full stack locally with Docker Compose.
- [Deploy on a remote server](/self-host/guides/deploy-remotely) puts that stack on a server you own.
- [Deploy to Kubernetes](/self-host/guides/deploy-to-kubernetes) runs it from the Helm chart.
  [Prepare a Kubernetes deployment for production](/self-host/guides/kubernetes-production) then
  covers replicas, disruption budgets, rollouts, and managed Kubernetes.
- [Deploy on Railway](/self-host/guides/deploy-on-railway) is a community-maintained deployment. There is
  no official support for it, and fixes depend on contributor availability.

## Where agents run

Agents execute in the runner service, in one of two sandboxes. Pick one before you open the
deployment to other people:

- [Run agents in a cloud sandbox (Daytona)](/self-host/agent-execution/daytona) gives every run its
  own isolated cloud sandbox. Use it for multi-user deployments.
- [Run agents locally](/self-host/agent-execution/run-agents-locally) executes agents inside the
  runner container. Local runs are the default, and they are not isolated from each other, so use
  them on a deployment you run for yourself or for a trusted team. They are also the only runs that
  can use [your own Claude, Pi, or ChatGPT subscription](/self-host/use-your-own-subscription)
  instead of a model API key.

[Sandbox isolation and security](/self-host/agent-execution/sandbox-isolation-and-security) covers
the difference in full. [Customize the agent runtime](/self-host/agent-execution/customize-the-agent-runtime)
adds tools, folders, or compute to either one.

## Editions {#editions}

Every self-hosted install runs the same public images. A [license key](/self-host/license-keys)
decides the plan:

- **No key** (Community plan): 1 project per organization and 1 organization per instance. Every
  page in this section applies to it.
- **Free key** (Registered plan): no project limit, 1 organization per instance.
- **Paid key** (Enterprise plan): no limits, and the governance features: SSO per organization,
  more roles, and the audit log.

[Editions](/misc/opensource) compares the plans and explains the licensing.

## Operate a deployment

- [Configuration](/self-host/configuration) lists every platform environment variable.
- [Runner and sandbox configuration](/self-host/configuration#agent-runner) lists every
  runner variable.
- [Back up and restore agent files](/self-host/agent-execution/back-up-agent-files) covers bucket
  versioning, undoing an accidental delete, and backing up the bundled store's volume.
- [Architecture](/self-host/infrastructure/architecture) and
  [Networking](/self-host/infrastructure/networking) describe the containers and the traffic
  between them.
- [Upgrading](/self-host/upgrading) covers version upgrades and migrations.

---

### Docs Tutorials Index (`docs/docs/tutorials/index.mdx`)

---
title: "Tutorials"
sidebar_label: "Overview"
description: "Step-by-step tutorials that build real agents in Agenta by chatting, each with a video and a written walkthrough."
sidebar_position: 0
---

Each tutorial builds one real agent from scratch. You build it by chatting with the agent: you describe the job, connect the apps it needs, save what works as a skill, and then automate it.

| Tutorial | What you build | Video |
| --- | --- | --- |
| [Build your first AI coworker](/tutorials/build-your-first-ai-coworker) | A sales copilot that researches prospects and prepares you for every sales call. | 10 min |
| [Track your competitors while you sleep](/tutorials/track-your-competitors) | An agent that researches your competitors every Monday and emails you a digest. | 7 min |
| [Build an inbound outreach agent](/tutorials/build-an-inbound-outreach-agent) | An agent that finds newly activated users, researches them, and drafts personal emails for you to approve in Slack. | 17 min |

If you are new to Agenta, start with [Build your first AI coworker](/tutorials/build-your-first-ai-coworker). It introduces the parts of an agent that the other tutorials use.

## The pattern behind every tutorial

All three tutorials follow the same steps:

1. **Connect the tools.** Add the integrations the agent needs, such as Gmail, Slack, or a web search tool.
2. **Solve the task once, together.** Ask the agent to do the job in a chat, look at the result, and give feedback until it is right.
3. **Save it as a skill.** Ask the agent to turn what worked into a skill, so it does the job the same way next time.
4. **Automate it.** Ask the agent to run the job on a schedule or when something happens in a connected app.
5. **Keep improving.** When a run is not quite right, tell the agent. It updates its own instructions and skills.

For more videos, see the [Agenta YouTube channel](https://www.youtube.com/@agentaAI).

---

### Design Agent Config Editing Benchmark README (`docs/design/agent-config-editing/benchmark/README.md`)

# Agent config editing: the one-shot benchmark (v2)

**The question this answers:** can a *small* model complete any configuration action a user asks
for **one-shot** — no errors, no retry, no error-then-fix — when the user types the way people
actually type? The goal is 95%.

The v1 spike (`docs/design/agent-config-editing/spikes/model-usability/`) measured **call shape**:
it handed a model the tool schema, took the JSON back, and applied it with the real engine offline.
That is why the selector key is `list` and why the tool description is 1.5 KB rather than 3.2 KB.
What it could not see is the product: the rendered instructions file, the platform guidance, the
approval gates, the sandbox, and the model's freedom to reach for a different tool entirely.

v2 is wire-level. Every trial drives `/services/agent/v0/invoke` — the endpoint the playground
drives — and every verdict is read back from the **stored revision row**. Never from the reply.

## Run it

```bash
export AGENTA_BASE=https://your-stack.example.com
export AGENTA_PROJECT_ID=...
export AGENTA_API_KEY=...

uv run run_benchmark.py --list                                  # cells and scenarios
uv run run_benchmark.py --cell claude-haiku-local --trials 3    # one cell
uv run run_benchmark.py --all-cells --trials 5                  # the matrix
uv run run_benchmark.py --dry-run --all-cells                   # plan only, spends nothing

uv run table.py results/<stamp>/results.json                    # re-render a summary
uv run table.py results/<new>/results.json --against results/<old>/results.json
```

Credentials come from the environment, or from `--env-file <path>` holding those three lines.
Nothing else about the target deployment is assumed, so the same benchmark runs against local
docker-compose, the preview stack, staging, or cloud.

**Exit code is 1** when the run misses `--threshold` (default 0.95), when a hard-fail instrument
fires, or when any trial was skipped. A benchmark that always exits 0 is invisible to CI.

## The two numbers, and why there are two

| | meaning |
|---|---|
| `one_shot` | every check passed **and** the trial stayed inside its budget (tool errors, commit calls) |
| `excl. harness` | `one_shot`, forgiving trials blocked only by a runtime failure with no error code |
| `eventual` | every check passed, whatever it cost along the way |

The **gap between them is the error-then-fix rate**. A product that errors on half its turns and
recovers reports itself as correct if you only publish `eventual`, and that is precisely the
outcome the 95% goal rejects. Both numbers appear in every table.

Each scenario states its own `budget`, because "one-shot" is not the same shape everywhere. A
conflict scenario allows one tool error and two commits: a 409 the model recovers from on the very
next call *is* the one-shot outcome there, since the platform was right to refuse.

**`excl. harness` is not a softer score, it is a different question.** An engine refusal carries a
`code` from the error envelope and is a model result. A harness error carries none — a malformed
tool-input serialization, an EISDIR — and is the runtime failing to carry a call the model made
correctly. Two same-text baseline runs of `claude-haiku-local` scored **37% and 24%** one-shot;
corrected, they are **45% and 42%**. Nearly all of that 13-point spread was one plumbing bug, and
a noise band that wide would swamp any wording change worth making. Report both: `one_shot` is
what a user experiences, `excl. harness` is what an instruction change can move, and the gap
between them is a bug with an owner.

## Failure shapes: why a score is not enough

Two cells can score the same on the same scenario and need **opposite** fixes. That is not
hypothetical — it is what the release gate's discovery cell measured on 6 August, driving the
verbatim `gstack-autoplan` prompt with a live key. Both harnesses landed on 2/3, for different
reasons:

| leg | shape | what happened |
|---|---|---|
| `pi_core` + `claude-haiku-4-5` (session 7b4a1f01) | `attempt_refused` | Copied the whole skill *directory* into `.agenta-imports/`, then referenced a path that did not match. The fail-closed deny correctly stopped it. It used the surface and got the details wrong. |
| `codex` + `gpt-5.6-luna` (session 4fa17164) | `described_no_action` | Correctly described the mechanism — "skills must be enabled through the agent configuration" — and then made **zero tool calls**. It knew the surface and never reached for it. |

A directive "always attempt the tool calls; do not only describe the mechanism" would plausibly
move the second and do nothing for the first. A path-handling correction would do the reverse. So
every trial carries an `outcome` label (`bench_lib.classify_outcome`), and the summary prints the
distribution per cell and the worst scenario/shape pairs:

| label | meaning | what it argues for |
|---|---|---|
| `one_shot` | passed, inside budget | — |
| `recovered` | passed, over budget | error-then-fix; look at the error code |
| `wrong_surface` | no config call, but the workspace **was written** — the job was done somewhere that is rebuilt next run, and reported as success | a location sentence |
| `described_no_action` | no config call, no write, and the reply explains the mechanism it declined to use | directive guidance |
| `no_action` | no config call and nothing to show for it | discoverability |
| `attempt_refused` | a config tool was called and refused | a mechanical correction; the error `code` names which |
| `committed_wrong` | a config tool succeeded and the stored row is still wrong | precision in the description |
| `unsettled` | never finished — wire error, or still gated at max rounds | not a model result |

Shell calls count toward `wrong_surface` only when the **command** is mutating (`cp`, `mv`, `>`,
`sed -i`, …). Classifying on the tool *name* would label a model that merely looked around before
explaining itself as `wrong_surface`, which is exactly the confusion the taxonomy exists to
prevent.

`fm-03-harness-skills-folder` carries a `baseline` block recording the two measurements above, so
a wording change has a before-number to beat on the two harnesses this benchmark could not measure
on its own.

**State the prediction before you measure.** A change proposed for one shape should say which
shape it is expected to move and which it is not; the outcome table then either confirms it or
shows the change moved something else, which is information either way.

## What a verdict is allowed to look at

**The stored revision row.** Not the reply. A denied tool call once produced a passing reply
because the model computed the answer it was meant to fetch (`qa_product.py`, the BASH_TOKEN
lesson). Prose is not evidence of a side effect.

The one exception is a read scenario, where the answer *is* the deliverable — and there the check
looks for a **per-trial random token** seeded into the configuration, which the model cannot
produce without having looked.

Checks address the stored row with **the same target grammar the model uses**:

```json
{ "check": "stored_contains",
  "path": [{"list": "skills", "key": "release-qa"},
           {"list": "files", "key": "checklist.md"}, "content"],
  "text": "smoke suite" }
```

### The check vocabulary

| check | asserts |
|---|---|
| `stored_equals` / `stored_contains` / `stored_not_contains` | an exact stored value or substring |
| `stored_matches` | a regex, where the *wording* is the model's to choose |
| `stored_count` | how many times a substring occurs — the disambiguation case |
| `stored_len` / `stored_present` / `stored_absent` | list length and entry membership |
| `stored_unchanged_except` | **collateral damage**: every branch outside `allowed` equals the baseline |
| `revision_created` / `no_revision_created` | a row was, or was not, written |
| `no_stored_marker` | no invented `@ag.*` marker survived into storage |
| `no_stored_gateway_without_connection` | no gateway tool committed without its connection |
| `turn_reply_contains` / `turn_reply_not_contains` | the reply, token-gated (read scenarios) |
| `turn_tool_called` | a call went out, optionally scoped to one scenario turn |

`stored_matches` exists to prevent **false failures**, which corrode a benchmark as fast as false
passes: a user asked for "the release-qa skill" and a model that writes "the release QA skill" has
done the job. Where the bytes matter — an anchor, a command, a token — `stored_contains` still
means exactly what it says.

## Scenarios

JSON under `scenarios/`, one file per action class, deliberately separate from the runner: adding a
task must never mean editing the driver, and a reviewer should be able to read the whole suite
without reading any Python. Each file's `about` block explains what the class measures.

| file | class | rows |
|---|---|---|
| `01-read.json` | read | read a value; read a list |
| `02-edit-instructions.json` | edit_text | replace a sentence; add a line |
| `03-skills.json` | skills | add, edit a body, remove, rename |
| `04-list-entries.json` | list_entries | remove, add, and the **nested** selector (a file inside a skill) |
| `05-import.json` | import | a skill from a file the user saved, through an approval gate |
| `06-conflict.json` | conflict | the head moved; did the other writer's change survive? |
| `07-multistep.json` | multistep | read-then-edit; two changes in one message |
| `08-failure-modes.json` | failure_mode | five failures seen in live QA, each a hard fail if reproduced |

Prompts are written the way a human types — no tool names, no field paths, no mechanism. One is
Mahmoud's verbatim message from session b59cb549.

### Anatomy of a scenario

```json
{
  "id": "conflict-01-stale-base",
  "seed":            { "instructions": { "agents_md": "..." } },
  "seed_workspace":  { "incident-review/SKILL.md": "...{{TOKEN}}..." },
  "tools":           [{ "type": "platform", "op": "list_connections" }],
  "requires":        ["gateway"],
  "turns": [
    { "prompt": "..." },
    { "before_turn": { "action": "commit_out_of_band", "patch": { } },
      "prompt": "..." }
  ],
  "budget": { "max_tool_errors": 0, "max_commit_calls": 1, "max_rounds": 8 },
  "checks": [ ]
}
```

`{{TOKEN}}` is replaced everywhere — seed, workspace files, prompts, checks — by one fresh random
token per trial, so no answer can come from priors, from the prompt, or from a previous trial.

`before_turn` moves the head **without the model**, which is the only honest way to produce a
conflict: a teammate editing the agent in the playground is what actually happens.

## The global instrument

`identical_call_resent_after_refusal` runs on **every** trial, not only where a scenario expects a
refusal — the behavior it catches can appear anywhere, and it is most surprising where nobody was
watching. It fires when a config tool call is re-sent byte-for-byte after a refusal the model
cannot fix by resending, which is the signature of reading `retryable` and ignoring `next_step`.

It excludes two things, both learned by watching it misfire: harness built-in tools (it first fired
on Claude's own `Edit` refusing "read the file first"), and refusals the envelope marked
`retryable: true`, where re-sending the identical call is exactly what the contract asks for.

## Cells

Eleven cells across three harnesses and two sandboxes. `--list` prints them. Subscription auth
where one exists, a vault key where subscription auth is refused — every Daytona cell is
managed-key, because Daytona rejects runtime-provided auth by design.

A cell missing its credential **SKIPs with the reason**, and a skipped trial fails the run. A skip
is an untested claim, never a pass.

## Version stamps, and why they are not optional

Every results file records, for each instruction surface the improvement loop is allowed to touch,
the **commit that last changed it** and a **sha256 of the bytes on disk at run time**:

| surface | file |
|---|---|
| tool descriptions | `sdks/python/agenta/sdk/agents/platform/op_catalog.py` |
| platform guidance | `services/runner/src/engines/sandbox_agent/platform-guidance.ts` |
| guidance composer | `services/runner/src/engines/sandbox_agent/system-prompt-appendix.ts` |
| mount guidance | `services/runner/src/engines/sandbox_agent/agent-mount-guidance.ts` |
| engine errors | `api/oss/src/core/workflows/change_set.py` |
| guidance skill | `.agents/skills/build-agent/SKILL.md` |

The digest is not redundant with the commit. An uncommitted edit is exactly what an improvement
loop produces, and a commit hash alone would attribute the new numbers to the old text. `table.py
--against` prints which surfaces changed between two runs before it prints the delta — a
per-scenario delta without that is a rumor.

## Results

`results/` is **append-only**. `MANIFEST.md` carries one line per run — when, what, the score, and
the stamps of the two surfaces most likely to have moved. A benchmark whose history can be edited
cannot show that a wording change helped, which is the whole point of the loop.

## The improvement loop

1. Run the matrix. Find the lowest cell x scenario rows.
2. Read the **failure shape**, not just the score. `described_no_action` and `attempt_refused` are
   different problems even at the same rate.
3. Name the **instruction surface** that failed the model: tool description wording, the platform
   guidance block, or the guidance skill. The shape, the `top failure` column, and the error `code`
   on each failing trial point at it.
4. Draft the minimal text change, and **write down which shape it should move and which it should
   not**. **Do not change tool structure** — schemas, operations, endpoints — except very
   minimally, with explicit justification.
5. Re-run the same cells and scenarios. `table.py --against` shows the delta with the stamps; the
   outcome table shows whether the shape you predicted is the one that moved.

A change that raises the score by moving a shape it was not aimed at has not been understood yet,
and the next change built on top of it will be guesswork.

Guidance text changes route through verify-runner's composer (it has a length tripwire, and the
budget being spent is the same small model's attention the author's own instructions draw on).
Tool description changes route through the SDK catalog.

## The UI tier

Designed, not built. It would drive the playground in a browser and answer what the wire cannot:
whether the approval **card** shows the human what they need to decide, and whether the config
drawer after a commit matches the row that was stored.

The seam is one function wide, in `bench_lib.TIERS` and `run_benchmark.run_turn`. A UI tier must
reuse the same scenarios and the same checks against the same stored row, or its numbers stop
being comparable to these — which would forfeit the only reason to build it.

## What the first three-harness run found

`results/20260806-200904/` — claude-haiku, pi-luna, codex-luna, local sandbox, 20 scenarios x 3
trials, 180 trials, $2.93.

| cell | one-shot | excl. harness | gap | guidance |
|---|---|---|---|---|
| claude-haiku-local | 42% | 53% | 11 pts | `92da411b` |
| pi-luna-local | 30% (35% excluding pi-unsupported rows) | 40% | 10 pts | `92da411b` |
| codex-luna-local | 23% | 32% | 9 pts | `92da411b` |
| pi-haiku-local (`results/20260806-212004/`) | **27%** | **75%** | **48 pts** | `cda38f6f` |

**The last row is not comparable to the first three, and the stamps are the only reason anyone
knows.** The platform guidance changed between the two runs — verify-runner landed the
instructions-source sentence at 21:00, between the three-cell slice (20:09) and the pi-haiku run
(21:20). So `pi-haiku-local` has no pre-change baseline, and its low `wrong_surface` count may
already reflect the fix rather than the harness. I published this table once without the guidance
column and had to correct it; the column is now mandatory whenever rows come from different runs.
This is the failure mode the version stamps exist to catch, and it caught it.

**Read the gap column before the score.** `pi-haiku-local` looks like the worst cell and is very
nearly the best one: it completes the task in 75% of trials and loses 48 points to a single
repeated error. A benchmark that only published `one_shot` would have sent someone to fix the
model.

That error turned out not to be plumbing at all — it is the `read_config` tool description. It
says "Send `target.path`" once in dotted prose, then shows two worked examples that are **bare
arrays with no key and no envelope**. Models copy the examples: pi sends `{"target": [...]}` and
drops the wrapper (32 occurrences), and claude emits
`{"target": \n<parameter name="path">[...]}`, reaching for an XML tag to name the wrapper (16
occurrences). One confusion, two serializers. `commit_revision` shows a complete argument object in
its example and does not have the problem.

**`wrong_surface` was 64 of 117 failures**, on every harness: the model edits the rendered
instructions file and reports success. Nothing is stored.

**The suite contains its own natural experiment for that finding.** The skill-location sentence
already exists in the platform guidance; an instructions-location sentence does not. Splitting the
same run by what the scenario targets:

| cell | instruction-target | skill-target |
|---|---|---|
| claude-haiku-local | 0/18 one-shot, 15 `wrong_surface` | 12/21, **0** `wrong_surface` |
| pi-luna-local | 2/18, 12 `wrong_surface` | 9/21, **0** `wrong_surface` |
| codex-luna-local | 0/18, 16 `wrong_surface` | 6/21, 13 `wrong_surface` |

Where the guidance covers the action, the failure disappears. Where it does not, the failure is
near-total. That is the strongest evidence this benchmark can produce that the missing sentence is
the cause rather than a correlate — and it is worth re-running as a control whenever a guidance
sentence is added or removed.

**Codex is the exception, and not for a wording reason.** Its workspace ships bundled system
skills (`.codex/skills/.system/skill-creator`, `.../skill-installer`) documenting how to install a
skill into `.codex/skills` — exactly the folder the guidance says does not count. Codex's
`wrong_surface` skill trials carry 47 references to `.codex/skills`, 15 to skill-creator, and 7
`init_skill.py` invocations, with replies like *"I'm using the skill-installer workflow … to
install it into the configured skills location."* A sentence in an appendix does not beat a
documented procedure sitting in the model's own workspace. Fixing it is a packaging decision about
the codex home the runner assembles, not a text change.

## Round 1 of the improvement loop

The instructions-source sentence landed at ~21:00 (`platform_guidance` `92da411b` -> `cda38f6f`).
Re-measured like-for-like, same 7 instruction-targeted scenarios, same 3 cells, 3 trials, against
`results/20260806-200904/`:

| cell | before | after (clean) |
|---|---|---|
| claude-haiku-local | 0/21 | 10/21 (48%) |
| pi-luna-local | 2/21 | 19/21 (90%) |
| codex-luna-local | 0/21 | 13/21 (62%) |
| **total** | **2/63 (3%)** | **42/63 (67%)** |

**The stamps separated the two causes, which is the whole reason they exist.** Three runs, and
exactly one surface moved between each pair:

| run | guidance | tools | one-shot | `wrong_surface` | `attempt_refused` |
|---|---|---|---|---|---|
| pre 20:09 | `92da411b` | `7d39c5d9` | 32% | 37% | 1% |
| 21:36 (contaminated) | `cda38f6f` | `7d39c5d9` | 24% | 10% | 52% |
| clean 22:09 | `cda38f6f` | `a85076d4` | 67% | 11% | 0% |

Between the first two only the **guidance** moved, and `wrong_surface` fell 37% -> 10%: that is
the sentence, single-variable. Between the last two only the **tools** stamp moved (a migration
milestone) and an outage was fixed, and `wrong_surface` stayed flat at 11% while one-shot went
24% -> 67%. So the sentence owns the `wrong_surface` drop and held it across an unrelated landing;
the one-shot recovery is the outage fix, not the sentence.

Do not read `3% -> 67%` as the sentence's effect. It spans three changes and is the honest
answer to "where were we, where are we now". The sentence's own effect is the `wrong_surface`
line. And do not compare the 32% and 67% one-shot figures directly: the first is across 20
scenarios, the second across the 7 hardest.

`wrong_surface` fell from 37% to 10% of trials and `fm-01` — the control — did not move, so the
predicted shape is the one that changed. Three caveats travel with the number and none of them are
optional: codex's jump is **jointly caused** (a codex-specific sentence landed in the same window),
pi regressed for reasons not readable through the outage below, and **the whole run is
contaminated** — the read-config endpoint began returning HTTP 500 on every call between the two
runs (84 occurrences), so this is a floor rather than a result. It is recorded here as provisional
and will be re-run against a healthy stack.

The reading that fits: the sentence made models reach for the tool instead of editing the file,
which exposed them far more to the tool path's own defects. The sentence worked; the tool path
became the binding constraint.

### The codex half

A codex-specific sentence landed in the same window, naming the bundled `skill-creator` and
`skill-installer` as installing somewhere that is not the configuration. Deleting those bundled
skills was investigated and **refused as unsafe** (they are literals inside the codex binary, a
sibling skill depends on them by relative path, and codex's own prompt references the `.system`
tree), so the sentence was the only lever. On the codex skill set:

| | before | after |
|---|---|---|
| one-shot | 6/21 (29%) | 14/21 (67%) |
| `wrong_surface` | 13 | 2 |

`fm-03` — the verbatim `gstack-autoplan` prompt that started all of this — went 1/3 to 3/3.
Attribution is the same argument as above: a migration milestone landed in the window too, but it
changed routing and error envelopes, which have no mechanism for changing *where* a model writes a
file. The `wrong_surface` collapse is the sentence.

## Notes for anyone extending this

- **MCP entries are nested** (`connection.url`, not a flat `url`), and the **hostname must
  resolve** — an outbound egress guard validates it before the run starts, so an invented
  `.example` host 500s the whole invoke before the model sees anything. Both cost a smoke run to
  learn.
- **A gated tool call appears in two wire turns** with the same `toolCallId`. Count distinct call
  ids (`bench_lib.distinct_calls`), or every approved commit counts twice and clean trials score
  as over budget.
- **Every harness names its tools differently, so never match a roster of identifiers.** Observed:
  claude `Edit`/`Write`/`Read File`/`Terminal`; pi `Edit`/`read`/`ls`/`find`/`grep`/`Bash`; codex
  `"Editing files"`, `"List files in 'x'"`, and **the shell command itself as the tool name**. The
  first classifier matched `("Edit", "Write", …)` exactly, so 31 codex trials that really did
  rewrite `AGENTS.md` were labelled `no_action` — and the taxonomy pointed at the wrong fix for an
  entire harness. Match on shape (`_EDIT_NAME_RE`, plus a mutating-command check against both the
  name and the input), and re-check any new harness against a real transcript.
- **The Pi harness rejects user MCP servers outright.** Scenarios that seed `mcps` carry
  `"unsupported_harness": ["pi_core"]` and skip there; without it the run fails before the model
  sees the task and 12 trials counted as config-editing failures that measured nothing.
- **Skip markers must be specific, or the benchmark hides failures behind a reassuring word.**
  The first credential matcher included the bare string `connection`, which also matches
  `All connection attempts failed` and `peer closed connection`. Four transport failures were
  labelled "missing credential" and skipped out of the denominator (`pi-haiku-local` read 12/44
  when it was 12/48). `TRANSPORT_MARKERS` is now checked first and never skips — a transport error
  falls through to `unsettled`, which is counted and visible. A skip is an untested claim; a
  *misclassified* skip is worse, because it hides a real failure.
- **Codex's search changes with task framing (n=1, unconfirmed).** Asked to READ a file seeded in
  the durable agent folder, codex found it with both vague ("your folder") and explicit wording.
  Asked to adopt the same file as its instructions, it looked at the workspace root and told the
  user to save a file they had already saved. That rules out reachability and delivery; what
  remains is a hypothesis worth one run if `fm-01` still fails after the guidance change.
- **Infrastructure must never be scored as model behaviour, and it will try to be, three ways.**
  (1) A skip matcher that pattern-matched `connection` swallowed transport failures. (2) A live
  outage produced 84 tool errors that read as refusals. (3) An upstream provider retry arrives as
  the assistant's *reply text* — `Retrying (attempt 1/3, waiting 2s)...` — on a turn that settles
  normally, which naive scoring reads as a model that did nothing; one rate-limited run put a cell
  at 10% with ten invented failures. Each is now caught (`TRANSPORT_MARKERS`, the pre-flight,
  `_PROVIDER_RETRY_RE`). Every instance inflated a FAILURE count, never a success count, which is
  the direction that quietly makes a product look worse than it is.
- **The pre-flight gates on the transport trials actually use, not on a route.** A migration
  flipped the config ops to handler mode, so a direct probe of the legacy endpoint could pass
  while the real path was broken — and that endpoint is scheduled for deletion, which would later
  make it a false red. The legacy probe is advisory; the gate is one live agent turn that must get
  a served `read_config`.
- **A pre-flight cannot catch an INTERMITTENT failure, and that limit is honest rather than
  fixable here.** One healthy live turn says nothing about a fault that spikes under concurrency.
  The right answer to a transport that fails silently is for the runner to surface it onto the
  wire, not for the benchmark to simulate load: tonight a runner-to-harness transport was
  reportedly failing in the runner logs while ZERO trace of it appeared in any wire data across
  seven runs. A client cannot assert on what it cannot see.
- **Never compare two runs' cell totals without checking the SCENARIO SET.** A cell read 19/21 in
  one run and 12/21 in the next and looked like a regression; the two runs measured different
  scenarios (instruction-targeted versus skill/read), so the pairing was meaningless. `table.py
  --against` warns on this; a hand-written comparison has no such guard.
- **When a turn dies, ask whether it made PROGRESS first — that names the owner.** A reply
  carrying a provider retry with ZERO tool calls died at the start: upstream capacity, not the
  product. Tool calls followed by silence is a session evicted or a transport dropped mid-run,
  which IS the product's problem. Two cells on one shared key failed the same way for different
  reasons within an hour, and the same lens split a certification cell's three failures into
  one-with-progress and two-without. Recorded per trial as `infra_signature`; both still score
  `unsettled`, because this is triage information, not a verdict.
- **Codex reports no usage on the wire**, so cost accounting is blind for codex cells and every
  total understates by whatever they spent.
- **`table.py` re-labels stored trials on read.** Outcome definitions will keep improving; an
  append-only history is only worth keeping if old runs can be re-read under the current one. The
  stored `results.json` is never modified.
- **`qa_matrix_lib` is imported, never copied.** It carries the `workflow_refs` parent-scoping fix,
  the assistant-message reconstruction that makes an approval reply valid, and the harness-kind
  enum gotchas. A copy drifts the day one of those is corrected.

---

### Design Agent Workflows Archive README (`docs/design/agent-workflows/archive/README.md`)

# Trash

This folder holds historical work-package notes, research spikes, proof-of-concept code,
and superseded RFCs for the agent workflow project.

It is not the source of truth. Current design pages live one level up. Read files here only
when you need build history, old rationale, or a discarded alternative.

## Contents

- `wp-*`: original work-package notes.
- `research/`: raw research from the early build.
- `harness-port-redesign/`: old redesign notes that led to the current SDK ports.
- `sdk-local-backend/`: blocked local backend notes.
- `old-rfcs/`: superseded protocol RFCs. Current protocol docs live in
  [../protocol.md](../protocol.md).

---

### Design Agent Workflows Interfaces README (`docs/design/agent-workflows/interfaces/README.md`)

# Agent Workflow Interfaces

The agent workflow stack spans a Python service, a Node runner, a sandboxed harness, a
browser client, the vault, and the trace pipeline. A change in one of these places often
breaks a contract that lives in another. This folder names those contracts so a reviewer
can tell, before reading the diff, which boundary a change touches and what it can break.

Read it as review context, not as a tutorial. The code is still the source of truth. Each
page points at the files that own the contract and says what to check when it moves.

## How the inventory is organized

The split is by blast radius, because blast radius is what decides how careful a review
has to be.

- **[Public edge](public-edge/)** holds the contracts that browser and workflow clients
  depend on. Break one and you break callers you do not control, so these change most
  conservatively.
- **[Cross-service](cross-service/)** holds contracts that cross a process, container, or
  external service boundary. Each side deploys and fails on its own, so a field can change
  on one side and reach an older version on the other.
- **[In-service](in-service/)** holds contracts that stay inside one process or package.
  They are still contracts. They break adapters, tests, and extension points even when no
  wire field changes.

## How to read each page

Every page follows the same shape so you can scan it fast:

- One short statement of what crosses the boundary and why it matters.
- The concrete contract: the real types, fields, and shapes, not a list of names.
- The files that own it.
- What to check when you change it, including the tests that move with it.

## The interfaces at a glance

One row per interface, so a reviewer can find the boundary a diff touches before opening a
page. `Status` is read from each page's prose: **stable** (wired and unlikely to move),
**evolving** (wired but actively changing or only partly enforced), **declared-not-wired**
(the shape exists but nothing applies it yet).

| Interface | Blast radius | Owner file(s) | Status | Tests |
|---|---|---|---|---|
| [`/invoke`](public-edge/workflow-invoke.md) | public | `decorators/routing.py`, `models/workflows.py`, `agent/app.py` | stable | `unit/agent/`, `utils/test_messages_endpoint.py` |
| [`/inspect`](public-edge/workflow-inspect.md) | public | `agent/schemas.py`, `agent/app.py` (builtin-URI binding), `models/workflows.py`, `decorators/routing.py` | stable | `unit/agents/test_dtos_agent_config.py`, `unit/agent/test_builtin_uri_binding.py` |
| [`/messages`](public-edge/agent-messages.md) | public | `adapters/vercel/{routing,messages,stream}.py`, `agentRequest.ts` | evolving (create-or-resume not observable until storage lands) | `utils/test_messages_endpoint.py`, `unit/agents/test_ui_messages.py` |
| [Agent config schema](public-edge/agent-config-schema.md) | public | `agent/schemas.py`, `sdk/utils/types.py` (`build_agent_v0_default`), `agents/dtos.py`, `core/workflows/build_kit.py`, `AgentTemplateControl.tsx` | evolving (creation defaults and shared settings; request fallback unchanged) | `unit/agents/test_dtos_agent_template.py`, `services/oss/tests/pytest/unit/agent/test_default_agent_template.py`, API `test_build_kit_overlay.py`, entity UI `agentSettings.test.tsx`, `agentConfigPatch.test.ts`, `sectionChanges.test.ts` |
| [`/run`](cross-service/service-to-agent-runner.md) | cross-service (the spine) | `protocol.ts`, `utils/wire.py`, `utils/ts_runner.py`, `server.ts`/`cli.ts` | stable (pinned by golden) | `unit/agents/test_wire_contract.py` + `golden/`, `services/runner/tests/unit/wire-contract.test.ts` |
| [Runner to harness](cross-service/runner-to-harness.md) | cross-service (ACP) | `engines/sandbox_agent.ts` + `sandbox_agent/{run-plan,capabilities,permissions}.ts` | evolving | `services/runner/tests/unit/sandbox-agent-*.test.ts` |
| [Runner to MCP server](cross-service/runner-to-mcp-server.md) | cross-service | `agents/mcp/`, `engines/sandbox_agent/{mcp,tool-mcp-assets,relay-guard}.ts`, `tools/{mcp-bridge,tool-mcp-http,tool-mcp-stdio,tool-mcp-env,relay,relay-client,relay-protocol,relay-watch}.ts` | evolving (internal channel delivered locally over loopback HTTP and on Daytona via the in-sandbox stdio shim, `client` tools included — a client call parks via a paused relay answer; user stdio disabled) | `services/runner/tests/unit/{mcp-servers,session-mcp-layering,tool-mcp-assets,tool-mcp-stdio,tool-relay-guard}.test.ts` |
| [Runner to tool callback](cross-service/runner-to-tool-callback.md) | cross-service | `tools/{callback,dispatch,direct,run-credential}.ts`, `apis/fastapi/tools/router.py` (`/tools/call`, `/tools/discover`, `_call_reserved_agenta_tool`), `core/tools/{discovery,service,platform_handlers}.py`, `agent/tools/resolver.py` | evolving (the `call` descriptor is wired and platform ops emit it; the legacy `tools.agenta.find_capabilities` route is deleted; reserved refs now dispatch server handlers, resolution flag-gated off until the runner half lands) | `services/runner/tests/unit/{code-tool,extension-tools,tool-credential-rotation,tool-callback-credential}.test.ts`, `api unit/tools/{test_workflow_tool_call,test_discovery,test_platform_handlers}.py`, `unit/agents/platform/test_op_catalog.py` |
| [Service and runner trace export](cross-service/service-and-runner-trace-export.md) | cross-service | `agent/tracing.py`, `tracing/otel.ts`, `extensions/agenta.ts` | stable | `services/runner/tests/unit/` |
| [Service to vault and tool providers](cross-service/service-to-vault-and-tool-providers.md) | cross-service (external) | `agent/app.py`, `platform/{resolve,connections}.py`, `agents/capabilities.py`, `tools/router.py` | stable | `unit/agents/connections/`, `unit/agents/platform/`, `unit/agents/tools/` |
| [Agent service handler](in-service/agent-service-handler.md) | in-service | `services/oss/src/agent/app.py` | stable | `services/oss/tests/pytest/unit/agent/` |
| [Neutral runtime DTOs](in-service/neutral-runtime-dtos.md) | in-service | `agents/dtos.py` | evolving | `unit/agents/test_dtos_*.py`, `test_harness_identity.py`, `test_agent_composition_seam.py` |
| [Runtime ports](in-service/runtime-ports.md) | in-service | `agents/interfaces.py` | evolving (`LocalBackend` stub) | `unit/agents/test_environment_lifecycle.py`, `test_harness_adapters.py` |
| [Backend adapter](in-service/backend-adapter.md) | in-service | `agents/interfaces.py`, `agents/adapters/sandbox_agent.py`, `agents/utils/wire.py` | evolving | `unit/agents/test_runner_adapter_config.py`, `test_environment_lifecycle.py`, `test_agent_composition_seam.py` |
| [Harness adapters](in-service/harness-adapters.md) | in-service | `agents/adapters/harnesses.py`, `agents/adapters/claude_settings.py`, `agents/dtos.py`, `sdk/agents/pi_builtins.py` | stable | `unit/agents/test_harness_adapters.py`, `test_dtos_harness_configs.py`, `unit/agents/adapters/test_claude_settings.py` |
| [Browser protocol adapter](in-service/browser-protocol-adapter.md) | in-service | `agents/adapters/vercel/{routing,messages,stream,sse}.py` | stable | `unit/agents/test_ui_messages.py`, `utils/test_messages_endpoint.py` |
| [Tool models and resolution](in-service/tool-models-and-resolution.md) | in-service | `agents/tools/{models,interfaces,resolver}.py`, `platform/{gateway,workflow,op_catalog,platform_tools}.py` | evolving | `unit/agents/tools/`, `unit/agents/platform/test_gateway_connection_resolve.py`, `unit/agents/platform/test_op_catalog.py` |
| [MCP models and resolution](in-service/mcp-models-and-resolution.md) | in-service | `agents/mcp/{models,resolver,wire}.py` | evolving (stdio wired; remote deferred; resolution feature-gated) | `unit/agents/mcp/` |
| [Model connection resolution](in-service/model-connection-resolution.md) | in-service | `agent/app.py`, `agents/connections/`, `platform/{resolve,connections}.py`, `agents/capabilities.py` | stable | `unit/agents/connections/` |
| [Runner engine internals](in-service/runner-engine-internals.md) | in-service (runner) | `server.ts`, `cli.ts`, `engines/sandbox_agent.ts` | stable | `services/runner/tests/unit/{server,cli}.test.ts` |
| [Permission responder](in-service/permission-responder.md) | in-service (runner) | `responder.ts`, `engines/sandbox_agent/permissions.ts` | stable | `services/runner/tests/unit/{responder,sandbox-agent-permissions}.test.ts` |
| [Sandbox permission](in-service/sandbox-permission.md) | in-service (runner) | `agents/dtos.py`, `protocol.ts`, `engines/sandbox_agent/{provider,run-plan}.ts` | evolving (network enforced on Daytona only; local rejected; filesystem nowhere) | `services/runner/tests/unit/{sandbox-agent-provider,sandbox-agent-run-plan}.test.ts` |

Paths are relative to the owner package (`sdks/python/agenta/sdk/`, `services/runner/src/`,
`services/oss/src/`, `api/oss/src/`); test paths are relative to each package's pytest root
unless prefixed.

## Follow-up design notes

- [Agent workflow interface architecture follow-ups](architecture-followups.md) tracks
  proposed fixes for interface-design risks found during review.

## Source of truth

When a field changes, update the owner file, the tests, and the matching page here in the
same PR. A page that has drifted from the code is worse than no page. It reads as
authoritative while it is wrong.

---

--- METRICS ---
- Files Extracted: 101
- Estimated Token Budget: ~113504 tokens
- Canonical Reference: https://codewiki.google/github.com/Agenta-AI/agenta
