Contributor conventions
Note: this page is generated from
AGENTS.mdin the repo root byscripts/gen-conventions-page.ts. Edit that file, not this page — it is overwritten on every generate.
Rules for AI agents (and humans) working on the projektor codebase. Everything here applies to every change. Detail that only some tasks need lives in the reference pages below; read the one that matches your task.
Portable source of truth across agent tools (Claude Code, Codex, Cursor, …).
CLAUDE.mdpoints here.
Reference, read when the task needs it
Section titled “Reference, read when the task needs it”| If you are… | Read |
|---|---|
| Running one test, the end-to-end suite, or hitting the pre-commit hook | apps/docs/src/content/docs/contributing/testing.md |
| Adding an island that needs the current project, or touching project tabs | apps/docs/src/content/docs/contributing/frontend.md |
| Cutting a release, or asking what ships and how versions work | apps/docs/src/content/docs/contributing/releasing.md |
| Splitting work across parallel workers and writing their spawn prompts | apps/docs/src/content/docs/contributing/fleet-planning.md |
| Picking up a ticket: definition of ready, states, completion reports, audit | get_workflow (MCP), or the workflow spec |
| Calling an MCP tool: exact input schema | MCP tool catalog, generated from source |
| Changing who can see a project | Access control |
What projektor is
Section titled “What projektor is”Internet-scale task management for AI agents and humans: an issue tracker and wiki on Cloudflare that agents reach over MCP and people use in a web app. “Internet-scale” means it inherits Cloudflare’s scale, holds up when a fleet of agents works at once, and is reachable from anywhere an agent runs.
Scope: a change belongs here if it helps capture and plan work, decide what’s next, coordinate who’s doing it, record what was done and learned, or see how work flows. It must also work on both surfaces (MCP and the web app), hold up at fleet scale, and coordinate work rather than execute it. CRM and sales pipelines, invoicing and HR, running agents or code, code hosting and review, and general chat are out of scope. The full test is in Design principles.
Design principles
- Fast and lightweight.
- Serverless, built on Cloudflare resources.
Implementation details:
- When implementing a feature or fixing a bug, always add a test that confirms the behaviour.
- Runtime: Hono on Cloudflare Workers
- Data: D1 (SQLite) for relational data, KV for caching (Access certs, user-by-email), R2 for file attachments
- Schema: Drizzle is the schema and primary query layer; raw
DB.prepareremains in the auth/workspace middleware hot path, the dev bootstrap, and a handful of service queries (FTS, counters) where hand-written SQL is clearer. - Monorepo: pnpm workspaces + turbo.
apps/api(the Worker),apps/web(Astro + Preact static site, served in production via CF Workers Static Assets),apps/docs(the Astro docs site linked throughout this file),packages/*(db, types, plugin-sdk),plugins/* - Deploy: a self-contained release artifact per
v*tag, shipped by a config-only deploy repo. The Worker and the built frontend ship together. See the releasing reference.
Coordination model (read this first)
Section titled “Coordination model (read this first)”Projektor expects multiple agents to work the same workspace concurrently. Before editing anything:
- Claim before editing. File claims (
claim_files) are path-level — they stop two agents editing the same files. Matching is exact string equality, not globs: claimingsrc/reserves nothing undersrc/, so name concrete paths and name them the same way the rest of the fleet does. Issue leases (claim_issue) are work-item-level — they stop two agents picking up the same ticket. The two are independent; you need both. - Your session goes stale if it goes quiet. Liveness is heartbeat-based:
SESSION_TTL_SECONDSinapps/api/src/services/agent-identity.tsis 120 seconds. Any call made with your session id (claim_issue,claim_files,update_issue,post_message) refreshes it, so use the two-call path below and you will rarely need an explicitheartbeat_agent. Go quiet for two minutes with no such call and your session goes stale: you must heartbeat again before you can claim, and your leases and claims are up for grabs in the meantime. - Both tiers self-heal. An issue lease or file claim held by a stale session is
reclaimed by the next claimer in the same call (
release_reason: "expired"). Still callrelease_filesandend_agentwhen you finish: reclaim only happens when someone else wants the path, so until then your claims sit there looking held, and a clean exit is what distinguishes you from a crash in the health data. A file claim with noagent_idhas no heartbeat to judge, so it lapses by age instead:FILE_CLAIM_TTL_SECONDS(default 24h, PROJ-928), after which the next claimer reclaims it; before that, onlyforcegets past it. - There’s a per-project cap on concurrently leased issues —
DEFAULT_AGENT_WIP_LIMIT = 3inapps/api/src/services/issue-leases.ts, overridable per project viaprojects.agent_wip_limit. It’s admission control on the backlog, not a rate limit: it bounds how much work can be in flight at once, not how fast you can ask. - A refused claim tells you who to talk to. Rejection is all-or-nothing: nothing is
claimed, and the error names the issue and agent holding the path — message them with
post_messageif you need it. Nothing is pushed to the holder on a plain rejection — its claim didn’t change.forceis different: it posts to both your issue scope (audit) and theirs (PROJ-635), since you just took something they thought they still held. Every contended path is recorded regardless.
This is the mechanism; the mechanical call sequence for this repo is under “Fleet
coordination protocol” below, and the design rationale (why leases, claims, and the
WIP cap are shaped this way) is the coordination model
doc. The workflow rules themselves (definition of ready, state machine, human review
gates) live in exactly one place, the workflow spec
— call get_workflow before claiming work; they aren’t restated here.
Planning and design docs live in the wiki, not the repo
Section titled “Planning and design docs live in the wiki, not the repo”Design records, implementation plans, and specs belong in the projektor wiki (create_wiki_page/update_wiki_page), not in a repo docs/ folder. Keeping them in the wiki makes them discoverable and searchable (search_wiki) instead of buried in git history. The only docs that belong in the repo are the root-level files (README.md, AGENTS.md, CONTRIBUTING.md, SECURITY.md, llms.txt), the public docs site (apps/docs, including the contributor reference pages above), apps/web/e2e/README.md and the images in docs/images/.
Human-authored files
Section titled “Human-authored files”Most docs may be generated or written by agents, but these paths are human-authored (Tom’s decision, PROJ-915):
README.mdapps/docs/src/content/docs/philosophy/**
Agents must not edit these files, not even to fix a typo or a stale fact. When your work makes one of them inaccurate, add a comment to the current editorial issue (PROJ-914 or its successor) that quotes the affected line and states the fact that changed. Docs checks may still scan these files and report drift, but the fix goes to the editorial issue, never into an agent’s diff. .github/CODEOWNERS requires @TAJD’s review on both paths.
Architecture: the service-layer contract (most important)
Section titled “Architecture: the service-layer contract (most important)”There are two surfaces over the same data — a REST API and an MCP (JSON-RPC) server. They MUST behave identically. The mechanism that guarantees this:
┌─► routes/<domain>.ts (REST: operationsRouter(...))operations/<domain>.ts ──────┤(one defineOperation per op) └─► mcp/<domain>.ts (MCP: ops.map(toMcpTool)) │ run(ctx, input) ▼services/<domain>.ts ─► D1 (ALL business logic + SQL live here)Rules:
- Each operation is declared once in
operations/<domain>.tswithdefineOperation(id, method + path, tier/role, input schema,run→ service call, optionalmcpResultshaping).routes/<domain>.tsandmcp/<domain>.tsare one-line adapters over that list (operations/define.ts); the OpenAPI spec and tool catalog are generated from it too (PROJ-895). - All business logic and SQL live in
services/<domain>.ts. No SQL inoperations/,routes/ormcp/. - REST and MCP must stay at parity. Add or change behavior in the service and operation so both surfaces get it. Adding a feature to only one surface is a bug;
mcp-parity.node.test.tsfails on drift. An operation’smcpResultreshapes rows for MCP, so a field added in the service reaches MCP only if that mapper passes it on. The deliberate REST-only operations (binary bodies, credential minting, OAuth consent, public share and feedback flows, human-only UI actions) are theREST_ONLYlist inapps/api/src/test/mcp-parity.node.test.ts, each with its reason; don’t re-flag them in audits. - Validation uses one shared Zod schema in
schemas/<domain>.ts(the operation’sinput, re-checked in the service) — so REST and MCP are validated identically. Never trust rawunknowninput in a wrapper. - Services throw typed errors from
services/errors.ts(ValidationError,NotFoundError,ForbiddenError,ConflictError, plusPayloadTooLargeErrorandUnsupportedMediaTypeErrorfor uploads). The wrappers translate them:- REST:
http/error-adapter.ts→ HTTP status (400/404/403/409/413/415) - MCP:
mcp/error-adapter.ts→ a tool result withisError: trueand{error: {code, message, fields?, hint?, details?}}(PROJ-893;codeis the service error kind). JSON-RPCerroris only for protocol faults and unexpected internal errors. Never return rawString(err)to clients.
- REST:
- Context is a
ServiceCtx(services/types.ts):{ db, kv, r2, workspaceId, userId, role?, authKind?, auth?, config }.authKindis"agent"for a token or OAuth grant and"human"for a browser login; it is set by the auth middleware, never by the caller, so use it (not a caller-supplied field) when behavior depends on who is calling. Build it withctxFromHono(c)in REST; the MCP dispatch (routes/mcp.ts) builds the equivalent and passesrolethroughPluginContext.
The security invariant: always scope by workspace
Section titled “The security invariant: always scope by workspace”Every query MUST be scoped by workspace_id (directly, or via a parent entity that was itself workspace-checked — e.g. comments verify their issue belongs to the workspace first). A missing scope is a cross-tenant data leak. This is the single most important correctness rule in the codebase.
The D1 limit: never bind a row-scaled array into one query
Section titled “The D1 limit: never bind a row-scaled array into one query”Cloudflare D1 rejects any query with more than 100 bound parameters. A query whose parameter count grows with an input array — drizzle inArray, a raw IN (...), or a batched mutation keyed by ids — will throw at runtime (a 500) once the array is large enough. This is invisible in tests: the vitest runner backs D1 with SQLite (cap 32766), so an un-chunked query passes CI and only fails on real D1.
Route every variable-length IN/inArray load through inChunks (services/sql.ts), which splits the array so each query stays under the cap:
const rows = await inChunks(issueIds, (chunk) => orm.select(...).from(...).where(and(inArray(table.id, chunk), eq(table.workspaceId, ctx.workspaceId))));// for a mutation that returns nothing, have the callback return []Bounded arrays (enums like priority) are fine to bind directly. When in doubt, chunk.
in-array-chunking.node.test.ts fails on a drizzle inArray in services/ that is neither
inside an inChunks callback nor a fixed array literal; a provably bounded one needs an entry
with its reason in apps/api/src/test/architecture/in-array-chunking-allowlist.ts. The test
does not see raw SQL IN (...), so the rule still applies there by hand.
File layout per domain
Section titled “File layout per domain”When adding/changing a domain (issues, projects, wiki, comments, …):
| File | Role |
|---|---|
apps/api/src/services/<domain>.ts |
business logic, SQL, validation, typed errors |
apps/api/src/schemas/<domain>.ts |
Zod schemas (single source of truth; shared primitives in schemas/common.ts) |
apps/api/src/operations/<domain>.ts |
operation definitions: path, role, input schema, service call, MCP result shape |
apps/api/src/routes/<domain>.ts |
REST adapter over the operations (mounted in index.ts) |
apps/api/src/mcp/<domain>.ts |
MCP adapter over the operations (composed in routes/mcp.ts) |
apps/api/src/test/<domain>.test.ts |
domain tests go here |
Test convention (don’t skip this): put a domain’s tests in its own <domain>.test.ts. Do not pile MCP tests into the shared test/mcp.test.ts — parallel work on multiple domains will collide there on merge. (mcp.test.ts is for cross-cutting dispatch behavior only.)
Conventions & gotchas
Section titled “Conventions & gotchas”- Adding a migration? After adding a new
.sqlfile topackages/db/migrations/, you must also add a corresponding?rawimport toapps/api/src/test/migrations.tsand append it to theMIGRATIONSarray. Without this the test DB won’t have the new table and integration tests will silently fail or error. Migrations are hand-written SQL — drizzle-kit’s generator is deliberately not wired up (PROJ-643): its journal was abandoned after0001, sodrizzle-kit generatediffed against a snapshot ~52 migrations stale and emitted a fullCREATE TABLEfor every table, which would fail against any non-empty database. Don’t re-add it without re-baselining the snapshot first. A migration that adds an index ends withPRAGMA optimize;so the planner has fresh statistics (PROJ-857). - Deletes never rely on FK cascades. Deleting a row that other tables reference must remove (or null) those rows explicitly in the service, in the same
db.batch()-ON DELETE CASCADE/SET NULLin the schema is not the cleanup (PROJ-407/918), and FTS mirrors, R2 objects and non-FK references have no cascade at all. Adding an FK withON DELETEmeans adding the cleanup and an entry inapps/api/src/test/architecture/fk-cleanup-allowlist.ts;fk-cleanup.node.test.tsfails otherwise. (PRAGMA foreign_keys = OFFis a no-op on D1/Miniflare, so tests can’t switch cascades off to prove cleanup.) - Issue search mirrors are written in the same batch as the issue.
issues_ftsis keyed byissues.search_rowid(never delete it by the UNINDEXEDissue_id), andissue_labelsmirrorsissues.labels, the table label search and filters read. A new path that writes title, body or labels must reusebuildFtsReindexStatements/buildLabelIndexStatementsinservices/issues.ts; a path that deletes issues must also delete their rows from both tables. - camelCase at the boundary, snake_case in the DB. Input schemas use
assigneeId,parentId, etc.; the service maps to theassignee_idcolumn. Keep both surfaces on the same naming. - JSON columns (
labels,scopes) are stored viaJSON.stringifyand returned as raw JSON strings — callersJSON.parseon read. There is no automatic (de)serialization. - Timestamps are unix seconds:
Math.floor(Date.now() / 1000). - IDs are
crypto.randomUUID(). - Issue numbers are allocated as
COALESCE(MAX(number),0)+1per project inside the INSERT itself, one statement, with the UNIQUE index on(project_id, number)as the backstop. Keep allocation in that statement; a separate read then write reintroduces the race. - Auth (
middleware/auth.ts): Cloudflare Access JWT (browser) ORAuthorization: Bearer <token>(agents) OR a dev bypass (DEV_USER_EMAIL, non-prod only, and never on/mcp/— a remote MCP client learns it must authenticate from the 401 challenge, so answering 200 makes the connector flow unreachable). API tokens are workspace-scoped — don’t widen that. - Login provisioning (
services/provisioning.ts): runs on every CF Access / dev-bypass login (not the token path). Cloudflare Access is the gate; config decides what a user gets inside —ADMIN_EMAILS→owner(first admin login also creates theDEFAULT_WORKSPACE_SLUGworkspace), everyone else →AUTO_JOIN_ROLE(defaultnone= invite-only; set it, e.g.viewer, to auto-join). Idempotent; safe to run per request. - Roles (
owner/admin/member/viewer) are enforced in services viactx.role. Mutations generally blockviewer; destructive ops may requireowner. - Group-based project access is the authorization model for project-scoped data. Access is default-deny: owner/admin see everything, but everyone else sees a project only if one of their groups holds a
(project, role)grant. The effective in-project role is the strongest grant across the user’s groups and replaces their workspace role inside that project (so a workspaceviewerwith amembergrant can write there). Enforce it throughservices/access.ts:visibleProjectPredicate(an indexedEXISTSsubquery — filter every project-scoped list query with it),effectiveProjectRole/requireProjectAccess(resolve a single resource;null→ 404 to hide existence), andcanWriteProject. Membership is read per-request, so grant/revoke takes effect on the next request with no session state. Thegroupsdomain (service/routes/mcp) is owner/admin-only CRUD over groups, members, and grants. - The plugin system is not wired at runtime yet (
pluginRegistryis empty;enabled_pluginsis unread). Treatplugins/*as not-yet-functional until that lands.
localStorage policy (frontend)
Section titled “localStorage policy (frontend)”localStorage may only store cosmetic preferences (theme, view mode, layout choices).
Never store server-side entity references (workspace slug, project ID, user ID) — a deleted
or renamed entity leaves a stale value that will silently cause API 4xx errors.
Before adding a new localStorage.setItem call, ask:
- Does a stale value ever reach an API request? If yes → don’t store it; derive it from props or build-time env instead.
- Does a missing value crash the UI or produce a non-graceful error? If yes → add a safe fallback, not localStorage.
Mark safe usages with a // safe-ls: comment explaining why (cosmetic, no API dep,
degrades gracefully). This is the convention established in PR #99.
Frontend: islands and the API layer
Section titled “Frontend: islands and the API layer”All island↔API calls go through apps/web/src/utils/api-client.ts:
buildHeaders(workspaceSlug, extra?)— adds the X-Workspace-Slug headerapiFetch<T>(path, opts)— wraps fetch with headers, credentials, JSON parse, and error throwing
No raw fetch( calls in island components. No local buildHeaders copies.
This mirrors the backend service-layer contract: routes are thin wrappers; islands are thin callers.
Dev workflow
Section titled “Dev workflow”pnpm installpnpm turbo type-check # tsc --noEmit across the monorepopnpm --filter @projektor/api test # vitest against an in-process Worker + D1
# One-time local secrets so the browser frontend can auth without Cloudflare Access:cp apps/api/.dev.vars.example apps/api/.dev.vars # DEV_USER_EMAIL + BOOTSTRAP_SECRETcp apps/web/.env.example apps/web/.env # PUBLIC_WORKSPACE_SLUG=projektor
pnpm dev # local dev - API on :8787, web on :4321# `dev` auto-applies D1 migrations to the local Miniflare DB first (db:migrate:local),# so /api/* won't 500 with "no such table" on a fresh checkout.GET /bootstrap (non-prod only, needs BOOTSTRAP_SECRET) seeds a workspace + user + token
- membership in one shot and prints the
claude mcp add ...command to connect an agent. Seed it once:
curl -H "X-Bootstrap-Secret: localdev" http://127.0.0.1:8787/bootstrapThen open http://localhost:4321 — with DEV_USER_EMAIL set, the dev auth bypass logs you in
as that user (a member of the seeded projektor workspace), and the islands load real data.
To run one test file or one test, see the testing reference.
Before opening a PR, run what CI runs (.github/workflows/ci.yml) — all must be green:
pnpm gen:docs # must leave no diff (catalog, specs, README stats, conventions page)pnpm lintpnpm turbo type-checkpnpm --filter @projektor/db testpnpm --filter @projektor/api test:coveragepnpm --filter @projektor/web test:coveragepnpm --filter @projektor/web build && pnpm --filter @projektor/api build && pnpm bundle-budgetpnpm --filter @projektor/docs buildFleet coordination protocol
Section titled “Fleet coordination protocol”The workflow rules live only in get_workflow (see “Coordination model” above). This
section is the call sequence agents use to avoid colliding in this repo.
Session identity (PROJ-894)
Section titled “Session identity (PROJ-894)”register_agent (and start_work) records the credential the call authenticated with on
the session (agent_sessions.credential_id + auth_method). A lone agent on its own
credential may then omit the agent id on claim_issue, heartbeat_agent and end_agent.
Fleets that share one credential (one pk_ token for every worker) should still pass
agentId explicitly: with several live sessions on the credential an omitted id is
ambiguous and is rejected. No per-connection state exists; the session is looked up from the
credential on every call (PROJ-452 statelessness holds).
The two-call path (PROJ-929)
Section titled “The two-call path (PROJ-929)”start_work and finish_work cover a whole session in two calls:
start_work({ issue, paths, name })at session start — registers the session, claims the issue and files (if given), and posts the start message. On any conflict the session is ended and nothing is left claimed (compensating cleanup; a crash mid-call leaves claims that go stale after the TTL). Save the returnedsessionId; the result also carries the claimedissue, so no follow-upget_issueis needed.finish_work({ sessionId, issue, completionReport?, status? })when done — optionally transitions the issue via the same pathupdate_issueuses (completion-report rules apply unchanged), then releases every claim/lease the session holds and ends it.
Session-scoped calls refresh the heartbeat (see “Coordination model”), so call
heartbeat_agent only if about a minute passes with none. Don’t wait for the 120-second
TTL: once it lapses, another agent can reclaim your lease and file claims.
start_work and finish_work compose from five primitives (register_agent,
claim_files, post_message, heartbeat_agent, release_files + end_agent) that
remain available for finer control; the fleet-planning reference lists that sequence.
Spawning workers? They will not use these primitives unless told to. Every spawn
prompt needs a ## Coordination (required) section and a Finish section; the
fleet-planning reference has the rules, the serialized files and the merge order.
Commits run a fast pre-commit hook (type-check plus lint on changed files). Use
git commit --no-verify for intermediate commits, then run the full list above before
opening a PR. There is deliberately no pre-push hook; CI is the gate.
MCP tools
Section titled “MCP tools”The tool list is generated from source into the
MCP tool catalog
(apps/api/scripts/gen-mcp-catalog.ts; CI fails if it is stale). Do not hand-maintain a
copy anywhere.
get_issueacceptsref: "PROJ-42"(project key + number), so you rarely need the UUID.- Load only the tools you need (PROJ-1056): append
?domains=<slug>,…to the MCP URL, for example?domains=agents,issues,comments,issue-links,workflowfor an issue-working agent. It filterstools/list, whose full definitions run to over 100KB; slugs are shown next to each domain in the tool catalog.get_tool_usagereports per-tool calls and response bytes, so you can see what your agents actually spend.
Built by Verdient.