Architecture.
On this page
Decisions #
- Single-owner server with registered, outbound SSH workers.
- Python/FastAPI API; React/TypeScript browser UI.
- PostgreSQL stores k0rtex state: the board in its default schema, the derived knowledge index in schema
knowledge. - MCP exposes project, ticket, discussion, and dispatch operations to agents.
- The server speaks no harness protocol. The worker drives each harness over the transport its provider names: a headless CLI streaming JSON (OpenCode, Claude Code) or Agent2Agent.
- Implementation is explicitly requested. Entering In review queues a Code Reviewer.
- One fresh agent process/session per execution attempt.
- One executing attempt per ticket; worker slots and profile limits bound concurrency.
flowchart TD
Human[Browser UI] -->|REST| API[FastAPI]
API --> Services[Application services]
External[External agents] -->|MCP| MCP[MCP server]
MCP --> Services
Services --> Store[PostgreSQL transaction thread]
Coordinator[Run coordinator] --> Services
Coordinator --> Runner[Agent runner]
Worker[Worker service] -->|outbound SSH| Coordinator
Runner <-->|k0rtex session stream over SSH| Worker
Worker <-->|CLI JSON lines or A2A| Harness[Harness in ticket checkout]
Harness -->|HTTP MCP| MCP
Store -->|Committed events / SSE| Human
Modules and ownership #
REST and MCP share the same Python workflows. domain.py defines request validation, state vocabulary, and application errors.
| Module | Owns |
|---|---|
services.py, tickets.py |
Board operations and ticket edits. transition_ticket checks actor, version, and eligibility; move_work_item couples entering review to reviewer enqueue. |
work.py, agents.py |
Transaction-local ticket primitives; agent selection and AgentSnapshot. Queueing saves the primary role, specialist definitions and active policies (policies.py). Later settings changes affect new attempts. |
runs.py |
RunLifecycle claims, attaches, cancels, recovers and finishes attempts. Finalization records changes and outcome effects, expires pending interactions, and emits events in one transaction. |
workflows.py |
Intake, refinement and retrospective: stage turns, questions, proposals and their approval, and the owner’s status moves. |
refinement.py |
RefinementSession: the board operations of one active stage turn, which check that the run is still the ticket’s. |
tasks.py |
The five agent Task kinds (implementation, review, clarify, plan, learn): role, instructions, expected results, retry eligibility and claim effects. The Task row fixes the Ticket, instructions and context. Each Run belongs to one Task and saves its own agent snapshot. |
mcp/ |
Mounts the external board tools and the run-scoped implementation, review and stage tools, and owns their session lifespans. Tools call application handlers shared with REST; scoped commands check ownership in their transaction. |
execution/ |
The coordinator claims runs and collects worker evidence. The agent runner follows the worker’s session stream, stores interactions centrally, and supplies board state to prompts.render_prompt. |
tenancy/ |
Organizations, teams, invitations and users, each as a repository (SQL over a transaction) and a service (one transaction per call, pure rules from policy.py, a tenancy.changed event). principals.py holds who a request runs for; access.py checks every REST route against the scope its template declares; signin.py decides whether an OAuth account gets in; workers.py says which work a worker takes by who owns it. |
integrations/auth/ |
Browser sessions and OAuth transactions (browser.py), and the two sign-in providers (oidc.py, github_oauth.py), which return a tenancy.Account. |
workers.py |
Registration, single-use pairing and SSH key authentication; the worker service itself is the separate k0rtex-worker package. Each connection exposes only k0rtex’s worker channel. The worker prepares ticket checkouts, launches agents, scans source and pushes reviewed commits. |
BoardStore owns one PostgreSQL connection and one executor thread, and holds a session advisory lock on its schema so a second backend cannot open it. Transactions run one at a time on that connection, which keeps event ids committing in order for SSE replay and lets claims read and write without row locks. Queries write ? placeholders; the store translates them for psycopg and binds values client-side. A service operation supplies a transaction callback; it either commits all state/event changes or rolls them back together. SQL execution stays within the persistence boundary except for explicit service queries. Board code keeps this small design: transaction functions per area rather than a repository class per table. The tenancy package is the exception, because its entities are plain records with many small queries shared between services, sign-in and worker placement: there each entity has a repository built from the transaction.
The run coordinator is an asynchronous in-process dispatcher over durable database records. A harness owns its native session history; k0rtex stores the harness’s session identifier and the normalized activity used by its UI.
Knowledge #
Knowledge lives on the server, behind one service (knowledge/service.py) that REST and MCP share. A worker only extracts: it scans the base checkout and returns files, symbols, import edges, packages, facts and source text (IndexReply).
| Part | Owns |
|---|---|
indexer.py |
Index jobs: asks a worker for extraction, writes it, retries a failed pass after a pause. Decision-only changes need no worker. |
chunking.py |
Passages: symbols (split, never cut off), module code between them, markdown sections, small config files, decisions. Ids derive from content. |
embedding_sync.py |
Keeps Qdrant matching the passages on its own loop. Indexing never waits for it. |
retrieval.py |
Full-text search (a generated tsvector ranked with ts_rank_cd, plus substring matches for parts of identifiers) and vector search, fused by rank; either alone when the other is unavailable. |
context.py |
retrieve_context within a size budget, and the brief of accepted decisions and project facts in every prompt. |
connection.py |
The embeddings base URL, model and key chosen in Settings, applied without a restart. |
The knowledge schema and the Qdrant collections are derived data. Each model and vector size has its own collection, so changing the model embeds everything again.
Data model #
| Entity | Relationships and purpose |
|---|---|
| Project | Unique key, immutable GitHub repository ID, default branch and required worker labels |
| Worker | Persistent SSH identity, owner-defined labels and session capacity; online presence belongs to the live connection |
| Ticket | Epic, WorkItem (a story) or Sub-Task. Optional parent is one level up in the same project. WorkItems may be classified as User Story or Bug. A request or staged epic also has a workflow stage. |
| Profile | Harness (a worker-side provider id, or none to use the project’s), optional model/agent, concurrency limit |
| Agent and defaults | Role-specific definition and provider; project defaults override board defaults. The Task kind selects the role: Analyst for Intake, Product Manager for Refine, Product Owner for Learn. |
| Policy | Standing instructions, global or for one project; enabled ones are saved with each queued Run and join the agents’ system instructions. |
| Task | Agent work on one Ticket. Kind, instructions and context identify the assignment. |
| Stage proposal | What a stage turn proposes, and the owner’s decision on it. |
| Run | One attempt on one Task, with its own workspace/profile, agent snapshot, session, status and result. |
| Comment | Ticket discussion with optional run attribution |
| Interaction | Permission or question from an agent and the validated human response |
| Event | Ordered committed activity, scoped to project/ticket/run when applicable |
References are validated by application transactions. Unique constraints enforce project keys, worker names, ticket numbering, and idempotency keys.
Dispatch and completion #
start_runchecks eligibility and absence of an active attempt in one transaction.- It records an implementation Task, first Run and event. Replaying an idempotency key returns that attempt. An explicit Task retry queues a fresh Run on the same Task if the scope and inputs still match.
- The coordinator randomly selects a connected worker with capacity and all required labels, respecting any manual pin and the global profile limit. The first claim persists ticket affinity atomically. Subsequent claims wait for that particular worker regardless of label changes.
- Claiming sets the run to
starting. Implementation moves the task toin_progress; a stage run marks its ticket as being worked on; review leaves the task in review. - The runner sends the worker the prompt, agents, model, effort and run-scoped MCP servers.
- The provider turns them into a launch, and the transport’s driver runs it in the ticket checkout.
- The server stores the harness’s session ID once the worker reports it.
- The worker’s activity is batched into events. Questions and permissions become persisted interactions, surfaced through SSE and answered through REST.
- The agent calls MCP
report_outcome. The run still owns the ticket until its prompt finishes. - A normal end-of-turn with a reported outcome succeeds. A completed implementation moves the ticket to review and enqueues a code review in the same transaction; a blocked outcome leaves it blocked. A manual move from ready to review uses the same queue operation.
- The Code Reviewer receives ticket context and a run-scoped
report_reviewtool. It can consult the Security Officer for sensitive changes. A successful turn publishes its report as a ticket comment. Review runs never transition the ticket. Only a human can accept a reviewed task as done.
Prompt termination alone never establishes ticket completion. A completed outcome followed by a protocol failure still results in a failed attempt and blocked ticket.
Intake and stages #
A ticket with a workflow stage is in the staged process. The stages are Intake (clarify), Refine
(plan), Deliver (build) and Learn (learn). Intake, Refine and Learn are conversations with one
agent; each turn is a Run whose purpose is refinement.
flowchart LR
Request[Request: Intake] -->|approved as epic| ToRefine[Epic: To refine]
Request -->|approved as story| Story[Story: Deliver]
ToRefine -->|owner starts refinement| Refine[Epic: Refine]
Refine -->|stories approved| Deliver[Epic: Deliver]
Deliver -->|last story closed| Learn[Epic: Learn]
Learn -->|verdict approved| Done[Done]
- A request is a provisional epic in Intake. The Analyst only classifies it. Approval turns the same row into an epic waiting To refine, or into a story, standalone or under an epic.
- Refinement starts only when the owner asks. Approving the Product Manager’s proposal creates the stories in Ready under the epic, which moves to In progress. Nothing is dispatched.
- A story is built on explicit request. The owner accepts its reviewed commit or moves it to Done.
- When every story of an epic is Done or Stopped, the Product Owner proposes a verdict, but only for an epic that k0rtex refined itself. Approval closes the epic and creates follow-up epics, which wait To refine.
A turn ends by asking a question or presenting a proposal. Only the owner approves, requests changes
or stops. submit_intake and submit_refinement record the same results from a caller that did the
work itself, with no Run. Answering a question stores the answer and queues the next turn in one
transaction. A failed turn leaves its ticket blocked until someone hands it back.
The Board shows requests and epics in the same status columns as other tickets, with their stage on the card.
State #
The ticket and run state machines are in the workflow.
Reliability and local boundaries #
- Serial database transactions prevent double claims and concurrent ticket numbering conflicts.
- Ticket versions detect stale edits even though database writes are serialized.
- A turn fails when the worker reports nothing for the idle timeout; waiting for the owner does not count.
- Harnesses run their own tools. One that cannot pause for the owner has its
askrules denied and says so. - Answers to questions are validated against the question’s schema.
- Database events back SSE cursor replay; reconnecting clients refresh their query caches.
- Startup marks in-flight attempts interrupted and expires pending interactions. Queued requests retain explicit user intent and may execute after startup.
- Unknown execution outcomes are not automatically retried. A retry creates a new attempt/session after the user inspects existing work.
- The HTTP listener binds to loopback behind a same-origin HTTPS proxy for a hosted board. A hosted origin requires an OAuth sign-in provider (OIDC or GitHub); requests then carry the signed-in user’s principal, which
access.pychecks against their organizations and teams. The independent SSH listener authenticates registered worker keys; pairing pins the server host key. - Only one k0rtex process uses a database; the advisory lock enforces it. Several API processes writing one database are outside this design: claims and the SSE cursor rely on serialized transactions.
Verification #
Tests use a real PostgreSQL database per test (cloned from a migrated template) and real HTTP MCP transports with deterministic CLI and A2A agents. They verify behavior across adapter boundaries, including competing dispatches, rollback, interrupted runs, permission/question round trips, cancellation, and missing outcomes. Playwright covers explicit dispatch through human review, responsive layout, and development proxy behavior.
This page is docs/architecture.md in the k0rtex repository. Suggest a change.