Metadata-Version: 2.4
Name: symfonic-team
Version: 0.1.0
Summary: Reusable multi-agent software development team powered by symfonic-core
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: symfonic-core[anthropic,openai,otel,postgres]==11.18.0
Requires-Dist: asyncpg
Requires-Dist: sqlalchemy[asyncio]>=2.0
Requires-Dist: cryptography>=42
Requires-Dist: pyyaml>=6
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: mypy>=1.11; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: fastapi>=0.115; extra == "dev"
Provides-Extra: admin
Requires-Dist: fastapi>=0.115; extra == "admin"

# Symfonic Team

**A reusable multi-agent development team.** One team, any project: give it a
brief and it produces a standalone, runnable project -- backend, frontend,
containers, tests and docs -- in its own directory, with its own git history and
no dependency on this library.

Built on [symfonic-core](https://pypi.org/project/symfonic-core/).

## What it actually does

A CEO turns the brief into directives for its managers, each manager plans
tasks for its own team, the executors do them, a verifier checks the result,
and the CEO reports -- plus a git committer when you ask for one. The
interesting part is not that they write code -- it is that the run does not
trust them:

- **Quality gates that must prove their claims.** A gate's `PASS` is recorded as
  `verified` only when it cites a check it really executed, matched against the
  run's own tool audit. Citing a command that never ran, or one contained in
  another command's text, does not verify. An e2e `PASS` additionally has to cite
  a check that drove a **browser**.
- **A self-correcting loop.** A failing gate sends a fix task back to the role
  that owns the code, bounded by per-gate budgets and attempt caps so it cannot
  spin.
- **Memory.** Each run extracts what it learned into a durable store and recalls
  it as it works. The store is scoped to the project's identity, so continuing a
  project keeps what it learned while a new directory starts empty -- and if you
  did start a new one, `project adopt-memory` brings the earlier memory across
  instead of relearning it. Within a project, each agent's memory lives at its
  own `tenant/<org>:<project>/<agent>` path and the team channel at
  `tenant/<org>:<project>`; records written by earlier layouts -- the old
  `tenant/<agent>` agent paths and channel posts at the bare tenant -- are no
  longer read by anything, and operators may drop them.
- **Storage that is not assumed.** Tickets, plans, status and the tool audit each
  choose Markdown, SQLite or Postgres independently.

`verified` is not decorative: an unverified gate makes the whole run exit
non-zero, so CI cannot read a half-proven build as a clean one. Pass
`--allow-failed-quality` for exploratory runs.

A run ends in the CEO's report, printed and written to `docs/CEO_REPORT.md`
with the outcome (`completed`, `escalated` or `budget_exhausted`) and what the
run cost. Every finished turn is checkpointed under the brief: `run --resume`
with the same brief replays the finished turns without calling a model, keeps
what they cost in the run's budget, and runs only the rest; a different brief
starts fresh. Verifier turns are never replayed -- a verdict has to cite checks
executed in the run that reports it.

`review` skips the planning: each unresolved ticket goes back to the agent that
owns it, and only those agents are engaged. A ticket assigned to a name that is
no agent of the team is listed as skipped.

## The team

```
CEO
├── Product Manager  → Product Owner · UX Designer · Tech Writer
├── CTO              → Architect · DB Admin · Backend · Frontend · DevOps · Security
│                      Chatbot Designer · NLP Engineer · Integration Engineer
└── QA Engineer      → API Tester · E2E Tester        (verifies the delivered work)

Git                  → commit + push once the run completed (--push)
```

The commit spends what is left of the run's budget; a run that reached a limit
is not committed, and says so.

The chart is discovered from `symfonic_team/agents/`: each agent package
declares who it reports to, and every package found is on the chart. A manager
only assigns work to the agents a brief needs.

## Quick start

```bash
python -m pip install symfonic-team
symfonic-team ceo --output ./my-app
```

The CEO prompts for your brief. To run with a brief you already have:

```bash
symfonic-team run \
  --name "MyApp" \
  --brief-file ./my-brief.md \
  --output ./output/my-app
```

`--output` is the project's directory, used **as given** -- the project name is
not appended. It is also where the project's identity marker lives, so reopening
the same directory continues the same project (and keeps its memory), while a new
directory starts a new one.

```bash
# An inline brief, and a push when it is done
symfonic-team run --name "TodoApp" --brief "Build a todo app with ..." \
  --output ./output/todo-app \
  --push --git-remote https://gitea.example.com/user/todo-app.git

# Re-engage the agents on tickets a run left unresolved
symfonic-team review --output ./output/my-app
```

## Commands

| Command | What it is for |
|---|---|
| `run` | Run the team on a brief |
| `ceo` | Give the team a brief and answer the CEO in the terminal |
| `review` | Re-engage agents on a project's unresolved tickets |
| `project` | Identity and storage maintenance: `recover-lease`, `migrate`, `rekey`, `adopt-memory` |
| `approve` | Provision the signed-approval trust anchor and effect ledger |
| `eval` | Regression evaluation scenarios, including fault injection |
| `canary` | Canary trials under an enforced spend ceiling |
| `worker` | Serve one team job over stdin/stdout JSON lines (see Job worker) |

Each takes `--help`.

### Operator guide

Start an interactive session with the CEO. The terminal prompts for the brief
if you omit `--brief` and `--brief-file`.

```bash
symfonic-team ceo --output ./output/inventory --brief-file ./brief.md
```

Answer the CEO directly at `Your answer >`. When the team approaches its
job budget, the terminal shows a proposal with new total token and call
limits. Type `approve` to authorize those exact limits or `reject` to
continue within the existing allowance. An approved increase takes effect
once the terminal can reserve it under the existing project cap. Later
increases each require their own approval.

At a question, type `/pause` or close the terminal to answer later. Resume
with the same project directory. The original brief and policy path are
saved beside the project.

```bash
symfonic-team ceo --output ./output/inventory --resume
```

To bring a pending `run` session into the terminal, pass `ceo --resume`
with the original `--name`, brief, output directory, and policy options.

#### Scripted operation

Scripts can list and resolve the same questions with `project questions`.

Example:

```
symfonic-team project questions --output ./output
symfonic-team project questions --output ./output --id ID --digest DIGEST --answer TEXT
symfonic-team project questions --output ./output --id ID --digest DIGEST --approve
symfonic-team project questions --output ./output --id ID --digest DIGEST --reject
symfonic-team run --name Inventory --output ./output --brief "Build an inventory app" --resume
```

`project questions` records decisions for scripted runs. Queued jobs support
a separate operation to apply an approved budget before resuming. See the
[worker human question protocol](docs/worker-human-questions.md).

## Configuration

Everything is environment variables. These are the ones an operator needs; the
code has many more for tuning.

### Which model runs the team

```env
SYMFONIC_PROVIDER_DEFAULT=openai   # openai | codex | claude | kimi
```

With no default set, the provider is auto-detected in the order `claude`,
`codex`, `kimi`, `openai` -- so a logged-in Claude subscription wins even when
you meant to use the local endpoint. **Set it explicitly for any run whose cost
or results you care about**, and read the provider back from the run's own state
rather than the log, which is block-buffered.

```env
SYMFONIC_LLM_URL=http://10.0.10.47:8080/v1   # the OpenAI-compatible endpoint
SYMFONIC_LLM_MODEL=qwen36-35b-gptq
SYMFONIC_CODEX_MODEL=gpt-5.6-terra
SYMFONIC_CODEX_REASONING_EFFORT=high         # minimal | low | medium | high
SYMFONIC_CLAUDE_MODEL=claude-sonnet-4-5
SYMFONIC_KIMI_MODEL=kimi-for-coding
```

### Staff and budget a project

Use `run --team-policy policy.json` to contract departments, assign model tiers,
and reserve a share of the project budget for the run. The CLI prints the
operator-owned usage report with tokens, model and estimated cost per member.
Consult the [ticket board, decision journal and exports](docs/project-tracking.md).
See the [policy fields and example](docs/team-policy.md). Use the
[worker continuation protocol](docs/worker-continuation.md) for queued jobs
that must survive a client disconnect or worker restart.

### Where the project's records live

Each artifact chooses its own backend: `markdown` (the default), `sqlite` or
`postgres`.

```env
SYMFONIC_TICKET_STORE=postgres
SYMFONIC_PLAN_STORE=postgres
SYMFONIC_STATUS_STORE=postgres
SYMFONIC_AUDIT_STORE=postgres
SYMFONIC_POSTGRES_DSN=postgresql://user:pass@localhost:5433/db
```

Postgres also backs durable memory. Switching an existing project's backends is
`symfonic-team project migrate`, never an edit of these variables alone.

### Observability

```env
SYMFONIC_TELEMETRY_ENABLED=1
SYMFONIC_OTEL_ENABLED=1                  # needs a collector on :4317
SYMFONIC_MEMORY_EXTRACTION_ENABLED=1
SYMFONIC_PARALLEL=false                  # true fans roles out
```

Every run writes `docs/metrics-summary.md` with token counts and the gate
outcomes. Cost comes from the kernel's pricing table, and a model that is not in it
costs `$0.0000` -- but the summary now says so beside the number rather than
leaving a zero that reads like a measurement:

```
- Cost: $0.0000
- Cost is $0 because no price is registered for gpt-5.6-terra, not because the
  run was free. ...
```

Supply prices as data, either inline or as a file, in USD per million tokens:

```env
SYMFONIC_PRICING={"gpt-5.6-terra": {"input": 1.25, "output": 10.0, "cache_read": 0.125, "cache_write": 1.5}}
SYMFONIC_PRICING=/etc/symfonic/pricing.json
```

Correcting a price is then a data change, not a release. A malformed list is
reported at run start and leaves the cost at zero rather than stopping the run.

No prices ship by default, deliberately: every provider this library selects uses
subscription tokens rather than a metered API key, and for a subscription there is
no per-token rate to register. A number here would be invented, which is worse than
an explained zero. Reasoning tokens also cannot be priced apart today -- the kernel
bills a separate reasoning line only when a pricing row carries a `reasoning` key,
and its override API accepts that key and then stores the row without it, so a
high-effort run under-reports by its reasoning tokens once prices are supplied.

## Generated projects

Each project is standalone -- its own Dockerfile, dependencies, tests and compose
file, importing nothing from this library:

```
symfonic-team/          ← this repo (the team)
output/
├── todo-app/           ← generated, has its own git history
└── my-app/
```

The only trace of the team is `.symfonic-project.json`, the identity marker that
lets a later run continue the same project.

## Service contract

`symfonic_team.service.contract` is the versioned job contract (v1) a job
source such as symfonic-builder speaks to a team worker out of process: one JSON
object per line, its `type` naming the frame (`TeamJobRequest`, `JobClaimed`,
`Heartbeat`, `HeartbeatAck`, `LeaseLost`, `TeamJobResult`, `ApprovalEvent`,
`ApprovalDecision`). A consumer that does not import this package validates
frames against the committed JSON Schema
`symfonic_team/service/contract/schema/v1.json`; after changing a record,
regenerate it with `python -m symfonic_team.service.contract` (a test fails
while the two differ). Approval payloads are hashed over one canonical
encoding (`payload_sha256`), fixed by a committed test vector.

### Job sandbox (worker mode)

In worker mode no shell, check or git command runs as a process of the worker.
`symfonic_team.service.worker` provides the `JobSandbox` port and its Docker
implementation, `DockerJobSandbox`:

- one container per job, started from the operator's `--job-image`, whose only
  host mount is `workspace_dir`; every shell and git command is a `docker exec`
  in it with its own timeout;
- one throwaway container per `run_check`, whose only host mount is that
  check's private snapshot at the same container path, so a citable check
  cannot write `workspace_dir`;
- every container: no network, an allowlisted environment (no database URL,
  provider key or forge token), pids, memory and cpu limits, a read-only root
  filesystem with a tmpfs `/tmp`, and never a pull; commands run as the
  worker's own non-root `uid:gid` (a worker with uid 0 or gid 0 is refused);
- every container is started attached with auto-remove, and its main process
  only waits on a pipe the worker process holds, up to `job_timeout_s`: a
  worker that dies, SIGKILL included, takes its containers and their commands
  down without calling `stop()`. That process runs under a different
  unprivileged uid (65534), so no command can stop or kill it;
- `stop()` raises unless every removal is confirmed, and the output captured
  from one command is capped (4 MiB per stream; the command is killed past it).

Host-side file access goes through `ConfinedFiles`: paths are opened component
by component relative to the workspace directory without following any
symlink, only regular files are accepted, and bytes are read or hashed through
the descriptor that was opened; a read is capped at 32 MiB. The workspace
revision walk goes through it too, so verdicts and the release manifest are
computed without following a symlink.

Both are injected into a run with
`core.tools.sandboxed.bind_job_sandbox(sandbox, confined_files)`, always
together. Outside worker mode nothing is bound and the tools run on the host as
they always did. Worker mode fails closed: once a run is marked
(`enter_worker_mode()`, or the bind itself), every command and file tool and
the revision walk refuse while the two are not bound. The worker must bind on
the run's RunContext, after `begin_run()`, before it creates any agent task.

`docker/job-image/Dockerfile` is the reference job image (python, pytest, git;
nothing is fetched at run time, so a job's dependencies must be in the image or
the workspace); its base image and pytest are pinned. An operator's own image
must provide `sh`, `bash`, `timeout` and `cat`.

```bash
docker build -t symfonic-team-job docker/job-image
pytest -m integration tests/service/test_job_sandbox.py   # needs a container runtime
```

### Job worker

`symfonic-team worker` serves one job per process over stdin/stdout:

```bash
symfonic-team worker --workspace-root /srv/jobs/workspaces \
    --state-root /srv/jobs/state --job-image symfonic-team-job
```

For a one-shot job, the first line on stdin is the `TeamJobRequest`. The worker answers
`JobClaimed`, sends a `Heartbeat` every `lease_ttl_s / 3` for the whole claim
(model calls, tool runs and approval waits included), raises an `ApprovalEvent`
for the plan and for the release, and ends with exactly one `TeamJobResult`,
after which the process exits. Stdout carries frames only; logs and anything a
run prints go to stderr. Exit status: 0 when the result was delivered (whatever
its outcome), 2 on a usage error, 3 when the claim ended without a result, 4
when the first line was not a valid `TeamJobRequest` (answered with an
`invalid_request` result when it named its job and lease; the reason is on
stderr). A line longer than 1 MiB or not valid UTF-8 is refused.

For a CEO question that can outlive its worker, enable `human_questions` in the
continuation envelope. The worker exits after a `TeamJobWaiting` frame and a
fresh lease resumes the job after the customer responds. See the
[Builder integration guide](docs/worker-human-questions.md).

- `workspace_dir` must be the existing directory `<workspace-root>/<lease_id>`
  and is locked for the claim; anything else is `invalid_request`.
- All bookkeeping (tickets, plans, status, tool audit, checkpoint, check
  snapshots) lives under `<state-root>/<lease_id>`, never in the workspace.
  `--state-root` inside the workspace root is refused.
- The memory scope is the request's `(tenant, org, project)`.
- The lease is lost on `LeaseLost`, a heartbeat whose `HeartbeatAck` does not
  arrive before the lease deadline, stdin closing or a failed stdout write. The
  run is then cancelled, the container stopped and no result is sent. Frames
  with another `job_id` or `lease_id` are refused.
- `job_timeout_s` counts from `JobClaimed`; past it the job fails with
  `job_timeout`. An approval not decided within `approval_timeout_s` fails with
  `approval_timeout`.
- The container is stopped before the release `ApprovalEvent`, whose payload is
  the release manifest; a workspace that differs when the decision arrives
  fails with `release_changed`. Artifacts are exactly the approved manifest.
- The compose and HTTP tools are never offered. Without `--job-image` or
  without a container runtime, the shell, check and git tools are not offered
  either.

`InMemoryJobSource` (`symfonic_team.service.worker.in_memory_job_source`) is
the same port in process, for tests and embedding.

```bash
pytest -m integration tests/service/test_worker.py   # needs a container runtime
```

## Extending the team

Use Python 3.12 or newer. An application can add an agent, give an existing
agent more specific instructions, and append native Symfonic Core guardrails.
For example, an analytics specialist can report to the CTO while using the
backend provider configuration:

```python
from symfonic_team.plugins import (
    AgentKind, AgentSpec, Guardrail, RoleGuidance, TeamExtension, use_extensions,
)

EXTENSION = TeamExtension(
    members=(AgentSpec(
        name="analytics_engineer", role="backend", kind=AgentKind.IMPLEMENTER,
        reports_to="cto", scope="Product analytics and event contracts.",
        description="Product analytics engineer.",
        instructions="Define each event's purpose, trigger, and payload.",
    ),),
    guidance=(RoleGuidance(
        role="frontend",
        instructions="Document the empty, loading, error, and success states for each user journey.",
        guardrails=(Guardrail("Verify keyboard navigation through the primary journey."),),
    ),),
)
```

For an embedded run, wrap the call that builds the team:

```python
from symfonic_team.composition import build_team_run

with use_extensions(EXTENSION):
    session = build_team_run(project, bundle)
    report = await session.run(brief)
```

For CLI or worker deployments, export the same object from your own installed
package and declare a Python entry point in its `pyproject.toml`:

```toml
[project.entry-points."symfonic_team.plugins"]
analytics = "my_company.team:EXTENSION"
```

Set `SYMFONIC_TEAM_EXTENSIONS=analytics` in the CLI or worker environment.
Multiple names are comma-separated. Install only trusted extension packages:
loading an entry point executes Python. Keep the same plugins and versions
available when resuming. New members can supply tools, tool manifests, a memory
policy, and context budgets through `AgentSpec`. The worker accepts built-in tool implementations for extension members and applies its
normal sandbox restrictions. Custom tool implementations are supported in trusted local runs. Built-in instructions
and guardrails remain active. The extended chart uses the normal staffing,
verification, provider, and Core telemetry paths.

## Development

```bash
./.venv/bin/ruff check symfonic_team tests
./.venv/bin/mypy symfonic_team
./.venv/bin/pytest -q                    # unit
./.venv/bin/pytest -q -m integration     # needs Postgres
```

Call the venv's tools explicitly. Bare `mypy` resolves to the pyenv shim, a
different version against a different environment, and reports two missing-stub
errors the venv's mypy does not -- the same two-interpreter problem this project
documents for `symfonic-core` below, in the toolchain instead of the dependency.

The integration lane is deselected by default and needs a reachable Postgres.

### CI

The shared install action resolves the core release pinned in `pyproject.toml` from
public PyPI. Pull requests run lint, type checks and unit tests. Main also runs
the integration, resilience, lease and privileged approval-signer jobs.
`tests/test_ci_workflows.py` checks that the workflows parse and use the shared installer.

### Which symfonic-core you are running

Install from the project root and check the identity with the same interpreter
you use to run Team.

```bash
./.venv/bin/python -m pip install -e ".[dev]"
./.venv/bin/python -c 'from symfonic_team.core.core_identity import core_identity_line; print(core_identity_line())'
```

The run header includes the distribution version and a digest of the imported
source, including agent prompt templates. A `MISMATCH` names an import path that
differs from the installed distribution.
