# 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/huyhuyhuy8s/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. All six must-haves 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/huyhuyhuy8s/turbo-12f/blob/main/prompts/context-creator-v2.md)). Instead, `gateOf` in [state.go](https://github.com/huyhuyhuy8s/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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/context/answer.go)) verifies every quote appears in human messages (case- and whitespace-normalized). 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/huyhuyhuy8s/turbo-12f/blob/main/internal/spec/lint.go)) checks 25 OpenSpec rules on `*st.Draft`; `spec.LintPlain` checks turn replies and `plain.md`. `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 (`catalogue/.json` default) | | `core_journey` | Main step-by-step user flow in requester's words | Refused | | `look` | Style, hex colors, typography, size, contrast, layout | Allowed (`catalogue/.json` default) | | `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 fills defaults for `pages`, `look`, and open `open_point`s. `conversationActions` exposes `CanDecide` and `HasSuggestions` so the UI swaps **Decide for me** for **Accept suggestions** when only non-delegable suggestions remain. ## 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 `context/state.json`, 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 via `gh`, detects Node.js/Go/Python/Rust, creates `staging` (or `t12-staging`), and registers `/projects.json`. - **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`. ## Standards the Context creator follows [#standards-the-context-creator-follows] Across [context-creator-v2.md](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/prompts/context-creator-v2.md) and [lint.go](https://github.com/huyhuyhuy8s/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. - **Three-round elicitation:** Caps at `8` questions per round (`1`: `goal`/`users`/`pages`; `2`: copy, WCAG `4.5:1`, fonts, `core_journey`; `3`: `out_of_scope` and `open_point`s) and at most `12` requirements per change. - **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/huyhuyhuy8s/turbo-12f/blob/main/internal/spec/files.go) and [views.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/spec/views.go)), committed to `staging` on `t12 confirm`: | 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/huyhuyhuy8s/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` plus `spec.LintPlain`. - **Project gate ([gate.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/devops/gate.go)):** Triggered by `t12 confirm` to verify `.t12/` configs, skill hashes, branches, dependencies, and base checks on `staging`. See [DevOps internals](/docs/architecture/roles-delivery-and-observer#devops-internalrolesdevops). - **Task gate:** [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, deterministic, and isolated from direct HTTP linking. Core and containment binaries (`t12`, `t12-cage`, `t12-container`) link no `net/http` while they verify code and hash-chained evidence, while companion processes and subprocess adapters handle UI HTTP, AI harnesses, Cloudflare, and GitHub. - **Zero Go dependencies:** Builds with the Go standard library only. - **No HTTP code:** `t12`, `t12-cage`, and `t12-container` link zero HTTP clients or servers. - **Deterministic gates:** Scripts verify every test, diff, and hash chain. - **Web workbench (`t12-ui`):** Serves the React app, manages auth/Observer, and shells out to `t12`. - **Subprocess & network adapters:** `t12-adapter` holds HTTP/token integrations (`context7`, SRE probes), while `t12` calls subprocess adapters (`ghcli`, `ghissue`, `ghrepo`, `fbreport`). - **AI harnesses:** `agy`, `omp`, and `claude` run behind RPC wrappers and guard hooks. Read [The factory pipeline](/docs/fundamentals/pipeline) first for a plain-language overview before diving into Go packages. ## 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/store`, `internal/schema`, `internal/gitio`, `internal/dag`, `internal/envfile`, `internal/access`, `internal/project` | Atomic JSON, tool schemas, git helpers, DAG ordering, configs, auth store | | Record & specs | `internal/record`, `internal/spec`, `internal/rollup`, `internal/approvals`, v1 `internal/model` | Hash-chained logs, OpenSpec views, lint rules, rollups, approvals | | Containment | `internal/sandbox`, `internal/cage`, `internal/container`, `internal/readonlysession`, `*rpc`, `internal/docs`, `internal/served`, `internal/skillmap`, `internal/runner`, `internal/eval`, `internal/bencheval` | Landlock/Docker cages, revert guards, harness RPCs, Context7 socket, skill checks, role evals & bench grading | | Roles & merge | `internal/roles/*`, `internal/mergequeue`, `internal/mergepolicy`, `internal/adapters/*` | Thirteen role packages, staging rebase queue, policy rules, external adapters | | Orchestration | `internal/orchestrator`, `internal/observer`, `internal/setup`, `internal/docschat` | Lane DAG scheduling, slot pools, file locks, failure routing, Observer loop, onboarding setup, docs chat | | Entry points | `internal/cli`, `internal/ui`, `cmd/*` | CLI dispatch, embedded React dashboard with SSE, and 12 helper binaries | ## 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`, `*rpc`, `project`, `spec`, `record`, `skillmap`, `gitio`, `store`, `catalogue`, root | Drives conversation turns, readiness checks, and harness runners | | `internal/roles/release` | `orchestrator`, `rollup`, `project`, `record`, `served`, `gitio`, `store` | Coordinates release checks, bisection, and fix-lane additions | | `internal/ui` | `roles/context`, `roles/release`, `omprpc`, `readonlysession`, `observer`, `access`, `approvals`, `record`, `rollup`, `project`, `spec`, `gitio`, `store`, `net/http` | Serves dashboard views, access controls, and embedded Observer controls | | `internal/observer` | `roles/context`, `roles/release`, `schema`, `orchestrator`, `approvals`, `access`, `record`, `rollup`, `readonlysession`, `store`, root | 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` ← `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/huyhuyhuy8s/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. External Node tooling is isolated to `internal/ui/web` (`bun` and `vite-plus` for embedded UI assets) and `docs-site`. Neither directory adds third-party Go modules. ## Core and network boundary [#core-and-network-boundary] `turbo-12f` splits binaries into `no net/http` core/containment programs and HTTP-capable companion or driver programs so containment code cannot accidentally link HTTP clients or server stacks. | Program group | Binaries | Network and model policy | | --- | --- | --- | | Core & cages (no `net/http`) | `cmd/t12`, `cmd/t12-cage`, `cmd/t12-container` | Zero `net/http`; `v2` `t12` invokes local harnesses and subprocess adapters (`ghcli`, `ghissue`, `ghrepo`, `fbreport`) while cages run offline | | Web UI server | `cmd/t12-ui` | Serves SPA, auth, approvals, and Observer; forks sibling `t12` for mutations | | Network adapters | `cmd/t12-adapter`, plus v1 `t12-runner`, `t12-cc`, `t12-job`, `t12-queue` | Links `net/http` directly (`t12-adapter`) or transitively (`internal/adapters/common`, `internal/skills`); handles Context7 Unix-socket proxy, intake, delivery, and SRE HTTP probes | | Helper tools | `cmd/t12-mutate`, `cmd/t12-wizard`, `cmd/t12-bench` | Runs Go mutation testing, host setup, and FactoryBench grading outside cages (zero `net/http`) | When a `no net/http` component 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, or `t12-adapter context7 serve` for caged docs lookups). `TestTheCoreAndTheCageProgramsLinkNoNetworkCode` in [naming_test.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/tests/e2e/system/naming_test.go) checks `t12`, `t12-cage`, and `t12-container` with `go list -buildvcs=false -deps` for `net/http` (`internal/roles/context` uses `internal/schema` rather than `internal/contextcreator` or `internal/drive`). Keeping the Go core stdlib-only and offline lets `turbo-12f` verify every build inside air-gapped cages while confining credentials and network calls to thin sibling adapters. ## Next steps [#next-steps] # Record and evidence (/docs/architecture/record-and-evidence) Every state transition, test verdict, decision, and token count under a request home appends to an immutable trail in `requests//`. Read models in `internal/rollup` fold that log into UI pages and CLI summaries with no separate mutable state files. Canonical JSON entries chained by SHA-256 under exclusive file locks. Sequenced `RoleReport`, `Decision`, and `Session` records verified by digest. Single-pass projections for lane states, flow graphs, quality, and scorecards. ## Hash-chained event logs [#hash-chained-event-logs] `internal/record` ([record.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/record/record.go)) chains events under `requests//events.jsonl` using canonical JSON from `internal/store`: - **Genesis & chaining:** Sequence `0` anchors on `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`. - **Crash-safe appending:** `appendLocked` holds an exclusive `flock` on `events.lock` and truncates any torn trailing line without a newline before writing. - **Sequenced blobs & fast statting:** `freshName` prefixes evidence and reports with a 4-digit sequence (`0001-...`); `EventsStat` checks `(size, modNano)` for SSE ticks; `StatusTracker` reads state in one pass. - **Full verification (`Home.Verify`):** Replays `Seq`, `Request`, `Prev`, and `Hash`, verifies every blob digest via `VerifyRef`, and rejects symlinks or path traversal. | Lock / file | Scope and ordering | | --- | --- | | `/active.lock` (`Home.WithActivity`) | Shared `flock` held by mutating CLI verbs so `t12-ui --drain` waits for idle | | Per-request `flock` files | Typed locks (`LockContext`, `LockAsk`, `LockConfirm`, `LockRun`, `LockRunMerge`, `LockRelease`), nested `LockConfirm -> LockContext -> LockAsk` and `LockRelease -> LockRunMerge -> LockRun` | | `IsLocked` / `RequestLocked` | Exposes active external CLI work to `t12-ui` and Observer | | `/projects.json` (`projects.lock`) | Connected GitHub repository registry managed via `Home.ConnectedProjects` ([projects.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/record/projects.go)) | [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, `approve`, `bugbash`, `confirm`, `release`, and `internal/roles/context` 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` | | **`Decision`** | Strategist rules, `"answered-for-you"`, Observer actions (`observer-`, `By: "observer"`), and rule proposals (plus `observer/log.jsonl` & `inflight.json`) | | **`Session` (`EvSession`)** | Harness runs, `SessionTool` calls, `SessionUsage` tokens, numbered `TranscriptRef` links (`transcript-[-N].jsonl`), plus `approval-asked` / `approval-decided` outcomes from `approvals.EndSession` | | **FactoryBench (`internal/benchreport`)** | Maps `events.jsonl` to `attempt.started` (`+autonomy:`), `usage`, `activity`, `gate`, `send_back`, `check_coverage`, `noop_checks`, and `human.waiting`/`resumed` | ## 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`). - **Flow graph (`GraphOf` & `ApplyLiveJob` in [graph.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/rollup/graph.go)):** Folds events into `FlowGraph`; 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`/`Outcomes` run `RecordOutcomesFor` on `t12 run` and `t12 release merge`, aggregate `CheckCoverage`, and propose `guardrail-*.json` after `EscapedGuardrailMin = 2` escaped bugs. ## 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`). | Aspect | v2 (`internal/record` and `internal/rollup`) | Legacy v1 (`internal/model`) | | --- | --- | --- | | Primary log layout | `requests//events.jsonl` + immutable blobs | `runs/.json` + `runs/.events.jsonl` | | Integrity hash | `prev` and `hash` chain over `store.Canonical` JSON | `state_sha` chained across snapshots and event rows | | Concurrency safety | Exclusive `events.lock` and request worktrees | Fixed lock order `lane -> integration -> run` | | State updates | Append events and fold projections in `rollup` | Three-way JSON merge (`ApplyChanges`) with `runMoved` guards | | Crash recovery | Automatic torn-tail truncation in `appendLocked` | Explicit `t12 repair` CLI pass | Because every view in `t12` and `t12 ui` is folded from one hash-chained log, there is no split-brain status database 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 locks, patch-bound approvals, and bounded triage loops. Flag `data-loss`, `auth`, `licence`, `delivery`, or `review` diffs before merge. Acquire queue lock, 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/huyhuyhuy8s/turbo-12f/blob/main/internal/mergequeue/mergequeue.go) guarantees that lanes update `staging` strictly one at a time without overwriting concurrent work: 1. **Acquire lock:** Takes an exclusive `flock` on `merge-queue.lock` (`LockWait`). 2. **Rebase in scratch worktree:** Checks out the lane commit inside `merge-scratch/` 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/huyhuyhuy8s/turbo-12f/blob/main/internal/mergepolicy/mergepolicy.go)) 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 approval required, 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 in [factory.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/cli/factory.go) and [gatefor.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/release/gatefor.go): | Stage | Functions | Behavior | | --- | --- | --- | | **Staging checks** | `releaseChecks` | Runs `qc`, `uicheck`, `redteam`, `deploy-dry-run`, and optional `qc.explorer` against `staging^{tree}`, writing `release//checks/.json`. | | **Bisect & fix** | `Bisect`, `fixRelease` | Locates the culprit merge between `main` and `staging` on failure, adds `-rf` via `release.AddFixLane`, and retries `pass < 3`. | | **Four-part gate** | `release.Gate`, `GateFor` | Requires passing `staging^{tree}` checks, surfacing `CheckCoverage` `noop-true`/`skipped` warnings, carried `signoffs.jsonl`, no `holds.jsonl`, zero lapsed sign-offs, and zero `Sev-1`/`Sev-2` bugs. | | **Main promotion** | `t12 release merge` | Checks `staging^{tree}` stability, merges `--no-ff` to `main`, runs `RecordOutcomesFor` and `devops.Promote` (`DryRunOnly{}`, `H10`), and appends `EvDelivered`. | ## SRE watch, triage, and rollback [#sre-watch-triage-and-rollback] Post-release checks run through `sre` ([sre.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/sre/sre.go), [triage.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/sre/triage.go), [cli/sre.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/cli/sre.go)) via `t12-adapter sre probe --url`: - **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`):** Classifies failing windows into `ProjectDefect` (files `"Incident found by SRE: ..."` via `cmdAsk`), `PlatformOutage` (alerts Operators at zero retry tokens), or `noise`. `--rollback` calls `devops.RollBack` inside the `24h` `RollBackWindow`. No change reaches `main` unverified: every lane rebases through a single merge lock, 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 under `requests//`. 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. Plan dependency-ordered worktrees and run each lane through 11 steps. 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.Gate` to verify clean branches, pinned skills, dependencies, and base checks on `branches.staging`. 3. **Lane execution (`t12 run`):** Calls `orchestrator.Run` ([orchestrator.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/orchestrator/orchestrator.go)). Strategist splits 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:** [factory.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/cli/factory.go) runs `qc`, `uicheck`, `redteam`, and `deploy-dry-run` (plus optional `qc.explorer`) on `staging`. Failures trigger `fixRelease` bisection and `-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` (`main`, `master`, or `staging`). ## Lane plan and sequential vs target execution [#lane-plan-and-sequential-vs-target-execution] Each worktree lane runs an 11-step sequence defined by `orchestrator.LanePlan`: | 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 | | 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`) | Evaluates `data-loss`, `auth`, `licence`, `delivery`, and `review` bound to `git patch-id --stable` | | 9 | `merge` (`internal/mergequeue`) | Takes `merge-queue.lock`, rebases onto `staging`, rechecks if tree changed, and fast-forwards | | 10 | `deploy-dry-run` (`internal/roles/devops`) | Validates staging deploy artifact once the quiet window clears | | 11 | `sre` (`internal/roles/sre`) | Watches staging health probes over a short observation window | [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 file locks [#concurrency-priority-and-file-locks] [slots.go](https://github.com/huyhuyhuy8s/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`, `code-review` | `4` (`project.DefaultAgentSlots`) | Resumed fixes first, longest `chain`, then FIFO | | `checkSlot` | `qc`, `ui-check`, `deslop`, `red-team`, `merge`, `deploy-dry-run`, `sre` | `max(1, NumCPU / 2)` (`DockerCPUs / 2` in Docker) | Same `priority{fix, chain, seq}` comparator | | Unslotted | `merge-policy` | Unbounded | Runs immediately inside `runLane` | Three coordination rules in [queue.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/orchestrator/queue.go) and [slots.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/orchestrator/slots.go) prevent lane collisions: - **File locks (`fileLocks`):** 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 `code-review` and `merge`) and `120s` (`DefaultQuietWindowS`) pass without queue changes. - **Live capacity resizing:** Every `15s` (`LiveCapacityEvery`), reads `.t12/config.json` and `.t12/preferences.json` from `refs/heads/` and updates pool limits live. ## Strategist task planning and parallel lanes [#strategist-task-planning-and-parallel-lanes] Before launching lanes, Orchestrator calls `strategist.Route` ([plan.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/strategist/plan.go), [dag.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/dag/dag.go)) to build a task DAG, falling back to `strategist.Tasks` when planning is skipped or invalid. | 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 `checkSplit` and `strategist.Split`. Split children require `size_waiver` (parking 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. ## Strategist rules, send-back sync, and fallback decisions [#strategist-rules-send-back-sync-and-fallback-decisions] When a step fails or reports blocking findings, `orchestrator.route` checks deterministic rules (`rules.Match`) before calling `strategist.Decide`: - **`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. - **Fallback & rule proposals:** Unmatched steps (`analyze`) or repeat `rootHash` hits (`state.hashes[hash] == 1`) invoke `strategist.Decide` and feed `proposals/strategist-rule-*.json`. ## 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 `engineer`-routed failures at zero request tokens (`diff-cap` checks `gitio.Tree.AddedLineCount`). 4. **Analyze retry tokens (`tokenPool`, default `2`):** Restarts from `analyze` (`ctx.Resume = "analyze"`). `diff-cap` send-backs 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. [autonomy.go](https://github.com/huyhuyhuy8s/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 `/access/mode.json` 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 `requests//events.jsonl`. ## 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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/devops/gate.go) runs pure Go automation (zero LLM calls) with `defaultCommandTimeout = 10m`. Standalone `Install` ([deploy.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/devops/deploy.go)) retries timed-out installs up to `InstallTimeoutRetries` (`2`), while `Gate` and `DeployDryRun` run `install` once. | Capability | Files | What Go does | | --- | --- | --- | | **Bootstrap, Init & Adopt** | `bootstrap.go`, `adopt.go` | Scaffolds templates (`InitLocalProject`) or adopts repos via `project.Detect` (Node.js, Go, Python, Rust, Effect-TS) onto `staging` or `t12-staging`. | | **Project Gate** | `gate.go`, `depscache.go` | Verifies `.t12/`, `skillmap.Check()`, branches, toolchain, `deps-cache` (propagating cleanup warnings in `NotDone`), and `CheckCoverage`. | | **Dry-run & Promote** | `deploy.go`, `promote.go` | Builds staging in cage, saves `/artifacts///dist`, runs `DryRunOnly{}` (`H10`), and supports `24h` `RollBack` | ## Release (`internal/roles/release`) [#release-internalrolesrelease] [internal/roles/release](https://github.com/huyhuyhuy8s/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 `/release//` ledgers (`checks`, `signoffs.jsonl`, `holds.jsonl`) plus `staging` history, bisects failing trees (`Bisect` / `AddFixLane`), and promotes clean trees to `main`. 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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/release/summary.go)) formats PRs outcome-first with `deslop.CheckProse` warnings. 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/huyhuyhuy8s/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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/sre/triage.go)). It writes normalized fingerprints under `/sre//fingerprints.json`, 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/huyhuyhuy8s/turbo-12f/blob/main/internal/observer/observer.go) runs inside `t12-ui` every `10s` when enabled with scoped `projects` or `conversations` in `/access/observer.json`. Each cycle picks the top waiting item in scope, injects `UserProfile` and any `roles.observer` override, and runs a `5m` toolless [observer.md](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/prompts/observer.md) session. ### 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` | - **Deduplication & lock checks:** `signoff` requires `checks.Pass()` and never overrides `"held back"`. `detectBuild` scans `runEvents` strictly after `confirmed.Seq`, and `observerHands.Busy` checks both UI jobs and external CLI request `flock` files (`actionBusy`, `buildBusy`). - **Handler execution & flags:** `observerHands` calls `ui.Server` handlers and passes `--by observer` (`ask`, `run --answer`), `--observer` (`approve --send-back`), and `Observer: true` (`Command` approvals). - **Audit logs & recovery:** Appends to `/observer/log.jsonl` (`0644`), writes `Home.WriteDecision` (`Kind: "observer-" + kind`, `By: "observer"`, `DecidedForYou: true`), records `"failed"` in `/observer/inflight.json` (`0600`) on crash restart, and maps `human.resumed` in `benchreport.Map`. 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`). Orchestrator schedules lanes across slot pools while deterministic Go checks enforce every boundary. Split confirmed specs into parallel DAG lanes and route failed steps. Investigate `staging`, write failing repro tests, and scope files within diff caps. Write tests first and implement fixes inside a persistent offline Docker cage. ## Strategist (`internal/roles/strategist`) [#strategist-internalrolesstrategist] [internal/roles/strategist](https://github.com/huyhuyhuy8s/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. - **Read-only boundary:** `Plan` ([plan.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/strategist/plan.go)) and `Decide` ([agent.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/strategist/agent.go)) run `readonlysession.Run` (`NoCommands: true`, `3m`) on `/worktrees/@strategist`. - **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`. - **Static routing & proposals:** Failures match [rules.json](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/strategist/rules.json) plus `.t12/preferences.json` `strategist.rules` first (`qc`/`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). Unmatched or repeat failures call `Decide` and emit `proposals/strategist-rule-*.json`. - **`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. 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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/analyzer/analyzer.go) is step 1 of every lane. It inspects `staging`, proves bug repros fail on base, and produces the schema-validated plan Engineer executes via `analyzer_plan` or `escalate` `{question}`. Analyzer runs a `15m` (`DefaultSessionTimeout`) caged session inside `in.Cage` with `approvals.GuardFor` (`DefaultCommandTimeout = 5m`) using [analyzer-v2.md](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/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 `EstimatedLines` cap; oversized tasks require acyclic seam `split` or child `size_waiver` | ## Engineer (`internal/roles/engineer`) [#engineer-internalrolesengineer] [internal/roles/engineer](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/engineer/engineer.go) is step 2 of every lane. It writes tests first and production code second inside a persistent Docker cage (`sandbox.StartLane`, `DefaultSessionTimeout = 20m`, `DefaultCommandTimeout = 10m`, `DefaultMaxTurns = 60`, `DefaultFixAttempts = 3`). 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`. ### Deterministic verification gates (`verify.go`) [#deterministic-verification-gates-verifygo] Go enforces `CheckTurnCap` (`turn-cap`) inside `loop()`, then commits and runs seven gates in [verify.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/engineer/verify.go): | Gate | Script check | Failure behavior | | --- | --- | --- | | `new-test` | Requires at least one newly added test file matching `TestGlobs` | Refuses `engineer_done` inside session | | `fails-on-base` | Runs new test files (and new `.feature` E2E scenarios) on `Base`; must exit non-zero | Refuses `engineer_done` (`proves nothing`) | | `passes-on-candidate` | Runs `UnitFiles` (`ExpandFiles`) on the candidate worktree | Refuses `engineer_done` | | `no-comments` | Rejects added comments in JS/TS, Go, Python (`.py`, `.pyi`), Rust (`.rs`), CSS, and SCSS outside allowlisted directives | Refuses `engineer_done` with line numbers | | `diff-cap` | Sums added source lines (`gitio.Tree.AddedLineCount`) against `budgets.diff_cap_lines` (`800`) | Sets `res.DiffCap = true`, resets to `base`, splits at Analyzer | | `build` | Runs `commands.build` inside verification cage | Refuses or consumes fix attempt | | `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: Strategist partitions work, Analyzer proves failures first, and Engineer cannot commit past seven deterministic gates. ## Next steps [#next-steps] # Quality, hygiene, and review roles (/docs/architecture/roles-quality-and-security) Steps 3 through 7 of every lane (`qc`, `ui-check`, `deslop`, `red-team`, `code-review`) plus release-only `explorer` 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. Catch stubs, clones, and narration filler on changed lines only. Scan secrets/CVEs, replay live attack recipes, and check rule packs. ## QC (`internal/roles/qc`) [#qc-internalrolesqc] [internal/roles/qc](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/qc/qc.go) runs deterministic verification inside the container cage with zero LLM calls: 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/huyhuyhuy8s/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`). 5. **Mutation (`20m`):** Runs StrykerJS on `MutateRanges` across changed JS/TS source and modified test files (`qc-mutation-kill`/`survived` block; `unreached` is `should-fix`). `/qc-cache//.json` caches `build`, `typecheck`, `lint`, and `unit`, 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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/uicheck/uicheck.go) compares settled screen PNGs byte-for-byte with zero LLM calls. When scenarios name screens, it renders or reuses `/ui-baselines//shots.jsonl` under a `15m` lock (`ui-baseline` blocks on failure). | 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 | 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/huyhuyhuy8s/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/huyhuyhuy8s/turbo-12f/blob/main/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/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/deslop/deslop.go) 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/huyhuyhuy8s/turbo-12f/blob/main/prompts/deslop-agent.md)). - **Scripted rules (`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`, `#14`, `#15`, `#17`, `#18`, `#19`, `#21`). - **Promotion & proposals:** Advisory rules emit `should-fix` until `/deslop/stats.json` records at least `20` hits with `80%` kept (or demotes `blocking` rules when over `25%` of at least `10` hits are dismissed). Patterns recurring across at least `3` runs (`RecurringRunsMin`) write `/proposals/guardrail-*.json` for `t12 rules approve|reject`. ## Red team (`internal/roles/redteam`) [#red-team-internalrolesredteam] [internal/roles/redteam](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/redteam/redteam.go) 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` (allowlists test fixtures for `generic-api-key`). `squashLane` retries `Tree.Squash` if intermediate commits leaked secrets. | | **`osv-scanner` (`v2.7.1`)** | Scans lockfiles against `~/t12/cache/osv` (`$T12_OSV_CACHE`), filtering `Base` advisories and reporting new ones as `should-fix`. | | **`originCheck`** | Flags `.post`/`.put`/`.patch`/`.delete` Hono routes and Effect Platform `HttpApiEndpoint` / router routes missing cross-origin enforcement (`should-fix`). | | **Visitor probes (`attack.go`)** | On `auth`/`input`/`data` `RiskTags`, `readonlysession.Run` (`10m`, `security_check`) probes `$APP` via `curl`; `app.Replay` promotes confirmed `recipe` hits to `blocking` and unconfirmed ones to `note`. | `Semgrep CE`, `ZAP passive`, and `nuclei -dast` remain in `NotDone`. ## Code review (`internal/roles/codereview`) [#code-review-internalrolescodereview] [internal/roles/codereview](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/codereview/codereview.go) pairs deterministic diff checks ([checks.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/roles/codereview/checks.go)) with one `10m` `readonlysession.Run` session ([code-review.md](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/prompts/code-review.md), tool `code_review`). - **Scripted gate (`unrequested`, `invented-dependency`):** Blocks edits outside `PlanFiles`, `PlanTests`, `TestGlobs`, `e2e/`, or lockfiles, and checks manifests against `npm`, `pnpm`, `yarn`, `bun`, Python, and Rust lockfiles. - **Stack-filtered packs (`codereview/packs/*.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. ## 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. - **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. 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 workspace tools** | `context`, `strategist` plan (`3m`), `sre` triage (`10m`), `observer` (`5m`) | `NoCommands: true` (JSON tool output only; `context` uses `Settings(nil, nil)`) | | **Read-only (`guardTree`)** | `deslop` (`5m`), `redteam` (`10m`), `codereview` (`10m`), `strategist` route (`3m`), `explorer` (`15m`) | `readonlysession.Run` (`confine: true`, optional `allow_read`) reverts edits on exit | | **Scoped write cage** | `analyzer` (`15m`), `engineer` (`20m`), `devops` (bootstrap only) | `analyzer` writes `TestGlobs`; `engineer` uses a Docker lane cage; `devops` writes CI YAML | ## Intake and routing [#intake-and-routing] | Role | Package | Trigger | Key deterministic guard | Details | | --- | --- | --- | --- | --- | | Context creator | `internal/roles/context` | `t12 ask`, UI | Verbatim quote check, zero open points, 25 lint rules | [Context and specs](/docs/architecture/context-and-specs) | | Strategist | `internal/roles/strategist` | `t12 run`, splits, errors | `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 | `internal/roles/analyzer` | Lane step 1 | `FinalSchema()`, `diffCap`, `reproFailsOnBase` | [Analyzer](/docs/architecture/roles-planning-and-build#analyzer-internalrolesanalyzer) | | Engineer | `internal/roles/engineer` | Lane step 2 | Docker lane cage, `turn-cap`, 7 `verify.go` gates | [Engineer](/docs/architecture/roles-planning-and-build#engineer-internalrolesengineer) | | QC | `internal/roles/qc` | Lane step 3, release | Sequential `build`–`mutation` + `ui-capture` (`qc-cache`) | [QC](/docs/architecture/roles-quality-and-security#qc-internalrolesqc) | | UI check | `internal/roles/uicheck` | Lane step 4, release | Settled PNG SHA-256 baselines, overflow/unstyled rules | [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` | Lane step 5 | Stack packs (`ts`, `go`, `python`, `rust`), `.md` fixer, `t12 rules judge` | [Deslop](/docs/architecture/roles-quality-and-security#deslop-internalrolesdeslop) | | Red team | `internal/roles/redteam` | Lane step 6, release | `gitleaks`, offline `osv-scanner`, `originCheck` (Hono/Effect), replayed probes | [Red team](/docs/architecture/roles-quality-and-security#red-team-internalrolesredteam) | | Code review | `internal/roles/codereview` | Lane 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`, dry-run, `merge` | Pure Go: `InstallTimeoutRetries`, `DryRunOnly{}` promotions | [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` | `sre` step, `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 via UI handlers | [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. ## 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. - **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`, `claude`):** Run outside cages behind RPC wrappers and guard hooks. - **Context7 socket (`t12-adapter`):** Proxies docs lookups over a Unix socket with `CONTEXT7_API_KEY`. - **Per-command gate:** In `review` mode, guard hooks pause commands on `/approvals/`. ## Linux Landlock and process limits [#linux-landlock-and-process-limits] [landlock_linux.go](https://github.com/huyhuyhuy8s/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/huyhuyhuy8s/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/huyhuyhuy8s/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. - **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, `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. ## Worker harness matrix and read-only guards [#worker-harness-matrix-and-read-only-guards] `turbo-12f` drives three agent CLIs (`agy`, `omp`, `claude`) through RPC wrappers (`internal/agyrpc`, `internal/omprpc`, `internal/ccrpc`). 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` | `internal/ccrpc` | `adapters/claude/guard-hook.ts` | Runs `bun --no-env-file ./guard-hook.ts` and emits JSON `permissionDecision` plus `updatedInput` | - **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` (`StatusCostCap`). - **Scratch home credentials (`PrepareSession`):** Copies `antigravity-oauth-token`, `credential-user-scope`, and conditional `application_default_credentials.json` (`0600`) 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-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 on a live file gate in `internal/approvals` ([approvals.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/approvals/approvals.go)): - **Fail-closed mode checks:** `guard-hook.ts` (`agy`, `claude`) and `guard.ts` (`omp`) read `/access/mode.json` before every command, blocking commands if unreadable or corrupt. - **Write-once decisions:** Asks write `-<6hex>.json` (`0600`) under `/approvals//`; approvals write `.decision.json` via hard link (`EEXIST` safe). `Pending` scans `30m`, `Recent` caps at `500`, and `Retention` prunes after `7d`. - **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 (`factory.Files`):** [skills/map.json](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/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/huyhuyhuy8s/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 from private JSON state, checks origin and CSRF tokens on every mutation, delegates git and pipeline writes to child `t12` processes, and manages host control files (`access/`, `approvals/`, `observer/`) plus read-only Observer sessions directly. React 19 + Optics UI bundled via Vite and embedded with zero-inline CSP. PBKDF2 passwords, 15m tokens, Tailscale Serve auth, and two-operator safety checks. Forks sibling `t12` under lock sync, streams `500ms` SSE graphs, and runs Observer. ## Subprocess delegation and factory-wide controls [#subprocess-delegation-and-factory-wide-controls] `internal/ui` ([requests.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/ui/requests.go), [control.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/ui/control.go), [mode.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/ui/mode.go), [approvals.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/ui/approvals.go), [observer.go](https://github.com/huyhuyhuy8s/turbo-12f/blob/main/internal/ui/observer.go)) reads projections directly from `record.Home`, `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 `mode.json`, and stream `T12_UI_PROGRESS=1` output to `liveBuffer` (`80` lines) and `commands/.log` (`0600`). | | **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` writes `/access/mode.json` (`review`, `default`, `auto`, `turbo`). In `Request Review`, `CommandApprovals` posts decisions to `/approvals//.decision.json`. | | **Observer loop** | `` drawer and `/observer` write scoped `projects`/`conversations` to `/access/observer.json`. Every `10s`, `SessionDecider` resolves 9 kinds via `Server` handlers and logs to `observer/log.jsonl`. | | **Setup & docs chat** | `setup.Manager` (`setup.go`) drives OAuth, API key, and test flows for GitHub, `agy`, `omp`, and `claude`; `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/huyhuyhuy8s/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-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/huyhuyhuy8s/turbo-12f/blob/main/internal/ui/web/vite.config.ts) rewrites runtime `