Architecture · v0.66.0

How the factory is technically built.

From the UI to the adapters talking to the coding CLIs. Hexagonal per module, locally runnable, no cluster, no service mesh. Look up which screw sits where, and why.

hexagonal · ports & adapters 7 run phases ADR-documented

Goal of the architecture

The platform is a control plane for AI-assisted software development. It bundles four tasks into one web app: project capture, artifact generation, run orchestration and quality assessment. Coding CLIs (Claude Code, Codex, Gemini, Kimi, Aider) are invoked as subprocesses; their output is structured into the database and made live-visible in the UI.

Two principles, deliberately not buzzword-loaded in V1:

  • Hexagonal per module. Every business module (e.g. run, wizard, settings) separates domain, application, web and, where needed, infrastructure. Domain depends neither on application nor on web.
  • Local execution. One Spring Boot process + Postgres in Docker. No cluster, no Kafka, no service mesh.
Browser → Spring MVC + Thymeleaf → Application services → Domain model
                                                              ↓
                       PostgreSQL ← Repositories ← Adapters
                       (Claude / Codex / Gemini / Aider / Kimi / local-LLM /
                        Bedrock / Vertex / Azure OpenAI / Mock / Git / FS)

Layers and modules

Inside the Maven module app all business modules live under io.softwarefabrik.app.<module>. Most modules use up to four sub-packages; adapter modules such as execution or review additionally split by vendor or reviewer:

  • domain/ — entities, value objects, repository interfaces, business services. Entities double as JPA entities (a deliberate V1 compromise); no web dependencies.
  • application/ — use-case services. Transaction boundaries (@Transactional).
  • web/ — Spring MVC controllers, Thymeleaf bindings, DTOs, SSE endpoints.
  • infrastructure/ — JPA repositories, external adapters, filesystem access, scheduled jobs.

Dependency rules

  • domain depends neither on application nor on web.
  • application does not depend on web.
  • application and web talk to the adapter port, never to a concrete adapter implementation.
  • Controllers live only in web; JPA repositories never in web or application.
  • Known legacy debt — cycles between modules and direct repository access from web — is frozen by a ratchet: existing cases are tolerated, new ones break the build.

ArchUnit tests pin these rules. A new wrong dependency turns CI red.

The 50 slices of the v0.66.0 codebase

agentauditcanarycommonconductorcontractevolutionexecutionexportgitguardrailskennzahlenleitplankenlicensemandantmcpmcpgatewayobservabilitypolicyprofilprojectdefinitionpromptprovenancequalitygatereviewrunsdlcsecretssecuritysettingsskillsspecsystempruefungteamvalidationwebwerkzeugwizardworkflowgithubissueskitextlaufstartlauftipproadmapvoraussetzungvorgabenansehenupdateimportgroesseanalysebericht

Modules in detail

ModulePurposeMain classes / routes
agentAgent roles + preferredModelAgentDefinition, AgentService, /agents
auditAppend-only audit logAuditEvent, table audit_event
commonShared utilitiesID generator, clock abstraction
conductorPlugins/Skills sync, AGENTS.md writer (v0.6.0+)PluginCatalog, SkillsCatalog, ConductorWorkspaceWriter
evolutionArtifact evolution of the control artifacts (ADR-0028): three-way comparison per section, consistency check, AI merging as a validated proposal (VorschlagsValidator)ArtefaktEvolutionService, DreiWegeVergleich, TextCompletionPort
executionRun execution, sandbox factory, output parserExecutionAdapterRegistry, LocalProcessSandbox + ContainerProcessSandbox, ExecutionSandboxFactory, ClaudeUsageJsonParser, TokenEstimator
gitGit in the workspace, inline diff before approvalGitService.diffSeit() (v0.8.0), shell-out to git
mcpMCP null state (ADR-0017): sink with workspace check (baseline in the audit chain), policy port for the MCP default ban and plugin approvals, signed runtime register of isolation proofsMcpWorkspacePruefung, McpServerPolicy, IsolationsnachweisRegister; table isolationsnachweis (V56)
canaryCanary harness (ADR-0022): proves per adapter and installed CLI version, using marker servers, that the null state holds (leaf slice)CanaryService, CanaryProfile, /admin/isolationsnachweise
licenseTier licenses, JWT lease/license/v1
observabilityPrometheus metrics, observability level 1 (since v0.9.0)ObservabilityConfig, Micrometer registry at /actuator/prometheus (ROLE_ADMIN)
policyApproval policiesApprovalDecision
profilProject profiles as data (PX-1, v0.44.0): detection, build steps, agent commands, test patterns, build/lock files per stack (leaf slice)ProfilKatalog, Projektprofil, YAML under softwarefabrik/profile/
projectdefinitionProject editor/projects, /projects/{id}/edit
promptMarkdown artifact generationTemplates under resources/prompts/
qualitygateVerdict aggregation/runs/{id}/quality-gate
reviewSeven read-only reviewersaider-review, claude-review, security-reviewer, architecture-reviewer, hallucination-reviewer, dependency-scan, spec-conformance (only for runs with a spec)
runRun model, RunTemplate (v0.7.0)Run, RunPhase, RunOrchestrationService, RunTemplate, /runs
secretsAPI-key encryptionAES-GCM, /integrations
securitySpring SecuritySecurityConfig
settingsGlobal defaults/einstellungen, table app_setting (V9); setting execution.sandbox.variant since v0.7.0
teamTeam compositionSerialised into AGENTS.md
validationBuild validationBuild gate per project profile (e.g. mvn verify, dotnet test, pytest, npm test), build container per project, linters as check steps
webUI cross-cuttingLayouts, theme toggle, dashboard
wizardSix-step project assistant with cost estimateWizardController, WizardService, WizardCostEstimator, TemplateRegistry (19 templates: 5 backend, 13 frontend, 1 repo import); tables wizard_draft (V12), version_cache (V13)
sdlcBacklog with dependencies, milestones, scheduled routinesPlanItem, ProjectMilestone, Routine, /backlog
mandantTenant isolation, budget cap, cost attributionTenantContext, /mandanten
skillsVersioned, tenant-scoped skill and plugin librarySkillVersion, /skills
guardrailsVendor-neutral engineering guardrails as a versioned resourceGuardrailsService, projected as AGENTS.md
provenanceWhy-trace per run (leaf slice)/runs/{id}/trace
exportAudit export bundle (leaf slice)/export
workflowWorkflow layer above the run: task graph, child runs, workspace leases, merge queue, integration gate (feature flag, off by default)WorkflowService, LeaseService, MergeCoordinator, IntegrationService, /workflows
kennzahlenProductivity and quality measurement derived from existing data (leaf slice, no schema of its own); quantities that cannot be measured are reported as a named gap instead of being filled with a numberKennzahlenService, Quote, Messluecke, /kennzahlen
contractContract registry: versioned contracts with content hash, structural validation, break detection (leaf slice)ContractRegistry, ContractValidator, /vertraege
leitplankenGuardrails per project and run (PX-7), agent control and preview (PX-8); leaf sliceLeitplankenService, /projects/{id}/leitplanken, /agents/{id}/steuerung
systempruefungSystem check and initial setup (UX-13/UX-14): is the factory ready for a real run? Plus allowing import folders and Git hosts in the UI (leaf slice)SystempruefungService, ErsteinrichtungService, /einrichtung/systempruefung, /einrichtung/start, /einrichtung/freigaben
werkzeugToolchain installation by the factory (PX-4c)WerkzeugVerwaltung, /admin/werkzeuge

Data flow: from wizard to quality gate

Wizardwizard_draft
→
Projectproject_definition
→
Artifactsprompt_artifact
→
Runrun
run_phase
execution_log
run_metrics
→
Quality Gaterun.quality_gate_decision
  1. Wizard collects answers in wizard_draft (survives browser reload and server restart).
  2. ProjectDefinition holds all editor fields. Status DRAFT → READY after artifact generation.
  3. Artifacts are generated by PromptAssemblyService, editable.
  4. Run orchestrates phases asynchronously (@Async), UI listens via SSE.
  5. Quality Gate invokes the selected reviewers one after another and aggregates to the verdict.

Iterative SDLC loop

The data flow above describes a single greenfield run up to the quality gate. Beyond the single run, the platform closes an iterative loop over a persistent workspace — the same project copy is built further across multiple runs, freshly created or imported from an existing repository via repo-import. Eight steps interlock:

  1. Plan. A plan run produces Markdown plans under plans/*.md in the workspace; from these a backlog of individually activatable items emerges.
  2. Select / activate. A backlog item is activated in the backlog and becomes the objective of the next build run.
  3. Build. A build run runs on its own branch (sdlc/run-…) in the persistent workspace, instead of directly on the base branch.
  4. Self-correction. If the build fails, the run engine repeats the correction automatically and in a bounded way: the run switches from NEEDS_CORRECTION back to RUNNING until the build is green or the retry limit is reached.
  5. Quality gate in the pipeline. The qualitygate module runs as a pipeline step in three modes: off, advisory (reports only) or blocking (stops delivery on a red verdict).
  6. Deliver. With a configured Git remote and a stored GitHub token the git module pushes the branch and opens a pull request; without remote/token it performs a local merge into the base branch.
  7. Learn. Findings land in project memory and flow as context into follow-up runs.
  8. Continue. Optionally the platform produces auto follow-up proposals for the next step — closing the loop back to step 1.

Persistence: Postgres + Flyway

Schema changes exclusively through Flyway migrations under app/src/main/resources/db/migration/. Every migration numbered (V<n>__<name>.sql), immutable after production.

MigrationsContent
V1–V9Base schema: projects, agents, teams, runs, phases, logs, metrics, budgets, settings
V12–V18Wizard state, version cache, model choice, templates, repo import, project memory
V19–V25Plan/build runs, branch isolation, remote + pull request, correction attempts, quality gate, allowed adapters
V26–V28Tenant, user-tenant binding, tenant budget
V29–V33Signed audit hash chain, policy as code, SBOM, SBOM signature, chain checkpoint
V34–V37Trigger provenance, hard tenant isolation, milestones, backlog dependencies
V38–V39Skill library, routines
V40–V43Workflow layer: run link, workflow aggregate, task graph, artifacts and budget
V44–V45Workspace leases with path ownership, merge queue, integration gate
V46–V48Contract registry with contract binding, structured contract findings
V49–V50Plan revisions on replanning, classification of merge conflicts by kind
V51Worker registration and task claims of the coordination layer
V52Test coverage per build — lines, branches, source; deliberately nullable
V53Rollback detection: merge commit as anchor, reversal by revert
V54Voluntarily reported effort per approval decision — nullable, because empty means „not reported“, not „zero minutes“
V56Register of isolation proofs (canary runs, signed)
V58Per-run flag marking costs as an estimate at the API rate (subscription mode) — nullable, empty means „unknown“
V59Voluntarily reported effort per plan approval (workflow.aufwand_minuten), so the plan approval counts in the „interventions“ metric — nullable like V54; holds only the most recent approval
V60Cache write tokens and the cost estimate (USD) reported by the agent CLI itself, per run — a cross-check of the factory's own valuation, not billing
V61Product specs (spec-driven development): spec, immutable spec_version with content hash, approval history spec_approval; spec mode per project
V62Spec and AC IDs on the backlog item (plan_item.spec_id, ac_ids) — nullable, empty means „no spec reference“
V63Spec reference and bound spec revision per workflow task (spec ID, AC IDs, version, hash) — parallel child runs work against the same revision
V64Outdated reason on the backlog item (plan_item.veraltet_grund), set by spec drift when a bound acceptance criterion is removed or changed
V65Questions raised by a spec run (spec_frage): question, answer or „not relevant“, who and when — input for the follow-up run
V66Spec format per project (project_definition.spec_format: FABRIK or SPEC_KIT) — controls whether runs work in the GitHub Spec Kit layout
V67Build directory per project (project_definition.build_directory, relative path such as app) — NULL means workspace root, i.e. the previous behaviour
V68Artifact versioning: prompt_artifact with SHA-256, origin, status, generator version and tenant_id; log artifact_materialization of which version a run wrote to the workspace
V69Artifact updates (artifact_update): analysis, approval and application of the set of six control artifacts, with status from PREVIEW to ROLLED_BACK
As of v0.66.0: 77 tables, 86 migrations. The numbers V10, V11, V55 and V57 are not assigned — gaps in the numbering are harmless for Flyway; renumbering a migration that has already shipped would not be.

Sandbox variants (ADR-0011)

The workspace is project-persistent — a local directory under SOFTWAREFABRIK_WORKSPACES_ROOT/<project-slug>. A directory per run no longer exists as of v0.13: a follow-up run should build on the result of the previous one. Build runs branch off onto sdlc/run-<id8> for that; child runs of a parallel workflow each get their own git worktree. The adapter is launched in the respective directory as its own process.

Local (default)

LocalProcessSandbox sets environment variables cleanly per process (no System.setenv at platform level), terminates processes hard on cancel/timeout (destroyForcibly()), writes stdout and stderr line-by-line into execution_log; the SSE stream reads from there.

Container per run (v0.7.0, ADR-0011 variant B)

ContainerProcessSandbox encapsulates build, SBOM and dependency scan of the generated project in an ephemeral Docker or Podman container; the agent CLIs themselves run as host processes with an ephemeral HOME. The container runs with:

  • --cpus 2 --memory 4g --pids-limit 512 as resource cap
  • --read-only root + /tmp as tmpfs
  • --network=none as class default; build and scans run with network (Maven dependencies, trivy database)
  • Bindmount on the workspace, -w /workspace

Enabled via setting execution.sandbox.variant=container; if Docker is missing from the PATH, ExecutionSandboxFactory falls back to the local variant with a log warning.

Adapter registry

Adapters are Spring beans implementing ExecutionAdapter. ExecutionAdapterRegistry collects every bean into a map <name → adapter>.

Adapter resolution order

  1. Run-specific override
  2. Global default (GLOBAL setting execution.adapter.default)
  3. YAML default, then the mock as the last fallback

The general override order PROJECT > USER > GLOBAL > YAML of the SettingService applies to settings; the registry reads the default adapter only at GLOBAL and YAML level — there is no project or user default for the adapter.

Security & CVE hygiene

  • Bootstrap admin is only created when SOFTWAREFABRIK_ADMIN_PASSWORD is explicitly set. No default passwords.
  • BCrypt for passwords, CSRF on every state-changing endpoint.
  • API keys encrypted with AES-GCM (master key from SOFTWAREFABRIK_SECRETS_MASTER_KEY) in DB.
  • Trivy and OWASP scans run per CI build. .trivyignore with documented exceptions.
  • pgJDBC 42.7.14 (pinned via the postgresql.version property; fixes CVE-2026-42198 and CVE-2026-54291, among others). docker-compose.yml pins Postgres to 127.0.0.1:5432.

Observability

Since v0.9.0 the platform exports Prometheus metrics (observability level 1). The Micrometer registry sits at /actuator/prometheus and serves JVM, HTTP and DB-pool metrics. Main class: ObservabilityConfig.

  • The endpoint is restricted to ROLE_ADMIN and scraped via HTTP Basic — no open metrics surface.
  • A shared application label separates multiple instances in the same Prometheus.
  • Deliberately level 1: no tracing pipeline, no bundled Grafana stack.

Version cache and @Scheduled jobs

So the wizard can always pre-fill current stable versions, the platform keeps a cache of version lookups. Two @Scheduled jobs keep it fresh:

  • Daily at 03:00 a job refreshes the version cache.
  • Daily at 04:00 a second job deletes expired wizard_draft rows (TTL 30 days).

Lookups follow the strategy pattern: a VersionLookupClient interface, three implementations:

  • MavenCentralVersionLookup — reads repo1.maven.org/maven2/…/maven-metadata.xml for Java libraries (Spring Boot, ArchUnit, OWASP Dependency-Check).
  • GitHubReleasesVersionLookup — fetches the latest release tag from the GitHub API (e.g. Trivy CLI).
  • NpmVersionLookup — queries registry.npmjs.org for Node packages (Playwright).

Cache keys are functional constants, not technical paths — e.g. spring-boot.3.x, archunit.latest, owasp.dependency-check.latest, trivy.cli.latest, playwright.npm.latest. That lets us swap the source without breaking consumers. Staleness is computed in Java (threshold 25 hours, a buffer over the 03:00 job): now - refreshed_at > 25h — deliberately not a Postgres GENERATED column, so the H2 test profile keeps working.

Admins inspect the cache at /einstellungen/wizard/versions: each row shows cache key, returned value, refreshed_at, last_error and a Stale badge; a "Refresh now" button triggers a synchronous lookup for all entries.

Settings architecture

The settings module is the platform's control panel. Three design choices work together:

  1. Scope hierarchy: every setting belongs to a scope (GLOBAL, USER, PROJECT). SettingService.effektiverWert(key, projectId, userId) searches narrow-to-wide: PROJECT first, then USER, then GLOBAL, then YAML.
  2. 5-minute TTL cache: resolved values are cached, so a resolve is essentially free 99 % of the time. A change via the UI evicts the affected entry immediately; the TTL only bounds how long a value changed by other means can stay stale. An app restart is never needed.
  3. Audit trail: every write to app_setting creates an audit_event with subject, scope and key (SETTING_CREATED, SETTING_UPDATED, SETTING_DELETED); the values themselves are logged as old/new only for security-relevant keys (sandbox, quality gate mode and strictness, guardrails, import folders, Git hosts, cost factor), otherwise deliberately not.

Concrete settings managed today:

KeyMeaningTypical value
workspace.rootRoot directory for all run workspaces/var/softwarefabrik/workspaces
workspace.git.user.nameAuthor of the factory's commits (effective from 0.41.3)Software Factory
workspace.git.user.emailEmail of the factory's commits (effective from 0.41.3)agent@softwarefabrik.local
execution.adapter.defaultDefault execution adapterclaude (YAML default: mock)
execution.sandbox.variantSandbox variant (local / container)local
run.quality-gate.modeQuality gate in the pipeline (off / advisory / blocking)advisory

Live streaming and SSE

A run's log view shows the output live; the run detail page reacts to status changes (e.g. with a browser notification when an approval is pending). Both use Server-Sent Events (SSE) — an open HTTP stream that pushes one-way messages to the browser. On the server, a background thread reads new execution_log entries and the run status from the database every 2 seconds.

  • Heartbeat: every 20 seconds a heartbeat event — keeps the connection open through reverse proxies.
  • Auto-reconnect: if the connection drops, the log view reconnects after 5 seconds.
  • Full state: on every (re)connect the server first sends all previous log entries of the run, so no gap appears.
  • Bounded load: at most 64 concurrent streams (softwarefabrik.sse.max-concurrent-streams) in a bounded thread pool; beyond that a new stream is rejected instead of letting the heap grow. A stream ends after 10 minutes.

The endpoint is /runs/{id}/logs/stream and delivers log, status and heartbeat events. Token usage and costs are not shown live but after the run completes.

Test strategy and coverage gate

Tests are not optional; they are part of the architecture. Three pillars:

  • Unit tests: per service class, fast, no Spring context, Mockito-based.
  • Integration tests: with Spring Boot test slices (@WebMvcTest, @DataJpaTest) against H2.
  • ArchUnit tests: pin layer boundaries and freeze known module cycles with a ratchet. Reach from application into web or into a concrete adapter class and a test fails.
  • Schema tests (since v0.30.0): H2 builds its schema from the very JPA mapping it is checked against, so a discrepancy between migration and mapping cannot surface there by construction. SchemaMappingTest compares the names of all expected tables and columns in seconds without Docker; SchemaValidierungTest applies every migration to a real Postgres via Testcontainers and has Hibernate check types and lengths with validate. Both are verified against a deliberately introduced discrepancy.

Coverage gate: JaCoCo ≥ 81 % branch / ≥ 85 % line. A service merged without tests doesn't pass mvn verify — intentionally strict. CI pipeline (.github/workflows/ci.yml): build + test + ArchUnit + JaCoCo + OWASP Dependency-Check + Trivy image scan + gitleaks. OWASP runs in its own non-blocking job and is skipped without an NVD key; Trivy scans the built Docker image.

What is deliberately NOT in the architecture

What the platform omits is as important as what it does. These omissions keep V1 readable and extensible:

  • No tenant hierarchy and no per-user budgets: tenant separation with its own policy, audit view, costs and export per tenant has been in place since v0.17; a user belongs to exactly one tenant, and the hard budget cap applies per tenant, not per user. Further open points under Known Limitations.
  • No own web IDE: the platform doesn't open a code editor in the browser. You work on the workspace with your local tools (VS Code, IntelliJ, …).
  • No own build server: the build gate builds per project profile inside the workspace, with the container sandbox in the project's build container, not on a build cluster.
  • No own LLM hosting: for code generation the platform only invokes coding CLIs (Claude Code, Codex, Kimi, Gemini, Aider). The one exception is the optional AI merge of artifact evolution, which can also call the Anthropic API directly via the official Java SDK. Air-gap setups go local CLI + local LLM (e.g. Ollama).
  • No plugin API for external adapters: in V1 adapters are added as Java classes in the codebase, not loaded as plugins. There is no plugin API.

License stack

Beside the product backend there is a separate stack for licensing, decoupled from the platform DB:

  • No dedicated identity provider: since the switch to Ed25519 (ADR-0005) Keycloak is no longer part of the license stack. Lease endpoints are public and protected by a device limit and rate limiter, admin endpoints by HTTP Basic.
  • License service as a Spring Boot microservice with its own PostgreSQL.
  • Lease JWT signed with EdDSA (Ed25519) — not RS256 — with embedded per-tier limits.
  • Offline verification in the client against the bundled public key (also published at https://license.softwarefabrik.io/api/v1/pubkey), fail closed on lease expiry.

The three tiers are Community, Professional and Enterprise. Community needs no account registration (lease issued via email + device-fingerprint hash). Lease duration depends on tier and delivery form; the values are collected on the pricing page.

In the delivery build the license system is always active; only in the development build does softwarefabrik.license.v1.enabled (default off) switch it on. With the license system active every new run with a real AI agent requires a valid lease; runs with the mock are license-free and do not count against the daily limit. Runs per day, a monthly euro limit set in the lease and the tier boundary for spec-driven development are enforced as well. Further lease values (parallel agents, team, SSO, audit) are not yet evaluated. Details in the license model.

Original goals (historical)

This section records what the first product planning expected of version 1. It used to live on the product page. The current state is described in the news and the known limitations.

Maturity model of the planning

The planning's maturity model defined five stages. By v0.17, M1 to M4 were reached, M5 except for one open point:

StageWhat works
M1 ReproducibleRun can be started, supervised, finished
M2 Solo-dev efficientQuick-start, global defaults, wizard with 19 templates, per-role model routing
M3 Tool-integratedAGENTS.md, plugins, skills synced; repo-import; project memory
M4 Operationally hardenedContainer sandbox for build and scans, live logs, inline diffs, browser notifications
M5 Multi-tenantDelivered (v0.17): project-boundary isolation, RBAC, SSO, admin UI, own policy, audit view, costs and export per tenant; open: budget cap per user

What version 1 deliberately did not need to do

  • graphical workflow designer
  • cloud scaling (distributed workers across several machines)
  • full-blown CI/CD platform

Recommended domain model

ProjectDefinition InstructionSet DefinitionOfDone AgentDefinition AgentTeam Run RunPhase Task ExecutionStep ExecutionLog ApprovalPolicy ApprovalDecision GitRepository GitCheckpoint BuildResult Artifact PromptArtifact

UX guiding decision

The user should not have to write Markdown files manually first.

Idea → structured UI capture → automatically generated Markdown artifacts → editable preview → run
Why this matters: exactly this makes the platform simpler and more productive than using Claude Code directly in the shell.