指南 · OPENAI
Codex 编排的开源规范:Symphony
了解 Symphony 如何作为 Codex 编排的开源规范,将 issue 跟踪器转变为始终在线的智能体系统,从而提升工程产出并减少上下文切换。
本篇转载 OpenAI 官方简体中文版(作者 Alex Kotliarskyi、Victor Zhu 和 Zach Brock),未另行翻译。英文原文:https://openai.com/index/open-source-codex-orchestration-symphony/
六个月前,在开发一个内部生产力工具时,我们团队做出了一个当时颇具争议的决定:构建一个完全没有人工编写代码的代码仓库。仓库中的每一行代码都必须由 Codex 生成。
为了实现这一目标,我们从底层重新设计了工程工作流。我们构建了一个对智能体友好的代码仓库,大量投入自动化测试和防护机制,并将 Codex 视为一个完整的团队成员。我们在此前关于运行框架 (harness) 工程的博客文章中记录了这一过程。
这一方法确实奏效了,但随后我们遇到了下一个瓶颈:上下文切换。
为了解决这个问题,我们构建了一个名为 Symphony 的系统。Symphony(在新窗口中打开) 是一个智能体编排器,它将类似 Linear 的项目管理看板转化为编程智能体的控制平面 (control plane)。每一个未关闭的任务都会对应一个智能体,智能体持续运行,而人类负责审查结果。
本文将介绍我们如何构建 Symphony — 在部分团队中将已合并到主分支的 Pull Request 数量提升了 500% — 以及如何将你自己的 issue 跟踪系统转化为一个始终在线的智能体编排系统。
交互式编程智能体的上限
即使编程智能体变得越来越易用 — 无论是通过 Web 应用还是 CLI 访问 — 它们本质上仍然是交互式工具。
随着 OpenAI 内部智能体工作规模的扩大,我们开始感受到一种新的负担。每位工程师都会打开多个 Codex 会话,分配任务、审查输出、引导智能体,然后不断重复这一过程。在实践中,大多数人通常只能同时管理 3 到 5 个会话,再多就会因为上下文切换而变得困难。一旦超过这个范围,生产力就会下降:我们会忘记每个会话正在做什么,在不同终端之间来回切换以将智能体拉回正轨,还需要调试那些中途停滞的长时间运行任务。
智能体本身运行很快,但系统的瓶颈在于人类注意力。我们实际上构建了一支能力极强的“初级工程师团队”,却让人类工程师对其进行细粒度管理。这种模式无法扩展。
视角的转变
我们意识到,我们优化的对象是错误的。我们一直围绕编程会话和已合并的 PR 来组织系统,而实际上,这两者只是达成目标的手段。软件工作流通常是围绕交付物组织的,例如 issue、任务、工单和里程碑。
于是我们开始思考:如果不再直接监督智能体,而是让它们从任务跟踪系统中主动获取工作,会发生什么?
这个想法最终演变为 Symphony — 一份书面规范 (spec),作为“监督者”来编排智能体工作。
将 issue 跟踪器转化为智能体编排器
Symphony 源于一个简单的理念:任何未关闭的任务都应由智能体接手并完成。我们不再在多个标签页中管理 Codex 会话,而是将 issue 跟踪系统作为控制平面 (control plane)。
在这一模式下,每一个未关闭的 Linear issue 都会映射到一个专属的智能体工作空间。Symphony 持续监控任务看板,确保每一个活跃任务在完成之前始终有智能体在循环执行。如果某个智能体崩溃或卡住,Symphony 会自动重启它;如果出现新的工作,Symphony 会立即接手并开始组织执行。
我们的工作流是基于工单状态构建的,将任务管理工具 Linear 作为一个状态机来使用。
在实践中,Symphony 将工作从会话和 Pull Request 中解耦。有些 issue 会在多个代码仓库中产生多个 PR;而另一些则只是纯粹的调研或分析,完全不会涉及代码库。
一旦以这种方式对工作进行抽象,工单就可以代表更大粒度的工作单元。
我们经常使用 Symphony 来编排复杂功能开发和基础设施迁移。例如,我们可以创建一个任务,让智能体分析代码库、Slack 或 Notion,并产出一份实现方案。当我们确认方案可行后,智能体会生成一棵任务树,将工作拆分为多个阶段,并定义任务之间的依赖关系。
智能体只会处理未被阻塞的任务,因此在这个 DAG(一个执行步骤序列)结构中,执行会自然且高效地并行展开。在下面的示例中,我们将 React 升级标记为依赖 Vite 迁移。正如预期,智能体会在 Vite 迁移完成之后才开始升级 React。 智能体还可以自行创建任务。在实现或审查过程中,它们经常会发现一些超出当前任务范围的改进点,例如性能问题、重构机会或更优架构。这时,它们会直接创建新的 issue,供我们后续评估和排期 — 其中许多后续任务同样会被智能体接手执行。在我们进行整体监督的同时,智能体能够保持有序并持续推进工作。
这种工作方式显著降低了启动不确定性任务的认知成本。即使智能体做错了,这些结果仍然具有信息价值,而我们的成本几乎为零。我们可以以极低成本创建工单,让智能体进行原型验证和探索,并随时丢弃不满意的结果。
由于编排器运行在开发环境 (devbox) 上且始终在线,我们可以在任何地方添加任务,并确信会有智能体接手处理。例如,我们团队中曾有工程师在一个网络条件较差的小木屋里,仅通过手机上的 Linear 应用就完成了三项重要变更。
这种工作方式带来的探索能力提升
在观察 Symphony 带来的影响时,最直观的变化是产出。在 OpenAI 的一些团队中,已合并到主分支的 PR 数量在前三周内增长了 6 倍。在 OpenAI 之外,Linear 创始人 Karri Saarinen 也提到,在 Symphony 发布后,工作空间创建量出现了明显增长(在新窗口中打开)。不过,更深层的变化在于团队对“工作”的理解方式。
当工程师不再需要花时间管理 Codex 会话时,代码变更的成本结构发生了根本变化。由于不再需要投入人力推动具体实现,每一次变更的感知成本显著下降。
这也改变了我们的工作方式。在 Symphony 中启动探索性任务变得非常轻量:尝试一个想法、探索一次重构、验证一个假设,然后只保留那些有价值的结果。
此外,它还扩大了可以发起工作的角色范围。产品经理和设计师现在可以直接在 Symphony 中提交功能请求,无需检出代码仓库,也无需管理 Codex 会话。他们只需描述需求,就能获得一个评审包,其中包含该功能在真实产品中的视频演示。
Symphony 在大型单体仓库(就像我们在 OpenAI 用的那种) 中同样表现出色。在这种环境下,将一个 PR 成功落地到主分支的“收尾阶段”往往缓慢且脆弱。系统会持续监控 CI,在需要时自动执行变基、解决冲突、重试不稳定的检查,并整体上推动变更通过整个流水线。当一个任务进入合并阶段时,我们已经可以高度确信该变更能够在无需人工干预的情况下顺利进入主分支。
进步也会带来新的问题
在这一层级上运作不可避免地存在权衡。当我们从交互式引导智能体转向按工单分配工作时,我们失去了在执行过程中持续干预并随时纠偏的能力。有时智能体产出的结果会完全偏离预期。但这些失败同样具有价值 — 它们暴露了系统中的缺口,并帮助我们提升系统的稳健性。
我们没有手动修补这些结果,而是增加防护措施和技能,使智能体在下一次能够正确完成任务。随着时间推移,这促使我们为运行框架 (harness) 增加了新的能力,例如运行端到端测试、通过 Chrome DevTools 驱动应用,以及管理 QA 冒烟测试。同时,我们也显著改进了文档,并明确了什么才是“好的结果”。
并非所有任务都适合 Symphony 这种工作方式。有些问题仍然需要工程师直接使用交互式 Codex 会话来处理,尤其是那些高度不确定或需要强判断力与专业经验的任务。在实践中,这类任务通常也是工程师最有兴趣投入精力的部分。
不同之处在于,Symphony 可以处理大部分常规实现工作。这使工程师能够一次专注于一个复杂问题,而不必在大量小任务之间频繁切换上下文。
我们还发现,将智能体当作状态机中的刚性节点并不是一个理想的模型。随着模型能力的提升,它们能够解决的问题远超我们试图限定的范围。例如,在早期版本中,所有 GitHub 集成都被放在外层运行框架 (harness) 中 — 当时我们假设 Codex 只负责代码修改,而将提交变更、运行测试等流程写死在系统中。早期版本的智能体工作方式只是让 Codex 完成具体任务本身,这种方式被证明具有不少局限性。事实上,Codex 完全可以创建多个 PR,也可以读取评审反馈并进行修改。因此我们为它提供了更多工具 — 例如 gh CLI、读取 CI 日志的技能等 — 现在我们可以让 Codex 执行更多类型的工作,例如关闭旧 PR,或生成已完成与已放弃任务的报告。这类工作已经远远超出了最初“功能实现”的范围。
因此,我们最终转向为智能体设定*“目标 (objective)”*,而不是严格的状态转换。这类似于优秀的管理者为团队成员设定目标的方式。模型的核心能力在于推理,因此应为其提供工具和上下文,然后让它们自主完成任务。
用 Symphony 构建 Symphony
当你打开 Symphony 代码仓库时,首先会注意到的是:从技术上讲,Symphony 其实只是一个 SPEC.md 文件 — 它定义了问题以及预期的解决方案。我们没有构建一个复杂的监督系统,而是通过定义问题和目标解法,为智能体提供高层次的引导。
Markdown
# Symphony Service Specification
Status: Draft v1 (language-agnostic)
Purpose: Define a service that orchestrates coding agents to get project work done.
## 1. Problem Statement
Symphony is a long-running automation service that continuously reads work from an issue tracker
(Linear in this specification version), creates an isolated workspace for each issue, and runs a
coding agent session for that issue inside the workspace.
The service solves four operational problems:
- It turns issue execution into a repeatable daemon workflow instead of manual scripts.
- It isolates agent execution in per-issue workspaces so agent commands run only inside per-issue
workspace directories.
- It keeps the workflow policy in-repo (`WORKFLOW.md`) so teams version the agent prompt and runtime
settings with their code.
- It provides enough observability to operate and debug multiple concurrent agent runs.
Implementations are expected to document their trust and safety posture explicitly. This
specification does not require a single approval, sandbox, or operator-confirmation policy; some
implementations may target trusted environments with a high-trust configuration, while others may
require stricter approvals or sandboxing.
Important boundary:
- Symphony is a scheduler/runner and tracker reader.
- Ticket writes (state transitions, comments, PR links) are typically performed by the coding agent
using tools available in the workflow/runtime environment.
- A successful run may end at a workflow-defined handoff state (for example `Human Review`), not
necessarily `Done`.
## 2. Goals and Non-Goals
### 2.1 Goals
- Poll the issue tracker on a fixed cadence and dispatch work with bounded concurrency.
- Maintain a single authoritative orchestrator state for dispatch, retries, and reconciliation.
- Create deterministic per-issue workspaces and preserve them across runs.
- Stop active runs when issue state changes make them ineligible.
- Recover from transient failures with exponential backoff.
- Load runtime behavior from a repository-owned `WORKFLOW.md` contract.
- Expose operator-visible observability (at minimum structured logs).
- Support restart recovery without requiring a persistent database.
### 2.2 Non-Goals
- Rich web UI or multi-tenant control plane.
- Prescribing a specific dashboard or terminal UI implementation.
- General-purpose workflow engine or distributed job scheduler.
- Built-in business logic for how to edit tickets, PRs, or comments. (That logic lives in the
workflow prompt and agent tooling.)
- Mandating strong sandbox controls beyond what the coding agent and host OS provide.
- Mandating a single default approval, sandbox, or operator-confirmation posture for all
implementations.
## 3. System Overview
### 3.1 Main Components
1. `Workflow Loader`
- Reads `WORKFLOW.md`.
- Parses YAML front matter and prompt body.
- Returns `{config, prompt_template}`.
2. `Config Layer`
- Exposes typed getters for workflow config values.
- Applies defaults and environment variable indirection.
- Performs validation used by the orchestrator before dispatch.
3. `Issue Tracker Client`
- Fetches candidate issues in active states.
- Fetches current states for specific issue IDs (reconciliation).
- Fetches terminal-state issues during startup cleanup.
- Normalizes tracker payloads into a stable issue model.
4. `Orchestrator`
- Owns the poll tick.
- Owns the in-memory runtime state.
- Decides which issues to dispatch, retry, stop, or release.
- Tracks session metrics and retry queue state.
5. `Workspace Manager`
- Maps issue identifiers to workspace paths.
- Ensures per-issue workspace directories exist.
- Runs workspace lifecycle hooks.
- Cleans workspaces for terminal issues.
6. `Agent Runner`
- Creates workspace.
- Builds prompt from issue + workflow template.
- Launches the coding agent app-server client.
- Streams agent updates back to the orchestrator.
7. `Status Surface` (optional)
- Presents human-readable runtime status (for example terminal output, dashboard, or other
operator-facing view).
8. `Logging`
- Emits structured runtime logs to one or more configured sinks.
### 3.2 Abstraction Levels
Symphony is easiest to port when kept in these layers:
1. `Policy Layer` (repo-defined)
- `WORKFLOW.md` prompt body.
- Team-specific rules for ticket handling, validation, and handoff.
2. `Configuration Layer` (typed getters)
- Parses front matter into typed runtime settings.
- Handles defaults, environment tokens, and path normalization.
3. `Coordination Layer` (orchestrator)
- Polling loop, issue eligibility, concurrency, retries, reconciliation.
4. `Execution Layer` (workspace + agent subprocess)
- Filesystem lifecycle, workspace preparation, coding-agent protocol.
5. `Integration Layer` (Linear adapter)
- API calls and normalization for tracker data.
6. `Observability Layer` (logs + optional status surface)
- Operator visibility into orchestrator and agent behavior.
### 3.3 External Dependencies
- Issue tracker API (Linear for `tracker.kind: linear` in this specification version).
- Local filesystem for workspaces and logs.
- Optional workspace population tooling (for example Git CLI, if used).
- Coding-agent executable that supports JSON-RPC-like app-server mode over stdio.
- Host environment authentication for the issue tracker and coding agent.
## 4. Core Domain Model
### 4.1 Entities
#### 4.1.1 Issue
Normalized issue record used by orchestration, prompt rendering, and observability output.
Fields:
- `id` (string)
- Stable tracker-internal ID.
- `identifier` (string)
- Human-readable ticket key (example: `ABC-123`).
- `title` (string)
- `description` (string or null)
- `priority` (integer or null)
- Lower numbers are higher priority in dispatch sorting.
- `state` (string)
- Current tracker state name.
- `branch_name` (string or null)
- Tracker-provided branch metadata if available.
- `url` (string or null)
- `labels` (list of strings)
- Normalized to lowercase.
- `blocked_by` (list of blocker refs)
- Each blocker ref contains:
- `id` (string or null)
- `identifier` (string or null)
- `state` (string or null)
- `created_at` (timestamp or null)
- `updated_at` (timestamp or null)
#### 4.1.2 Workflow Definition
Parsed `WORKFLOW.md` payload:
- `config` (map)
- YAML front matter root object.
- `prompt_template` (string)
- Markdown body after front matter, trimmed.
#### 4.1.3 Service Config (Typed View)
Typed runtime values derived from `WorkflowDefinition.config` plus environment resolution.
Examples:
- poll interval
- workspace root
- active and terminal issue states
- concurrency limits
- coding-agent executable/args/timeouts
- workspace hooks
#### 4.1.4 Workspace
Filesystem workspace assigned to one issue identifier.
Fields (logical):
- `path` (workspace path; current runtime typically uses absolute paths, but relative roots are
possible if configured without path separators)
- `workspace_key` (sanitized issue identifier)
- `created_now` (boolean, used to gate `after_create` hook)
#### 4.1.5 Run Attempt
One execution attempt for one issue.
Fields (logical):
- `issue_id`
- `issue_identifier`
- `attempt` (integer or null, `null` for first run, `>=1` for retries/continuation)
- `workspace_path`
- `started_at`
- `status`
- `error` (optional)
#### 4.1.6 Live Session (Agent Session Metadata)
State tracked while a coding-agent subprocess is running.
Fields:
- `session_id` (string, `<thread_id>-<turn_id>`)
- `thread_id` (string)
- `turn_id` (string)
- `codex_app_server_pid` (string or null)
- `last_codex_event` (string/enum or null)
- `last_codex_timestamp` (timestamp or null)
- `last_codex_message` (summarized payload)
- `codex_input_tokens` (integer)
- `codex_output_tokens` (integer)
- `codex_total_tokens` (integer)
- `last_reported_input_tokens` (integer)
- `last_reported_output_tokens` (integer)
- `last_reported_total_tokens` (integer)
- `turn_count` (integer)
- Number of coding-agent turns started within the current worker lifetime.
#### 4.1.7 Retry Entry
Scheduled retry state for an issue.
Fields:
- `issue_id`
- `identifier` (best-effort human ID for status surfaces/logs)
- `attempt` (integer, 1-based for retry queue)
- `due_at_ms` (monotonic clock timestamp)
- `timer_handle` (runtime-specific timer reference)
- `error` (string or null)
#### 4.1.8 Orchestrator Runtime State
Single authoritative in-memory state owned by the orchestrator.
Fields:
- `poll_interval_ms` (current effective poll interval)
- `max_concurrent_agents` (current effective global concurrency limit)
- `running` (map `issue_id -> running entry`)
- `claimed` (set of issue IDs reserved/running/retrying)
- `retry_attempts` (map `issue_id -> RetryEntry`)
- `completed` (set of issue IDs; bookkeeping only, not dispatch gating)
- `codex_totals` (aggregate tokens + runtime seconds)
- `codex_rate_limits` (latest rate-limit snapshot from agent events)
### 4.2 Stable Identifiers and Normalization Rules
- `Issue ID`
- Use for tracker lookups and internal map keys.
- `Issue Identifier`
- Use for human-readable logs and workspace naming.
- `Workspace Key`
- Derive from `issue.identifier` by replacing any character not in `[A-Za-z0-9._-]` with `_`.
- Use the sanitized value for the workspace directory name.
- `Normalized Issue State`
- Compare states after `lowercase`.
- `Session ID`
- Compose from coding-agent `thread_id` and `turn_id` as `<thread_id>-<turn_id>`.
## 5. Workflow Specification (Repository Contract)
### 5.1 File Discovery and Path Resolution
Workflow file path precedence:
1. Explicit application/runtime setting (set by CLI startup path).
2. Default: `WORKFLOW.md` in the current process working directory.
Loader behavior:
- If the file cannot be read, return `missing_workflow_file` error.
- The workflow file is expected to be repository-owned and version-controlled.
### 5.2 File Format
`WORKFLOW.md` is a Markdown file with optional YAML front matter.
Design note:
- `WORKFLOW.md` should be self-contained enough to describe and run different workflows (prompt,
runtime settings, hooks, and tracker selection/config) without requiring out-of-band
service-specific configuration.
Parsing rules:
- If file starts with `---`, parse lines until the next `---` as YAML front matter.
- Remaining lines become the prompt body.
- If front matter is absent, treat the entire file as prompt body and use an empty config map.
- YAML front matter must decode to a map/object; non-map YAML is an error.
- Prompt body is trimmed before use.
Returned workflow object:
- `config`: front matter root object (not nested under a `config` key).
- `prompt_template`: trimmed Markdown body.
### 5.3 Front Matter Schema
Top-level keys:
- `tracker`
- `polling`
- `workspace`
- `hooks`
- `agent`
- `codex`
Unknown keys should be ignored for forward compatibility.
Note:
- The workflow front matter is extensible. Optional extensions may define additional top-level keys
(for example `server`) without changing the core schema above.
- Extensions should document their field schema, defaults, validation rules, and whether changes
apply dynamically or require restart.
- Common extension: `server.port` (integer) enables the optional HTTP server described in Section
13.7.
#### 5.3.1 `tracker` (object)
Fields:
- `kind` (string)
- Required for dispatch.
- Current supported value: `linear`
- `endpoint` (string)
- Default for `tracker.kind == "linear"`: `https://api.linear.app/graphql`
- `api_key` (string)
- May be a literal token or `$VAR_NAME`.
- Canonical environment variable for `tracker.kind == "linear"`: `LINEAR_API_KEY`.
- If `$VAR_NAME` resolves to an empty string, treat the key as missing.
- `project_slug` (string)
- Required for dispatch when `tracker.kind == "linear"`.
- `active_states` (list of strings)
- Default: `Todo`, `In Progress`
- `terminal_states` (list of strings)
- Default: `Closed`, `Cancelled`, `Canceled`, `Duplicate`, `Done`
#### 5.3.2 `polling` (object)
Fields:
- `interval_ms` (integer or string integer)
- Default: `30000`
- Changes should be re-applied at runtime and affect future tick scheduling without restart.
#### 5.3.3 `workspace` (object)
Fields:
- `root` (path string or `$VAR`)
- Default: `<system-temp>/symphony_workspaces`
- `~` and strings containing path separators are expanded.
- Bare strings without path separators are preserved as-is (relative roots are allowed but
discouraged).
#### 5.3.4 `hooks` (object)
Fields:
- `after_create` (multiline shell script string, optional)
- Runs only when a workspace directory is newly created.
- Failure aborts workspace creation.
- `before_run` (multiline shell script string, optional)
- Runs before each agent attempt after workspace preparation and before launching the coding
agent.
- Failure aborts the current attempt.
- `after_run` (multiline shell script string, optional)
- Runs after each agent attempt (success, failure, timeout, or cancellation) once the workspace
exists.
- Failure is logged but ignored.
- `before_remove` (multiline shell script string, optional)
- Runs before workspace deletion if the directory exists.
- Failure is logged but ignored; cleanup still proceeds.
- `timeout_ms` (integer, optional)
- Default: `60000`
- Applies to all workspace hooks.
- Non-positive values should be treated as invalid and fall back to the default.
- Changes should be re-applied at runtime for future hook executions.
#### 5.3.5 `agent` (object)
Fields:
- `max_concurrent_agents` (integer or string integer)
- Default: `10`
- Changes should be re-applied at runtime and affect subsequent dispatch decisions.
- `max_retry_backoff_ms` (integer or string integer)
- Default: `300000` (5 minutes)
- Changes should be re-applied at runtime and affect future retry scheduling.
- `max_concurrent_agents_by_state` (map `state_name -> positive integer`)
- Default: empty map.
- State keys are normalized (`lowercase`) for lookup.
- Invalid entries (non-positive or non-numeric) are ignored.
#### 5.3.6 `codex` (object)
Fields:
For Codex-owned config values such as `approval_policy`, `thread_sandbox`, and
`turn_sandbox_policy`, supported values are defined by the targeted Codex app-server version.
Implementors should treat them as pass-through Codex config values rather than relying on a
hand-maintained enum in this spec. To inspect the installed Codex schema, run
`codex app-server generate-json-schema --out <dir>` and inspect the relevant definitions referenced
by `v2/ThreadStartParams.json` and `v2/TurnStartParams.json`. Implementations may validate these
fields locally if they want stricter startup checks.
- `command` (string shell command)
- Default: `codex app-server`
- The runtime launches this command via `bash -lc` in the workspace directory.
- The launched process must speak a compatible app-server protocol over stdio.
- `approval_policy` (Codex `AskForApproval` value)
- Default: implementation-defined.
- `thread_sandbox` (Codex `SandboxMode` value)
- Default: implementation-defined.
- `turn_sandbox_policy` (Codex `SandboxPolicy` value)
- Default: implementation-defined.
- `turn_timeout_ms` (integer)
- Default: `3600000` (1 hour)
- `read_timeout_ms` (integer)
- Default: `5000`
- `stall_timeout_ms` (integer)
- Default: `300000` (5 minutes)
- If `<= 0`, stall detection is disabled.
### 5.4 Prompt Template Contract
The Markdown body of `WORKFLOW.md` is the per-issue prompt template.
Rendering requirements:
- Use a strict template engine (Liquid-compatible semantics are sufficient).
- Unknown variables must fail rendering.
- Unknown filters must fail rendering.
Template input variables:
- `issue` (object)
- Includes all normalized issue fields, including labels and blockers.
- `attempt` (integer or null)
- `null`/absent on first attempt.
- Integer on retry or continuation run.
Fallback prompt behavior:
- If the workflow prompt body is empty, the runtime may use a minimal default prompt
(`You are working on an issue from Linear.`).
- Workflow file read/parse failures are configuration/validation errors and should not silently fall
back to a prompt.
### 5.5 Workflow Validation and Error Surface
Error classes:
- `missing_workflow_file`
- `workflow_parse_error`
- `workflow_front_matter_not_a_map`
- `template_parse_error` (during prompt rendering)
- `template_render_error` (unknown variable/filter, invalid interpolation)
Dispatch gating behavior:
- Workflow file read/YAML errors block new dispatches until fixed.
- Template errors fail only the affected run attempt.
## 6. Configuration Specification
### 6.1 Source Precedence and Resolution Semantics
Configuration precedence:
1. Workflow file path selection (runtime setting -> cwd default).
2. YAML front matter values.
3. Environment indirection via `$VAR_NAME` inside selected YAML values.
4. Built-in defaults.
Value coercion semantics:
- Path/command fields support:
- `~` home expansion
- `$VAR` expansion for env-backed path values
- Apply expansion only to values intended to be local filesystem paths; do not rewrite URIs or
arbitrary shell command strings.
### 6.2 Dynamic Reload Semantics
Dynamic reload is required:
- The software should watch `WORKFLOW.md` for changes.
- On change, it should re-read and re-apply workflow config and prompt template without restart.
- The software should attempt to adjust live behavior to the new config (for example polling
cadence, concurrency limits, active/terminal states, codex settings, workspace paths/hooks, and
prompt content for future runs).
- Reloaded config applies to future dispatch, retry scheduling, reconciliation decisions, hook
execution, and agent launches.
- Implementations are not required to restart in-flight agent sessions automatically when config
changes.
- Extensions that manage their own listeners/resources (for example an HTTP server port change) may
require restart unless the implementation explicitly supports live rebind.
- Implementations should also re-validate/reload defensively during runtime operations (for example
before dispatch) in case filesystem watch events are missed.
- Invalid reloads should not crash the service; keep operating with the last known good effective
configuration and emit an operator-visible error.
### 6.3 Dispatch Preflight Validation
This validation is a scheduler preflight run before attempting to dispatch new work. It validates
the workflow/config needed to poll and launch workers, not a full audit of all possible workflow
behavior.
Startup validation:
- Validate configuration before starting the scheduling loop.
- If startup validation fails, fail startup and emit an operator-visible error.
Per-tick dispatch validation:
- Re-validate before each dispatch cycle.
- If validation fails, skip dispatch for that tick, keep reconciliation active, and emit an
operator-visible error.
Validation checks:
- Workflow file can be loaded and parsed.
- `tracker.kind` is present and supported.
- `tracker.api_key` is present after `$` resolution.
- `tracker.project_slug` is present when required by the selected tracker kind.
- `codex.command` is present and non-empty.
### 6.4 Config Fields Summary (Cheat Sheet)
This section is intentionally redundant so a coding agent can implement the config layer quickly.
- `tracker.kind`: string, required, currently `linear`
- `tracker.endpoint`: string, default `https://api.linear.app/graphql` when `tracker.kind=linear`
- `tracker.api_key`: string or `$VAR`, canonical env `LINEAR_API_KEY` when `tracker.kind=linear`
- `tracker.project_slug`: string, required when `tracker.kind=linear`
- `tracker.active_states`: list of strings, default `["Todo", "In Progress"]`
- `tracker.terminal_states`: list of strings, default `["Closed", "Cancelled", "Canceled", "Duplicate", "Done"]`
- `polling.interval_ms`: integer, default `30000`
- `workspace.root`: path, default `<system-temp>/symphony_workspaces`
- `worker.ssh_hosts` (extension): list of SSH host strings, optional; when omitted, work runs
locally
- `worker.max_concurrent_agents_per_host` (extension): positive integer, optional; shared per-host
cap applied across configured SSH hosts
- `hooks.after_create`: shell script or null
- `hooks.before_run`: shell script or null
- `hooks.after_run`: shell script or null
- `hooks.before_remove`: shell script or null
- `hooks.timeout_ms`: integer, default `60000`
- `agent.max_concurrent_agents`: integer, default `10`
- `agent.max_turns`: integer, default `20`
- `agent.max_retry_backoff_ms`: integer, default `300000` (5m)
- `agent.max_concurrent_agents_by_state`: map of positive integers, default `{}`
- `codex.command`: shell command string, default `codex app-server`
- `codex.approval_policy`: Codex `AskForApproval` value, default implementation-defined
- `codex.thread_sandbox`: Codex `SandboxMode` value, default implementation-defined
- `codex.turn_sandbox_policy`: Codex `SandboxPolicy` value, default implementation-defined
- `codex.turn_timeout_ms`: integer, default `3600000`
- `codex.read_timeout_ms`: integer, default `5000`
- `codex.stall_timeout_ms`: integer, default `300000`
- `server.port` (extension): integer, optional; enables the optional HTTP server, `0` may be used
for ephemeral local bind, and CLI `--port` overrides it
## 7. Orchestration State Machine
The orchestrator is the only component that mutates scheduling state. All worker outcomes are
reported back to it and converted into explicit state transitions.
### 7.1 Issue Orchestration States
This is not the same as tracker states (`Todo`, `In Progress`, etc.). This is the service's internal
claim state.
1. `Unclaimed`
- Issue is not running and has no retry scheduled.
2. `Claimed`
- Orchestrator has reserved the issue to prevent duplicate dispatch.
- In practice, claimed issues are either `Running` or `RetryQueued`.
3. `Running`
- Worker task exists and the issue is tracked in `running` map.
4. `RetryQueued`
- Worker is not running, but a retry timer exists in `retry_attempts`.
5. `Released`
- Claim removed because issue is terminal, non-active, missing, or retry path completed without
re-dispatch.
Important nuance:
- A successful worker exit does not mean the issue is done forever.
- The worker may continue through multiple back-to-back coding-agent turns before it exits.
- After each normal turn completion, the worker re-checks the tracker issue state.
- If the issue is still in an active state, the worker should start another turn on the same live
coding-agent thread in the same workspace, up to `agent.max_turns`.
- The first turn should use the full rendered task prompt.
- Continuation turns should send only continuation guidance to the existing thread, not resend the
original task prompt that is already present in thread history.
- Once the worker exits normally, the orchestrator still schedules a short continuation retry
(about 1 second) so it can re-check whether the issue remains active and needs another worker
session.
### 7.2 Run Attempt Lifecycle
A run attempt transitions through these phases:
1. `PreparingWorkspace`
2. `BuildingPrompt`
3. `LaunchingAgentProcess`
4. `InitializingSession`
5. `StreamingTurn`
6. `Finishing`
7. `Succeeded`
8. `Failed`
9. `TimedOut`
10. `Stalled`
11. `CanceledByReconciliation`
Distinct terminal reasons are important because retry logic and logs differ.
### 7.3 Transition Triggers
- `Poll Tick`
- Reconcile active runs.
- Validate config.
- Fetch candidate issues.
- Dispatch until slots are exhausted.
- `Worker Exit (normal)`
- Remove running entry.
- Update aggregate runtime totals.
- Schedule continuation retry (attempt `1`) after the worker exhausts or finishes its in-process
turn loop.
- `Worker Exit (abnormal)`
- Remove running entry.
- Update aggregate runtime totals.
- Schedule exponential-backoff retry.
- `Codex Update Event`
- Update live session fields, token counters, and rate limits.
- `Retry Timer Fired`
- Re-fetch active candidates and attempt re-dispatch, or release claim if no longer eligible.
- `Reconciliation State Refresh`
- Stop runs whose issue states are terminal or no longer active.
- `Stall Timeout`
- Kill worker and schedule retry.
### 7.4 Idempotency and Recovery Rules
- The orchestrator serializes state mutations through one authority to avoid duplicate dispatch.
- `claimed` and `running` checks are required before launching any worker.
- Reconciliation runs before dispatch on every tick.
- Restart recovery is tracker-driven and filesystem-driven (no durable orchestrator DB required).
- Startup terminal cleanup removes stale workspaces for issues already in terminal states.
## 8. Polling, Scheduling, and Reconciliation
### 8.1 Poll Loop
At startup, the service validates config, performs startup cleanup, schedules an immediate tick, and
then repeats every `polling.interval_ms`.
The effective poll interval should be updated when workflow config changes are re-applied.
Tick sequence:
1. Reconcile running issues.
2. Run dispatch preflight validation.
3. Fetch candidate issues from tracker using active states.
4. Sort issues by dispatch priority.
5. Dispatch eligible issues while slots remain.
6. Notify observability/status consumers of state changes.
If per-tick validation fails, dispatch is skipped for that tick, but reconciliation still happens
first.
### 8.2 Candidate Selection Rules
An issue is dispatch-eligible only if all are true:
- It has `id`, `identifier`, `title`, and `state`.
- Its state is in `active_states` and not in `terminal_states`.
- It is not already in `running`.
- It is not already in `claimed`.
- Global concurrency slots are available.
- Per-state concurrency slots are available.
- Blocker rule for `Todo` state passes:
- If the issue state is `Todo`, do not dispatch when any blocker is non-terminal.
Sorting order (stable intent):
1. `priority` ascending (1..4 are preferred; null/unknown sorts last)
2. `created_at` oldest first
3. `identifier` lexicographic tie-breaker
### 8.3 Concurrency Control
Global limit:
- `available_slots = max(max_concurrent_agents - running_count, 0)`
Per-state limit:
- `max_concurrent_agents_by_state[state]` if present (state key normalized)
- otherwise fallback to global limit
The runtime counts issues by their current tracked state in the `running` map.
Optional SSH host limit:
- When `worker.max_concurrent_agents_per_host` is set, each configured SSH host may run at most
that many concurrent agents at once.
- Hosts at that cap are skipped for new dispatch until capacity frees up.
### 8.4 Retry and Backoff
Retry entry creation:
- Cancel any existing retry timer for the same issue.
- Store `attempt`, `identifier`, `error`, `due_at_ms`, and new timer handle.
Backoff formula:
- Normal continuation retries after a clean worker exit use a short fixed delay of `1000` ms.
- Failure-driven retries use `delay = min(10000 * 2^(attempt - 1), agent.max_retry_backoff_ms)`.
- Power is capped by the configured max retry backoff (default `300000` / 5m).
Retry handling behavior:
1. Fetch active candidate issues (not all issues).
2. Find the specific issue by `issue_id`.
3. If not found, release claim.
4. If found and still candidate-eligible:
- Dispatch if slots are available.
- Otherwise requeue with error `no available orchestrator slots`.
5. If found but no longer active, release claim.
Note:
- Terminal-state workspace cleanup is handled by startup cleanup and active-run reconciliation
(including terminal transitions for currently running issues).
- Retry handling mainly operates on active candidates and releases claims when the issue is absent,
rather than performing terminal cleanup itself.
### 8.5 Active Run Reconciliation
Reconciliation runs every tick and has two parts.
Part A: Stall detection
- For each running issue, compute `elapsed_ms` since:
- `last_codex_timestamp` if any event has been seen, else
- `started_at`
- If `elapsed_ms > codex.stall_timeout_ms`, terminate the worker and queue a retry.
- If `stall_timeout_ms <= 0`, skip stall detection entirely.
Part B: Tracker state refresh
- Fetch current issue states for all running issue IDs.
- For each running issue:
- If tracker state is terminal: terminate worker and clean workspace.
- If tracker state is still active: update the in-memory issue snapshot.
- If tracker state is neither active nor terminal: terminate worker without workspace cleanup.
- If state refresh fails, keep workers running and try again on the next tick.
### 8.6 Startup Terminal Workspace Cleanup
When the service starts:
1. Query tracker for issues in terminal states.
2. For each returned issue identifier, remove the corresponding workspace directory.
3. If the terminal-issues fetch fails, log a warning and continue startup.
This prevents stale terminal workspaces from accumulating after restarts.
## 9. Workspace Management and Safety
### 9.1 Workspace Layout
Workspace root:
- `workspace.root` (normalized path; the current config layer expands path-like values and preserves
bare relative names)
Per-issue workspace path:
- `<workspace.root>/<sanitized_issue_identifier>`
Workspace persistence:
- Workspaces are reused across runs for the same issue.
- Successful runs do not auto-delete workspaces.
### 9.2 Workspace Creation and Reuse
Input: `issue.identifier`
Algorithm summary:
1. Sanitize identifier to `workspace_key`.
2. Compute workspace path under workspace root.
3. Ensure the workspace path exists as a directory.
4. Mark `created_now=true` only if the directory was created during this call; otherwise
`created_now=false`.
5. If `created_now=true`, run `after_create` hook if configured.
Notes:
- This section does not assume any specific repository/VCS workflow.
- Workspace preparation beyond directory creation (for example dependency bootstrap, checkout/sync,
code generation) is implementation-defined and is typically handled via hooks.
### 9.3 Optional Workspace Population (Implementation-Defined)
The spec does not require any built-in VCS or repository bootstrap behavior.
Implementations may populate or synchronize the workspace using implementation-defined logic and/or
hooks (for example `after_create` and/or `before_run`).
Failure handling:
- Workspace population/synchronization failures return an error for the current attempt.
- If failure happens while creating a brand-new workspace, implementations may remove the partially
prepared directory.
- Reused workspaces should not be destructively reset on population failure unless that policy is
explicitly chosen and documented.
### 9.4 Workspace Hooks
Supported hooks:
- `hooks.after_create`
- `hooks.before_run`
- `hooks.after_run`
- `hooks.before_remove`
Execution contract:
- Execute in a local shell context appropriate to the host OS, with the workspace directory as
`cwd`.
- On POSIX systems, `sh -lc <script>` (or a stricter equivalent such as `bash -lc <script>`) is a
conforming default.
- Hook timeout uses `hooks.timeout_ms`; default: `60000 ms`.
- Log hook start, failures, and timeouts.
Failure semantics:
- `after_create` failure or timeout is fatal to workspace creation.
- `before_run` failure or timeout is fatal to the current run attempt.
- `after_run` failure or timeout is logged and ignored.
- `before_remove` failure or timeout is logged and ignored.
### 9.5 Safety Invariants
This is the most important portability constraint.
Invariant 1: Run the coding agent only in the per-issue workspace path.
- Before launching the coding-agent subprocess, validate:
- `cwd == workspace_path`
Invariant 2: Workspace path must stay inside workspace root.
- Normalize both paths to absolute.
- Require `workspace_path` to have `workspace_root` as a prefix directory.
- Reject any path outside the workspace root.
Invariant 3: Workspace key is sanitized.
- Only `[A-Za-z0-9._-]` allowed in workspace directory names.
- Replace all other characters with `_`.
## 10. Agent Runner Protocol (Coding Agent Integration)
This section defines the language-neutral contract for integrating a coding agent app-server.
Compatibility profile:
- The normative contract is message ordering, required behaviors, and the logical fields that must
be extracted (for example session IDs, completion state, approval handling, and usage/rate-limit
telemetry).
- Exact JSON field names may vary slightly across compatible app-server versions.
- Implementations should tolerate equivalent payload shapes when they carry the same logical
meaning, especially for nested IDs, approval requests, user-input-required signals, and
token/rate-limit metadata.
### 10.1 Launch Contract
Subprocess launch parameters:
- Command: `codex.command`
- Invocation: `bash -lc <codex.command>`
- Working directory: workspace path
- Stdout/stderr: separate streams
- Framing: line-delimited protocol messages on stdout (JSON-RPC-like JSON per line)
Notes:
- The default command is `codex app-server`.
- Approval policy, cwd, and prompt are expressed in the protocol messages in Section 10.2.
Recommended additional process settings:
- Max line size: 10 MB (for safe buffering)
### 10.2 Session Startup Handshake
Reference: https://developers.openai.com/codex/app-server/
The client must send these protocol messages in order:
Illustrative startup transcript (equivalent payload shapes are acceptable if they preserve the same
semantics):
```json
{"id":1,"method":"initialize","params":{"clientInfo":{"name":"symphony","version":"1.0"},"capabilities":{}}}
{"method":"initialized","params":{}}
{"id":2,"method":"thread/start","params":{"approvalPolicy":"<implementation-defined>","sandbox":"<implementation-defined>","cwd":"/abs/workspace"}}
{"id":3,"method":"turn/start","params":{"threadId":"<thread-id>","input":[{"type":"text","text":"<rendered prompt-or-continuation-guidance>"}],"cwd":"/abs/workspace","title":"ABC-123: Example","approvalPolicy":"<implementation-defined>","sandboxPolicy":{"type":"<implementation-defined>"}}}
initializerequest- Params include:
clientInfoobject (for example{name, version})capabilitiesobject (may be empty)
- If the targeted Codex app-server requires capability negotiation for dynamic tools, include the necessary capability flag(s) here.
- Wait for response (
read_timeout_ms)
- Params include:
initializednotificationthread/startrequest- Params include:
approvalPolicy= implementation-defined session approval policy valuesandbox= implementation-defined session sandbox valuecwd= absolute workspace path- If optional client-side tools are implemented, include their advertised tool specs using the protocol mechanism supported by the targeted Codex app-server version.
- Params include:
turn/startrequest- Params include:
threadIdinput= single text item containing rendered prompt for the first turn, or continuation guidance for later turns on the same threadcwdtitle=<issue.identifier>: <issue.title>approvalPolicy= implementation-defined turn approval policy valuesandboxPolicy= implementation-defined object-form sandbox policy payload when required by the targeted app-server version
- Params include:
Session identifiers:
- Read
thread_idfromthread/startresultresult.thread.id - Read
turn_idfrom eachturn/startresultresult.turn.id - Emit
session_id = "<thread_id>-<turn_id>" - Reuse the same
thread_idfor all continuation turns inside one worker run
10.3 Streaming Turn Processing
The client reads line-delimited messages until the turn terminates.
Completion conditions:
turn/completed-> successturn/failed-> failureturn/cancelled-> failure- turn timeout (
turn_timeout_ms) -> failure - subprocess exit -> failure
Continuation processing:
- If the worker decides to continue after a successful turn, it should issue another
turn/starton the same livethreadId. - The app-server subprocess should remain alive across those continuation turns and be stopped only when the worker run is ending.
Line handling requirements:
- Read protocol messages from stdout only.
- Buffer partial stdout lines until newline arrives.
- Attempt JSON parse on complete stdout lines.
- Stderr is not part of the protocol stream:
- ignore it or log it as diagnostics
- do not attempt protocol JSON parsing on stderr
10.4 Emitted Runtime Events (Upstream to Orchestrator)
The app-server client emits structured events to the orchestrator callback. Each event should include:
event(enum/string)timestamp(UTC timestamp)codex_app_server_pid(if available)- optional
usagemap (token counts) - payload fields as needed
Important emitted events may include:
session_startedstartup_failedturn_completedturn_failedturn_cancelledturn_ended_with_errorturn_input_requiredapproval_auto_approvedunsupported_tool_callnotificationother_messagemalformed
10.5 Approval, Tool Calls, and User Input Policy
Approval, sandbox, and user-input behavior is implementation-defined.
Policy requirements:
- Each implementation should document its chosen approval, sandbox, and operator-confirmation posture.
- Approval requests and user-input-required events must not leave a run stalled indefinitely. An implementation should either satisfy them, surface them to an operator, auto-resolve them, or fail the run according to its documented policy.
Example high-trust behavior:
- Auto-approve command execution approvals for the session.
- Auto-approve file-change approvals for the session.
- Treat user-input-required turns as hard failure.
Unsupported dynamic tool calls:
- Supported dynamic tool calls that are explicitly implemented and advertised by the runtime should be handled according to their extension contract.
- If the agent requests a dynamic tool call (
item/tool/call) that is not supported, return a tool failure response and continue the session. - This prevents the session from stalling on unsupported tool execution paths.
Optional client-side tool extension:
- An implementation may expose a limited set of client-side tools to the app-server session.
- Current optional standardized tool:
linear_graphql. - If implemented, supported tools should be advertised to the app-server session during startup using the protocol mechanism supported by the targeted Codex app-server version.
- Unsupported tool names should still return a failure result and continue the session.
linear_graphql extension contract:
-
Purpose: execute a raw GraphQL query or mutation against Linear using Symphony's configured tracker auth for the current session.
-
Availability: only meaningful when
tracker.kind == "linear"and valid Linear auth is configured. -
Preferred input shape:
{ "query": "single GraphQL query or mutation document", "variables": { "optional": "graphql variables object" } } -
querymust be a non-empty string. -
querymust contain exactly one GraphQL operation. -
variablesis optional and, when present, must be a JSON object. -
Implementations may additionally accept a raw GraphQL query string as shorthand input.
-
Execute one GraphQL operation per tool call.
-
If the provided document contains multiple operations, reject the tool call as invalid input.
-
operationNameselection is intentionally out of scope for this extension. -
Reuse the configured Linear endpoint and auth from the active Symphony workflow/runtime config; do not require the coding agent to read raw tokens from disk.
-
Tool result semantics:
- transport success + no top-level GraphQL
errors->success=true - top-level GraphQL
errorspresent ->success=false, but preserve the GraphQL response body for debugging - invalid input, missing auth, or transport failure ->
success=falsewith an error payload
- transport success + no top-level GraphQL
-
Return the GraphQL response or error payload as structured tool output that the model can inspect in-session.
Illustrative responses (equivalent payload shapes are acceptable if they preserve the same outcome):
{"id":"<approval-id>","result":{"approved":true}}
{"id":"<tool-call-id>","result":{"success":false,"error":"unsupported_tool_call"}}
Hard failure on user input requirement:
- If the agent requests user input, fail the run attempt immediately.
- The client detects this via:
- explicit method (
item/tool/requestUserInput), or - turn methods/flags indicating input is required.
- explicit method (
10.6 Timeouts and Error Mapping
Timeouts:
codex.read_timeout_ms: request/response timeout during startup and sync requestscodex.turn_timeout_ms: total turn stream timeoutcodex.stall_timeout_ms: enforced by orchestrator based on event inactivity
Error mapping (recommended normalized categories):
codex_not_foundinvalid_workspace_cwdresponse_timeoutturn_timeoutport_exitresponse_errorturn_failedturn_cancelledturn_input_required
10.7 Agent Runner Contract
The Agent Runner wraps workspace + prompt + app-server client.
Behavior:
- Create/reuse workspace for issue.
- Build prompt from workflow template.
- Start app-server session.
- Forward app-server events to orchestrator.
- On any error, fail the worker attempt (the orchestrator will retry).
Note:
- Workspaces are intentionally preserved after successful runs.
11. Issue Tracker Integration Contract (Linear-Compatible)
11.1 Required Operations
An implementation must support these tracker adapter operations:
-
fetch_candidate_issues()- Return issues in configured active states for a configured project.
-
fetch_issues_by_states(state_names)- Used for startup terminal cleanup.
-
fetch_issue_states_by_ids(issue_ids)- Used for active-run reconciliation.
11.2 Query Semantics (Linear)
Linear-specific requirements for tracker.kind == "linear":
tracker.kind == "linear"- GraphQL endpoint (default
https://api.linear.app/graphql) - Auth token sent in
Authorizationheader tracker.project_slugmaps to Linear projectslugId- Candidate issue query filters project using
project: { slugId: { eq: $projectSlug } } - Issue-state refresh query uses GraphQL issue IDs with variable type
[ID!] - Pagination required for candidate issues
- Page size default:
50 - Network timeout:
30000 ms
Important:
- Linear GraphQL schema details can drift. Keep query construction isolated and test the exact query fields/types required by this specification.
A non-Linear implementation may change transport details, but the normalized outputs must match the domain model in Section 4.
11.3 Normalization Rules
Candidate issue normalization should produce fields listed in Section 4.1.1.
Additional normalization details:
labels-> lowercase stringsblocked_by-> derived from inverse relations where relation type isblockspriority-> integer only (non-integers become null)created_atandupdated_at-> parse ISO-8601 timestamps
11.4 Error Handling Contract
Recommended error categories:
unsupported_tracker_kindmissing_tracker_api_keymissing_tracker_project_sluglinear_api_request(transport failures)linear_api_status(non-200 HTTP)linear_graphql_errorslinear_unknown_payloadlinear_missing_end_cursor(pagination integrity error)
Orchestrator behavior on tracker errors:
- Candidate fetch failure: log and skip dispatch for this tick.
- Running-state refresh failure: log and keep active workers running.
- Startup terminal cleanup failure: log warning and continue startup.
11.5 Tracker Writes (Important Boundary)
Symphony does not require first-class tracker write APIs in the orchestrator.
- Ticket mutations (state transitions, comments, PR metadata) are typically handled by the coding agent using tools defined by the workflow prompt.
- The service remains a scheduler/runner and tracker reader.
- Workflow-specific success often means "reached the next handoff state" (for example
Human Review) rather than tracker terminal stateDone. - If the optional
linear_graphqlclient-side tool extension is implemented, it is still part of the agent toolchain rather than orchestrator business logic.
12. Prompt Construction and Context Assembly
12.1 Inputs
Inputs to prompt rendering:
workflow.prompt_template- normalized
issueobject - optional
attemptinteger (retry/continuation metadata)
12.2 Rendering Rules
- Render with strict variable checking.
- Render with strict filter checking.
- Convert issue object keys to strings for template compatibility.
- Preserve nested arrays/maps (labels, blockers) so templates can iterate.
12.3 Retry/Continuation Semantics
attempt should be passed to the template because the workflow prompt may provide different
instructions for:
- first run (
attemptnull or absent) - continuation run after a successful prior session
- retry after error/timeout/stall
12.4 Failure Semantics
If prompt rendering fails:
- Fail the run attempt immediately.
- Let the orchestrator treat it like any other worker failure and decide retry behavior.
13. Logging, Status, and Observability
13.1 Logging Conventions
Required context fields for issue-related logs:
issue_idissue_identifier
Required context for coding-agent session lifecycle logs:
session_id
Message formatting requirements:
- Use stable
key=valuephrasing. - Include action outcome (
completed,failed,retrying, etc.). - Include concise failure reason when present.
- Avoid logging large raw payloads unless necessary.
13.2 Logging Outputs and Sinks
The spec does not prescribe where logs must go (stderr, file, remote sink, etc.).
Requirements:
- Operators must be able to see startup/validation/dispatch failures without attaching a debugger.
- Implementations may write to one or more sinks.
- If a configured log sink fails, the service should continue running when possible and emit an operator-visible warning through any remaining sink.
13.3 Runtime Snapshot / Monitoring Interface (Optional but Recommended)
If the implementation exposes a synchronous runtime snapshot (for dashboards or monitoring), it should return:
running(list of running session rows)- each running row should include
turn_count retrying(list of retry queue rows)codex_totalsinput_tokensoutput_tokenstotal_tokensseconds_running(aggregate runtime seconds as of snapshot time, including active sessions)
rate_limits(latest coding-agent rate limit payload, if available)
Recommended snapshot error modes:
timeoutunavailable
13.4 Optional Human-Readable Status Surface
A human-readable status surface (terminal output, dashboard, etc.) is optional and implementation-defined.
If present, it should draw from orchestrator state/metrics only and must not be required for correctness.
13.5 Session Metrics and Token Accounting
Token accounting rules:
- Agent events may include token counts in multiple payload shapes.
- Prefer absolute thread totals when available, such as:
thread/tokenUsage/updatedpayloadstotal_token_usagewithin token-count wrapper events
- Ignore delta-style payloads such as
last_token_usagefor dashboard/API totals. - Extract input/output/total token counts leniently from common field names within the selected payload.
- For absolute totals, track deltas relative to last reported totals to avoid double-counting.
- Do not treat generic
usagemaps as cumulative totals unless the event type defines them that way. - Accumulate aggregate totals in orchestrator state.
Runtime accounting:
- Runtime should be reported as a live aggregate at snapshot/render time.
- Implementations may maintain a cumulative counter for ended sessions and add active-session
elapsed time derived from
runningentries (for examplestarted_at) when producing a snapshot/status view. - Add run duration seconds to the cumulative ended-session runtime when a session ends (normal exit or cancellation/termination).
- Continuous background ticking of runtime totals is not required.
Rate-limit tracking:
- Track the latest rate-limit payload seen in any agent update.
- Any human-readable presentation of rate-limit data is implementation-defined.
13.6 Humanized Agent Event Summaries (Optional)
Humanized summaries of raw agent protocol events are optional.
If implemented:
- Treat them as observability-only output.
- Do not make orchestrator logic depend on humanized strings.
json943{"id":1,"method":"initialize","params":{"clientInfo":{"name":"symphony","version":"1.0"},"capabilities":{}}}944{"method":"initialized","params":{}}945{"id":2,"method":"thread/start","params":{"approvalPolicy":"<implementation-defined>","sandbox":"<implementation-defined>","cwd":"/abs/workspace"}}946{"id":3,"method":"turn/start","params":{"threadId":"<thread-id>","input":[{"type":"text","text":"<rendered prompt-or-continuation-guidance>"}],"cwd":"/abs/workspace","title":"ABC-123: Example","approvalPolicy":"<implementation-defined>","sandboxPolicy":{"type":"<implementation-defined>"}}}9479489491.initializerequest950 - Params include:951 -clientInfoobject (for example{name, version})952 -capabilitiesobject (may be empty)953 - If the targeted Codex app-server requires capability negotiation for dynamic tools, include the954 necessary capability flag(s) here.955 - Wait for response (read_timeout_ms)9562.initializednotification9573.thread/startrequest958 - Params include:959 -approvalPolicy= implementation-defined session approval policy value960 -sandbox= implementation-defined session sandbox value961 -cwd= absolute workspace path962 - If optional client-side tools are implemented, include their advertised tool specs using the963 protocol mechanism supported by the targeted Codex app-server version.9644.turn/startrequest965 - Params include:966 -threadId967 -input= single text item containing rendered prompt for the first turn, or continuation968 guidance for later turns on the same thread969 -cwd970 -title=<issue.identifier>: <issue.title>971 -approvalPolicy= implementation-defined turn approval policy value972 -sandboxPolicy= implementation-defined object-form sandbox policy payload when required by973 the targeted app-server version974975Session identifiers:976977- Readthread_idfromthread/startresultresult.thread.id978- Readturn_idfrom eachturn/startresultresult.turn.id979- Emitsession_id = "<thread_id>-<turn_id>"980- Reuse the samethread_idfor all continuation turns inside one worker run981982### 10.3 Streaming Turn Processing983984The client reads line-delimited messages until the turn terminates.985986Completion conditions:987988-turn/completed-> success989-turn/failed-> failure990-turn/cancelled-> failure991- turn timeout (turn_timeout_ms) -> failure992- subprocess exit -> failure993994Continuation processing:995996- If the worker decides to continue after a successful turn, it should issue anotherturn/start997 on the same livethreadId.998- The app-server subprocess should remain alive across those continuation turns and be stopped only999 when the worker run is ending.10001001Line handling requirements:10021003- Read protocol messages from stdout only.1004- Buffer partial stdout lines until newline arrives.1005- Attempt JSON parse on complete stdout lines.1006- Stderr is not part of the protocol stream:1007 - ignore it or log it as diagnostics1008 - do not attempt protocol JSON parsing on stderr10091010### 10.4 Emitted Runtime Events (Upstream to Orchestrator)10111012The app-server client emits structured events to the orchestrator callback. Each event should1013include:10141015-event(enum/string)1016-timestamp(UTC timestamp)1017-codex_app_server_pid(if available)1018- optionalusagemap (token counts)1019- payload fields as needed10201021Important emitted events may include:10221023-session_started1024-startup_failed1025-turn_completed1026-turn_failed1027-turn_cancelled1028-turn_ended_with_error1029-turn_input_required1030-approval_auto_approved1031-unsupported_tool_call1032-notification1033-other_message1034-malformed10351036### 10.5 Approval, Tool Calls, and User Input Policy10371038Approval, sandbox, and user-input behavior is implementation-defined.10391040Policy requirements:10411042- Each implementation should document its chosen approval, sandbox, and operator-confirmation1043 posture.1044- Approval requests and user-input-required events must not leave a run stalled indefinitely. An1045 implementation should either satisfy them, surface them to an operator, auto-resolve them, or1046 fail the run according to its documented policy.10471048Example high-trust behavior:10491050- Auto-approve command execution approvals for the session.1051- Auto-approve file-change approvals for the session.1052- Treat user-input-required turns as hard failure.10531054Unsupported dynamic tool calls:10551056- Supported dynamic tool calls that are explicitly implemented and advertised by the runtime should1057 be handled according to their extension contract.1058- If the agent requests a dynamic tool call (item/tool/call) that is not supported, return a tool1059 failure response and continue the session.1060- This prevents the session from stalling on unsupported tool execution paths.10611062Optional client-side tool extension:10631064- An implementation may expose a limited set of client-side tools to the app-server session.1065- Current optional standardized tool:linear_graphql.1066- If implemented, supported tools should be advertised to the app-server session during startup1067 using the protocol mechanism supported by the targeted Codex app-server version.1068- Unsupported tool names should still return a failure result and continue the session.10691070linear_graphqlextension contract:10711072- Purpose: execute a raw GraphQL query or mutation against Linear using Symphony's configured1073 tracker auth for the current session.1074- Availability: only meaningful whentracker.kind == "linear"and valid Linear auth is configured.1075- Preferred input shape:10761077json1078 {1079 "query": "single GraphQL query or mutation document",1080 "variables": {1081 "optional": "graphql variables object"1082 }1083 }108410851086-querymust be a non-empty string.1087-querymust contain exactly one GraphQL operation.1088-variablesis optional and, when present, must be a JSON object.1089- Implementations may additionally accept a raw GraphQL query string as shorthand input.1090- Execute one GraphQL operation per tool call.1091- If the provided document contains multiple operations, reject the tool call as invalid input.1092-operationNameselection is intentionally out of scope for this extension.1093- Reuse the configured Linear endpoint and auth from the active Symphony workflow/runtime config; do1094 not require the coding agent to read raw tokens from disk.1095- Tool result semantics:1096 - transport success + no top-level GraphQLerrors->success=true1097 - top-level GraphQLerrorspresent ->success=false, but preserve the GraphQL response body1098 for debugging1099 - invalid input, missing auth, or transport failure ->success=falsewith an error payload1100- Return the GraphQL response or error payload as structured tool output that the model can inspect1101 in-session.11021103Illustrative responses (equivalent payload shapes are acceptable if they preserve the same outcome):11041105json1106{"id":"<approval-id>","result":{"approved":true}}1107{"id":"<tool-call-id>","result":{"success":false,"error":"unsupported_tool_call"}}110811091110Hard failure on user input requirement:11111112- If the agent requests user input, fail the run attempt immediately.1113- The client detects this via:1114 - explicit method (item/tool/requestUserInput), or1115 - turn methods/flags indicating input is required.11161117### 10.6 Timeouts and Error Mapping11181119Timeouts:11201121-codex.read_timeout_ms: request/response timeout during startup and sync requests1122-codex.turn_timeout_ms: total turn stream timeout1123-codex.stall_timeout_ms: enforced by orchestrator based on event inactivity11241125Error mapping (recommended normalized categories):11261127-codex_not_found1128-invalid_workspace_cwd1129-response_timeout1130-turn_timeout1131-port_exit1132-response_error1133-turn_failed1134-turn_cancelled1135-turn_input_required11361137### 10.7 Agent Runner Contract11381139TheAgent Runnerwraps workspace + prompt + app-server client.11401141Behavior:114211431. Create/reuse workspace for issue.11442. Build prompt from workflow template.11453. Start app-server session.11464. Forward app-server events to orchestrator.11475. On any error, fail the worker attempt (the orchestrator will retry).11481149Note:11501151- Workspaces are intentionally preserved after successful runs.11521153## 11. Issue Tracker Integration Contract (Linear-Compatible)11541155### 11.1 Required Operations11561157An implementation must support these tracker adapter operations:115811591.fetch_candidate_issues()1160 - Return issues in configured active states for a configured project.116111622.fetch_issues_by_states(state_names)1163 - Used for startup terminal cleanup.116411653.fetch_issue_states_by_ids(issue_ids)1166 - Used for active-run reconciliation.11671168### 11.2 Query Semantics (Linear)11691170Linear-specific requirements fortracker.kind == "linear":11711172-tracker.kind == "linear"1173- GraphQL endpoint (defaulthttps://api.linear.app/graphql)1174- Auth token sent inAuthorizationheader1175-tracker.project_slugmaps to Linear projectslugId1176- Candidate issue query filters project usingproject: { slugId: { eq: $projectSlug } }1177- Issue-state refresh query uses GraphQL issue IDs with variable type[ID!]1178- Pagination required for candidate issues1179- Page size default:501180- Network timeout:30000 ms11811182Important:11831184- Linear GraphQL schema details can drift. Keep query construction isolated and test the exact query1185 fields/types required by this specification.11861187A non-Linear implementation may change transport details, but the normalized outputs must match the1188domain model in Section 4.11891190### 11.3 Normalization Rules11911192Candidate issue normalization should produce fields listed in Section 4.1.1.11931194Additional normalization details:11951196-labels-> lowercase strings1197-blocked_by-> derived from inverse relations where relation type isblocks1198-priority-> integer only (non-integers become null)1199-created_atandupdated_at-> parse ISO-8601 timestamps12001201### 11.4 Error Handling Contract12021203Recommended error categories:12041205-unsupported_tracker_kind1206-missing_tracker_api_key1207-missing_tracker_project_slug1208-linear_api_request(transport failures)1209-linear_api_status(non-200 HTTP)1210-linear_graphql_errors1211-linear_unknown_payload1212-linear_missing_end_cursor(pagination integrity error)12131214Orchestrator behavior on tracker errors:12151216- Candidate fetch failure: log and skip dispatch for this tick.1217- Running-state refresh failure: log and keep active workers running.1218- Startup terminal cleanup failure: log warning and continue startup.12191220### 11.5 Tracker Writes (Important Boundary)12211222Symphony does not require first-class tracker write APIs in the orchestrator.12231224- Ticket mutations (state transitions, comments, PR metadata) are typically handled by the coding1225 agent using tools defined by the workflow prompt.1226- The service remains a scheduler/runner and tracker reader.1227- Workflow-specific success often means "reached the next handoff state" (for example1228Human Review) rather than tracker terminal stateDone.1229- If the optionallinear_graphqlclient-side tool extension is implemented, it is still part of1230 the agent toolchain rather than orchestrator business logic.12311232## 12. Prompt Construction and Context Assembly12331234### 12.1 Inputs12351236Inputs to prompt rendering:12371238-workflow.prompt_template1239- normalizedissueobject1240- optionalattemptinteger (retry/continuation metadata)12411242### 12.2 Rendering Rules12431244- Render with strict variable checking.1245- Render with strict filter checking.1246- Convert issue object keys to strings for template compatibility.1247- Preserve nested arrays/maps (labels, blockers) so templates can iterate.12481249### 12.3 Retry/Continuation Semantics12501251attemptshould be passed to the template because the workflow prompt may provide different1252instructions for:12531254- first run (attemptnull or absent)1255- continuation run after a successful prior session1256- retry after error/timeout/stall12571258### 12.4 Failure Semantics12591260If prompt rendering fails:12611262- Fail the run attempt immediately.1263- Let the orchestrator treat it like any other worker failure and decide retry behavior.12641265## 13. Logging, Status, and Observability12661267### 13.1 Logging Conventions12681269Required context fields for issue-related logs:12701271-issue_id1272-issue_identifier12731274Required context for coding-agent session lifecycle logs:12751276-session_id12771278Message formatting requirements:12791280- Use stablekey=valuephrasing.1281- Include action outcome (completed,failed,retrying, etc.).1282- Include concise failure reason when present.1283- Avoid logging large raw payloads unless necessary.12841285### 13.2 Logging Outputs and Sinks12861287The spec does not prescribe where logs must go (stderr, file, remote sink, etc.).12881289Requirements:12901291- Operators must be able to see startup/validation/dispatch failures without attaching a debugger.1292- Implementations may write to one or more sinks.1293- If a configured log sink fails, the service should continue running when possible and emit an1294 operator-visible warning through any remaining sink.12951296### 13.3 Runtime Snapshot / Monitoring Interface (Optional but Recommended)12971298If the implementation exposes a synchronous runtime snapshot (for dashboards or monitoring), it1299should return:13001301-running(list of running session rows)1302- each running row should includeturn_count1303-retrying(list of retry queue rows)1304-codex_totals1305 -input_tokens1306 -output_tokens1307 -total_tokens1308 -seconds_running(aggregate runtime seconds as of snapshot time, including active sessions)1309-rate_limits(latest coding-agent rate limit payload, if available)13101311Recommended snapshot error modes:13121313-timeout1314-unavailable13151316### 13.4 Optional Human-Readable Status Surface13171318A human-readable status surface (terminal output, dashboard, etc.) is optional and1319implementation-defined.13201321If present, it should draw from orchestrator state/metrics only and must not be required for1322correctness.13231324### 13.5 Session Metrics and Token Accounting13251326Token accounting rules:13271328- Agent events may include token counts in multiple payload shapes.1329- Prefer absolute thread totals when available, such as:1330 -thread/tokenUsage/updatedpayloads1331 -total_token_usagewithin token-count wrapper events1332- Ignore delta-style payloads such aslast_token_usagefor dashboard/API totals.1333- Extract input/output/total token counts leniently from common field names within the selected1334 payload.1335- For absolute totals, track deltas relative to last reported totals to avoid double-counting.1336- Do not treat genericusagemaps as cumulative totals unless the event type defines them that1337 way.1338- Accumulate aggregate totals in orchestrator state.13391340Runtime accounting:13411342- Runtime should be reported as a live aggregate at snapshot/render time.1343- Implementations may maintain a cumulative counter for ended sessions and add active-session1344 elapsed time derived fromrunningentries (for examplestarted_at) when producing a1345 snapshot/status view.1346- Add run duration seconds to the cumulative ended-session runtime when a session ends (normal exit1347 or cancellation/termination).1348- Continuous background ticking of runtime totals is not required.13491350Rate-limit tracking:13511352- Track the latest rate-limit payload seen in any agent update.1353- Any human-readable presentation of rate-limit data is implementation-defined.13541355### 13.6 Humanized Agent Event Summaries (Optional)13561357Humanized summaries of raw agent protocol events are optional.13581359If implemented:13601361- Treat them as observability-only output.1362- Do not make orchestrator logic depend on humanized strings.1363
参考实现使用 Elixir 编写 — 因为当代码的生成成本接近于零时,我们终于可以根据语言本身的优势来做选择,例如 Elixir 在并发方面的能力 — 但其核心思想其实可以通过一份简单的 Markdown 文档来表达。我们建议你让常用的编程智能体参考该规范 (spec),并实现一套自己的版本。
Symphony 的第一个版本只是一个运行在 `tmux` 中的 Codex 会话,它会轮询 Linear,并为新任务生成子智能体。它能够工作,但稳定性并不理想。第二个版本被集成进我们的主项目代码仓库中,而该仓库本身就是围绕智能体设计的。我们已经构建了智能体运行框架 (harness),为智能体提供在该仓库中完成高质量工作的技能和上下文,因此 Symphony 的作用只是将这些组件连接起来。
当基础功能具备之后,我们开始用 Symphony 来构建 Symphony 本身。
当我们在内部演示该系统 — 展示其如何管理任务并附带工作证明视频 — 时,反馈非常积极:Symphony 项目频道迅速增长,组织内的多个团队也开始自发使用它。在 OpenAI,对外发布之前的前提是先达到内部的产品市场契合。基于我们在内部看到的使用情况,我们很快意识到应该将 Symphony 推广到公司之外。
因此,我们将这一想法提炼为一个独立的 `SPEC.md`,并让 Codex 来实现它。在参考实现中,我们选择了 Elixir,这是一门相对小众但在编排和监督并发进程方面具有优秀原语的语言。Codex 一次性完成了 Elixir 实现,随后我们持续迭代规范和实现。为了进一步打磨规范,我们还让 Codex 使用多种语言进行实现 — 包括 TypeScript、Go、Rust、Java 和 Python — 并通过这些实现结果识别歧义并简化系统。它在每种语言中都成功完成了实现。
在构建 Codex 的过程中,我们去除了大量非本质复杂度,例如对特定代码仓库或 Linear MCP 的依赖。Symphony 不再依赖内部仓库或工作流,其核心方法被简化为:
> 对于每一个未关闭的任务,都确保有一个智能体在其独立工作空间中运行。
除了帮助处理正在进行的工作之外,如今开发工作流本身也成为智能体能够理解并遵循的内容。开发工作流 — 处理 issue、检出代码仓库、将任务标记为进行中以便 PM 知道工作已启动、创建 PR、将其移动到审核状态、附加视频等 — 现在都被记录在一个简单的 `WORKFLOW.md` 文件中。这一整套流程原本由人类执行,但从未被显式记录。与其依赖这些隐性的步骤,我们现在将其文档化,并由 Symphony 确保智能体严格遵循。这使我们能够构建真正与人协同工作的智能体。如果我们决定让智能体在完成工作后附加自我反思,只需将该步骤写入 `WORKFLOW.md`,Symphony 就会引导智能体执行这一流程。
我们还使用了 Codex 的 [app server 模式(在新窗口中打开)](https://developers.openai.com/codex/app-server/),这是 Codex 内置的一种无头 (headless) 运行模式。在这种模式下,我们可以运行 Codex,并通过文档完善的 JSON-RPC API 以编程方式与其交互,例如启动线程或响应对话轮次。这相比通过 CLI 或实时 `tmux` 会话与 Codex 交互,更加便捷且更具可扩展性。
Codex App Server 非常契合我们的使用场景:我们既利用了 Codex 提供的运行框架 (harness),又能够通过各种接口进行扩展。例如,为了避免将 Linear 的访问令牌暴露给子智能体,我们使用[动态工具调用 (dynamic tool call)(在新窗口中打开)](https://developers.openai.com/codex/app-server/#dynamic-tool-calls-experimental) 来暴露底层的 `linear_graphql` 函数,从而在不依赖 MCP、也不向容器暴露访问令牌的情况下,对 Linear 执行任意请求。
### 展望未来
Symphony 是一个刻意保持简洁的编排层。我们将其开源,是为了展示 Codex App Server 在与不同工作流工具(例如 Linear)结合使用时的能力。因此,我们并不打算将 Symphony 作为一个独立产品来持续维护。你可以将它视为一个参考实现。类似于许多开发者曾让编程智能体基于运行框架 (harness) 工程文章来快速搭建代码仓库,我们也希望你让自己的智能体参考 Symphony 的 [spec(在新窗口中打开)](https://github.com/openai/symphony/blob/main/SPEC.md) 和 [repository(在新窗口中打开)](https://github.com/openai/symphony),构建适配自身环境的实现版本。
其核心能力来自 Codex 及其 app server。Symphony 的作用,是将我们已经在使用的两个系统 — Codex 和 Linear — 连接起来,从而解决工作管理问题。随着编程智能体在推理和遵循指令方面不断增强,我们预计其他公司的瓶颈也会从“写代码”转向“管理智能体工作”。值得注意的是,尝试这类系统的门槛已经变得非常低 — 你完全可以直接用 Codex 构建自己的系统。
### 社区反响
我们很高兴看到工程社区在发布后的几周内开始使用 Symphony。截至 4 月 23 日,[该项目已在 GitHub 上获得超过 1.5 万颗星(在新窗口中打开)](https://github.com/openai/symphony)。