Extend the factory
Step-by-step recipes to add CLI verbs, UI actions, database stores, project settings, flow steps, prompts, role skills, review rules, catalogues, and diagrams.
Follow these code-anchored recipes to add commands, stores, settings, prompts, rule packs, catalogues, and diagrams to the factory. Paths are relative to the repository root. Run the matching test package after each change.
Pick your recipe
| What you want to add | Primary files touched | Verification test |
|---|---|---|
| CLI verb & UI action | internal/cli/, internal/ui/, internal/ui/web/ | go test -short ./tests/unit/cli/... ./tests/unit/ui/... |
| Database store | internal/db/schema/migrations/, your package, an internal/db/importer hook | go test ./internal/<pkg>/... with T12_TEST_DATABASE_URL set |
| Project preference | internal/project/{project,schema}.go, internal/ui/prefs.go | go test ./tests/unit/project/... |
| Flow step | internal/orchestrator/, internal/cli/run_steps.go, assets/strategist/rules.json, internal/ui/web/src/lib/steps.ts | go test ./internal/cli/ -run TestEveryFlowStepIsWiredAndOwned |
| Prompt or role skill | assets/prompts/*.md, assets/skills/*/SKILL.md, assets/skills/map.json | go test ./tests/unit/skillmap/... |
| Deslop or Code review rule | assets/deslop/*/rules.json, assets/codereview/packs/*.json | go test ./tests/unit/{deslop,codereview}/... |
| Project catalogue | catalogue/<type>.json, catalogue/templates/, internal/project/project.go | go test ./tests/unit/project/... |
| Architecture diagram | docs-site/components/mdx/diagrams/specs/ | bun run verify:diagrams && bun run check:llms |
Add a CLI verb and UI action
State lives in Postgres, so a UI action never writes files. It either shells out to t12 with --by <email> or, in cloud mode (s.Cloud != nil), dispatches the same verb to the GitHub Actions worker. Implement and test the CLI verb first.
Implement and register the CLI verb
- Add the verb under
internal/cli/usingflag.FlagSetandparse(set, args, ...)(cli.go), accepting--homeand, where the action is attributed to a person,--by. - Open the home with
e.openHome(*home).Mainalready opened the database for every verb not listed innoDatabase, so the verb gets it throughe.DB. - Keep
net/httpout ofinternal/cli/soTestTheCoreAndTheCageProgramsLinkNoNetworkCodeButTheDatabaseClientkeeps passing; place direct HTTP calls undercmd/t12-adapter/orcmd/t12-<name>/. - Register the verb with
commands["<verb>"] = command{usage, run}in aninit(), matchingask.go,confirm.goandruninfactory.go,requests.go(conversation,request) anddb.go(db).
Add the UI route and guards
- Add the route to
Server.Handler()ininternal/ui/server.go. Conversation routes go inregisterConversationRoutes, which serves both/api/c/{id}and/api/r/{id}. - Wrap the handler in
s.signedIn(...), which answers401without a session and403for aPOSTwithout the matchingX-CSRF-Token. Adds.operator(...)for Operator-only routes, ors.teamOnly(...)for project pages aclientmust not see. - Resolve access in the handler:
s.requestOfreturns areqAccesswithEditor,AcceptorandRun;s.projectOfreturns the project name and repository and answers404unless the person has access. - Refuse with
forbid(...)and return errors throughs.writeActionResult. Calls.requireAI(email)ors.requireGitHub(email)first when the action starts a conversation or project: they answer409when the person has no connected AI or GitHub. - Start the work with
s.command(v.User.Email, a.ID, "<verb>", "--home", s.Home.Dir, ..., "--by", v.User.Email)ors.start(...). Branch ons.Cloud != niland calls.Cloud.Dispatch(...)the waystartBuildinbuild.godoes.
Add the web control
Update types in internal/ui/web/src/api/types.ts and add a button or <Confirm> in src/pages/ or src/components/ that calls run(path, form, success) from useActions (src/lib/use-actions.ts). run shows the server's error text, and a 409 refetches the page.
Rebuild and test
scripts/build-ui.sh
go build -o bin/ ./cmd/...
go test -short ./tests/unit/cli/... ./tests/unit/ui/...Where each guard lives
signedIn, operator and Handler() are in internal/ui/server.go; teamOnly is in internal/ui/team_only.go; reqAccess, requestOf and accessTo are in internal/ui/requests.go; requireAI and requireGitHub are in internal/ui/capabilities.go.
Add a store
Every durable record lives in Neon Postgres (ADR 0005); the state home holds scratch only. A new store follows the ADR's store contract.
Take a client and add a migration
- Accept a
*db.Clientin the constructor, never a path.schema.Open(ctx)runs once inmain, readsDATABASE_URL, migrates, and returnsdb.ErrNoDatabaseURLwhen it is unset; pass the client down. - Add a new file
internal/db/schema/migrations/NNNN_name.sqlnumbered after the last one (names match^\d{4}_[a-z0-9_]+\.sql$, without gaps). A merged migration is never edited: its checksum is recorded and an edited file is refused. - Pick the right shape: a few KB of mutable JSON is a
documentsrow, an unbounded list is a table orlog_entriesstream, and anything hashed or binary is a blob.
Replace locks with database primitives
| Need | Use |
|---|---|
| Read-modify-write one small record | UpdateDoc, or an UPDATE ... WHERE rev = $n compare-and-swap |
| Append to a hash chain | AppendChained(ctx, stream, genesis, build) with a pure build(seq, prev) |
| Several rows that change together | Batch, one transaction; put guards in SQL |
| Exclusion over long work | WithLease(ctx, name, ttl, wait, fn) |
Mark a write Idem only if repeating it leaves the same state; Exec is never retried. Map errors.Is(err, db.ErrUnique | ErrNotFound | ErrLeaseHeld ...) to your package's errors at the boundary.
Import old files and test
- If the store replaces files in an old home, register an import step in
init()withimporter.Register("<name>", importer.Order<Band>, hook)and write only throughe.Execwithdb.Idemstatements, sot12 db import --home DIR --dry-runstays side-effect free. - Delete the file store in the same change: no dual write and no
if file exists. - Test with
dbtest.New(t)orrecordtest.New(t), which skip whenT12_TEST_DATABASE_URLis unset:
scripts/test-db.sh start
eval "$(scripts/test-db.sh env)"
go test ./internal/<pkg>/...Add a project preference
- Add struct field: Add the exported field and
jsontag toPreferencesininternal/project/project.goand set any non-zero default inDefaultPreferences(). - Register schema rule: Add a
settingentry topreferenceSettingsininternal/project/schema.go(key,kindinkString/kSlug/kRepo/kInt/kEnum/kArgv/kStrings/kGlobs/kBool, bounds/enum,help). - Mark safety keys: Set
safety: truewhenever relaxing the key could hide defects.t12 config setthen stores the change as aproposaldocument (config-<key>-<timestamp>.json) until an Operator approves it witht12 config approve. - Expose in UI (optional): Add the key to
plainKeysininternal/ui/prefs.goto show it on the plain Preferences page. - Test:
go test ./tests/unit/project/...Change a flow
A flow is the ordered steps every lane of a conversation runs. team (the default) has six, classic has eleven; both end with the merge policy, the merge and the deploy dry run (ADR 0006). To add a step to a flow:
- Step constant: Add the step name as a constant in
internal/orchestrator(next toAnalyze,Engineer,QA). - StepFunc: Add its
StepFuncto the map returned bycli.runSession.stepsininternal/cli/run_steps.go. - Flow and owner: Add the step to the flow's
Stepsininternal/orchestrator/flow.go, in run order, with the step right beforePolicyas the lane's last check. For theteamflow also add an entry toOwners, naming the team member who does it. - Routing rule: Add a
found_byrule for the step toassets/strategist/rules.json, so a blocking finding has a route (for exampleqagoes toengineerwith"tokens": 0, a fix attempt). Theteamflow routes failures by these rules alone and never asks the Strategist agent. - Web label: Add a label, icon and description for the step to
internal/ui/web/src/lib/steps.ts; the lane grid shows it, with the team member under it for a team conversation.
TestEveryFlowStepIsWiredAndOwned fails until the step is wired, owned and routed:
go test ./internal/cli/ -run TestEveryFlowStepIsWiredAndOwnedA conversation records its flow in a flow-chosen event before its first part starts, and everything that reads a conversation takes its steps from that event. Changing a flow therefore never moves a conversation that already started.
Add or edit a prompt or role skill
assets/embed.go embeds prompts/, skills/, strategist/, codereview/, deslop/ and the harness guard hooks into assets.Files. Keep phrasing neutral so tests/unit/skillmap/wording_test.go passes.
- Add or edit
assets/prompts/<name>.md. Start it with# <Title>, a blank line, thenVersion: <N>on line 3 (internal/contextcreator/promptinfo.go); the eight Context creator prompts require it, and several role prompts carry it too. - Increment
<N>on every edit of a Context creator prompt, then update its version and 12-character SHA-256 prefix inlockedPromptsintests/unit/contextcreator/prompts_test.go; the failing test prints the new values. - Test:
go test ./tests/unit/contextcreator/... ./tests/unit/skillmap/...Add a Deslop or Code review rule
- Add a rule to
"rules"inassets/deslop/typescript/rules.json(orassets/deslop/<stack>/rules.jsonforgo,python,rust, matchingResolveStack) with"fixtures": { "must_catch": [...], "must_not_catch": [...] }:
| Field | Allowed values |
|---|---|
id | ^DS-[A-F]\d+-[a-z][a-z-]*$, unique in the pack |
manifesto | Non-empty array from #2, #5, #6, #8, #14, #15, #17, #18, #19, #21 |
tool | diff-regex, test-literal, vi-mock, clone, dead-weight, prose |
status | advisory or blocking; at least one must_catch fixture is required |
- Set
"status": "advisory"soRule.FindingSeverity()emitsshould-fixwhile thedeslop-statsdocument tracks precision. It proposes promotion at 20 or more hits with80%kept, and demotion when more than25%of at least 10 judged hits are dismissed. Runs recurring across 3 requests (RecurringRunsMin) raiseguardrail-slopproposals. - Test:
go test ./tests/unit/deslop/...Add a project catalogue
- Create
catalogue/<type>.json(^[a-z0-9][a-z0-9-]*$) withtype,version(1or higher),title,template,project,defaults, andmust_haves. - List
must_havesin exact order (goal,users,pages,core-journey,look,out-of-scope), each withquestionandwhy_askplusrecommendedonpagesandlook. Give eachdefaultsentry anidslug,topic,question,default,reasonand at least onealternativesvalue other than the default (keeping strings compliant withwording_test.go). - For buildable types, add
catalogue/templates/<template-name>/with apackage.jsonand settemplatetotemplates/<template-name>. Leavetemplateempty for plan-only types likedesktop.json. A new project'st12 ask --typereadscatalogue/<type>.jsondirectly; add<type>toProjectTypes(internal/project/project.go) so a project'stypesetting andt12 ask --repo --typeaccept it. - Test:
go test ./tests/unit/project/...Add or update an architecture diagram
Architecture diagrams render as theme-matched animated SVGs defined under docs-site/components/mdx/diagrams/ and embed via <FactoryDiagram />.
- Create
docs-site/components/mdx/diagrams/specs/<name>.ts(or edit an existing spec) and register it indocs-site/components/mdx/diagrams/index.ts. - Keep zones, nodes, edges, and playback scenarios inside
viewBoxwith zero overlaps and validcodeReftargets. - Embed
<FactoryDiagram name="<name>" />(optionally withcaption="...") in an MDX page, then runbun run verify:diagramsandbun run check:llmsfromdocs-site/.
Next steps
Contributing and testing
Build turbo-12f binaries safely, run Go, TypeScript and database tests (scripts/test-db.sh, T12_TEST_DATABASE_URL), use t12-mutate, and follow repository and changelog rules.
Architecture decisions and status
Why turbo-12f keeps host tools, replaces the v1 QC stage, gates features on stored run metrics, budgets per-test CPU, keeps all state in Neon Postgres, runs as a small team by default, and what remains open.