# Context and specs (/docs/architecture/context-and-specs)
`turbo-12f` anchors every specification to words the requester wrote so downstream agents cannot invent unasked scope. [internal/roles/context](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/context/turn.go) runs a toolless conversation until three deterministic Go checks pass, then exports OpenSpec files plus three audience views. Context creator is the Product Owner of the default `team` flow: it talks with the person and writes the spec, and owns no lane step. Both flows start from the same spec.
All six must-haves (goal, users, pages, core journey, look, what is out) must be populated and matched to exact human quotes.
Every behavioral edge case (`open_point`) must be answered or accepted.
Drafts must pass OpenSpec structural lint and plain-language word caps.
## How Context knows context is enough to start [#how-context-knows-context-is-enough-to-start]
The Context creator LLM never decides when a project is ready ([context-creator-v2.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/context-creator-v2.md)). Who accepts follows from the person's access to the request (see [Autonomy and people](/docs/fundamentals/autonomy-and-people)), so there is no acceptor must-have. Instead, `gateOf` in [state.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/context/state.go) enforces three ordered checks on `*st.Draft`:
1. **Six must-haves backed by verbatim quotes:** `st.MustHaves.Missing()` must be empty, and `said(words, given.Quote)` ([answer.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/context/answer.go)) verifies every quote appears in human messages (case- and whitespace-normalized). The six are `goal`, `users`, `pages`, `core_journey`, `look`, and `out_of_scope`.
2. **Zero open points remaining:** Behavioral gaps (`open_point`) keep the plan unconfirmed (`still open with the person: ...`) and block confirmation.
3. **Zero structural contract violations:** `spec.Lint` ([lint.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/spec/lint.go)) checks 25 OpenSpec rules on `*st.Draft`. Before a turn is accepted, `spec.LintPlain` also checks the turn reply and the plain view, and refuses words the person did not use themselves.
`spec.MustHaveKeys` uses underscores in Go (`core_journey`, `out_of_scope`), while `catalogue/*.json` uses hyphens (`core-journey`, `out-of-scope`).
| Key | Purpose | Hand-back allowed |
| --- | --- | --- |
| `goal` | Core outcome the project exists to deliver | Refused (`refusalRe` check) |
| `users` | Target audience and operator roles | Refused |
| `pages` | Every page or screen, content, and actions | Allowed (the type's recommended page set) |
| `core_journey` | Main step-by-step user flow in requester's words | Refused |
| `look` | Style, hex colors, typography, size, contrast, layout | Allowed (the type's recommended look) |
| `out_of_scope` | Explicit non-goals excluded from this change | Refused |
| `open_point` | Remaining behavioral detail (limits, errors, rollovers) | Allowed: accepts `recommended` for remaining points |
When `refusalRe` matches `"you decide"` or `"skip it"`, Context takes its last recommendation for `pages` and `look` and accepts its recommended answer for open `open_point`s. For `goal`, `users`, `core_journey`, and `out_of_scope` it keeps asking. `conversationActions` sets `CanDecide` when an open question is an `open_point` or a must-have with a recommendation, and `HasSuggestions` when any open question carries one; the UI shows **Decide for me** and **Accept suggestions** from these two flags.
The recommendation comes from the project type's catalogue (`web-blog` version 3, `web-app` version 2, `desktop` version 2). `pages` and `look` carry a `recommended` answer in all three. See [Catalogues](/docs/reference/catalogues).
## Image attachments, GitHub issues, and existing repositories [#image-attachments-github-issues-and-existing-repositories]
Context creator validates multimodal, multi-issue, and repository inputs on `t12 ask` and `t12 ui` before mutating state:
- **Limits (`internal/imginput`):** Up to `5` PNG, JPEG, WebP, or GIF files (`MaxPerTurn = 5`, `MaxBytes = 5 MiB` each), validated against magic bytes and image headers.
- **Storage & lifecycle:** Saved via `Home.Evidence`, recorded as `record.Ref` on `EvInput` and in the request's `context-state` database document, reloaded on `--resume`, and written to `attachments.json` (`spec.Change.Attachments`) on `t12 confirm`.
- **Limits (`internal/adapters/ghissue`):** `t12 ask --issue` (repeatable or `--issues-file`) and `IssuePicker` attach up to `5` issues (`1..20` via `T12_MAX_ISSUE_INPUTS` or `context.max_issue_inputs`). `ghissue.ParseRefs` and `ListIssuesWith` reject PRs.
- **Immutable snapshots:** Snapshots under `evidence/` populate `sources` on `EvRequestOpened`/`EvInput` and render in `issuesPromptSection`.
- **Pre-confirm edits:** `rolecontext.UpdateIssues` updates `github-issues.json` and re-runs the turn via `POST /api/c/{id}/issues`, `t12 conversation issues`, or `t12 ask --add-issue|--remove-issue|--set-issues`.
- **Adoption (`internal/adapters/ghrepo`, `project.Detect`, `devops.Adopt`):** `--repo owner/repo` on `t12 ask` or `t12 repo connect` (and `RepoPicker`) clones the repository, using the person's own GitHub connection in the cloud build. It detects Node.js/Go/Python/Rust, creates `staging` (or `t12-staging`), and registers the project in the `projects` table. Anyone can connect a repository into their own team.
- **Context & lint:** `rolecontext.loadProject` injects a bounded overview (`maxOverviewBytes = 8 KiB`, `maxTreeEntries = 80`, `maxReadmeBytes = 1800`); `spec.Lint` treats `ExistingProject` or `Repository` like `BuildsOn` for `RuleKeeps` and optional `quality`.
## The mock UI [#the-mock-ui]
Context sends a `mock_ui` with its turns once pages and look are known: the picture the person approves before anything is built. It picks one template that fits the request, gives it a palette and the words each screen shows, and the UI renders it as a sandboxed page with no network access. The rules mirror [design/mock-templates.md](https://github.com/cone-labs/turbo-12f/blob/main/design/mock-templates.md).
| Part | What the code enforces |
| --- | --- |
| **Template** | One of `countdown`, `landing`, `mobile-app`, `game`, `portfolio`, `blog`, `ecommerce`, `dashboard` (`MockTemplates`) |
| **Screens** | At most `6` screens (`maxMockScreens`) and `8` items each; each screen `id` names a glossary screen. App templates may name a `layout`: `list`, `form`, `detail`, `calendar`, `board`, `settings`, or `chart` |
| **Palette** | Seven `#RRGGBB` colours. Text needs `4.5:1` contrast on background and on surface, muted text `3:1` on background, or `checkMockUI` refuses the call |
| **Style** | A `mood` (eight values), a `font` (`sans`, `serif`, `mono`, `rounded`, `display`), and a `brand` name clipped to `40` characters |
| **Pinned comments** | The person pins change requests on the mock (up to `60`, `1000` characters each, on `desktop`, `tablet`, or `mobile`). Context must answer every pending pin with a new `mock_ui` |
| **Viewer designs** | **Dark**, **Light**, and **Project colours** (the palette Context drew). With no choice, `dashboard` and `mobile-app` draw Dark and the other templates draw Project colours |
The person's approval is a `mock-ui-approved` event written by the acceptor (the opener, or a team owner or member). It records the choice but is not one of the three readiness gates. The mock itself lives in the `context-state` document, not in ``.
## Standards the Context creator follows [#standards-the-context-creator-follows]
Across [context-creator-v2.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/context-creator-v2.md) and [lint.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/spec/lint.go), Context enforces five standards:
- **ISO/IEC/IEEE 29148:2018 traits:** Every requirement must be `necessary`, `appropriate`, `singular`, `unambiguous`, `complete`, `feasible`, `verifiable`, `correct`, and `conforming`.
- **Normative `SHALL` & MoSCoW:** Requires uppercase `SHALL` (`RuleShall`) and `must`/`should`/`could` (`RulePriority`), while banning vague terms (`RuleVague`), `TBD` (`RuleTBD`), and prose filler (`RuleFiller`).
- **User stories & BDD Gherkin:** Capabilities open with `"As a , I want , so that "` (`RuleStory`), `must` items carry `GIVEN`/`WHEN`/`THEN`, and `feature`/`change` capabilities include an `error: true` path.
- **Batched elicitation:** Asks up to `8` questions per batch (`maxQuestions`). The first batch normally carries the missing must-haves (up to six), later batches only `open_point`s, and the person answers them one at a time. A change holds at most `12` requirements.
- **Plain-language accessibility (`spec.LintPlain`):** Caps turn replies and `plain.md` sentences at `25` words (`PlainSentenceWords`), banning factory terms (`lane`, `branch`, `commit`, `CI`, `token`, `hash`, role names) and filler.
| Group | Rules | What Go enforces |
| --- | --- | --- |
| Change and DAG | `change`, `capability`, `story`, `task` | Lower-case dashed IDs, `title`/`why`, user story, `TaskTypes`, bug-only `Severities`, `depends_on`, `dag.Order` |
| Identifiers & wording | `id`, `duplicate-id`, `title`, `shall`, `priority`, `vague`, `tbd`, `prose-filler` | Unique `-REQ-NNN` / `-SC-NNN`, unique titles, `SHALL`, priority, zero banned terms |
| Provenance | `source`, `source-turn`, `decision`, `keeps` | `source` in `said`/`accepted`/`decided for you`; positive `turn`; decision ID; `keeps` requires `BuildsOn`, `ExistingProject`, or `Repository` |
| Scenarios | `scenario`, `gwt`, `readonly`, `error-scenario` | Scenarios on `must`; `Given`/`When`/`Then`; no mutating verbs in read-only; `error` scenario on `feature`/`change` |
| Quality & glossary | `quality`, `quality-number`, `glossary`, `glossary-used`, `screen` | `quality` on first change with digits; non-empty glossary with every term and `screen` ID used in scenarios |
## Export standards (`openspec/changes//` and generated views) [#export-standards-openspecchangesid-and-generated-views]
Context writes canonical **OpenSpec** source files plus three read-only views (`spec.IsView` in [files.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/spec/files.go) and [views.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/spec/views.go)), committed to `staging` on `t12 confirm`. A confirmation stands only while its spec is on the project's `staging` branch: one made into a repository that was lost (a cloud runner's scratch disk) is committed again into the new repository instead of being reported as done.
| File | Kind | Purpose |
| --- | --- | --- |
| `proposal.md` | Canonical | Change ID, Project, `Builds on`, `# Request` quotes, `Why`, `What Changes`, `Capabilities`, `"Your words"` |
| `specs//spec.md` | Canonical | Delta markdown (`## ADDED Requirements`), user story, metadata, and Gherkin scenarios |
| `glossary.md` | Canonical | Domain terms and UI `screen` IDs (`home`, `post-page`) used by `e2e/t12/capture.ts` and `ui-check` |
| `decisions.md` | Canonical | Decision log (`Question`, `Source`, `Options`, `Choice`, `Reason`, `Changeable`) |
| `design.md` | Canonical | Optional visual spec (hex palette, contrast, fonts, `px` size, rounding, per-screen layout) |
| `attachments.json` | Canonical | Image attachment metadata when intake included images |
| `srs.md` | Read-only view | Tailored 9-section ISO/IEC/IEEE 29148:2018 SRS (`1. Purpose`–`9. Deliverables`) |
| `plain.md` | Read-only view | Requester-readable summary checked by `spec.LintPlain` (`[change this]` markers on defaults) |
| `uat.md` | Read-only view | Manual bug-bash checklist (`Start`, `Do`, `Expect`, `[ ] pass / fail`, grouped error cases) |
## Three readiness gates [#three-readiness-gates]
- **Spec gate ([state.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/context/state.go)):** Runs three deterministic Go checks on every draft turn: verbatim human quotes on all six must-haves, zero remaining `open_point` questions, and `spec.Lint` on the draft.
- **Project gate ([gate.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/devops/gate.go)):** Triggered by `t12 confirm`. DevOps first bootstraps an empty project repository, then verifies `.t12/` configs, skill hashes, branches, dependencies, and base checks on `staging`. See [DevOps internals](/docs/architecture/roles-delivery-and-observer#devops-internalrolesdevops).
- **Task gate:** Not a separate step today.
[design.md](https://github.com/All-Chat-Bridge-for-CRM/ConvoRelay/blob/main/docs/factory/design.md) specifies a standalone pre-lane Task Gate to drop duplicate or already-passing scenarios. Today `strategist` enforces `dag.Order` and 1:1 partitions while Orchestrator enforces `depsDone` and `pausedDeps` (see [Strategist internals](/docs/architecture/roles-planning-and-build#strategist-internalrolesstrategist) and [Orchestrator execution](/docs/architecture/request-lifecycle#strategist-task-planning-and-parallel-lanes)).
Context creator isolates requirement capture from implementation: three deterministic Go checks prove the spec is grounded and contract-valid before any repository file is touched.
## Next steps [#next-steps]
# System overview (/docs/architecture/overview)
`turbo-12f` keeps its Go runtime small and deterministic, and keeps every durable record in one Postgres database. Cage binaries (`t12-cage`, `t12-container`) link no HTTP code except the database client, while companion processes handle UI HTTP, cloud runs, AI harnesses, Cloudflare, and GitHub.
- **Zero Go dependencies:** Builds with the Go standard library only.
- **One store:** Postgres through `internal/db`; the state home on disk is scratch.
- **Deterministic gates:** Scripts verify every test, diff, and hash chain.
- **Web workbench (`t12-ui`):** Serves the React app, manages accounts and Observer, and shells out to `t12`.
- **Cloud worker (`t12-cloud-worker`):** Runs a request in GitHub Actions against the same database.
- **AI harnesses:** `agy` and `omp` run behind RPC wrappers and guard hooks, on the requesting person's own credentials.
Read [The factory pipeline](/docs/fundamentals/pipeline) first for a plain-language overview before diving into Go packages.
## Postgres is the only store [#postgres-is-the-only-store]
[ADR 0005](https://github.com/cone-labs/turbo-12f/blob/main/docs/adr/0005-neon-source-of-truth.md) makes Neon Postgres the single source of truth. Every process needs `DATABASE_URL` and stops at start-up without it (`db.ErrNoDatabaseURL`); there is no local file mode.
| Kept in Postgres | Kept on local disk (``, `T12_HOME`) |
| --- | --- |
| Accounts, teams, sessions, projects, conversations, runs | Git worktrees and project checkouts |
| Hash-chained `events` streams and evidence `blobs` | Build and dependency caches, merge scratch |
| Small mutable state as `documents`, append logs as `log_entries` | Cage and agent scratch homes, per-run credential homes |
| `leases` instead of lock files, `approvals`, `outbox`, metrics | The approval spool a sandboxed guard hook writes to |
Everything on disk can be rebuilt from GitHub plus the database. An old state home enters only once, through `t12 db import --home DIR`.
| Topic | What the code does |
| --- | --- |
| Access | Neon's HTTPS SQL API with the standard library only; a `Batch` is one transaction; no Postgres driver |
| Retries | `Query` and statements marked idempotent retry on transient errors; `Exec` never retries; one HTTP attempt times out at 30 s |
| Migrations | Embedded in `internal/db/schema/migrations` (`0001_infra` to `0018_hosting`), applied once under an advisory lock; `t12 db migrate`, `status`, `compact`, `import` |
| Test database | `T12_TEST_DATABASE_URL` with `dbtest.New(t)`; `scripts/test-db.sh` starts a local Postgres behind `cmd/t12-neon-local`, reached through `T12_DB_ENDPOINT` |
| No-network cage | `t12-container` runs a `db.Broker` on a Unix socket (`T12_DB_BROKER`); `DATABASE_URL` never enters the container |
| Transfer metering | Each process counts the response bytes and HTTPS calls it reads and adds them to its `db_usage` row of the day about once a minute; the Usage page compares them with the Neon plan's monthly transfer |
## Six-layer package stack [#six-layer-package-stack]
The target v2 design in [design.md](https://github.com/All-Chat-Bridge-for-CRM/ConvoRelay/blob/main/docs/factory/design.md) stacks Go packages from storage up to CLI and HTTP entry points.
| Layer | Packages | Responsibility |
| --- | --- | --- |
| Foundation | `internal/db`, `internal/store`, `internal/schema`, `internal/gitio`, `internal/dag`, `internal/envfile`, `internal/project` | Postgres client and migrations, canonical JSON and SHA-256 helpers, tool schemas, git helpers, DAG ordering, configs |
| Record & specs | `internal/record`, `internal/access`, `internal/connections`, `internal/projectenv`, `internal/metrics`, `internal/spec`, `internal/rollup`, `internal/approvals`, v1 `internal/model` | Hash-chained streams, accounts and per-user connections, sealed project variables, OpenSpec views, rollups, approvals |
| Containment | `internal/sandbox`, `internal/cage`, `internal/container`, `internal/readonlysession`, `*rpc`, `internal/workersession`, `internal/docs`, `internal/served`, `internal/skillmap`, `internal/runner`, `internal/eval` | Landlock/Docker cages, revert guards, harness RPCs, Context7 socket, skill checks, role evals |
| Roles & merge | `internal/roles/*`, `internal/mergequeue`, `internal/mergepolicy`, `internal/adapters/*`, `internal/hosting`, `internal/trysite` | Thirteen role packages, staging rebase queue, policy rules, external adapters, production deploys to a person's Cloudflare or Vercel account, free test sites |
| Orchestration | `internal/orchestrator`, `internal/observer`, `internal/setup`, `internal/docschat` | Lane DAG scheduling, slot pools, in-process file locks, failure routing, Observer loop, onboarding setup, docs chat |
| Entry points | `internal/cli`, `internal/ui`, `internal/cloud/*`, `cmd/*` | CLI dispatch, embedded React dashboard with SSE, the cloud backend, and 12 helper binaries beside `t12` |
## Downward import rule [#downward-import-rule]
In the target architecture, dependencies flow strictly downward. Roles never import each other or the orchestrator, and only the orchestrator writes lane progression events to the log.
While the v1-to-v2 transition finishes, `go list` shows five places where packages still cross layer boundaries:
| Package | Temporary imports | Why it exists today |
| --- | --- | --- |
| `internal/roles/context` | `orchestrator`, `schema`, `omprpc`, `workersession`, `project`, `spec`, `record`, `skillmap`, `gitio`, `store`, `imginput`, `catalogue`, `adapters/ghissue` | Drives conversation turns, readiness checks, and harness runners |
| `internal/roles/release` | `orchestrator`, `rollup`, `roles/deslop`, `roles/devops`, `project`, `record`, `served`, `gitio`, `store`, `adapters/ghrepo`, `cloud/issuelink` | Coordinates release checks, bisection, and fix-lane additions |
| `internal/ui` | `roles/context`, `roles/release`, `roles/devops`, `observer`, `access`, `approvals`, `connections`, `projectenv`, `uistate`, `board`, `omprpc`, `readonlysession`, `record`, `rollup`, `project`, `spec`, `gitio`, `store`, `metrics`, `mergepolicy`, `orchestrator`, `sandbox`, `setup`, `imginput`, `adapters/ghcli`, `adapters/ghissue`, `adapters/ghrepo`, `cloud/ghapi`, `cloud/kanban`, `net/http` | Serves dashboard views, accounts, connections, board, and embedded Observer controls |
| `internal/observer` | `roles/context`, `roles/release`, `orchestrator`, `approvals`, `access`, `record`, `rollup`, `readonlysession`, `schema`, `store` | Scans waiting work and runs `session.go` via `Actor` and `Hands` without importing `internal/ui` |
| Sibling roles & rollup | `qc` ← `uicheck`/`deslop`; `engineer` ← `qc`; `strategist` ← `orchestrator`; `orchestrator`/`analyzer`/`deslop` ← `rollup` | Shares helper functions and `Plan` schemas across adjacent stages |
## Zero-dependency Go stdlib rule [#zero-dependency-go-stdlib-rule]
[go.mod](https://github.com/cone-labs/turbo-12f/blob/main/go.mod) targets Go `1.27`, excludes `docs-site` via `ignore ./docs-site`, and has zero `require` lines. Every binary in `cmd/` builds strictly with the Go standard library, including the Postgres client.
External Node tooling is isolated to `internal/ui/web` (`bun` and `vite-plus` for embedded UI assets), `docs-site`, and `site` (the Astro marketing site). None of these directories adds third-party Go modules.
## Core and network boundary [#core-and-network-boundary]
`turbo-12f` splits binaries so containment code cannot link HTTP clients or servers of its own. The one exception is `internal/db`, the Postgres client, which a cage reaches over a Unix-socket broker instead of the network.
| Program group | Binaries | Network and model policy |
| --- | --- | --- |
| Core & cages | `cmd/t12`, `cmd/t12-cage`, `cmd/t12-container` | Import `net/http` only through `internal/db`; cages run offline; `t12` invokes local harnesses and subprocess adapters (`ghcli`, `ghissue`, `ghrepo`, `t12-adapter context7 call`) |
| Web UI server | `cmd/t12-ui` | Serves SPA, auth, approvals, and Observer; forks sibling `t12` for mutations |
| Cloud worker | `cmd/t12-cloud-worker` | Runs in GitHub Actions against the shared database; resolves the requesting person's credentials from a per-run reference |
| Network adapters | `cmd/t12-adapter`, plus v1 `t12-runner`, `t12-cc`, `t12-job`, `t12-queue` | Links `net/http` directly or transitively (`internal/adapters/common`, `internal/skills`); handles the Context7 Unix-socket proxy, intake, delivery, and SRE HTTP probes |
| Helper tools | `cmd/t12-mutate`, `cmd/t12-wizard`, `cmd/t12-neon-local` | Mutation testing and host setup link HTTP only through `internal/db`; `t12-neon-local` is the test-only Neon SQL shim |
When a core or cage binary needs direct HTTP calls or UI actions, it calls a sibling binary across an OS process or Unix-socket boundary (`sibling("t12")` in `cmd/t12-ui`, `t12-adapter sre probe --url` in SRE, `t12-adapter context7 serve` and `call` for docs lookups, `t12-adapter hosting call` for Cloudflare and Vercel deploys, health checks and test-site deletes, `db.Broker` for the database).
`TestTheCoreAndTheCageProgramsLinkNoNetworkCodeButTheDatabaseClient` in [naming_test.go](https://github.com/cone-labs/turbo-12f/blob/main/tests/e2e/system/naming_test.go) runs `go list -buildvcs=false -deps` on `t12`, `t12-cage`, and `t12-container` and allows `net/http` only in `internal/db`. Helpers the core needs live in network-free packages (`internal/credhome`, `internal/contextcreator/ccstate`, `internal/hosting`) beside the packages that make HTTP calls (`internal/connections`, `internal/adapters/hosting`). `internal/hosting` sends each provider call to `t12-adapter hosting call` as JSON on stdin, so no token is on a command line.
Keeping the Go core stdlib-only and the cages offline lets `turbo-12f` verify every build in isolation, while Postgres holds the one record and thin sibling adapters confine credentials and network calls.
## Next steps [#next-steps]
# Record and evidence (/docs/architecture/record-and-evidence)
Every state transition, test verdict, decision, and token count in a request appends to an immutable trail in Postgres: the `request:` stream of the `events` table plus its evidence blobs. Read models in `internal/rollup` fold that log into UI pages and CLI summaries with no separate mutable status store.
Canonical JSON lines chained by SHA-256, checked inside one INSERT.
Sequenced `RoleReport`, `Decision`, and `Session` records verified by digest.
Single-pass projections for lane states, flow graphs, quality, and scorecards.
## Where each kind of state lives [#where-each-kind-of-state-lives]
[ADR 0005](https://github.com/cone-labs/turbo-12f/blob/main/docs/adr/0005-neon-source-of-truth.md) fixes one table or document kind for every record. `` (`T12_HOME`) only holds scratch.
| Table or kind | What it holds | Mutability |
| --- | --- | --- |
| `events` | Hash-chained logs for streams `request:` and `run:` | Append-only; a trigger refuses UPDATE and DELETE |
| `blobs`, `blob_chunks`, `files` | Evidence and reports in 1 MiB chunks (gzip when it saves 10 percent), named per scope such as `request:` | Blobs are content-addressed; a file name points at one hash, and freshly sequenced names never collide |
| `documents(kind, key)` | Small mutable JSON with a revision: `context-state`, `approval-mode`, `observer-setting`, `proposal`, `release-checks`, `artifact` | Compare-and-swap on `rev` |
| `log_entries` | Plain append logs: `access`, `observer`, `release::signoffs`, `promotions:` | Append-only |
| `leases` | Locks with a TTL on the database clock | Renewed while held, freed when the holder dies |
| `runs`, `lanes`, `decisions`, `role_reports`, `approvals`, `outbox` | Structured copies and queues derived from or beside the event log | Row operations |
| `changes` | One revision counter per scope (a conversation, `convs`, `access`, `approvals`, one person's own state, `global`) that database triggers bump on every write to the tables a page reads | Counters only go up; lease renewals do not bump them |
| `db_usage` | Response bytes and HTTPS calls each process (`ui`, `worker`) has read, one row per day and source | Added to about once a minute |
## Hash-chained event logs [#hash-chained-event-logs]
`internal/record` ([record.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/record/record.go)) chains events into the `request:` stream using canonical JSON from `internal/store`:
- **Genesis & chaining:** Sequence `1` links to `SHA256("t12-request-genesis:" + req)`. Each event strips `hash`, encodes via `store.Canonical`, writes its SHA-256 into `hash`, and links the prior digest in `prev`.
- **Atomic appending:** One statement inserts the event only if it extends the chain, records the names and hashes of the event's files, and bumps `conversations.last_seq`. A lost race retries; repeated losers queue on a short `append:` lease.
- **Sequenced blobs & cache keys:** `freshName` prefixes evidence and reports with a 4-digit sequence (`0001-...`); `EventsStat` returns `(last seq, last event time)` for SSE ticks; `StatusTracker` reads state in one pass.
- **Full verification (`Home.Verify`):** Replays `Seq`, `Request`, `Prev`, and `Hash`, checks that the stored hash columns match the verbatim line, verifies every blob digest an event names, and rejects paths that leave the request. The web server, which checks on every page, verifies only what it has not checked yet (`verifycache.go`).
| Lease | Scope and ordering |
| --- | --- |
| `activity:` (`Home.WithActivity`) | One per running CLI command; `t12-ui --drain` takes `home:activity-drain` and reports busy while any activity lease is live |
| `req::` | Typed locks (`LockContext`, `LockAsk`, `LockConfirm`, `LockRun`, `LockRunMerge`, `LockRelease`), nested `LockConfirm -> LockContext -> LockAsk` and `LockRelease -> LockRunMerge -> LockRun` |
| `RequestLocked` / `IsLocked` | Expose active external CLI work to `t12-ui` and Observer by reading live leases |
| `projects` table | Connected GitHub repository registry managed via `Home.ConnectedProjects` ([projects.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/record/projects.go)); no registry file or lock |
A holder that dies stops renewing, so its lease frees itself and no stale lock file needs cleaning up. A web server shows which requests are busy from one view of the live lease names that is at most 3 s old (`db.Client.LiveLeaseNames`); the lock itself is always taken in the database.
`t12 db import --home DIR` is the only code that reads the old file layout. It verifies each `events.jsonl` chain first, copies lines byte-exact into `events.line`, loads `requests//` files into `blobs` and `files` with unchanged hashes, and is safe to rerun. Stop the factory before importing and do not re-import after cutover.
[design.md](https://github.com/All-Chat-Bridge-for-CRM/ConvoRelay/blob/main/docs/factory/design.md) restricts event appends to the orchestrator alone. Today several CLI verbs (`approve`, `bugbash`, `confirm`, `release`), `internal/roles/context`, the merge queue, and the cloud backend also call `Home.Append` directly.
## Typed evidence records [#typed-evidence-records]
| Record type | What it captures |
| --- | --- |
| **`RoleReport`** | Step execution (`Did`, `Done`, `NotDone`, `Next`), `Verdict`, `Findings`, `Checks` (`CheckCoverage`: `ran`/`skipped`/`noop-true`), `Cost`, `Context`, `Cage`, `Preferences`, and Context7 `Docs`; also copied to `role_reports` |
| **`Decision`** | Strategist rules (the team flow routes by rules alone; only `classic` adds Strategist agent decisions), `"answered-for-you"`, Observer actions (`observer-`, `By: "observer"`), and rule proposals; Observer state lives in `log_entries` stream `observer` and the `observer-inflight` document |
| **`Session` (`EvSession`)** | Harness runs with `Tools` calls and `SessionUsage` tokens; read-only sessions keep numbered transcripts (`transcript-[-N].jsonl`) behind a `TranscriptRef`; `approval-asked` / `approval-decided` outcomes come from `approvals.EndSession` |
## Read-side projections in internal/rollup [#read-side-projections-in-internalrollup]
`internal/rollup` derives all status views, flow graphs, and scorecards directly by folding `events`, `reports`, and `decisions`:
- **Twelve lane states:** `StateWaiting`, `StateBuilding`, `StateChecking`, `StateFixing`, `StateYourOK`, `StateOnTest`, `StateHeldBack`, `StateStuck`, `StateLive`, `StateUndone`, `StateLiveFixes`, and `StateSplit` power UI and CLI summaries via single-pass helpers (`TasksFromEvents`, `Summarize`, `NowFromEvents`, `PlanFromEvents`, `QualityFromEvents`). A lane paused as a Problem reads as resumable, and a person's answer moves a stuck part on.
- **Waiting on a person (`wait.go`):** `WaitsOnPerson` says a conversation is blocked, asking, or has a part that is stuck or waits for an OK; `WaitPaused` says it has had no event for longer than the project's `budgets.wait_hours`, and `PausedNow` words it. Nothing is written: any new event ends the pause.
- **Flow graph (`GraphOf` & `ApplyLiveJob` in [graph.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/rollup/graph.go)):** Folds events into `FlowGraph`, taking its steps from the conversation's flow: the `flow-chosen` event written before its first part starts (`team` or `classic`; a log with none ran `classic`). Only `EvStepDone` with `Detail["by"] == "orchestrator"` advances lane steps, and `EvSendBack` emits `ReworkEdge` only when `from` exists in `stepIndex`.
- **Acceptance & quality:** `Acceptance` maps scenarios to tests and files; `QualityOf` computes catch rate from pre-merge versus escaped bugs.
- **Scorecards & outcomes:** `Score` records outcomes for every conversation (`RecordOutcomes`, also `t12 outcomes`), and `t12 run` and `t12 release merge` record them for their conversations (`RecordOutcomesFor`) as `decision-outcome` events. Scorecards aggregate `CheckCoverage` and propose `guardrail-*` documents after `EscapedGuardrailMin = 2` escaped bugs.
Each network call costs a round trip, so the web server keeps two process-local caches in `db.Client.Memo`: an event cache holding the verified prefix of each log (`PrimeEvents` fills many logs in one query) and a blob cache keyed by SHA-256. A miss is always correct. The home page also stores derived summaries as `ui-home-summary` documents stamped with `last_seq`; `T12_UI_SUMMARY_STORE=off` disables them. A polled page is versioned by the `changes` revisions of the scopes it reads: a request that sends that version in `If-None-Match` gets a 304 without the page being built, and no page is older than a minute (`internal/ui/conditional.go`).
`record.Home.observe` tells the metrics recorder about events that change waits or samples. `agent_spans`, `human_waits`, and `sloppiness_samples` rows are keyed by stable ids, so a replayed event upserts instead of duplicating. They are derived views that can be rebuilt from the log.
## Legacy v1 model contrast [#legacy-v1-model-contrast]
Before `internal/record` introduced request-scoped streams, turbo-12f v1 stored per-task state in `internal/model` (`Version = 8`). That state now lives in Postgres too.
| Aspect | v2 (`internal/record` and `internal/rollup`) | Legacy v1 (`internal/model`) |
| --- | --- | --- |
| Primary log layout | `events` stream `request:` plus immutable blobs | `runs` row plus `events` stream `run:` |
| Integrity hash | `prev` and `hash` chain over `store.Canonical` JSON | `state_sha` chained across snapshots and event rows |
| Concurrency safety | Chain check inside the INSERT; `req:` leases | `run:`, `lane:` and `integration:` leases, fixed order lane -> integration -> run |
| State updates | Append events and fold projections in `rollup` | Three-way JSON merge (`ApplyChanges`) with `runMoved` guards |
| Crash recovery | A crash leaves the whole statement or none | Explicit `t12 repair` CLI pass |
Because every view in `t12` and `t12 ui` is folded from one hash-chained log in one database, there is no split-brain status store to repair. If `t12 conversation verify` passes, the history is intact.
## Next steps [#next-steps]
# Release and SRE (/docs/architecture/release-and-sre)
Merging feature work into `staging`, validating the combined tree, promoting to `main`, and watching live traffic all run through deterministic leases, patch-bound approvals, and bounded triage loops. The release ledger, checks, artifacts, and promotions are database streams and documents, not files in the state home. Both flows share all of it: in the `team` flow DevOps owns each lane's `merge-policy`, `merge` and `deploy-dry-run` steps, and the release checks are identical in `classic`.
Flag `data-loss`, `auth`, `licence`, `delivery`, or `review` diffs before merge.
Verify the record, take the queue lease, rebase onto `staging`, recheck if changed, and fast-forward.
Run staging-wide checks, bisect failures, and require human sign-off for `main`.
Probe live URLs, group errors by fingerprint, file incidents, or roll back.
## Serialized merge queue [#serialized-merge-queue]
[mergequeue.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/mergequeue/mergequeue.go) guarantees that lanes update `staging` strictly one at a time without overwriting concurrent work:
1. **Verify and acquire lease:** Checks `Home.Verify` for the request, then takes the `home:merge-queue` lease and waits for it (`LockWait`); a dead holder's lease expires on its own.
2. **Rebase in scratch worktree:** Checks out the lane commit inside `/merge-scratch/` (disposable) and rebases onto `staging`.
3. **Recheck if tree changed:** Compares rebased `res.Tree` against the verified tree (`checked`). If different, `Recheck` reruns `Install` and `qc.Run` without mutation testing.
4. **Compare-and-swap update:** Advances `staging` via `git update-ref refs/heads/ ` (or `git merge --ff-only` if checked out) and records `EvMerged`.
## Merge policy and patch-bound approvals [#merge-policy-and-patch-bound-approvals]
Before entering the merge queue, `merge-policy` ([mergepolicy.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/mergepolicy/mergepolicy.go)), the lane step before `merge` in both flows, evaluates four diff rules plus the synthetic `review` check:
| Rule | Trigger or scope | Approver and autonomy behavior |
| --- | --- | --- |
| `data-loss` | `migrations/**` lines dropping/renaming tables or columns, or deleting rows | Acceptor (who confirmed the request) approves, even under `turbo` |
| `auth` | Paths matching `AuthGlobs` or `"auth"` risk tag | Operator/approver under `review`, `default`, `auto` (unless policy is `"auto"`); waived in `turbo` |
| `licence` | New `package.json` packages with licenses outside `Allow` (`DefaultLicences`) | Operator/approver when `MatchesWait` is active; waived in `turbo` |
| `delivery` | Edits to `delivery`, `watch`, or `credentials` in `.t12/config.json` | Operator/approver when `MatchesWait` is active; waived in `turbo` |
| `review` | Synthetic check on every lane when resolved autonomy is `"review"` (`PartsWait`) | Acceptor approval via `t12 approve` (waits even when policy mode is `"auto"`) |
Every approval written by `t12 approve` binds to `git patch-id --stable`. If `Engineer` or `Merge` later alters the patch content, the prior approval lapses automatically and requires fresh review.
## Release checks, bisection, and the release gate [#release-checks-bisection-and-the-release-gate]
Once all active lanes merge onto `staging`, the request-level `release` lane runs `stepRelease` in [run_release.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/cli/run_release.go) and reads the gate in [gatefor.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/release/gatefor.go):
| Stage | Functions | Behavior |
| --- | --- | --- |
| **Staging checks** | `releaseChecks` | After a dependency install, runs `qc` (full E2E and the build), `uicheck`, `redteam`, `deploy-dry-run` (only when no kept artifact has built files on this host), and optional `qc.explorer` against `staging^{tree}`, saving a `release-checks` document keyed `/` through `Ledger.SaveChecks`. A passing result is reused for the tree; a failed one is reused only by the same factory build (`Checks.Factory`), so a newer build re-runs it. |
| **Bisect & fix** | `Bisect`, `fixRelease` | Locates the culprit merge between `main` and `staging` on failure, adds `-rf` via `release.AddFixLane`, and re-runs the factory up to `3` extra passes (`pass < 3` in `factory.go`). |
| **Four-part gate** | `release.Gate`, `GateFor` | Requires passing `staging^{tree}` checks, surfacing `CheckCoverage` `noop-true`/`skipped` warnings, carried sign-offs from the ledger, no holds, zero lapsed sign-offs, and zero `Sev-1`/`Sev-2` bugs. |
| **Release pull request** | `ClosingIssues`, `RenderPRBody` | The body carries the gate, the checks, the plain and detailed reports, and one `Closes #n` line for every plan, feature, lane, and need-decision issue named in the records of the release's conversations, so GitHub closes them when the pull request merges. |
| **Main promotion** | `t12 release merge` | Checks `staging^{tree}` stability, merges `--no-ff` to `main`, pushes `main` to GitHub with networked git when the project is bound to a repository, then runs `RecordOutcomesFor` and `devops.Promote` with the deployer for the connected hosting account (`devops.AccountFromEnv`), appends a promotion row, and appends `EvDelivered`. |
With no Cloudflare or Vercel account connected, the deployer is `DryRunOnly{}` and `devops.Promote` refuses production (`promote.no-account`, `NoAccountAdvice`): the merge to `main` still lands and each request is delivered, but nothing goes live. With an account, `Promote` deploys to the person's Cloudflare account (preferred) or, for a static project, Vercel, rebuilds the tree's files first when a worker job starts without them (`ensureBuilt`), checks that the new address answers, rolls back to the previous promoted tree if it does not (a failure when none exists), and records the live `url` on the promotion row. A project that needs its Worker and has only Vercel connected is refused before anything uploads (`promote.unservable`). After a release delivers, the cloud worker closes any of those issues GitHub did not and labels them `status:done`.
| Record | Storage | Old path (import format only) |
| --- | --- | --- |
| Sign-offs and holds | `log_entries` streams `release::signoffs` and `release::holds`, appended by `Ledger.SignOff` and `Ledger.Hold` | `release//signoffs.jsonl`, `holds.jsonl` |
| Release checks | `documents` kind `release-checks`, key `/` | `release//checks/.json` |
| Kept artifact | `documents` kind `artifact`, key `/`; the built `dist/` is a host-local cache | `artifacts///` |
| Promotions | `log_entries` stream `promotions:`; a real deploy's row carries the live `url` | `artifacts//promotions.jsonl` |
| SRE fingerprints | `documents` kind `sre-fingerprints`, key `` | `sre//fingerprints.json` |
`devops.Promote` refuses a tree whose built files are not on this host (`promote.no-build`; `promote.no-account` when no hosting account is connected): run the staging dry-run for that tree here, then promote again. `t12 release merge` rebuilds the tree itself first when a real deploy is about to upload it.
## SRE watch, triage, and rollback [#sre-watch-triage-and-rollback]
Post-release checks run through `sre` ([sre.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/sre/sre.go), [triage.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/sre/triage.go), [cli/sre.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/cli/sre.go)) via `t12-adapter sre probe --url`. The watch and triage commands (`t12 sre`) are the same in both flows; only the `classic` flow also ends each lane with an `sre` step.
- **Fingerprints (`Fingerprint`):** Normalizes hex strings (``), ports (`:`), and integers (``) before hashing with `SHA-256[:16]` so duplicate errors collapse to one ID.
- **Thresholds:** Marks endpoints down after `DownAfter` (`3`) failures, logs responses over `SlowAfter` (`2s`) as `should-fix`, and flags gaps wider than `2 * every` as `Unwatched`.
- **Triage & rollback (`t12 sre triage`):** With `--rollback`, first calls `devops.RollBack` through the connected hosting account's deployer, inside the `24h` `RollBackWindow`. It then classifies the failing window as `ProjectDefect` (files `"Incident found by SRE: ..."` via `cmdAsk`), `PlatformOutage` (printed for the Operators, no retry token spent), or `noise` (closed).
No change reaches `main` unverified: every lane rebases through a single merge lease, approvals bind to exact patch IDs, and failing staging trees bisect automatically before a human merges.
## Next steps [#next-steps]
# Request lifecycle and orchestration (/docs/architecture/request-lifecycle)
Every feature, fix, or incident moves through `turbo-12f` as an append-only request: a hash-chained event stream `request:` in Postgres. The orchestrator splits accepted specs into dependency-ordered lanes, runs deterministic gates and AI steps, merges passing lanes onto `staging`, and validates the release before merging to `main`.
Lock an OpenSpec change with verbatim quotes, then pass the Project Gate.
Split the spec into dependency-ordered worktrees and run each lane through the flow's steps (six in `team`).
Evaluate merge policy, rebase sequentially, and wait for a quiet queue.
Run whole-tree staging checks, bisect failures, sign off, and merge to `main`.
## End-to-end request flow [#end-to-end-request-flow]
1. **Intake (`t12 ask`):** Starts on `--project-dir` or `--repo`, collects quoted must-haves, images, and issues via `t12 conversation issues` or `POST /api/c/{id}/issues`, and clears readiness checks.
2. **Confirmation (`t12 confirm`):** Binds the request to a new or adopted repository, initializes `.t12/`, and runs `devops.ProjectGate` to verify clean branches, pinned skills, dependencies, and base checks on `branches.staging`. `--acceptor` names the person who accepts the conversation.
3. **Lane execution (`t12 run`):** Calls `orchestrator.Run` ([orchestrator.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/orchestrator/orchestrator.go)). `orchestrator.ChooseFlow` records the conversation's flow, then the Tech Lead's split (`strategist.Route`) turns the spec into dependency-linked tasks (`EvTaskAdded`) that run in parallel worktree lanes.
4. **Release lane:** Once non-parked lanes merge into `staging`, `orchestrator.Run` launches the request-level `release` lane (`ReleaseLane = "release"`).
5. **Release checks & bisection:** `stepRelease` ([run_release.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/cli/run_release.go)) installs dependencies on `staging`, then runs `qc`, `uicheck`, `redteam`, and `deploy-dry-run` (plus optional `qc.explorer`), the same in both flows. The result is stored per `staging` tree: a passed tree is not checked again, and a failed one is run again by a newer factory build. When Red team or the explorer proves a finding, `fixRelease` bisects the merges since `main` and opens `-rf` fix lanes for up to `3` passes.
6. **Promotion (`t12 release merge`):** After `t12 release gate` turns green and the acceptor signs off, `branches.staging` merges `--no-ff` into `branches.main` (default `main`) once every request's hash chain verifies, and the merge is pushed to GitHub. On a team project the acceptor is any owner, member or Operator (a client only on their own requests); otherwise the opener. `devops.Promote` then deploys the artifact that staging built to the person's own Cloudflare or Vercel account, checks the site answers, and rolls back if it does not; with no account connected, production stays a dry run and is refused.
## Flows: the steps every lane runs [#flows-the-steps-every-lane-runs]
Each worktree lane runs the steps of the conversation's flow ([flow.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/orchestrator/flow.go)). `ChooseFlow` reads the project's `flow` preference once and records it as a `flow-chosen` event before the first part starts, so a conversation keeps its flow when the preference changes later; a conversation whose lanes ran before flows existed keeps `classic`. `t12 run` prints the choice, for example `flow: team (analyze, engineer, qa, merge-policy, merge, deploy-dry-run)`.
| Step | Team member | Responsibility |
| --- | --- | --- |
| 1 | `analyze` (Tech Lead, `internal/roles/analyzer`) | Plans changed files, test specs, and predicted screens on `staging` |
| 2 | `engineer` (Developer, `internal/roles/engineer`) | Writes failing tests first, then production code inside a Docker cage; each candidate it hands over is checked in its session (`qc`, `ui-check`, Red team's origin check) |
| 3 | `qa` (QA, `stepQA`) | Runs `qc`, then `ui-check`, then one `code-review` session, stopping at the first that fails; reuses a `qc` or `ui-check` pass the Developer's session earned on the same commit |
| 4 | `merge-policy` (DevOps, `internal/mergepolicy`) | Evaluates `data-loss`, `auth`, `licence`, `delivery`, and `review` bound to `git patch-id --stable` |
| 5 | `merge` (DevOps, `internal/mergequeue`) | Verifies the request's hash chain, takes the `home:merge-queue` lease, rebases onto `staging`, rechecks if tree changed, and fast-forwards |
| 6 | `deploy-dry-run` (DevOps, `internal/roles/devops`) | Validates staging deploy artifact once the quiet window clears |
A part costs three agent sessions (plan, build, review). QA's one review stands in for Code review, Deslop, and Red team, so it gets three times a single reviewer's cost budget. A blocking `qa` finding goes back to the Developer as a fix attempt, and no Strategist session is asked. Deslop, Red team, and SRE do not run per part; Red team still runs in the release checks.
| Step | Role | Responsibility |
| --- | --- | --- |
| 1 | `analyze` (`internal/roles/analyzer`) | Plans changed files, test specs, and predicted screens on `staging` |
| 2 | `engineer` (`internal/roles/engineer`) | Writes failing tests first, then production code inside a Docker cage; each candidate it hands over is checked in its session, and the lane's `qc` and `ui-check` steps reuse a pass on the same commit |
| 3 | `qc` (`internal/roles/qc`) | Runs `build`, `typecheck`, `lint`, `comment-ban`, `test-guard`, `scenario-text`, `unit`, `e2e`, and `mutation` |
| 4 | `ui-check` (`internal/roles/uicheck`) | Settles `5s` (`SettleSeconds`), compares PNG SHA-256 baselines, and flags overflow or unpredicted screens |
| 5 | `deslop` (`internal/roles/deslop`) | Runs regex, AST, and clone hygiene rules plus a read-only audit |
| 6 | `red-team` (`internal/roles/redteam`) | Runs `gitleaks`, `osv-scanner`, cross-origin POST checks, and visitor replay probes |
| 7 | `code-review` (`internal/roles/codereview`) | Checks unrequested edits, unlisted dependencies, hypotheses, and prior findings |
| 8 | `merge-policy` (`internal/mergepolicy`) | Same as the team flow |
| 9 | `merge` (`internal/mergequeue`) | Same as the team flow |
| 10 | `deploy-dry-run` (`internal/roles/devops`) | Same as the team flow |
| 11 | `sre` (`internal/roles/sre`) | Watches staging health probes over a short observation window |
A part costs five agent sessions, and a failure no rule routes (or the second hit of the same root cause) asks a Strategist session where it goes.
In both flows the step right before `merge-policy` is the lane's last check (`Flow.Review`): `qa` in `team`, `code-review` in `classic`. Adding a step means a constant in `internal/orchestrator`, a `StepFunc` in `cli.runSession.steps`, an entry in the flow's `Steps` (and `Owners`), a `found_by` rule in `assets/strategist/rules.json`, and a label in the web's `lib/steps.ts`; `TestEveryFlowStepIsWiredAndOwned` fails until it is wired, owned, and routed.
[design.md](https://github.com/All-Chat-Bridge-for-CRM/ConvoRelay/blob/main/docs/factory/design.md) specifies running `E2E`, `UI check`, and `Red team` in parallel after `qc`. Today `runLane` in `internal/orchestrator/orchestrator.go` runs every step strictly sequentially.
## Concurrency, priority, and locks [#concurrency-priority-and-locks]
[slots.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/orchestrator/slots.go) separates LLM concurrency from verification container concurrency using two semaphore pools (`slotOf`):
| Pool | Steps covered | Default capacity | Priority order |
| --- | --- | --- | --- |
| `agentSlot` | `analyze`, `engineer`, `qa`, `code-review` | `4` (`project.DefaultAgentSlots`) | Resumed fixes first, longest `chain`, then FIFO |
| `checkSlot` | `merge`, `deploy-dry-run`, and in `classic` `qc`, `ui-check`, `deslop`, `red-team`, `sre`; the checks an Engineer session runs on its candidates take one too | `max(1, NumCPU / 2)` (`DockerCPUs / 2` in Docker) | Same `priority{fix, chain}` comparator, then arrival order |
| Unslotted | `merge-policy` | Unbounded | Runs immediately inside `runLane` |
Three coordination rules in [queue.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/orchestrator/queue.go) and [slots.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/orchestrator/slots.go) prevent lane collisions inside one run:
- **File locks (`fileLocks`):** In-process, active when `overlap` is `"wait"` (vs. default `"parallel"`). Engineer locks `Analyze` target paths in sorted order before editing and releases on `Merge` or send-back.
- **Quiet window (`waitQuiet`):** Delays `deploy-dry-run` until `queued == 0` (counting lanes between the flow's last check and `merge`) and `120s` (`DefaultQuietWindowS`) pass without queue changes.
- **Live capacity resizing:** Every `15s` (`LiveCapacityEvery`), reads `capacity.agent_slots` and `capacity.check_slots` from `.t12/preferences.json` on `refs/heads/` and updates pool limits live.
Locks between processes are database leases, not lock files: a holder renews its lease while it works and a dead holder's lease expires on its own.
| Lease | Held by | Behavior |
| --- | --- | --- |
| `req::` | `ask`, `confirm`, `context`, `run`, `run-merge`, `release` | Waits 10 s, then reports another command holds it; `confirm` then `context` then `ask` order kept |
| `home:merge-queue` | Merge queue | Waits until the lane before it finishes |
| `activity:` | Every CLI command | `t12-ui --drain` reports busy (exit 3) while any activity lease is live |
| `append:` | Event appends that lose a race | Losers append one at a time; the chain check in the INSERT still guards it |
## Task planning (the Tech Lead's split) and parallel lanes [#task-planning-the-tech-leads-split-and-parallel-lanes]
Before launching lanes, Orchestrator calls `strategist.Route` ([plan.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/strategist/plan.go), [dag.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/dag/dag.go)) to build a task DAG, falling back to `strategist.Tasks` when planning is skipped or invalid. This split runs in both flows; in `team` it is the Tech Lead's first job.
| Mechanism | How Orchestrator handles it |
| --- | --- |
| **Upfront queue & snapshots** | `QueueTasks` writes `EvTaskAdded` upfront (`Tasks` replays on resume); each step snapshots `Ctx.Tasks` under `tasksMu`. |
| **Dynamic seam splits** | Oversized tasks split into `-1..N` via the Tech Lead's `split` plan (`checkSplit`) and `strategist.Split`; the over-size candidate is kept on the `t12//--oversize` branch so the parts start from its code. A split part that is still over the limit cannot split again and needs a `size_waiver`, which waits for a person below `turbo`. |
| **Task Gate status** | `design.md` defines a pre-lane Task Gate to drop duplicate/passing work; today Strategist checks DAG partitions and Orchestrator enforces `depsDone`/`pausedDeps`. |
See [Strategist internals](/docs/architecture/roles-planning-and-build#strategist-internalrolesstrategist) for `PlanTimeout` and partition rules.
## Failure routing rules, send-back sync, and the classic Strategist [#failure-routing-rules-send-back-sync-and-the-classic-strategist]
When a step fails or reports blocking findings, `orchestrator.route` matches the deterministic rules in [rules.json](https://github.com/cone-labs/turbo-12f/blob/main/assets/strategist/rules.json) (`rules.Match`). In the `team` flow that is the whole decision: a `qa` finding goes to the Developer as a fix attempt (`tokens: 0`), and an `engineer` failure goes to the Tech Lead's `analyze` on a retry token.
- **`merge` send-back sync (`sendback.go`):** `handleSendBack` emits `EvSendBack` with `"sync_staging": true`. At Engineer start, `syncWorktreeIfPending` calls `gitio.SyncOntoStaging`, squashes onto `staging`, blocks on binary/`UD` conflicts, and leaves text conflict markers with a cleared index for the caged Engineer.
- **Classic only, Strategist fallback & rule proposals:** In `classic`, unmatched steps (`analyze`) or repeat `rootHash` hits (`state.hashes[hash] == 1`) invoke `strategist.Decide` and feed `proposal` documents keyed `strategist-rule-*`. `t12 run` leaves `Config.Strategist` unset for `team`, so no Strategist session runs.
## Recovery ladders and autonomy levels [#recovery-ladders-and-autonomy-levels]
Before spending a retry token or parking a lane, Orchestrator climbs five recovery rungs:
1. **In-place retry (`StepRetries`):** Retries infrastructure errors (`couldNotRun`) with no open questions, appending `EvRetried`.
2. **Auto-answer (`AnswerQuestions`):** Calls `answerForYou` when questions stop a step, logs `"answered-for-you"` (`EvAnswer`), and reruns (`i--`).
3. **Engineer fix attempts (`FixAttempts`, default `3`):** Handles `Conflict`, `turn-cap`, and failures a rule routes to the Developer (`qa`, `qc`, `merge`, `deploy-dry-run`) at zero request tokens.
4. **Analyze retry tokens (`tokenPool`, default `2`):** Sends the lane back to `analyze` with the failure as its resume prompt. A `diff-cap` finding (counted by `gitio.Tree.AddedLineCount`) and second hits (`state.hashes[hash] == 1`) of a `rootHash` run with `free: true`.
5. **Lane pause (`EvProblem`):** Triggers on a third identical `rootHash` (`state.hashes[hash] >= 2`) or exhausted budgets, setting `errPaused` and `pausedDeps` while other lanes continue. A person's answer after a Problem (the UI's "Try again" sends one) reopens the lane with fresh fix attempts and hashes.
[autonomy.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/project/autonomy.go) resolves four presets via `Preferences.ResolveAutonomy(os.Getenv("T12_AUTONOMY"))`. Selecting a mode in `t12 ui` writes the `approval-mode` document and injects `T12_AUTONOMY` into worker subprocesses; in `review` (`Request Review`), every shell command also waits in `internal/approvals`.
| Level | `FixAttempts` | `RetryTokens` per task | `StepRetries` | `AnswerQuestions` | Merge-policy and review waits |
| --- | --- | --- | --- | --- | --- |
| `review` | Config value (default 3) | Config value (default 2) | `0` | `0` | `PartsWait: true` (every lane waits), `MatchesWait: true`, `diff-cap-waiver` waits |
| `default` | Config value (default 3) | Config value (default 2) | `0` | `0` | `MatchesWait` true unless `merge_policy.mode` is `"auto"`; `diff-cap-waiver` waits |
| `auto` | Minimum `4` | Minimum `3` | `2` | `1` | Same match waits as `default`; `diff-cap-waiver` waits |
| `turbo` | Minimum `5` | Minimum `5` | `4` | `3` | `MatchesWait: false`; only `"data-loss"` waits (`diff-cap-waiver` waived) |
Orchestrator keeps model judgment out of lane progression: every split, retry, merge lock, and pause is driven by deterministic Go state over the `request:` event stream.
## Next steps [#next-steps]
# Delivery, operations, and Observer (/docs/architecture/roles-delivery-and-observer)
Four components handle repository onboarding, staging-to-main releases, post-release monitoring, and optional unattended operator decisions (`devops`, `release`, `sre`, and `internal/observer`).
Bootstrap or adopt repos, run Project Gate, and build dry-run artifacts.
Verify whole-tree staging checks, bisect failures, and merge to `main`.
Probe live URLs, group errors by fingerprint, and triage or roll back.
Resolve waiting items every 10s via read-only UI sessions when enabled.
## DevOps (`internal/roles/devops`) [#devops-internalrolesdevops]
[internal/roles/devops](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/devops/gate.go) runs pure Go automation (zero LLM calls) with `defaultCommandTimeout = 10m`. In the `team` flow DevOps is the team member who owns each lane's `merge-policy`, `merge` and `deploy-dry-run` steps (scripts, no agent session); the `classic` flow runs the same three steps. Standalone `Install` ([deploy.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/devops/deploy.go)) retries timed-out installs up to `InstallTimeoutRetries` (`2`), while `Gate` and `DeployDryRun` run the install once (`DeployDryRun` only when the tree has no `node_modules`).
| Capability | Files | What Go does |
| --- | --- | --- |
| **Bootstrap, Init & Adopt** | `bootstrap.go`, `connect.go`, `adopt.go` | `Bootstrap` scaffolds the starter template, `.t12/` config, and CI workflow into a new repository. A clone with no commits (what GitHub hands out for a repository the factory just created under the person's own account) counts as empty and keeps its `origin`. A non-empty repo that is not already bootstrapped (no `.t12/config.json`) is refused. `InitLocalProject` does the same for `t12 repo init`, and treats the cloud's registration of the same repository under the same name as its own; another repository under that name is refused. `Adopt` takes an existing repo via `project.Detect` (Node.js, Go, Python, Rust, Effect-TS) onto `staging` or `t12-staging`. |
| **Project Gate** | `gate.go`, `depscache.go` | Verifies the `.t12/` config files, that every role's skills resolve to their pinned hashes (`skills.Check()`), both branches, and the toolchain; installs dependencies through the `deps-cache`; then runs `build`, `lint`, `typecheck` and `unit` in the cage on the staging base. A command that is a no-op is recorded as such, so a `["true"]` placeholder never reads as a green check. |
| **Dry-run & Promote** | `deploy.go`, `promote.go`, `account.go` | Builds staging in cage and keeps the artifact as an `artifact` document (key `/`); nothing is uploaded at this step. The built `dist/` is a rebuildable cache under `/artifacts/`. Promotions go to the `promotions:` log stream. With no hosting account connected the deployer is `DryRunOnly{}` (`H10`): production stays a dry run, and the release gate says to connect an account. With a Cloudflare (token and account id) or Vercel connection of the person's own, `AccountDeployer` deploys the artifact (Cloudflare Workers through wrangler, or static files to Vercel; a project that needs its Worker needs Cloudflare), checks that the site answers, and redeploys the previous tree if it does not. `RollBack` works within `24h`. |
## Release (`internal/roles/release`) [#release-internalrolesrelease]
[internal/roles/release](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/release/gate.go) is a pure Go gatekeeper triggered on the `release` lane, `t12 release gate`, and `t12 release merge`.
It reads the project's release ledger from the database, bisects failing trees (`Bisect` / `AddFixLane`), and promotes clean trees to `main`. The ledger is a `release-checks` document per `/` plus the `release::signoffs` and `release::holds` log streams. The release checks run `qc`, `ui-check`, a `red-team` session on twice a single lane's budget, the deploy dry-run, and `explorer` when `qc.explorer` is on. On `Adopted` repos, `release.Open` pushes only the staging branch and opens the PR without creating a repo or pushing `main`. `RenderPRBody` ([summary.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/release/summary.go)) formats PRs outcome-first with `deslop.CheckProse` warnings and ends with a `Closes #N` line for each GitHub issue the conversations' records name, so the merge closes them.
See [Release and SRE](/docs/architecture/release-and-sre) for the 4-part gate, `--no-ff` merge sequence, and bisection rules.
## SRE (`internal/roles/sre`) [#sre-internalrolessre]
[internal/roles/sre](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/sre/sre.go) pairs deterministic HTTP probing (`t12-adapter sre probe --url`) with a `10m` `NoCommands: true` triage session ([triage.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/sre/triage.go)). The `t12 sre` watch and triage commands are the same in both flows; the per-lane `sre` step is the last step of a `classic` lane only, and the team flow has no such step.
It keeps the normalized fingerprints of each project in the `sre-fingerprints` document (key: the project), files follow-up requests on project defects, or triggers `devops.RollBack`. See [SRE watch, triage, and rollback](/docs/architecture/release-and-sre#sre-watch-triage-and-rollback).
## Observer (`internal/observer`) [#observer-internalobserver]
[internal/observer](https://github.com/cone-labs/turbo-12f/blob/main/internal/observer/observer.go) runs inside `t12-ui` every `10s` once an Operator switches it on for chosen `projects` or `conversations` (the `observer-setting` document; `POST /api/observer` needs an Operator). The cloud build does not start the loop. Each cycle recovers any interrupted item, picks the top waiting item in scope, and acts for the request's opener, or for the Operator who enabled it when no person opened it. It injects that person's `UserProfile` and any `roles.observer` override, then runs a `5m` `NoCommands` [observer.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/observer.md) session that reads only the evidence staged for the item.
### Waiting item priority order (`kinds.go`) [#waiting-item-priority-order-kindsgo]
| Priority | Kind | Allowed actions | Required right | Blocked by active job |
| --- | --- | --- | --- | --- |
| 1 | `command` | `allow`, `deny` | `acceptor` | None (`never`) |
| 2 | `approve-part` | `approve`, `send-back` | `acceptor` | `action` job |
| 3 | `stuck` | `retry`, `wait` | `run` | `action` or `build` |
| 4 | `answer` | `answer`, `decide-for-me` | `editor` | `action` job |
| 5 | `confirm` | `confirm`, `answer`, `wait` | `acceptor` | `action` job |
| 6 | `build` | `build`, `wait` | `acceptor` | `action` or `build` |
| 7 | `signoff` | `signoff`, `hold`, `wait` | `acceptor` | `action` job |
| 8 | `hold` | `hold`, `wait` | `acceptor` | `action` job |
| 9 | `release` | `release`, `wait` | `acceptor` | `action` or `build` |
The rights come from the acting person's access to the request. On a team project, `acceptor`, `editor` and `run` belong to its owners, members and Operators; a client who opened the request has only `acceptor`, so only `acceptor` kinds. On a request with no project, the opener has all three. A `confirm` item needs a project name when the request has none, and `release` only appears for a person who made the latest sign-off.
- **Evidence as files:** Records live in the database, so before each decision the loop writes the files the item names (`events.jsonl`, `reports`, `evidence`, `lanes/.json`, `context/draft/plain.md`, and for release kinds `release/checks.json`, `signoffs.jsonl`, `holds.jsonl`) into a scratch folder under `/observer/` and deletes it afterwards. The decision must list at least `2` options, a reason, and evidence files that exist.
- **Deduplication & lock checks:** Each `(kind, request, item)` is decided once, whatever the result. `signoff` requires `checks.Pass()` and never overrides `"held back"`, and `detectBuild` scans `runEvents` strictly after `confirmed.Seq`. `observerHands.Busy` checks both UI jobs and the request's `leases` rows that external CLI runs hold (`actionBusy`, `buildBusy`). Just before acting, the loop re-checks that the setting is still on and the item still waits, else it logs `skipped`.
- **Handler execution & flags:** `observerHands` calls `ui.Server` handlers and passes `--by observer` (`ask`, `run --answer`), `--observer` (`approve --send-back`), and `Observer: true` (`Command` approvals). Approving a part also starts the build.
- **Audit logs & recovery:** Each outcome is a line in the `observer` `log_entries` stream (`done`, `failed`, or `skipped`). The loop writes `Home.WriteDecision` (`Kind: "observer-" + kind`, `By: "observer"`, `DecidedForYou: true`) and keeps the item in the `observer-inflight` document while it works. After a crash the next cycle logs it as `failed` and leaves it to a person.
Delivery and operations stay deterministic by default: DevOps, Release, and SRE use scripts for every gate, and even optional Observer automation runs toolless and writes an auditable decision per action.
## Next steps [#next-steps]
# Planning and build roles (/docs/architecture/roles-planning-and-build)
After Context creator confirms an OpenSpec change on `staging`, three roles turn requirements into verified lane commits (`strategist`, `analyzer`, and `engineer`). In the default `team` flow they are the Tech Lead's split, the Tech Lead's plan step and the Developer's build; the `classic` flow names them Strategist, Analyzer and Engineer. Orchestrator schedules lanes across slot pools while deterministic Go checks enforce every boundary.
Split confirmed specs into parallel DAG lanes (the Tech Lead's split in the team flow) and, in `classic` only, route failed steps.
Investigate `staging`, write failing repro tests, and scope files within diff caps. The Tech Lead's plan step in the team flow.
Write tests first and implement fixes inside a persistent offline Docker cage. The Developer in the team flow.
## Strategist (`internal/roles/strategist`) [#strategist-internalrolesstrategist]
[internal/roles/strategist](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/strategist/strategist.go) handles pre-lane DAG planning and post-failure routing, pairing deterministic rule tables with `3m` read-only sessions. Planning (`Route`) runs in both flows, as the Tech Lead's split of the conversation into parts. The routing agent (`Decide`) runs only in the `classic` flow: the team flow routes every failure by `rules.json` alone.
- **Read-only boundary:** `Plan` ([plan.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/strategist/plan.go)) runs `readonlysession.Run` (`NoCommands: true`, `3m`) on a detached `staging` checkout at `/worktrees/@strategist`. `Decide` ([agent.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/strategist/agent.go)) runs a `3m` read-only session in the lane's own cage, in the `classic` flow only.
- **DAG planning (`Route` & `Tasks`):** When `ShouldPlan` sees at least `2` non-quality capabilities or `3` non-quality requirements, `Plan` emits parallel lanes; invalid outputs fall back to deterministic `strategist.Tasks`. The planner is told to size each lane at about half of `budgets.diff_cap_lines`, because estimates run low and a lane that lands over the cap is thrown away after an expensive build. Both assign dependency-ordered `Sprint` waves, and `t12 run --sprint N` runs only tasks up to wave `N`.
- **Static routing & proposals:** Failures match [rules.json](https://github.com/cone-labs/turbo-12f/blob/main/assets/strategist/rules.json) plus `.t12/preferences.json` `strategist.rules` first (`qc`/`qa`/`merge`/`deploy-dry-run` → `engineer` at `0` tokens; `engineer`/`code-review`/`deslop`/`red-team`/`ui-check` → `analyzer` at `1` token; `should-fix` → `chore`; `note` → report only). In the `classic` flow, unmatched or repeat failures call `Decide`, which can write a `proposal` document named `strategist-rule-*.json`; the `team` flow never calls it.
- **`validatePlannedTasks`:** Verifies non-empty `reason`, valid `TaskTypes`, `dag.Order` acyclicity, zero dependencies on `quality`, `1` capability per `bug` lane, an isolated `quality` leaf lane, and an exact 1:1 requirement/scenario partition.
- **Parallel context & splits:** `ParallelContext(all, current)` injects `## Parallel lanes` (`Strategist notes`, `Running in parallel with`, `Waiting on this lane`) into Analyzer and Engineer prompts; `strategist.Split` spawns `-1..N`.
- **Rule proposals:** After `ProposalRepeats` (`2`) fallback decisions within `ProposalWindow` (`30` days) share `(step, route)`, `propose` writes a rule proposal for Operator approval with `t12 rules approve` or `reject`. Proposals are rows in the `documents` table (kind `proposal`), not files under ``.
Both `Tasks` and `Plan` currently log `NotDone`: `"Entry steps for security, devops and incident tasks (D15)"`.
## Analyzer (`internal/roles/analyzer`) [#analyzer-internalrolesanalyzer]
[internal/roles/analyzer](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/analyzer/analyzer.go) is step 1 of every lane in both flows (the Tech Lead's plan step in the team flow). It inspects `staging`, proves bug repros fail on base, and produces the schema-validated plan Engineer executes via `analyzer_plan` or `escalate` `{question}`. An escalated question goes to a person, or the orchestrator answers it itself when the project's autonomy level says so.
Analyzer runs a `15m` (`DefaultSessionTimeout`) caged session of at most `40` turns inside `in.Cage` with `approvals.GuardFor` (`DefaultCommandTimeout = 5m`) using [analyzer-v2.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/analyzer-v2.md). Its policy confines writes strictly to `in.TestGlobs` (`confine: true`, `read_only: in.ProtectedPaths`).
| Plan field / check | Go validation in `plan.go` |
| --- | --- |
| **Root cause & repro** | `evidence`, `root_cause` (required on bugs/send-backs), `repro` `{test, name}` (`reproFailsOnBase`), `cause_class` |
| **Files & criteria** | `approach`, `files` (`add`/`edit`/`delete`), `criteria` mapping IDs to `unit` or `e2e` `.feature` files, `screens` for `"ui"` tags |
| **Source line estimate** | `estimated_lines` counts added production source lines only (excludes tests, E2E, lockfiles, deletions, binaries) |
| **Diff cap & splits** | Enforces `FinalSchema()`, protected paths, and the `EstimatedLines` limit: an estimate above two thirds of `budgets.diff_cap_lines` (`SplitAbove`) requires an acyclic seam `split`, or a `size_waiver` for a single-requirement task that cannot split by criteria. A split part with one requirement may use the whole cap, and cannot split again |
## Engineer (`internal/roles/engineer`) [#engineer-internalrolesengineer]
[internal/roles/engineer](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/engineer/engineer.go) is step 2 of every lane in both flows (the Developer in the team flow). It writes tests first and production code second inside a persistent Docker cage (`sandbox.StartLane`, `DefaultSessionTimeout = 20m`, `DefaultCommandTimeout = 10m`, `DefaultMaxTurns = 60`, `DefaultFixAttempts = 3`). The session's real time limit adds `15m` (`CheckAllowance`) for each of the `FixAttempts + 1` candidates it may hand over, because the session waits while the factory builds and tests what it handed over.
On `merge` send-backs, `orchestrator/sendback.go` runs `gitio.SyncOntoStaging` on the host and `internal/cli/factory.go` refreshes `.feature` files and `e2e/t12/capture.ts`. Engineer never runs `git add` or `git commit`, never edits `e2e/features/*.feature`, and exits via `engineer_done` or `escalate`. Its prompt ends with the worktree's file list (up to `400` paths, then a count per folder), so it opens files by path instead of listing folders.
Both Analyzer and Engineer may `escalate` a question, and the orchestrator records it as a question event. At `autonomy.level` `auto` the factory answers a lane's question itself once (`turbo`: up to `3` times) with the smallest change that satisfies the spec, and records an `answered-for-you` decision. Otherwise the lane waits for a person; in the cloud build the worker opens a GitHub issue labelled `need-decision` with the options and resumes the lane when someone replies. See [Cloud hosting](https://github.com/cone-labs/turbo-12f/blob/main/docs/cloud-hosting.md).
### Checks inside the session (`verify.go`) [#checks-inside-the-session-verifygo]
`engineer_done` does not end the session. The factory commits what the session handed over, runs the seven gates in [verify.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/engineer/verify.go), and, when they pass, runs QC, the screen check and Red team's origin check on that candidate. A refusal comes back as the answer to `engineer_done`, so the same warm session fixes it with everything it has read still in context; a new session starts only when one ends with its candidate still refused, for example out of turns. A check that could not run at all (`Blocked`) is not the Developer's to fix: the candidate goes through and the lane's own step reports it. When every check passes, the lane's `qc` and `ui-check` steps (or the first two parts of `qa`) reuse those results while the worktree still holds that candidate. Checks running at once across lanes are bounded by the run's check slots. Go enforces `CheckTurnCap` (`turn-cap`) when a session ends without finishing.
| Gate | Script check | Failure behavior |
| --- | --- | --- |
| `new-test` | Requires at least one added or updated test file matching `TestGlobs` | Refuses `engineer_done` inside session |
| `fails-on-base` | Runs each added or updated test file (and new `.feature` E2E scenarios) on `Base`; must exit non-zero (skipped for guard-only lanes) | Refuses `engineer_done` (`proves nothing`) |
| `passes-on-candidate` | Runs `UnitFiles` (`ExpandFiles`) on the added or updated test files in a checkout of the candidate | Refuses `engineer_done` |
| `no-comments` | Rejects added comments in JS/TS, Go, Python (`.py`, `.pyi`), Rust (`.rs`), CSS, and SCSS or Less outside allowlisted directives | Refuses `engineer_done` with line numbers |
| `diff-cap` | Sums added source lines (`gitio.Tree.AddedLineCount`) against `budgets.diff_cap_lines` (`800`); every refusal states the lines used and warns at 80% | Refused once so the session can trim; finishing again unchanged sets `res.DiffCap = true` and hands the task to the Analyzer's split. The candidate is kept on `t12//--oversize` first, and each part's Engineer starts from that attempt's version of the files its plan lists |
| `build` | Runs `commands.build` in a checkout of the candidate | Refuses `engineer_done` |
| `protected-path` | Blocks edits to `.github/workflows/**`, `.t12/**`, `.agents/**`, and unsafe symlinks | Refuses `engineer_done` |
Planning and build roles keep every change small and testable: the split partitions work, Analyzer proves failures first, and Engineer cannot commit past seven deterministic gates. Both flows run all three; only `classic` adds the Strategist's failure routing.
## Next steps [#next-steps]
# Quality, hygiene, and review roles (/docs/architecture/roles-quality-and-security)
In the default `team` flow, one `qa` step per lane runs the checks: the `qc` tests, then the `ui-check` screens, then one `code-review` session, stopping at the first that fails. A blocking finding goes straight back to the Developer as a fix attempt (`found_by: qa` → `engineer` at `0` tokens in `rules.json`). The `classic` flow runs steps 3 through 7 of every lane as separate steps (`qc`, `ui-check`, `deslop`, `red-team`, `code-review`). Release-only `explorer` and the release-check runs of `qc`, `ui-check` and `red-team` are the same in both flows. Together they verify candidates through caged execution, visual baselines, stack rules, offline scanners, replay recipes, and spec-vs-standards code review.
Run build, lint, tests, mutation, PNG baselines, and optional UX probes. QC and UI check run inside `qa` in the team flow.
Catch stubs, clones, and narration filler on changed lines only. Runs per lane in `classic` only.
Scan secrets/CVEs, replay live attack recipes, and check rule packs. Red team runs per lane in `classic` only; Code review runs once inside `qa` in the team flow.
## QC (`internal/roles/qc`) [#qc-internalrolesqc]
[internal/roles/qc](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/qc/qc.go) runs deterministic verification inside the container cage with zero LLM calls. It is the first part of `qa` in the team flow and the `qc` step in `classic`; the release checks run it in both. The Developer's session also runs it on every candidate it hands over, and the lane step reuses a passing result while the worktree still holds that candidate. The steps run in this order:
1. **Static (`10m`):** Runs `build`, `typecheck`, and `lint`, checking worktree cleanliness (`qc-tree-clean`).
2. **Hygiene & guards:** Runs `comment-ban` (max `100` lines), `scenario-text`, and `test-guard` via `GuardTests` ([guard.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/qc/guard.go)) blocking `.skip`/`.only`/deletions across JS/TS, Go, Python `.py`, and Rust `.rs`.
3. **Unit (`UnitLimit`):** Runs `commands.unit` bounded by `runner.Limit("unit")` under `runner.DefaultLock()`.
4. **E2E & capture (`15m`):** Runs Playwright specs (`reports/e2e/results.json`) and `ui-capture` (`e2e.SettleSeconds = 5`). Skipped when an earlier step already failed.
5. **Mutation (`20m`):** Runs StrykerJS on `MutateRanges` across changed JS/TS source and modified test files. A changed test file with no killed mutant is `qc-mutation-kill` (`blocking`); a test file that reaches no mutant is `unreached`, and surviving mutants are `survived`, both `should-fix`. Skipped when an earlier step already failed.
`/qc-cache//.json` caches `build`, `typecheck`, `lint`, and `unit` for the same tree and command. The cache is local scratch that the host rebuilds on demand, while `e2e`, `ui-capture`, and `mutation` always run fresh. Reports log `fixedNotDone` notes for whole-unit runs and assertion edits.
Every step records `CheckResult` coverage (`ran`, `skipped`, `noop-true`) on `RoleReport.Checks` so `["true"]` placeholders surface in review briefs and scorecards.
## UI check (`internal/roles/uicheck`) [#ui-check-internalrolesuicheck]
[internal/roles/uicheck](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/uicheck/uicheck.go) compares settled screen PNGs byte-for-byte with zero LLM calls. It is the second part of `qa` in the team flow, the `ui-check` step in `classic`, and part of the release checks in both. When scenarios name screens, it renders the base commit's shots once and reuses `/ui-baselines//shots.jsonl`, a local scratch cache keyed by tree, image, capture script, E2E command, and lockfile. A render waits on the `ui-baseline-` lease and may take `15m`; a failed render blocks the lane (`ui-baseline`).
| Verdict | Severity | Meaning |
| --- | --- | --- |
| `ui-new` | `note` | New screen not yet on `staging` |
| `ui-predicted` | `note` | Screen hash changed and `s.Screen` is in Analyzer's `Predicted` |
| `ui-unpredicted` | `blocking` | Screen hash changed unexpectedly (saves `before-*.png` evidence) |
| `ui-unstyled` | `blocking` or `should-fix` | Missing applied stylesheet (`blocking` on new/changed screens) |
| `ui-overflow` | `should-fix` | Rendered viewport overflows horizontally |
| `ui-axe` | `should-fix` | axe-core found serious or critical accessibility issues on the shot (advisory, never fails the check) |
When a lane finishes, UI check also records sloppiness samples: the pixel difference on screens the plan did not name, axe counts, and one-off styling added to UI source. They are best effort and never block a run; see [Metrics](https://github.com/cone-labs/turbo-12f/blob/main/docs/metrics.md).
Region/pixel diff images (`odiff`, `looks-same`), `ui-mask` regions, and before/after sign-off gallery pairs (`D37`) remain in `NotDone`.
## Explorer (`internal/roles/explorer`) [#explorer-internalrolesexplorer]
[internal/roles/explorer](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/explorer/explorer.go) runs on the `release` lane when `qc.explorer` is `true`, probing `$APP` as a cautious first-time user ([qc-explorer.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/qc-explorer.md)).
- **Session scope:** Runs `readonlysession.Run` (`15m`, `explore_report`) with Playwright Chromium and `curl` against empty/oversized inputs, unicode, double submits, reloads, `375x812` viewports, and post-signout routes.
- **Deterministic replay:** Every finding needs `steps`, a `sh` `recipe` capturing `"$SHOTS/"`, an `expect` string, and `severity`. Go replays each recipe against `served.App`; only reproducible hits stay actionable.
## Deslop (`internal/roles/deslop`) [#deslop-internalrolesdeslop]
[internal/roles/deslop](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/deslop/deslop.go) runs per lane in the `classic` flow only; the team flow does not run it. It inspects added and changed lines only (excluding `deslop.exclude_paths`), runs a deterministic `.md` em-dash fixer, and runs a `5m` read-only audit ([deslop-agent.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/deslop-agent.md)).
- **Scripted rules (`assets/deslop/*/rules.json`):** Checks `typescript` (`11` rules including Effect `DS-A3-swallowed-error`), `go` (`8`), `python` (`8`), `rust` (`8`), and Markdown prose via `deslop.CheckProse` including release PR bodies.
- **Read-only audit (`deslop_review`):** Evaluates `fake-success`, `additive-workaround`, `over-built` (function/inline/delete ladder), and `doc-narration`, plus adjudicating rule hits (`t12 rules judge`). Unrun audits log `NotDone` (`Manifesto #15`).
- **11 rules:** `DS-A1-placeholder`, `DS-A2-fake-success`, `DS-A3-swallowed-error`, `DS-A4-additive-workaround`, `DS-B6-test-literal`, `DS-B9-owned-module-mock`, `DS-D13-new-clone`, `DS-D14-dead-weight`, `DS-D15-type-laundering`, `DS-F19-narration-filler`, `DS-F20-prose-words`.
- **Manifesto tags:** Rules map to offline Manifesto IDs (`#2`, `#5`, `#6`, `#8`, `#15`); guardrail proposals add `#21`.
- **Promotion & proposals:** Per-rule counts live in the `deslop-stats` database document (updated by compare-and-swap, so concurrent requests all count). An advisory rule with at least `20` hits and `80%` kept gets a `promote-blocking` proposal; a blocking rule with over `25%` of at least `10` judged hits dismissed gets `demote-advisory`. Patterns recurring across at least `3` runs (`RecurringRunsMin`) get an `add-guardrail` proposal. Proposals are `proposal` documents named `guardrail-*.json`; an Operator decides them with `t12 rules approve|reject`, and `t12 rules judge --rule ID --verdict confirm|dismiss` feeds the counts.
## Red team (`internal/roles/redteam`) [#red-team-internalrolesredteam]
[internal/roles/redteam](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/redteam/redteam.go) runs per lane in the `classic` flow only; both flows run it in the release checks. It audits commits, dependencies, write routes, and live visitor security without altering worktree code.
| Check | Mechanism and findings |
| --- | --- |
| **`gitleaks` (`v8.30.1`)** | Scans commits via synthetic `.git` with only the factory's own config, so a lane's `.gitleaks.toml` or `.gitleaksignore` cannot hide a secret. The config allowlists test fixtures and lower-case dotted key names such as `app.settings.v1` for `generic-api-key`. `squashLane` retries `Tree.Squash` if intermediate commits leaked secrets. |
| **`osv-scanner` (`v2.7.1`)** | Scans `package-lock.json` offline against `~/t12/cache/osv` (`$T12_OSV_CACHE`), filtering `Base` advisories and reporting new ones as `should-fix`. |
| **`originCheck`** | Needs a `serve` command. Serves the commit fresh in its cage and sends each write route (`.post`/`.put`/`.patch`/`.delete` on Hono or other routers, with mounted base paths, and Effect Platform `HttpApiEndpoint`) one request from another site and one from the site itself. A route that accepts the foreign write, or answers both alike without refusing, is `blocking`; a redirect that may have written is `should-fix`. It also runs on every candidate inside the Developer's session. |
| **Visitor probes (`attack.go`)** | On `auth`/`input`/`data` `RiskTags`, `readonlysession.Run` (`10m`, `security_check`, `$0.25` budget) probes `$APP` via `curl`; `app.Replay` promotes confirmed `recipe` hits to `blocking` and unconfirmed ones to `note`. A session that ends on its cost cap is run once more on twice the budget; the release check starts on twice the budget (`$0.50`). |
`Semgrep CE`, `ZAP passive`, and `nuclei -dast` remain in `NotDone`.
## Code review (`internal/roles/codereview`) [#code-review-internalrolescodereview]
[internal/roles/codereview](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/codereview/codereview.go) is the `code-review` step of each `classic` lane and the last part of `qa` in the team flow, where it runs once after the tests and screens pass. It pairs deterministic diff checks ([checks.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/roles/codereview/checks.go)) with one `10m` `readonlysession.Run` session ([code-review.md](https://github.com/cone-labs/turbo-12f/blob/main/assets/prompts/code-review.md), tool `code_review`).
- **Scripted gate (`unrequested`, `invented-dependency`):** `unrequested` is a `note` for each changed file outside `PlanFiles`, `PlanTests`, `TestGlobs`, `e2e/`, or a lockfile whose manifest the plan names, and the session decides whether it is scope creep (`blocking`) or required wiring. `invented-dependency` is `blocking`: a dependency added to `package.json`, `go.mod`, `Cargo.toml`, or `pyproject.toml` that the matching lockfile (`npm`, `pnpm`, `yarn`, `bun`, Go, Python, or Rust) does not pin or resolve.
- **Stack-filtered packs (`assets/codereview/*.json`):** Filters `lean` (`5`), `security-web` (`8`), `tests` (`4`), and `typescript` (`5`) via `project.StackTagsIn` (`effect`, `cloudflare-workers`, `typescript`, `javascript`, `nodejs`, `go`, `python`, `rust`).
- **5-step review protocol:** Adjudicates `prior_findings`, forms `2`–`4` hypotheses before reading Engineer's summary, checks `spec` and `standards`, and emits four-part findings (`what`, `problem`, `fix`, `skip`) deduplicated across `(rule, path, lines)` ranges.
Every quality and security role pairs a cheap script gate with bounded, replay-verified read-only analysis, so unverified claims never block or pass a lane. The team flow keeps the tests, the screens and one review per part; Deslop and Red team per part are `classic` extras.
## Next steps [#next-steps]
# Agent roles (/docs/architecture/roles)
Every automated step in `turbo-12f` wraps its LLM session inside a Go script shell. Go builds prompts from embedded files, confines workspace permissions, validates structured outputs or test results afterward, and writes a `RoleReport`.
- **Bounded context:** Prompts receive explicit trees, scopes, findings, or diff hunks, and every session that works in a worktree starts with the list of its files, so it opens paths instead of guessing them.
- **Deterministic verdicts:** Exit codes, diff checks, SHA-256 baselines, and replays compute `Pass`/`Fail`/`Blocked`.
- **Least-privilege tools:** Each role gets only the read/write surface its step requires.
- **Bounded reasoning:** Clarifies specs, plans lanes, writes tests/code, or audits diffs.
- **Structured exit:** Finishes via schema-checked tool calls (`analyzer_plan`, `engineer_done`, `code_review`).
- **Never self-certifies:** Agents cannot mark their own work passed or waive gates.
## The team and its packages [#the-team-and-its-packages]
A conversation runs one of two flows (`orchestrator.Flow`, chosen from the project's `flow` preference). The default, `team`, groups the role packages into the members of a small development team; each part costs three agent sessions (plan, build, review), and a failed check is routed by rules alone.
| Team member | Lane steps | Packages it drives | Agent sessions per part |
| --- | --- | --- | --- |
| Product Owner | None: talks with the person before any part exists | `internal/roles/context` | None per part (it runs during the conversation) |
| Tech Lead | Splits the conversation into parts, then `analyze` | `internal/roles/strategist` (`Route`, `Split`), `internal/roles/analyzer` | One plan |
| Developer | `engineer` | `internal/roles/engineer` | One build, plus fix attempts |
| QA | `qa`: tests, then screens, then one review; stops at the first that fails | `internal/roles/qc`, `internal/roles/uicheck`, `internal/roles/codereview` | One review, on three times the budget of a single classic reviewer |
| DevOps | `merge-policy`, `merge`, `deploy-dry-run` | `internal/mergepolicy`, `internal/mergequeue`, `internal/roles/devops` | None (scripts) |
The `classic` flow runs the same packages as eleven separate steps and adds `deslop`, `red-team`, and `sre` to every lane, plus a Strategist session (`strategist.Decide`) for failures no rule routes. Both flows share the release checks (`qc`, `uicheck`, `redteam`, `deploy-dry-run`, optional `qc.explorer`), the record, the cages, the merge queue, and sign-off. See [ADR 0006](https://github.com/cone-labs/turbo-12f/blob/main/docs/adr/0006-a-small-team-flow-next-to-the-classic-one.md) for the measurement that made `team` the default.
## All role packages [#all-role-packages]
While [design.md](https://github.com/All-Chat-Bridge-for-CRM/ConvoRelay/blob/main/docs/factory/design.md) groups the system into 11 logical roles, the codebase splits quality into `qc`, `uicheck`, and `explorer` plus `release`, totaling 13 packages under `internal/roles/` alongside layer-5 `internal/orchestrator`.
### Containment modes across roles [#containment-modes-across-roles]
| Mode | Roles and timeouts | Workspace access |
| --- | --- | --- |
| **No commands** | `context`, `strategist` plan (`3m`), `sre` triage (`10m`), `observer` (`5m`) | `NoCommands: true` denies `bash` for `strategist` plan, `sre` and `observer`. `context` runs in an empty scratch folder with no built-in tools; `observer` reads only the evidence files staged for the item |
| **Read-only (`guardTree`)** | `codereview` (`10m`, also QA's review), `deslop` (`5m`), `redteam` (`10m`), `strategist` route (`3m`), `explorer` (`15m`) | `readonlysession.Run` (`confine: true`, optional `allow_read`) reverts edits on exit |
| **Scoped write cage** | `analyzer` (`15m`), `engineer` (`20m`, plus `15m` for each check of a candidate) | `analyzer` writes `TestGlobs`; `engineer` uses a Docker lane cage |
`devops`, `release`, and `qc` run no LLM session. `devops` bootstrap writes the starter template, `.t12/` config, and the CI workflow into a fresh repository on the host.
### Intake and routing [#intake-and-routing]
| Role | Package | Trigger | Key deterministic guard | Details |
| --- | --- | --- | --- | --- |
| Context creator (Product Owner) | `internal/roles/context` | `t12 ask`, UI | Verbatim quote check, zero open points, 25 lint rules, mock UI contrast check | [Context and specs](/docs/architecture/context-and-specs) |
| Strategist (Tech Lead's split) | `internal/roles/strategist` | `t12 run`, splits; failures only in `classic` | `rules.json` table, DAG partition check, `Tasks` fallback | [Strategist](/docs/architecture/roles-planning-and-build#strategist-internalrolesstrategist) |
### Build and check [#build-and-check]
| Role | Package | Trigger | Key deterministic guard | Details |
| --- | --- | --- | --- | --- |
| Analyzer (Tech Lead) | `internal/roles/analyzer` | Lane step 1 | `FinalSchema()`, `diffCap`, `reproFailsOnBase` | [Analyzer](/docs/architecture/roles-planning-and-build#analyzer-internalrolesanalyzer) |
| Engineer (Developer) | `internal/roles/engineer` | Lane step 2 | Docker lane cage, `turn-cap`, 7 `verify.go` gates, QC, screen and origin checks on each candidate inside the session | [Engineer](/docs/architecture/roles-planning-and-build#engineer-internalrolesengineer) |
| QC (QA) | `internal/roles/qc` | `qa` first check; `classic` step 3; release | Sequential `build`–`mutation` + `ui-capture` (`qc-cache`) | [QC](/docs/architecture/roles-quality-and-security#qc-internalrolesqc) |
| UI check (QA) | `internal/roles/uicheck` | `qa` second check; `classic` step 4; release | Settled PNG SHA-256 baselines, overflow/unstyled rules, advisory axe-core findings | [UI check](/docs/architecture/roles-quality-and-security#ui-check-internalrolesuicheck) |
| Explorer | `internal/roles/explorer` | Release (`qc.explorer`) | Fresh `served.App` replay of Playwright/`curl` recipes | [Explorer](/docs/architecture/roles-quality-and-security#explorer-internalrolesexplorer) |
### Security and review [#security-and-review]
| Role | Package | Trigger | Key deterministic guard | Details |
| --- | --- | --- | --- | --- |
| Deslop | `internal/roles/deslop` | `classic` step 5 | Stack packs (`typescript`, `go`, `python`, `rust`), `.md` fixer, `t12 rules judge` | [Deslop](/docs/architecture/roles-quality-and-security#deslop-internalrolesdeslop) |
| Red team | `internal/roles/redteam` | `classic` step 6; release | `gitleaks`, offline `osv-scanner`, `originCheck` on a freshly served app, replayed probes | [Red team](/docs/architecture/roles-quality-and-security#red-team-internalrolesredteam) |
| Code review (QA) | `internal/roles/codereview` | `qa` last check; `classic` step 7 | `unrequested` / `invented-dependency` gate, stack-filtered packs | [Code review](/docs/architecture/roles-quality-and-security#code-review-internalrolescodereview) |
### Delivery and operations [#delivery-and-operations]
| Role | Package | Trigger | Key deterministic guard | Details |
| --- | --- | --- | --- | --- |
| DevOps | `internal/roles/devops` | `confirm`, `deploy-dry-run`, `merge` | Pure Go: empty-repo bootstrap, `InstallTimeoutRetries`, promotions that stay `DryRunOnly{}` until a hosting account is connected | [DevOps](/docs/architecture/roles-delivery-and-observer#devops-internalrolesdevops) |
| Release | `internal/roles/release` | `release` lane, `gate`, `merge` | Pure Go: tree-pinned ledgers, proof `Bisect`, `--no-ff` merge | [Release and SRE](/docs/architecture/release-and-sre) |
| SRE | `internal/roles/sre` | `classic` `sre` step, `t12 sre watch`, `triage` | `t12-adapter sre probe`, fingerprints, `24h` `RollBack` | [Release and SRE](/docs/architecture/release-and-sre) |
| Observer | `internal/observer` | `t12 ui` loop (`10s`) | `NoCommands: true`, 9-kind priority, acts with the opener's rights | [Observer](/docs/architecture/roles-delivery-and-observer#observer-internalobserver) |
Every role isolates AI judgment inside a Go harness: scripts supply exact context, enforce workspace confinement, and compute the final `RoleReport` verdict. The team flow decides only how many of those harnesses a part passes through.
## Deep-dive guides by stage [#deep-dive-guides-by-stage]
# Sandbox and harnesses (/docs/architecture/sandbox-and-harnesses)
`turbo-12f` runs builds, tests, and model sessions inside stacked OS containment boundaries with secrets stripped from child environments. Durable state lives in Postgres, so a cage keeps no network and reaches the database only through a host-side broker.
- **Network disabled:** Docker uses `--network none`; Landlock filters TCP/Unix sockets.
- **Secrets scrubbed:** `IsForbiddenEnvKey` strips API keys, tokens, and git/linker overrides.
- **Scoped writes:** Read-only roles revert changes; Engineer writes only its lane worktree.
- **Harnesses (`agy`, `omp`):** Run outside cages behind RPC wrappers and guard hooks, on the requesting person's own credentials.
- **Context7 socket (`t12-adapter`):** Proxies docs lookups over a Unix socket with `CONTEXT7_API_KEY`.
- **Per-command gate:** In `review` mode, guard hooks ask through a scratch spool that a host bridge copies to the `approvals` table.
## Linux Landlock and process limits [#linux-landlock-and-process-limits]
[landlock_linux.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/sandbox/landlock_linux.go) enforces filesystem and socket sandboxing on Linux with zero external libraries. Re-executing with `argv[0]` set to `"t12-landlock-exec"` applies the kernel ruleset before launching the child:
| Kernel feature | Enforcement |
| --- | --- |
| **ABI 4 (`netTCP`)** | TCP bind and connect filters on supported kernels |
| **ABI 5 (`MinCageABI`)** | Required by `t12-cage` for directory-scoped containment |
| **ABI 6 & ABI 9** | Abstract Unix socket/signal scoping (`ABI 6`) and `fsResolveUnix` (`ABI 9`) |
| **Process hardening** | Sets `PR_SET_NO_NEW_PRIVS` and caps `RLIMIT_NPROC` at `userTasks() + 8192` |
## Docker verification containers and persistent lane cages [#docker-verification-containers-and-persistent-lane-cages]
On Linux and macOS (`MinMacOSMajor = 26`), [sandbox.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/sandbox/sandbox.go) runs checks inside Docker containers with `--network none`, `--cap-drop ALL`, `--security-opt no-new-privileges`, and `--pids-limit 8192`.
- **User & engine resolution ([docker_host.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/sandbox/docker_host.go)):** `ContainerUser()` passes `uid:gid` on Linux and `0:0` on Darwin (`T12_CONTAINER_USER` overrides). `ResolveDockerHost` and `DockerClientEnv` select Docker or Colima sockets under `T12_CONTAINER_ENGINE` (`auto`, `docker`, `colima`), stripping `DOCKER_CONTEXT`.
- **State-home checkouts & `deps-cache`:** Checkouts mount from `/checkouts/` with a startup mount probe (`24h` sweep); `node_modules` cache under `/deps-cache/` (`8`-entry LRU, `14d` TTL).
- **Persistent lane cages (`sandbox.StartLane`):** Starts one background container per lane (`t12-lane-`, `--label t12.lane=`) with `.git` mounted read-only to avoid per-turn container startup cost.
- **Cloud worker uses Docker cages:** The `t12-worker.yml` job sets `T12_SANDBOX_ADAPTER=docker` for `run`, `confirm`, `release-merge`, and `try-publish`, because Landlock denies every TCP bind and a web project's E2E server (`wrangler dev` on `127.0.0.1:8787`) could not start under it. A `Prepare lane cages` step first pulls (or builds and pushes) the project's cage image, then `scripts/bootstrap-cages.sh` pulls the pinned runtime and scanner images and the red team's offline npm database.
- **Offline after install:** `devops.Install` sets `Network: true` only when `adapter == "docker"` during Project Gate dependency installs; `qc`, `uicheck`, and `redteam` stay offline.
- **Environment scrubbing (`IsForbiddenEnvKey`):** Strips API keys, tokens, `DATABASE_URL`, `PROD`/`PRODUCTION` vars, git overrides, `PYTHONPATH`, `LD_PRELOAD`, `DYLD_INSERT_LIBRARIES`, `AGY_ADC_AUTH`, `GOOGLE_*`, and `DOCKER_HOST`.
## Namespace containment and container self-wrap [#namespace-containment-and-container-self-wrap]
- **`t12-cage` (`internal/cage`):** Creates Linux user and PID namespaces (`CLONE_NEWUSER | CLONE_NEWPID`), binds `Pdeathsig: SIGKILL`, and runs `"t12-cage-init"`. Outside-cage `Commit` opens `.git` with `O_NOFOLLOW` and rejects nested `.git` directories.
- **`t12-container` (`internal/container`):** Wraps `bin/t12` inside a read-only `--network none` container for full CLI containment. Because Postgres is the only store, the host runs a `db.Broker` on a Unix socket in a private folder and mounts it into the container (`T12_DB_BROKER`); the broker adds the connection string and forwards to Neon, so `DATABASE_URL` never enters the container.
The broker does not parse SQL, so the container has the host's database access for the life of the run, while the cage keeps no network, no capabilities, and a read-only root.
## Worker harness matrix and read-only guards [#worker-harness-matrix-and-read-only-guards]
`turbo-12f` drives agent CLIs through RPC wrappers (`internal/agyrpc`, `internal/omprpc`, `internal/ccrpc`). The app offers `agy` and `omp`; `claude` is retired as a connection but still wired in code. For image attachments (`internal/imginput`), `omprpc` and `ccrpc` pass image blocks (checking vision capability), while `agyrpc` fails explicitly rather than silently dropping images.
| Harness | Go RPC driver | Guard hook script | Guard mechanism |
| --- | --- | --- | --- |
| `agy` | `internal/agyrpc` | `adapters/agy/guard-hook.ts` | Sets `toolPermission: "request-review"`; hook rewrites `run_command` via `overwrite` + `BypassSandbox: true`; `CheckWorkspace` refuses `.agents/` |
| `omp` | `internal/omprpc` | `adapters/omp/guard.ts` | Intercepts `tool_call` events inside the extension runtime to reject forbidden writes and commands |
| `claude` (retired in the app) | `internal/ccrpc` | `adapters/claude/guard-hook.ts` | Runs `bun --no-env-file ./guard-hook.ts` and emits JSON `permissionDecision` plus `updatedInput` |
`internal/project` still lists `claude` among `Harnesses`, and `workersession` still dispatches it to `ccrpc` (API-key mode needs `T12_CLAUDE_AUTH=api_key` and `ANTHROPIC_API_KEY`). The app does not offer it: a stored `claude` agent setting is read as `omp` on the same `anthropic/` model, and a run that names `claude` needs the person's omp connection.
- **Model, effort & token caps:** `project.SplitAgyRoleModel` splits legacy slugs, and `agyrpc.Argv` emits `--model` and `--effort`. `agyrpc.RunWorker` records `Session.ToolCalls` from `step_update` and enforces `MaxTokens` and a dollar budget (`StatusCostCap`); the budget is measured in a derived token cap that counts cache reads at a quarter. A session whose shell commands agy refused (`command` or `unsandboxed`) ends as `StatusNoCall` and says how many were refused.
- **Scratch home credentials (`PrepareSession`):** Copies `antigravity-oauth-token`, `credential-user-scope`, and conditional `application_default_credentials.json` (`0600`) from the run's credential home (`T12_CREDENTIALS_HOME`, else the real home) into scratch homes.
- **Conditional keys:** Forwards `GEMINI_API_KEY` and `GOOGLE_GEMINI_BASE_URL` only when `settings.json` sets `"modelProvider": "gemini"`, and forwards `AGY_ADC_AUTH` / `GOOGLE_*` only when `AGY_ADC_AUTH` is `true` or `1`.
### Read-only and scoped role containment [#read-only-and-scoped-role-containment]
- **Read-only sessions (`readonlysession.Run`):** Runs `NoCommands: true` or `guardTree` (`confine: true`), writes numbered transcripts (`transcript-[-N].jsonl`), applies `roles.*` overrides, and reverts edits on exit.
- **Scoped/toolless sessions:** `analyzer` runs a `15m` caged session (`TestGlobs` writable); `context` runs without shell tools (`Settings(nil, nil)`).
## Per-person credentials per run [#per-person-credentials-per-run]
Runs use the credentials of the person who asked for them, held in `internal/connections` and sealed with `T12_PROJECT_ENV_KEY`. Each person connects GitHub (a GitHub App user token), agy (a Gemini key or Google sign-in, optionally with a Google Cloud project and location), and omp (Anthropic or OpenAI keys, or its own sign-in). Two optional hosting connections, Cloudflare (API token and account id) and Vercel (token and optional team), are for a release's production deploy only: the cloud worker redeems them for the `release-merge` action alone, never for an action that starts an agent.
| Where the run starts | How it gets the credentials |
| --- | --- |
| `t12-ui` on a host | Resolves the person's connections from the database and writes sign-in files into a credential home under `/credentials/-` (`0700`), removed after the job |
| `t12-cloud-worker` | Receives only a random per-run reference (`T12_INPUT_CREDENTIALS`), redeems it from the same database, and rewrites its own environment before starting git, `t12`, or a harness |
A run without the needed connection fails before it starts: `agy` needs the agy connection, `omp` and `claude` need the omp connection. Factory-wide credentials stay in the environment only when the Operator sets `T12_SHARED_CREDENTIALS=1`.
## Per-command approvals (`Request Review` mode) [#per-command-approvals-request-review-mode]
When an Operator sets factory mode to `review` (`Request Review`) in `t12 ui`, every agent shell command waits for a decision recorded in the `approvals` table ([approvals.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/approvals/approvals.go), [bridge.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/approvals/bridge.go)). A guard hook runs inside the harness sandbox and cannot reach the database, so it talks to the host through a scratch spool directory:
- **Per-session bridge:** `approvals.GuardFor` starts a bridge goroutine per session and `approvals.EndSession` stops it. The bridge inserts each ask into `approvals`, writes decisions made in the table (UI or Observer) into the spool, and mirrors the `approval-mode` document into `mode.json` there.
- **Fail-closed mode checks:** `guard-hook.ts` (`agy`, `claude`) and `guard.ts` (`omp`) read the spool's `mode.json` before every command; the bridge writes `{"mode":"unreadable"}` when the document cannot be read, so commands block until the mode is chosen again.
- **Write-once decisions:** Asks write `-<6hex>.json` under `/approvals//`; a decision is written once (`UPDATE ... WHERE decided_at IS NULL`), and a decision the hook already wrote, such as its timeout, wins for the hook and is recorded in the table. `Pending` scans `30m`, `Recent` caps at `500`, and asks older than `Retention` (`7d`) are pruned.
- **Guard vs. role timeouts:** `WaitTimeout` (`30m`) sits inside `HookTimeout` (`31m` / `1860s`), while `approvals.EndSession` closes undecided asks (`409` on late UI posts) whenever a shorter role timer finishes first:
| Caller | Session timeout | Caller | Session timeout |
| --- | --- | --- | --- |
| `analyzer`, `explorer` | `15m` | `deslop`, `observer` | `5m` |
| `codereview`, `redteam`, `sre` | `10m` | `strategist` | `3m` |
## Prompt assembly and Context7 socket forwarding [#prompt-assembly-and-context7-socket-forwarding]
- **Embedded prompts & skills (`assets.Files`):** [assets/skills/map.json](https://github.com/cone-labs/turbo-12f/blob/main/assets/skills/map.json) pins each skill to a SHA-256 digest and `SOURCE` line within `budget_words: 9000` (`skillmap.Check()` runs at confirm; [wording_test.go](https://github.com/cone-labs/turbo-12f/blob/main/tests/unit/skillmap/wording_test.go) checks neutral phrasing).
- **Context7 socket proxy (`internal/docs`, `internal/adapters/docs`):** Launches `t12-adapter context7 serve` on `/tmp/t12d-.../c7.sock`. Its `Forwarder` forwards only `POST /mcp` calls for `resolve-library-id` and `query-docs` with `CONTEXT7_API_KEY` injected outside the cage, logging lookups to `RoleReport.Docs`.
Even when AI harnesses execute on the host, every shell command is rewritten through a fail-closed guard hook into an offline, secret-free cage.
## Next steps [#next-steps]
# UI and access (/docs/architecture/ui-and-access)
The web workbench (`cmd/t12-ui`) authenticates sessions against the identity tables in Postgres, checks origin and CSRF tokens on every mutation, delegates git and pipeline writes to child `t12` processes, and reads and writes accounts, teams, approvals, and Observer state through the same database. Nothing about people or access lives in files under ``.
React 19, React Router, and Tailwind v4 bundled via Vite and embedded with zero-inline CSP.
PBKDF2 passwords, GitHub or email sign-up, 15m links, Tailscale Serve auth, and team roles.
Forks sibling `t12`, streams `500ms` SSE graphs, and runs the Observer loop.
## Subprocess delegation and factory-wide controls [#subprocess-delegation-and-factory-wide-controls]
`internal/ui` ([requests.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/requests.go), [control.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/control.go), [mode.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/mode.go), [approvals.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/approvals.go), [observer.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/observer.go)) reads projections through `record.Home` (backed by the database), `internal/rollup`, `internal/roles/context`, and `internal/roles/release`.
| Control surface | Mechanism |
| --- | --- |
| **Sibling `t12` forks** | Mutations spawn `sibling("t12")` (`Setpgid: true`), inject `T12_AUTONOMY` from the stored approval mode, and stream `T12_UI_PROGRESS=1` output to `liveBuffer` (`80` lines) and the `job-log:` log stream. |
| **External lock sync** | `actionSlot` probes `LockContext`/`LockAsk`/`LockConfirm`/`LockRelease` via `Home.RequestLocked`; `buildSlot` probes `LockRun`; `controlOf` clears stale `Paused`/`Stopped` markers when external CLI locks run. |
| **Graceful halt** | Pause, stop, and shutdown terminate process groups (`SIGTERM`, `5s` `haltGrace`, `SIGKILL`); `Server.Close()` closes `s.closed` and `BaseContext` so open SSE streams exit cleanly. |
| **Permission & approvals** | `ModeMenu` inside `PromptBar` sets the host mode (`review`, `default`, `auto`, `turbo`; `POST /api/mode`, Operators only) stored as the `approval-mode` document. In `Request Review`, `CommandApprovals` decides rows of the `approvals` table. |
| **Observer loop** | `` drawer and `/observer` let an Operator write scoped `projects`/`conversations` to the `observer-setting` document. Every `10s`, `SessionDecider` resolves 9 kinds via `Server` handlers and appends to the `observer` log stream. The loop runs only in `t12-ui`, never in the Vercel function. |
| **Setup & docs chat** | `setup.Manager` (`setup.go`) drives sign-in, API-key, and test flows for the GitHub, `agy`, and `omp` connections; `docschat.Wrap` serves `/api/docs-chat` SSE answers on `t12-ui` and `--serve-dir`. |
- **Socket path:** `StartAdmin` opens `/admin.sock` (`0600`) or `$T12_ADMIN_SOCKET`, falling back to `$XDG_RUNTIME_DIR/t12-.sock` (non-symlink `0700` dir) or `/tmp/t12-/.sock` when exceeding the 100-byte socket limit (skipping `chmod` on `EINVAL`/`ENOTSUP` for Colima VirtioFS).
- **Drain lifecycle:** `drainGate` transitions `serving` → `draining` (up to `5m` `maxDrainHold` holding `/active.lock` exclusively) → `closing` → `closed` for `t12-ui --status`, `--drain`, and `--shutdown`.
## Embedded SPA and CSP hardening [#embedded-spa-and-csp-hardening]
[server.go](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/server.go) embeds the built frontend via `//go:embed all:web/dist` and enforces strict browser headers:
```text
Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' blob:; connect-src 'self'; form-action 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'
```
- **Headers & images:** Pairs zero-inline CSP with `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: same-origin`, and `Cache-Control: no-store`. `GET /api/c/{id}/images/{name}` checks conversation access and image MIME types.
- **Origin, CSRF & cookies:** `sameOrigin` matches `Origin` to `Server.BaseURL` or `r.Host`; signed-in `POST`s verify `X-CSRF-Token` with `subtle.ConstantTimeCompare` against `store.SHA256("csrf:" + session)[:32]`. Cookies set `HttpOnly`, `SameSiteLaxMode`, and `Secure` on `https`.
- **Build-time CSP patches:** `cspSafeLibraries` in [vite.config.ts](https://github.com/cone-labs/turbo-12f/blob/main/internal/ui/web/vite.config.ts) rewrites runtime `