docs(taskmaster): PRD + task graph for agentic teams foundation

Converts docs/agentic-teams.md §16 steps 1-3 into a trackable PRD and 48
appended tasks (IDs 115-162) in the master tag. Steps 4-8 land as 5 low
priority placeholders wired onto the spine, pending the §15 open questions.

The PRD is grounded in the current codebase rather than the design doc's
indicative sketches, which changed the shape of the work:

- RBAC `tasks` is already owned by the inference queue, and bindings are
  normalized at parse time, so existing RbacDefinition rows literally hold
  "tasks". Taking the name for work items needs a one-shot guarded backfill
  to `inference-tasks` (task 116).
- deploy/entrypoint.sh uses `prisma db push`, so migration SQL never runs in
  production. Invariants are service-layer, not CHECK constraints.
- Ephemeral pods do not exist: restartPolicy is hardcoded Always and
  ContainerSpec has no volume/workdir fields (tasks 140-142).
- `exec` is cheap: KubernetesOrchestrator already implements exec/attach over
  k8s.Exec/k8s.Attach; only an API + CLI surface is missing (tasks 144-145).
- No git provider client exists in product code (task 148).
- ChatService caps its tool loop at 12 iterations, so the AgentRuntime runs a
  headless coding agent in-pod rather than extending chat (tasks 146-147).

Names the git-repo entity CodeRepo (CLI `repos`) to avoid colliding with the
repository/ data-access layer; AgentProject carries an optional llmId so the
brain-ownership question can be settled either way without a migration.

Generated task_*.md files are left untracked, matching how this repo has
treated them since the first commit.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N4wNHWf7xSwnZCWpJcyv9p
This commit is contained in:
Michal
2026-08-08 09:58:20 +01:00
parent d24c30761b
commit 797df2299d
2 changed files with 1510 additions and 8 deletions

View File

@@ -0,0 +1,808 @@
# PRD: Agentic Teams — Foundation
## Overview
mcpctl today orchestrates MCP servers, projects, prompts, skills, and chat agents. It does not
orchestrate *work*. This PRD adds the foundation that lets human developers and autonomous agents
be peers in the same project: a versioned vision layer (Epic → epictask → task), git repositories
attached to projects, agents as many-to-many project members, ephemeral per-session pods where
agents do real work, a swappable agent runtime, a task lifecycle with QA/Security/SRE gates, and a
single human accept gate that fires a merge through the git provider's API.
The design record is `docs/agentic-teams.md`. This PRD converts §16 steps 1–3 of that document
into an implementation spec. Steps 4–8 are named as deferred work at the end, deliberately
without detail — they depend on open design questions (`docs/agentic-teams.md` §15) that are not
closed.
## Problem
Two failure classes motivate this work.
**Nothing tracks work.** There is no Epic, EpicTask, Task, Repository, or AgentProject model in
`src/db/prisma/schema.prisma`, and no repository, service, route, or CLI code for any of them.
Agents can chat and call tools, but there is no unit of work to assign, no lifecycle to advance,
no branch or PR to attach, and no gate for a human to accept.
**Completed tasks do not add up to the vision.** From the design doc: you have a grand vision, you
split it into tasks, you complete all the tasks, and you are left with a stick with wheels instead
of a car. The root cause is not execution — it is that decomposition is lossy, tasks are graded
mechanically ("compiles / lint / renders") rather than against intent, and integration is nobody's
job. The fix is an authoritative, versioned Epic that every task can walk up to, so "what am I
serving, and what does done-for-this look like" is always answerable.
A third, practical problem shapes the ordering: the design document's "don't rebuild, delegate"
principle is correct in spirit, but several primitives it assumes do not exist in mcpctl yet.
Those are enumerated under **Execution Substrate Changes** and must land before any agent can work
a task.
## Scope & Non-Goals
**In scope** (design doc §16 steps 1–3):
1. Epic / EpicTask / Task / CodeRepo entities + AgentProject membership, with project linkage,
mcpd CRUD, CLI verbs, RBAC, backup, docs, and tests.
2. An `AgentRuntime` adapter interface and a first implementation running a headless coding agent
inside an ephemeral per-session pod. Prove: pod spawn → clone repos → work a task branch →
push → report.
3. Task lifecycle with QA / Security / SRE stages, PR linkage, the human accept gate, and merge
through the git provider API, with post-merge failure reopening the task.
**Explicitly out of scope** — these are named in *Deferred* below and get placeholder tasks only:
the Tier-2 design/product critic and Epic-comparison loop; collaboration modes (standup, joint
`exec` sessions as a workflow); the confidence signal and escalation dashboard; per-persona memory
and the coverage ledger; script artifacts and the baseline scorecard.
**Not being built at all:** a permission engine. mcpctl enforces coarse gates (who may transition
a task, what RBAC a session needs); fine-grained per-tool approval stays inside the agent runtime.
## Decisions Already Made
| Decision | Choice | Rationale |
|---|---|---|
| Work-item RBAC name | Work items take `tasks`; the inference queue moves to `inference-tasks` | Matches the design doc's vocabulary. The `inference-tasks` alias already exists, so the URL prefix `/api/v1/inference-tasks` is unchanged |
| Roadmap-node spelling | Model `EpicTask`, resource `epictasks`, aliases `epictask`, `et` | Design doc §15 Q2; one word, matches the doc's own usage |
| Git-repo resource name | Model `CodeRepo`, resource `repos`, aliases `repo`, `repository`, `repositories` | Avoids `repository.repository.ts` and the collision with the data-access-layer term used throughout `src/mcpd/src/repositories/` |
| Epic revisions | Epic joins the existing `ResourceRevision` system as `resourceType: 'epic'` | The Epic is the auditable source of truth for "is this done"; scope changes must be visible. `ResourceType` is a string union by design, so this is a non-migration change |
| Agent membership | New `AgentProject` junction; `Agent.projectId` retained and kept in sync for one release | Design doc §4. `ProjectMember` was deliberately dropped in migration `20260223120000_remove_project_members`; this is a narrower reversal — agent membership only, not human membership, which stays RBAC-driven |
| Invariants | Enforced in the service layer, not CHECK constraints | See *Deployment constraint* below |
| Agent brain | Home brain (`Agent.llmId`) for bare chat; the project's `llmProvider`/`llmModel` when the agent acts inside a project; optional per-membership override on `AgentProject.llmId` | Design doc §15 Q1 leans this way. **This is the one open question that blocks the data model** — the `AgentProject.llmId` column exists so the decision can be reversed without a migration |
### Deployment constraint (affects every schema task)
`deploy/entrypoint.sh` provisions the database with `prisma db push --accept-data-loss`, not
`prisma migrate deploy`. Hand-written SQL in `src/db/prisma/migrations/` therefore **never runs in
production**. The single existing CHECK constraint, `ChatThread_agent_xor_project` (migration
`20260717234728_add_project_chat_threads`), is absent from any `db push`-provisioned database and
is enforced only by `ChatService`.
Consequence: every invariant introduced here must be either expressible in the Prisma schema
(unique constraints, non-null columns, enums, foreign keys) or enforced in the service layer with
a test. Do not write CHECK constraints and assume they hold.
## Core Concepts
### The vision layer
```
Epic (the vision — project-scoped, versioned, revision-tracked)
└── EpicTask — a roadmap node; chains to other epictasks (dependency graph)
└── Task — the unit of work, with its own lifecycle
```
An **Epic** holds the agreed done-criteria written at vision time, its scope-change history, and
accepted-tradeoff decisions. An Epic is done only when 100% of the vision is delivered, **or** the
user explicitly accepted the tradeoffs — recorded so "done" is honest and auditable.
An **EpicTask** is a roadmap node. EpicTasks chain to one another, so visualising them yields a
dependency graph rather than a flat sequence. Each carries the decomposed subset of the Epic's
acceptance criteria, so per-node completeness is computable.
A **Task** is the unit of work, owned by an EpicTask. Because Task → EpicTask → Epic, every task
can resolve what it is serving by walking up the chain.
### Two-level verification
| Level | Checks | Who | When |
|---|---|---|---|
| Tier 1 — correctness / security / ops | Builds, runs, passes tests, stays secure, and the deployment-as-code is right for this project's real infrastructure | Developer + QA + Security + SRE personas | Inside the task's own lifecycle, before Done |
| Tier 2 — vision fidelity | Does the assembled result match the vision | Design/product critic | At the Epic level — **deferred, not in this PRD** |
Tier 1 stages are gates *inside* the task loop. Their feedback bounces the task back to
`InProgress`. They are not post-submit reviewers.
The **SRE/Release stage** reviews the deployment-as-code — is it targeting the right
infrastructure, by the right method, with the right tooling. It reviews the deployment
*definition*; it does not deploy. It exists because a large share of failures come from implicit
operational rules a developer LLM does not know. Concrete example: this cluster runs default-deny
network policies, so any new workload needs explicit egress and ingress rules. A developer LLM
watching a connection fail will deep-dive the network-debugging path when the real cause is a
missing egress policy silently dropping traffic. The SRE persona, holding per-project infra
knowledge, flags that in review.
### Agents as people
An agent exists independently of any project — a persistent identity with a name, description,
system prompt, and a home brain. It joins zero, one, or many projects. Per-project role and
scope hang off the membership junction, not off the agent.
### Pod per session
Each agent session gets its own ephemeral pod. The pod *is* the workspace: an init container
clones the project's repositories, the session is attached to project prompts, MCP tools, and
scoped secrets, and the pod dies at session end. Agents do not share a live filesystem with each
other — handoffs happen via git (branch + diff + verdict pinned to a commit). A single human may
share one agent's environment via `exec`.
## Schema Changes
All new models follow existing house conventions: `id String @id @default(cuid())`,
`version Int @default(1)` as an optimistic-concurrency counter bumped unconditionally in the
repository layer (see `agent.repository.ts` `updateData.version = { increment: 1 }`), plus
`createdAt` / `updatedAt`.
### Epic
```prisma
model Epic {
id String @id @default(cuid())
name String
description String @default("")
// The agreed statement of the vision. Body of the Epic.
content String @db.Text
// Checkable outcomes + intent/quality attributes that define 100% delivery.
// Array of { id, text, kind: 'outcome' | 'quality', met: boolean }.
doneCriteria Json @default("[]")
// Accepted-tradeoff records: { what, why, who, deScopedBy, at }.
acceptedTradeoffs Json @default("[]")
projectId String
status EpicStatus @default(open)
semver String @default("0.1.0")
currentRevisionId String?
ownerId String
version Int @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
epicTasks EpicTask[]
@@unique([name, projectId])
@@index([projectId])
@@index([name])
}
enum EpicStatus {
open
delivered // 100% of doneCriteria met
delivered_with_tradeoffs
cancelled
}
```
### EpicTask
```prisma
model EpicTask {
id String @id @default(cuid())
name String
description String @default("")
epicId String
// Decomposed subset of the Epic's doneCriteria this node is responsible for.
doneCriteria Json @default("[]")
status EpicTaskStatus @default(todo)
ownerId String
version Int @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
epic Epic @relation(fields: [epicId], references: [id], onDelete: Cascade)
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
tasks Task[]
dependsOn EpicTaskEdge[] @relation("EpicTaskEdgeFrom")
blocks EpicTaskEdge[] @relation("EpicTaskEdgeTo")
@@unique([name, epicId])
@@index([epicId])
}
// Chaining between roadmap nodes. Modelled as an explicit edge table rather
// than a self-referencing array so the graph can be walked in both directions
// and edges can later carry a type.
model EpicTaskEdge {
id String @id @default(cuid())
fromId String // the dependent node
toId String // the prerequisite node
createdAt DateTime @default(now())
from EpicTask @relation("EpicTaskEdgeFrom", fields: [fromId], references: [id], onDelete: Cascade)
to EpicTask @relation("EpicTaskEdgeTo", fields: [toId], references: [id], onDelete: Cascade)
@@unique([fromId, toId])
@@index([fromId])
@@index([toId])
}
enum EpicTaskStatus {
todo
in_progress
done
cancelled
}
```
Cycle prevention in the edge graph is a service-layer check (see *Deployment constraint*): before
creating an edge, walk `to`'s transitive dependencies and reject if `from` is reachable.
### Task
```prisma
model Task {
id String @id @default(cuid())
name String
title String
description String @default("") @db.Text
epicTaskId String
repoId String?
// The agent currently responsible. Null while unassigned.
assigneeId String?
state TaskState @default(todo)
// Drives how much Tier-1 verification is engaged: trivial work may pass on a
// light self-check; risky work engages QA / Security / SRE.
risk TaskRisk @default(normal)
// Git linkage, populated when the agent pushes.
branch String?
headCommit String?
prUrl String?
prNumber Int?
// Free-form reviewer comment attached at the accept gate.
reviewNote String? @db.Text
ownerId String
version Int @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
epicTask EpicTask @relation(fields: [epicTaskId], references: [id], onDelete: Cascade)
repo CodeRepo? @relation(fields: [repoId], references: [id], onDelete: SetNull)
assignee Agent? @relation(fields: [assigneeId], references: [id], onDelete: SetNull)
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
verdicts TaskVerdict[]
sessions AgentSession[]
events TaskEvent[]
@@unique([name, epicTaskId])
@@index([epicTaskId])
@@index([state])
@@index([assigneeId])
}
enum TaskState {
todo
in_progress
building // compile, run, smoke
self_testing // developer's own tests
qa_review
security_review
sre_review
done // leaves the developer's loop
awaiting_review // human accept gate
merged
reopened // post-merge failure
cancelled
}
enum TaskRisk {
trivial // docs, formatting — light self-check may suffice
normal
high // auth, secrets, migrations, cross-contract
}
// A Tier-1 persona's verdict, pinned to the commit it judged. Immutable —
// this is the provenance record the design doc calls "QA verified 3f2ab".
model TaskVerdict {
id String @id @default(cuid())
taskId String
stage TaskState // qa_review | security_review | sre_review
agentId String?
commit String
passed Boolean
summary String @db.Text
// Structured findings: [{ severity, message, path?, line? }]
findings Json @default("[]")
createdAt DateTime @default(now())
task Task @relation(fields: [taskId], references: [id], onDelete: Cascade)
agent Agent? @relation(fields: [agentId], references: [id], onDelete: SetNull)
@@index([taskId])
@@index([taskId, stage])
}
// Append-only transition log. Every state change writes one row.
model TaskEvent {
id String @id @default(cuid())
taskId String
fromState TaskState?
toState TaskState
actorType String // 'user' | 'agent' | 'system'
actorId String?
note String? @db.Text
createdAt DateTime @default(now())
task Task @relation(fields: [taskId], references: [id], onDelete: Cascade)
@@index([taskId, createdAt])
}
```
### CodeRepo
```prisma
model CodeRepo {
id String @id @default(cuid())
name String
projectId String
// Clone URL. https for token auth, ssh for key auth.
url String
defaultBranch String @default("main")
// Relative path under the session workspace root. Defaults to `name`.
path String @default("")
// Git provider, for PR/merge API calls. 'gitea' is the only driver in v1.
provider String @default("gitea")
// Secret holding the provider credential. Resolved through SecretService at
// session-provision time — never stored in plaintext on the row.
credSecretId String?
credSecretKey String?
ownerId String
version Int @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
cred Secret? @relation(fields: [credSecretId], references: [id])
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
tasks Task[]
@@unique([name, projectId])
@@index([projectId])
}
```
### AgentProject
Mirrors `ProjectServer` (`schema.prisma`): explicit join model with its own cuid `id`, `createdAt`,
cascade on both sides, `@@unique([a, b])`. Indexes on both columns follow `PersonalityPrompt`,
because both reverse lookups are needed ("agents of project", "projects of agent").
```prisma
model AgentProject {
id String @id @default(cuid())
agentId String
projectId String
// Per-project persona role. TEXT, not an enum, so adding a role later is a
// non-migration change (same reasoning as ResourceProposal.resourceType).
// v1 values: 'developer' | 'qa' | 'security' | 'sre'.
role String @default("developer")
// Optional per-membership brain override. Present so the open question in
// docs/agentic-teams.md §15 Q1 can be answered either way without a migration.
llmId String?
createdAt DateTime @default(now())
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
llm Llm? @relation(fields: [llmId], references: [id], onDelete: SetNull)
@@unique([agentId, projectId])
@@index([agentId])
@@index([projectId])
}
```
`Agent.projectId` is **retained** and written in sync with the junction for one release, so
existing `prepareContext` / `findByProjectId` paths keep working. A follow-up removes it.
### AgentSession
```prisma
model AgentSession {
id String @id @default(cuid())
agentId String
projectId String
taskId String?
// Orchestrator handle — pod name on k8s, container id on docker.
containerId String?
state SessionState @default(pending)
image String
// Reaped when now() > expiresAt. Swept by the same style of GC loop as the
// inference-task sweep in main.ts.
expiresAt DateTime
lastError String? @db.Text
ownerId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
endedAt DateTime?
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
task Task? @relation(fields: [taskId], references: [id], onDelete: SetNull)
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
@@index([state])
@@index([taskId])
@@index([agentId])
}
enum SessionState {
pending
provisioning
running
ended
failed
}
```
### Back-relations on existing models
Prisma requires both sides of every relation. The blocks above show only the owning side; the
following fields must be added to existing models or `prisma generate` fails:
| Model | Fields to add |
|---|---|
| `Project` | `epics Epic[]`, `codeRepos CodeRepo[]`, `agentMemberships AgentProject[]`, `sessions AgentSession[]` |
| `User` | `ownedEpics Epic[]`, `ownedEpicTasks EpicTask[]`, `ownedTasks Task[]`, `ownedRepos CodeRepo[]`, `ownedSessions AgentSession[]` |
| `Agent` | `projectMemberships AgentProject[]`, `assignedTasks Task[]`, `verdicts TaskVerdict[]`, `sessions AgentSession[]` |
| `Llm` | `agentProjects AgentProject[]` |
| `Secret` | `codeRepos CodeRepo[]` |
`Agent.projectId` and its `project Project?` relation stay as-is during the transition release, so
`Project` carries both `agents Agent[]` (existing) and `agentMemberships AgentProject[]` (new).
### Test helper
`src/db/tests/helpers.ts` `clearAllTables` must gain `deleteMany` calls for every new model —
globals with nullable foreign keys do not cascade.
## API Changes
All routes sit under `/api/v1`, follow the existing Fastify + zod-in-the-service pattern, and
resolve `project` / `agent` name strings to ids at the route layer (as `routes/skills.ts` does).
### New endpoints
```
# Vision layer
GET|POST /api/v1/epics ?project=<name>
GET|PUT|DELETE /api/v1/epics/:id
GET /api/v1/epics/:id/roadmap → epictask graph + per-node completeness
POST /api/v1/epics/:id/tradeoffs → append an accepted-tradeoff record
GET|POST /api/v1/epictasks ?epic=<name>&project=<name>
GET|PUT|DELETE /api/v1/epictasks/:id
POST|DELETE /api/v1/epictasks/:id/edges → { toId } add/remove a dependency edge
# Work items
GET|POST /api/v1/tasks ?project=&epictask=&state=&assignee=
GET|PUT|DELETE /api/v1/tasks/:id
POST /api/v1/tasks/:id/transition → { toState, note? }
POST /api/v1/tasks/:id/verdict → record a QA/Security/SRE verdict
POST /api/v1/tasks/:id/accept → { note? } human accept gate → merge
POST /api/v1/tasks/:id/reject → { note } → back to in_progress
GET /api/v1/tasks/:id/events
# Repositories
GET|POST /api/v1/repos ?project=<name>
GET|PUT|DELETE /api/v1/repos/:id
# Agent membership
GET /api/v1/agents/:name/projects
POST|DELETE /api/v1/agents/:name/projects/:project → { role?, llm? }
GET /api/v1/projects/:name/agents
# Sessions & exec
GET|POST /api/v1/sessions ?project=&agent=&task=
GET|DELETE /api/v1/sessions/:id
POST /api/v1/sessions/:id/exec → one-shot exec, returns { exitCode, stdout, stderr }
GET /api/v1/sessions/:id/attach → WebSocket, bidirectional stdio
# Git provider webhook
POST /api/v1/webhooks/git/:provider → post-merge failure reopens the task
```
### Changed endpoints
`/api/v1/inference-tasks/*` is unchanged in shape. Only its RBAC resource name changes (see
below).
## RBAC Changes
### The `tasks` namespace split
`src/mcpd/src/validation/rbac-definition.schema.ts` currently declares `tasks` in
`RBAC_RESOURCES` and aliases `task`, `inference-task`, and `inference-tasks` all onto it — with
the comment "the only 'task' we have is inference for now". That is no longer true.
Required changes:
1. `RBAC_RESOURCES` gains `epics`, `epictasks`, `tasks` (now meaning work items), `repos`,
`sessions`, and `inference-tasks`.
2. `RESOURCE_ALIASES` maps `task → tasks`, `epic → epics`, `epictask → epictasks`,
`et → epictasks`, `repo → repos`, `repository → repos`, `repositories → repos`,
`session → sessions`, and `inference-task → inference-tasks`. The entry
`'inference-tasks': 'tasks'` is **removed**.
3. `mapUrlToPermission` in `src/mcpd/src/main.ts` gains `epics`, `epictasks`, `tasks`, `repos`,
`sessions`, and maps `/api/v1/inference-tasks` to `inference-tasks`. Non-CRUD verbs need
explicit cases above the map: `POST /tasks/:id/accept|reject|transition` → `run:tasks:<name>`,
`POST /sessions/:id/exec` and `GET /sessions/:id/attach` → `run:sessions:<name>`.
4. `nameResolvers` (`main.ts`) gains `epics`, `epictasks`, `tasks`, `repos`, `sessions` so
name-scoped grants match when the URL carries a cuid.
### One-shot binding backfill
`ResourceBindingSchema` transforms `resource` through `normalizeResource` **at parse time** and
stores the normalized string, so existing `RbacDefinition.roleBindings` rows already contain the
literal `"tasks"` meaning *inference*. After the split, those grants would silently become
work-item grants.
A one-shot startup migration must rewrite `resource: "tasks"` → `"inference-tasks"` across all
`RbacDefinition` rows. Model the walk on `migrateAdminRole` in `src/mcpd/src/main.ts` (it iterates
`rbacRepo.findAll()` and rewrites `roleBindings` in place).
It must be **guarded so it runs exactly once** — a blanket rewrite on every boot would clobber
legitimate new work-item grants. Use the existing system-settings pattern: a boolean key in the
`mcpctl-system-settings` Secret (`SYSTEM_SETTINGS_SECRET` in
`src/mcpd/src/bootstrap/system-settings.ts`), read before the walk and written after. Wildcard
bindings (`resource: '*'`) are untouched — they already cover both.
Document the rename in `docs/inference-tasks.md`.
## CLI Changes
Two project rules govern every resource added here:
- Everything settable via `apply -f` **must** also be a `create` flag.
- `mcpctl get RESOURCE NAME -o yaml` **must** round-trip through `mcpctl apply -f`.
### New commands
```
mcpctl get epics|epictasks|tasks|repos|sessions [--project NAME]
mcpctl describe epic|epictask|task|repo|session NAME
mcpctl create epic|epictask|task|repo ...
mcpctl edit epic|epictask|task|repo NAME
mcpctl delete epic|epictask|task|repo NAME
mcpctl describe epic NAME # roadmap: epictask graph + per-node completeness
mcpctl tasks accept NAME [--note ..] # human accept gate → merge via provider API
mcpctl tasks reject NAME --note .. # → back to in_progress
mcpctl exec --project NAME AGENT -- bash
```
`mcpctl exec` semantics (design doc §10): exec drops the human into the **working environment** —
the cloned repos, branches, tools, and deps. It does **not** attach to the agent's reasoning loop.
The agent remains a separate process the human can still talk to.
### Files to touch
| Concern | File |
|---|---|
| Resource aliases | `src/cli/src/commands/shared.ts` `RESOURCE_ALIASES` |
| `get` columns + yaml kind | `src/cli/src/commands/get.ts` — row interfaces, `getColumnsForResource`, `RESOURCE_KIND`, `toApplyDocs` strip blocks |
| `describe` formatters | `src/cli/src/commands/describe.ts` — clean sections and tables, not key-value dumps |
| `create` subcommands | `src/cli/src/commands/create.ts` |
| `apply -f` | `src/cli/src/commands/apply.ts` — spec schemas, `ApplyConfigSchema` keys, `KIND_TO_RESOURCE`, dry-run counts, apply loops |
| `edit` | `src/cli/src/commands/edit.ts` `validResources` |
| Scoped fetch | `src/cli/src/index.ts` `fetchResource` / `fetchSingleResource` for `--project` scoping |
| Completions | `scripts/generate-completions.ts` `CANONICAL_RESOURCES` + `ALIAS_ENTRIES`, then `pnpm completions:generate` |
Completions are generated, never hand-edited; `src/cli/tests/completions.test.ts` runs the
generator with `--check` and fails on drift.
## Execution Substrate Changes
These are the primitives the design document assumes but mcpctl does not have. They gate step 2.
### 1. Ephemeral pods
`ContainerSpec` in `src/mcpd/src/services/orchestrator.ts` has only image, name, command, env,
ports, limits, labels, and network. `generatePodSpec` in
`src/mcpd/src/services/k8s/manifest-generator.ts` hardcodes `restartPolicy: 'Always'`, and no code
anywhere uses the Kubernetes Job API.
`ContainerSpec` must gain:
- `restartPolicy?: 'Always' | 'Never' | 'OnFailure'`
- `workdir?: string`
- `volumes?: Array<{ name: string; mountPath: string; kind: 'emptyDir' }>` — the session
workspace
- `initContainers?: Array<{ name; image; command; env?; volumeMounts? }>` — the repo-clone step
Both backends implement them: `KubernetesOrchestrator` and `DockerContainerManager`.
### 2. Session provisioning
A `SessionService` that: creates the `AgentSession` row; resolves the project's `CodeRepo` list and
their credentials through `SecretService` (resolution failure is fatal for the attempt, matching
`InstanceService.attemptStart`); builds a spec with an init container that clones each repo to its
`path` under the workspace volume and checks out the task branch; starts the pod; and transitions
the row to `running`.
Reaping runs as a GC sweep in the same style as the existing inference-task sweep in
`src/mcpd/src/main.ts`: sessions past `expiresAt` are stopped, removed, and marked `ended`. Note
these loops assume a single mcpd replica — there is no leader election, and this inherits that.
### 3. Exec surface
The hard part already exists. `McpOrchestrator` declares `execInContainer`, `execInteractive`, and
`attachInteractive`; `KubernetesOrchestrator` implements the latter two over `k8s.Exec` and
`k8s.Attach`, and `src/mcpd/src/services/transport/persistent-stdio.ts` uses them in production
today. This work is an **API and CLI surface over a proven primitive**: a one-shot exec route, a
WebSocket attach route with terminal resize and proper exit-code propagation, and the
`mcpctl exec` client.
### 4. Git provider client
No Gitea or GitHub API client, PR creation, or webhook handling exists in product code. PRs are
made today by the root-level `pr.sh` (curl against the Gitea API) or by an agent calling the
`gitea-mcp-server` MCP tool.
A `GitProvider` interface in mcpd with a Gitea driver: `createPullRequest`, `getPullRequest`,
`getCombinedStatus`, `mergePullRequest`. Credentials resolve from the `CodeRepo`'s Secret.
`pr.sh` is the reference for the endpoint shapes (`POST /api/v1/repos/:owner/:repo/pulls`).
A webhook receiver validates the provider signature and reopens the task on post-merge failure.
## AgentRuntime Interface
mcpctl builds an *interface*, not a runtime. `ChatService` is not a candidate — its tool loop is
capped at `MAX_ITERATIONS = 12` (clamped 1..50), which is a soft-DoS guard appropriate for chat
and far too small for a coding task.
```ts
export interface AgentRuntime {
startSession(opts: RuntimeSessionOpts): Promise<RuntimeSession>;
send(sessionId: string, message: string): Promise<void>;
status(sessionId: string): Promise<RuntimeStatus>;
result(sessionId: string): Promise<RuntimeResult>; // branch, head commit, summary
endSession(sessionId: string): Promise<void>;
}
```
Implementation #1 runs a battle-tested headless coding agent inside the session pod. It already
solves per-tool permission approval, git and branch mechanics, subagents, streaming, and MCP
client behaviour — all things the design document explicitly declines to rebuild. The persona is
delivered as prompt files in the container, which suits a file-aware coding runtime.
A second adapter is explicitly deferred; the interface exists so it stays possible.
## Task Lifecycle
```
todo → in_progress → building → self_testing
→ qa_review (feedback → in_progress)
→ security_review (feedback → in_progress)
→ sre_review (feedback → in_progress)
→ done → awaiting_review
accept → merged
reject → in_progress
merged --post-merge failure (webhook)--> reopened
```
Verification effort scales with `Task.risk`: `trivial` work may pass on a light self-check;
`high` engages all three review stages. The stages decide their own depth.
Transitions are guarded by a table of legal `(from, to)` pairs and applied as **compare-and-swap**
— `updateMany` with the expected `state` in the `where` clause, then check the affected-row count.
This is the same idiom `InferenceTaskRepository` uses so two racing claimants cannot both win.
Every transition appends a `TaskEvent`.
The human approval gate is **not** a per-tool tri-state. It is a task-level yes/no plus a comment
on the resolved outcome, and accepting it fires the merge. The human should not have to go to git.
## Testing Strategy
### Unit — `src/db/tests/`
- Schema tests per model (pattern: `skill-schema.test.ts`): create, unique constraints, cascade
behaviour on project/epic/task delete, `AgentProject` uniqueness.
- `clearAllTables` in `helpers.ts` covers every new model.
### Unit — `src/mcpd/tests/`
- Service tests: Epic done-criteria roll-up; EpicTask edge cycle rejection; task transition table
including every illegal pair; compare-and-swap under concurrent transition.
- Route tests per resource (pattern: `prompt-routes.test.ts`, `agent-routes.test.ts`).
- RBAC: the `tasks` → `inference-tasks` backfill runs once and is idempotent on a second boot;
a pre-existing `view:tasks` grant still authorizes `/api/v1/inference-tasks` afterwards and does
**not** authorize `/api/v1/tasks`; name-scoped grants resolve for all new resources.
- Orchestrator: `generatePodSpec` emits `restartPolicy`, workdir, volumes, and init containers.
- Git provider: Gitea driver against a mocked HTTP server.
### Unit — `src/cli/tests/`
- `get -o yaml` → `apply -f` round-trip for every new resource.
- `create` flag coverage: every field settable in `apply` has a matching flag.
- `completions.test.ts` assertions for the new resource words.
### Smoke — `src/mcplocal/tests/smoke/`
Every feature ships smoke tests. Follow the CRUD pattern in `personality.smoke.test.ts`: a
`Date.now().toString(36)` name suffix, a `healthz()` preflight that **skips rather than fails**
when the daemon is unreachable, `mcpctl --direct` shelling, and explicit `afterAll` cleanup.
- `epic.smoke.test.ts` — Epic → EpicTask → Task create/list/describe/delete against live mcpd.
- `repo.smoke.test.ts` — CodeRepo CRUD, credential reference resolves.
- `session.smoke.test.ts` — provision a session pod against the real cluster, confirm the repo is
cloned, exec a command, confirm the pod is reaped.
- `task-lifecycle.smoke.test.ts` — drive a task through the full transition chain including a
rejected accept-gate bounce.
When a smoke test fails, fix the environment (deploy, backend, RBAC) — never weaken the assertion.
## Deferred
Named here so the boundary is explicit. Each gets a single placeholder task with no detail, to be
expanded once the corresponding open questions in `docs/agentic-teams.md` §15 are closed.
- **Tier-2 vision critic and Epic-comparison.** A review-only, non-executing design/product
persona that judges the assembled result against the Epic in its native medium, producing
reopen / new-task / `exec` outcomes. Blocked on §15 Q13 (does this need render/screenshot
infrastructure, or can a design-aware persona judge from a structured artifact?).
- **Collaboration modes.** On-demand async standup (`mcpctl standup --project NAME`) and `exec`
as a workflow rather than a command. Blocked on §15 Q4 and Q5.
- **Confidence signal and escalation dashboard.** Evidence-anchored confidence (retrieve K similar
past tasks with their *outcomes*, ask how confident we are this resolves cleanly), thresholds
driving autonomy, and a single cross-project human decision queue. Blocked on §15 Q12
(web / TUI / CLI?). Retrieval quality is the crux — weak retrieval quietly poisons the model.
- **Memory and the coverage ledger.** Global per-agent memory plus per-project knowledge, and a
commit-pinned coverage ledger enabling delta-verification. Non-negotiable prerequisite:
invalidation when a covered region changes, or the ledger becomes false confidence. Keep the
trust boundary — the ledger is platform-verified machine fact; agent prose notes are opinion and
never the gate.
- **Script artifacts and the baseline scorecard.** Reusable executable `script` artifacts at task,
project, and agent scope, plus a provisioned baseline-rules scorecard. Blocked on §15 Q15 and
Q16. Watch the incentive integrity risk: reward *reused* tools, not tool proliferation.
## Implementation Phases
**Phase A — foundation (blocks everything)**
1. RBAC `tasks` namespace split, alias repoint, and the one-shot guarded binding backfill.
2. Prisma models Epic, EpicTask, EpicTaskEdge, Task, TaskVerdict, TaskEvent, CodeRepo,
AgentSession + enums + migration + `clearAllTables`.
3. `AgentProject` junction, with `Agent.projectId` kept in sync for one release.
**Phase B — mcpd CRUD**
4. Epic resource: repository, service, zod validation, routes, `main.ts` wiring, revision opt-in.
5. EpicTask resource plus the edge graph and cycle rejection.
6. Task resource plus the transition table and compare-and-swap transitions.
7. CodeRepo resource with credential resolution.
8. RBAC wiring for all new resources: `mapUrlToPermission`, `nameResolvers`, non-CRUD verb cases.
9. Backup and YAML kinds for the new resources — `BACKUP_KINDS`, `APPLY_ORDER`, `kindMap`, the
export loop, `serializeResource`, and `main.ts` `kindFromSegment` / `importResource` /
`deleteResource`. Fix the pre-existing gap where `skill` is missing from the latter two.
**Phase C — CLI**
10. `get` columns and `describe` formatters for all new resources.
11. `create`, `apply -f`, `edit`, `delete`, with the yaml round-trip test.
12. Shell completions and their guard test.
13. Roadmap view: `describe epic` rendering the epictask graph with per-node completeness.
**Phase D — execution substrate**
14. Extend `ContainerSpec` and both orchestrator backends with restart policy, workdir, volumes,
and init containers.
15. `SessionService`: provisioning, repo-clone init container, credential resolution, TTL and GC.
16. `AgentRuntime` interface plus adapter #1 running a headless coding agent in-pod.
17. Exec surface: one-shot exec route, WebSocket attach, and `mcpctl exec`.
**Phase E — lifecycle and PR**
18. Task lifecycle state machine, transition API, and `TaskEvent` log.
19. `GitProvider` interface plus the Gitea driver.
20. PR linkage and the human accept gate firing merge through the provider API.
21. QA / Security / SRE stage verdicts, risk-scaled, pinned to a commit.
22. Post-merge failure webhook reopening the task.
**Phase F — cross-cutting**
23. Documentation: `docs/epics.md`, `docs/tasks.md`, `docs/repos.md`, `docs/sessions.md`, the
README resources table, and the CLAUDE.md resource cheatsheet.
24. Smoke tests for every new resource plus the session and lifecycle flows.
**Phase G — deferred placeholders**
25. Tier-2 vision critic and Epic-comparison loop.
26. Collaboration modes: async standup and `exec` joint sessions.
27. Confidence signal and escalation dashboard.
28. Per-agent memory and the coverage ledger.
29. Script artifacts and the baseline scorecard.

View File

@@ -2549,16 +2549,710 @@
"testStrategy": "1. Gate proxy model smoke test: identical behavior to current hardcoded gate (begin_session, tools/list filtering, ungating). 2. Composition test: model extending [gate, paginate] inherits both behaviors. 3. Conflict detection test: two parents intercepting same hook differently = compile-time error. 4. Discovery test: drop a .ts file in proxymodels dir, mcpctl get proxymodels shows it. 5. Existing smoke tests (proxy-pipeline.test.ts) pass unchanged after migration.",
"subtasks": [],
"updatedAt": "2026-03-07T01:26:57.383Z"
},
{
"id": "115",
"title": "RBAC tasks namespace split and alias repoint",
"description": "Split the RBAC 'tasks' resource into 'tasks' (work items) and 'inference-tasks', update RBAC_RESOURCES and RESOURCE_ALIASES in rbac-definition.schema.ts",
"details": "In src/mcpd/src/validation/rbac-definition.schema.ts:\n1. Update RBAC_RESOURCES array to include: 'epics', 'epictasks', 'tasks', 'repos', 'sessions', 'inference-tasks'\n2. Update RESOURCE_ALIASES:\n - task → tasks (work items)\n - epic → epics\n - epictask → epictasks, et → epictasks\n - repo → repos, repository → repos, repositories → repos\n - session → sessions\n - inference-task → inference-tasks\n3. REMOVE the entry 'inference-tasks': 'tasks'\n4. Export normalizeResource unchanged (it uses the alias map)",
"testStrategy": "Unit tests in src/mcpd/tests/validation/: verify normalizeResource('task') returns 'tasks', normalizeResource('inference-task') returns 'inference-tasks', normalizeResource('et') returns 'epictasks'. Test that RBAC_RESOURCES includes all new entries.",
"priority": "high",
"dependencies": [],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "116",
"title": "One-shot RBAC binding backfill migration",
"description": "Implement guarded startup migration to rewrite existing 'tasks' bindings to 'inference-tasks' so pre-existing grants continue authorizing inference endpoints",
"details": "In src/mcpd/src/main.ts or a new bootstrap module:\n1. Read system settings from SYSTEM_SETTINGS_SECRET (see src/mcpd/src/bootstrap/system-settings.ts pattern)\n2. Check for boolean key 'rbacTasksBackfillComplete'\n3. If false/missing: iterate rbacRepo.findAll(), for each RbacDefinition row, rewrite roleBindings where resource === 'tasks' to resource: 'inference-tasks'\n4. Use rbacRepo.update() to persist changes\n5. Set 'rbacTasksBackfillComplete': true in system settings after completion\n6. Wildcard bindings (resource: '*') are untouched\n7. Model on migrateAdminRole pattern in main.ts",
"testStrategy": "Unit test: create RbacDefinition with resource:'tasks', run backfill, verify resource changed to 'inference-tasks'. Test idempotency: run twice, verify no duplicate rewrites. Test wildcard unchanged.",
"priority": "high",
"dependencies": [
"115"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "117",
"title": "Add Epic, EpicTask, EpicTaskEdge Prisma models",
"description": "Add Epic, EpicTask, EpicTaskEdge models with enums EpicStatus and EpicTaskStatus to schema.prisma following PRD specifications",
"details": "In src/db/prisma/schema.prisma add:\n1. enum EpicStatus { open, delivered, delivered_with_tradeoffs, cancelled }\n2. enum EpicTaskStatus { todo, in_progress, done, cancelled }\n3. model Epic with: id, name, description, content (@db.Text), doneCriteria (Json), acceptedTradeoffs (Json), projectId, status, semver, currentRevisionId, ownerId, version, createdAt, updatedAt. Relations: project, owner (User), epicTasks[]. @@unique([name, projectId]), @@index([projectId]), @@index([name])\n4. model EpicTask with: id, name, description, epicId, doneCriteria (Json), status, ownerId, version, createdAt, updatedAt. Relations: epic, owner, tasks[], dependsOn (EpicTaskEdge[]), blocks (EpicTaskEdge[]). @@unique([name, epicId]), @@index([epicId])\n5. model EpicTaskEdge with: id, fromId, toId, createdAt. Relations using @relation names. @@unique([fromId, toId]), @@index([fromId]), @@index([toId])\n6. Add reverse relations to User and Project models",
"testStrategy": "Schema tests in src/db/tests/: create Epic, verify unique constraint on (name, projectId), test cascade delete from Project, test EpicTask creation with Epic reference, test EpicTaskEdge uniqueness.",
"priority": "high",
"dependencies": [],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "118",
"title": "Add Task, TaskVerdict, TaskEvent Prisma models",
"description": "Add Task, TaskVerdict, TaskEvent models with enums TaskState and TaskRisk to schema.prisma for work item tracking",
"details": "In src/db/prisma/schema.prisma add:\n1. enum TaskState { todo, in_progress, building, self_testing, qa_review, security_review, sre_review, done, awaiting_review, merged, reopened, cancelled }\n2. enum TaskRisk { trivial, normal, high }\n3. model Task with: id, name, title, description (@db.Text), epicTaskId, repoId?, assigneeId?, state, risk, branch?, headCommit?, prUrl?, prNumber?, reviewNote? (@db.Text), ownerId, version, createdAt, updatedAt. Relations: epicTask, repo (CodeRepo?), assignee (Agent?), owner, verdicts[], sessions[], events[]. @@unique([name, epicTaskId]), indexes on epicTaskId, state, assigneeId\n4. model TaskVerdict with: id, taskId, stage (TaskState), agentId?, commit, passed, summary (@db.Text), findings (Json), createdAt. Relations: task, agent. @@index([taskId]), @@index([taskId, stage])\n5. model TaskEvent with: id, taskId, fromState?, toState, actorType, actorId?, note? (@db.Text), createdAt. @@index([taskId, createdAt])\n6. Add reverse relations to Agent model (assignedTasks[], verdicts[])",
"testStrategy": "Schema tests: create Task linked to EpicTask, verify cascade on EpicTask delete, test TaskVerdict immutability pattern, test TaskEvent append-only by creating multiple events for same task.",
"priority": "high",
"dependencies": [
"117"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "119",
"title": "Add CodeRepo Prisma model",
"description": "Add CodeRepo model to schema.prisma for git repository management within projects",
"details": "In src/db/prisma/schema.prisma add:\n1. model CodeRepo with: id, name, projectId, url, defaultBranch (@default(\"main\")), path (@default(\"\")), provider (@default(\"gitea\")), credSecretId?, credSecretKey?, ownerId, version, createdAt, updatedAt\n2. Relations: project (Project), cred (Secret?), owner (User), tasks (Task[])\n3. @@unique([name, projectId]), @@index([projectId])\n4. Add repos CodeRepo[] relation to Project model\n5. Add codeRepos CodeRepo[] relation to Secret model\n6. Add ownedRepos CodeRepo[] relation to User model",
"testStrategy": "Schema tests: create CodeRepo linked to Project, verify unique constraint on (name, projectId), test cascade delete from Project, test SetNull behavior when Secret is deleted.",
"priority": "high",
"dependencies": [],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "120",
"title": "Add AgentProject junction model",
"description": "Add AgentProject many-to-many junction table linking Agents to Projects with role and optional LLM override",
"details": "In src/db/prisma/schema.prisma add:\n1. model AgentProject with: id, agentId, projectId, role (@default(\"developer\")), llmId?, createdAt\n2. Relations: agent (Agent), project (Project), llm (Llm?)\n3. @@unique([agentId, projectId]), @@index([agentId]), @@index([projectId])\n4. Add projectMemberships AgentProject[] to Agent model\n5. Add agentMemberships AgentProject[] to Project model\n6. Add agentProjects AgentProject[] to Llm model\n7. Keep Agent.projectId for backward compatibility (one release)",
"testStrategy": "Schema tests: create AgentProject junction, verify unique constraint prevents duplicate membership, test cascade on both Agent and Project delete, test SetNull on Llm delete.",
"priority": "high",
"dependencies": [],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "121",
"title": "Add AgentSession Prisma model",
"description": "Add AgentSession model with SessionState enum for ephemeral per-session pod tracking",
"details": "In src/db/prisma/schema.prisma add:\n1. enum SessionState { pending, provisioning, running, ended, failed }\n2. model AgentSession with: id, agentId, projectId, taskId?, containerId?, state, image, expiresAt, lastError? (@db.Text), ownerId, createdAt, updatedAt, endedAt?\n3. Relations: agent (Agent), project (Project), task (Task?), owner (User)\n4. @@index([state]), @@index([taskId]), @@index([agentId])\n5. Add sessions AgentSession[] to Agent, Project, Task, User models",
"testStrategy": "Schema tests: create AgentSession with all relations, test cascade on Agent/Project delete, test SetNull on Task delete, verify state enum transitions.",
"priority": "high",
"dependencies": [
"118",
"120"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "122",
"title": "Update clearAllTables test helper",
"description": "Add deleteMany calls for all new models to clearAllTables in src/db/tests/helpers.ts",
"details": "In src/db/tests/helpers.ts clearAllTables function:\n1. Add deleteMany for TaskEvent (child first)\n2. Add deleteMany for TaskVerdict\n3. Add deleteMany for AgentSession\n4. Add deleteMany for Task\n5. Add deleteMany for EpicTaskEdge\n6. Add deleteMany for EpicTask\n7. Add deleteMany for Epic\n8. Add deleteMany for CodeRepo\n9. Add deleteMany for AgentProject\n10. Order matters: delete children before parents to avoid FK violations\n11. Follow existing pattern in the file",
"testStrategy": "Run existing test suite to verify clearAllTables works correctly with new models. Add explicit test that creates rows in all new tables then calls clearAllTables and verifies tables are empty.",
"priority": "high",
"dependencies": [
"117",
"118",
"119",
"120",
"121"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "123",
"title": "Epic repository layer",
"description": "Create EpicRepository in src/mcpd/src/repositories/ following existing repository patterns",
"details": "Create src/mcpd/src/repositories/epic.repository.ts:\n1. Export EpicRepository class following agent.repository.ts pattern\n2. Methods: create, findById, findByName, findByProjectId, findAll, update, delete\n3. update must increment version (optimistic concurrency)\n4. Include relations in queries where needed (epicTasks, project, owner)\n5. Add type exports for CreateEpicData, UpdateEpicData\n6. Register in repository index file",
"testStrategy": "Unit tests in src/mcpd/tests/repositories/: test CRUD operations, test optimistic concurrency version increment, test findByProjectId filtering, test cascade behavior.",
"priority": "medium",
"dependencies": [
"117"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "124",
"title": "Epic service layer with revision integration",
"description": "Create EpicService with CRUD operations, revision tracking via ResourceRevision, and done-criteria roll-up logic",
"details": "Create src/mcpd/src/services/epic.service.ts:\n1. Inject EpicRepository, ResourceRevisionRepository, ProjectRepository\n2. create(): validate project exists, create Epic, create initial ResourceRevision with resourceType:'epic'\n3. update(): bump semver, create ResourceRevision, update currentRevisionId\n4. getById(), getByName(), listByProject()\n5. addTradeoff(): append to acceptedTradeoffs JSON array\n6. computeStatus(): roll up EpicTask completion to determine if Epic is delivered/delivered_with_tradeoffs\n7. getRoadmap(): return epictask graph with per-node completeness percentages\n8. Follow PromptService pattern for revision integration",
"testStrategy": "Unit tests: test create writes revision, test update bumps semver and writes revision, test addTradeoff appends correctly, test computeStatus logic for all EpicStatus values.",
"priority": "medium",
"dependencies": [
"123"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "125",
"title": "Epic zod validation schemas",
"description": "Create Epic validation schemas in src/mcpd/src/validation/ for request/response validation",
"details": "Create src/mcpd/src/validation/epic.schema.ts:\n1. DoneCriterionSchema: z.object({ id: z.string(), text: z.string(), kind: z.enum(['outcome', 'quality']), met: z.boolean() })\n2. AcceptedTradeoffSchema: z.object({ what: z.string(), why: z.string(), who: z.string(), deScopedBy: z.string().optional(), at: z.string() })\n3. CreateEpicSchema: name, content, doneCriteria (array), projectId or project (name), description optional\n4. UpdateEpicSchema: partial of create fields plus status\n5. EpicResponseSchema for API responses\n6. Follow prompt.schema.ts patterns",
"testStrategy": "Unit tests: validate CreateEpicSchema accepts valid input, rejects missing required fields, validates doneCriteria array structure, validates status enum values.",
"priority": "medium",
"dependencies": [
"117"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "126",
"title": "Epic routes and API endpoints",
"description": "Create Epic routes in src/mcpd/src/routes/ with CRUD endpoints plus roadmap and tradeoffs",
"details": "Create src/mcpd/src/routes/epic.routes.ts:\n1. GET /api/v1/epics - list with ?project=<name> filter\n2. POST /api/v1/epics - create, resolve project name to id\n3. GET /api/v1/epics/:id - get by id\n4. PUT /api/v1/epics/:id - update\n5. DELETE /api/v1/epics/:id - delete\n6. GET /api/v1/epics/:id/roadmap - return epictask graph with completeness\n7. POST /api/v1/epics/:id/tradeoffs - append accepted tradeoff\n8. Register routes in main.ts\n9. Follow agent-routes.ts pattern for auth and validation",
"testStrategy": "Route tests in src/mcpd/tests/routes/: test CRUD endpoints, test project name resolution, test roadmap returns graph structure, test tradeoffs append correctly.",
"priority": "medium",
"dependencies": [
"124",
"125"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "127",
"title": "EpicTask repository and service layers",
"description": "Create EpicTaskRepository and EpicTaskService with edge graph management and cycle detection",
"details": "Create src/mcpd/src/repositories/epic-task.repository.ts and src/mcpd/src/services/epic-task.service.ts:\n1. Repository: CRUD for EpicTask, edge CRUD for EpicTaskEdge, findByEpicId\n2. Service.addEdge(): before creating edge, walk toId's transitive dependencies (via dependsOn edges), reject if fromId is reachable (cycle detection)\n3. Service.removeEdge(): simple delete\n4. Service.getGraph(): return nodes with edges for visualization\n5. Service.computeCompleteness(): calculate percentage of doneCriteria met per node\n6. Follow existing repository/service patterns",
"testStrategy": "Unit tests: test edge creation, test cycle detection rejects A→B→C→A, test completeness calculation with mixed met/unmet criteria, test transitive dependency walk.",
"priority": "medium",
"dependencies": [
"117",
"123"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "128",
"title": "EpicTask routes and API endpoints",
"description": "Create EpicTask routes with CRUD and edge management endpoints",
"details": "Create src/mcpd/src/routes/epic-task.routes.ts:\n1. GET /api/v1/epictasks - list with ?epic=<name>&project=<name> filters\n2. POST /api/v1/epictasks - create\n3. GET /api/v1/epictasks/:id - get\n4. PUT /api/v1/epictasks/:id - update\n5. DELETE /api/v1/epictasks/:id - delete\n6. POST /api/v1/epictasks/:id/edges - add dependency edge { toId }\n7. DELETE /api/v1/epictasks/:id/edges - remove edge { toId }\n8. Register in main.ts",
"testStrategy": "Route tests: test CRUD, test edge creation returns error on cycle, test edge deletion, test filters work correctly.",
"priority": "medium",
"dependencies": [
"127"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "129",
"title": "Task repository with compare-and-swap transitions",
"description": "Create TaskRepository with optimistic locking state transitions using updateMany with where clause",
"details": "Create src/mcpd/src/repositories/task.repository.ts:\n1. Standard CRUD methods following existing patterns\n2. transition(id, fromState, toState): use prisma.task.updateMany({ where: { id, state: fromState }, data: { state: toState, version: { increment: 1 } } }), return affected count\n3. If affected count is 0, the transition failed (race or wrong state)\n4. findByFilters(): support epicTaskId, state, assigneeId filters\n5. Include verdict and event relations where appropriate",
"testStrategy": "Unit tests: test transition succeeds when state matches, test transition returns 0 when state doesn't match (simulating race), test concurrent transitions only one wins.",
"priority": "medium",
"dependencies": [
"118"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "130",
"title": "Task service with lifecycle state machine",
"description": "Create TaskService implementing the full task lifecycle with transition guards and event logging",
"details": "Create src/mcpd/src/services/task.service.ts:\n1. Define VALID_TRANSITIONS map: { [fromState]: [allowedToStates] } based on PRD lifecycle diagram\n2. transition(id, toState, actorType, actorId, note): check transition is valid, call repo.transition, if success create TaskEvent, return result\n3. assign(id, agentId): set assigneeId\n4. recordVerdict(id, stage, agentId, commit, passed, summary, findings): create TaskVerdict, if failed transition back to in_progress\n5. accept(id, userId, note): transition to merged, trigger merge via GitProvider\n6. reject(id, userId, note): transition to in_progress\n7. reopenOnPostMergeFailure(id): transition merged→reopened",
"testStrategy": "Unit tests: test all valid transitions succeed, test invalid transitions throw, test TaskEvent created on every transition, test verdict creation, test accept triggers merge.",
"priority": "medium",
"dependencies": [
"129"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "131",
"title": "Task routes and API endpoints",
"description": "Create Task routes with CRUD, transition, verdict, accept/reject, and events endpoints",
"details": "Create src/mcpd/src/routes/task.routes.ts:\n1. GET /api/v1/tasks - list with ?project=&epictask=&state=&assignee= filters\n2. POST /api/v1/tasks - create\n3. GET /api/v1/tasks/:id - get\n4. PUT /api/v1/tasks/:id - update\n5. DELETE /api/v1/tasks/:id - delete\n6. POST /api/v1/tasks/:id/transition - { toState, note? }\n7. POST /api/v1/tasks/:id/verdict - record QA/Security/SRE verdict\n8. POST /api/v1/tasks/:id/accept - { note? } human gate → merge\n9. POST /api/v1/tasks/:id/reject - { note } → back to in_progress\n10. GET /api/v1/tasks/:id/events - list TaskEvents\n11. Register in main.ts",
"testStrategy": "Route tests: test CRUD, test transition endpoint, test verdict recording, test accept triggers merge, test reject changes state, test events returns ordered list.",
"priority": "medium",
"dependencies": [
"130"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "132",
"title": "CodeRepo repository and service layers",
"description": "Create CodeRepoRepository and CodeRepoService with credential resolution through SecretService",
"details": "Create src/mcpd/src/repositories/code-repo.repository.ts and src/mcpd/src/services/code-repo.service.ts:\n1. Repository: standard CRUD, findByProjectId\n2. Service.create(): validate project exists, validate credSecretId/Key if provided\n3. Service.resolveCredentials(repoId): fetch Secret via SecretService, extract the key, return credential (never store plaintext)\n4. Service.update(): validate changes\n5. Service.delete(): check no active sessions reference this repo\n6. Follow existing service patterns for validation",
"testStrategy": "Unit tests: test create with valid project, test credential resolution returns correct value, test create fails with invalid secret reference, test findByProjectId returns filtered list.",
"priority": "medium",
"dependencies": [
"119"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "133",
"title": "CodeRepo routes and API endpoints",
"description": "Create CodeRepo routes with CRUD endpoints",
"details": "Create src/mcpd/src/routes/code-repo.routes.ts:\n1. GET /api/v1/repos - list with ?project=<name> filter\n2. POST /api/v1/repos - create, resolve project name\n3. GET /api/v1/repos/:id - get (credential fields return references, not values)\n4. PUT /api/v1/repos/:id - update\n5. DELETE /api/v1/repos/:id - delete\n6. Register in main.ts\n7. Ensure credentials are never exposed in responses",
"testStrategy": "Route tests: test CRUD, test project filter, test response does not include credential values, test delete succeeds when no sessions reference repo.",
"priority": "medium",
"dependencies": [
"132"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "134",
"title": "RBAC wiring for new resources",
"description": "Update mapUrlToPermission and nameResolvers in main.ts for epics, epictasks, tasks, repos, sessions",
"details": "In src/mcpd/src/main.ts:\n1. Add to mapUrlToPermission cases: epics, epictasks, tasks, repos, sessions\n2. Map /api/v1/inference-tasks to 'inference-tasks' resource\n3. Add non-CRUD verb cases above the map:\n - POST /tasks/:id/accept|reject|transition → run:tasks:<name>\n - POST /sessions/:id/exec, GET /sessions/:id/attach → run:sessions:<name>\n4. Add nameResolvers for epics, epictasks, tasks, repos, sessions (fetch by id, return name for scoped grants)\n5. Follow existing patterns for permission mapping",
"testStrategy": "Unit tests: verify mapUrlToPermission returns correct permission strings for all new routes, test nameResolvers resolve id→name correctly, test non-CRUD verbs get run: prefix.",
"priority": "medium",
"dependencies": [
"115",
"126",
"128",
"131",
"133"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "135",
"title": "Backup and YAML kinds for new resources",
"description": "Add new resources to BACKUP_KINDS, APPLY_ORDER, kindMap, and export/import loops",
"details": "Update backup/apply infrastructure:\n1. Add 'Epic', 'EpicTask', 'Task', 'CodeRepo' to BACKUP_KINDS array\n2. Update APPLY_ORDER for correct dependency ordering (Epic before EpicTask before Task)\n3. Add to kindMap: { Epic: 'epics', EpicTask: 'epictasks', Task: 'tasks', CodeRepo: 'repos' }\n4. Update serializeResource for each new kind\n5. Update kindFromSegment in main.ts import handler\n6. Update importResource for create/update logic per kind\n7. Update deleteResource for each kind\n8. Fix existing gap: add 'skill' to importResource/deleteResource if missing",
"testStrategy": "Integration tests: test backup exports all new resource types, test apply imports Epic→EpicTask→Task in correct order, test round-trip export→import preserves data.",
"priority": "medium",
"dependencies": [
"126",
"128",
"131",
"133"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "136",
"title": "CLI get columns and describe formatters for new resources",
"description": "Add column definitions and describe formatters for epics, epictasks, tasks, repos, sessions in CLI",
"details": "In src/cli/src/commands/get.ts:\n1. Add row interfaces: EpicRow, EpicTaskRow, TaskRow, CodeRepoRow, AgentSessionRow\n2. Add to getColumnsForResource for each: define column names, widths, formatters\n3. Add to RESOURCE_KIND map: epics→Epic, epictasks→EpicTask, tasks→Task, repos→CodeRepo, sessions→AgentSession\n4. Add to toApplyDocs strip blocks\n\nIn src/cli/src/commands/describe.ts:\n5. Add describe handlers with clean sections and tables (not key-value dumps)\n6. For Epic: show roadmap section with epictask names and completeness\n7. For Task: show lifecycle state, assignee, PR link if present",
"testStrategy": "Unit tests: test getColumnsForResource returns correct columns for each resource, test describe output formatting matches expected structure.",
"priority": "medium",
"dependencies": [
"126",
"128",
"131",
"133"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "137",
"title": "CLI create subcommands for new resources",
"description": "Add create subcommands for epic, epictask, task, repo with all settable fields as flags",
"details": "In src/cli/src/commands/create.ts:\n1. Add 'epic' subcommand: --name, --project, --content, --done-criteria (JSON), --description\n2. Add 'epictask' subcommand: --name, --epic, --project, --done-criteria, --description, --depends-on (comma-separated names)\n3. Add 'task' subcommand: --name, --title, --epictask, --epic, --project, --description, --risk, --repo\n4. Add 'repo' subcommand: --name, --project, --url, --default-branch, --path, --provider, --cred-secret, --cred-key\n5. Every field settable in apply must have a corresponding flag\n6. Follow existing create subcommand patterns",
"testStrategy": "Unit tests: test each create subcommand parses all flags correctly, test required flags are enforced, test API calls are made with correct payload.",
"priority": "medium",
"dependencies": [
"136"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "138",
"title": "CLI apply and edit support for new resources",
"description": "Add new resources to apply -f spec schemas and edit validResources",
"details": "In src/cli/src/commands/apply.ts:\n1. Add spec schemas: EpicSpecSchema, EpicTaskSpecSchema, TaskSpecSchema, CodeRepoSpecSchema\n2. Add to ApplyConfigSchema discriminated union\n3. Add to KIND_TO_RESOURCE map\n4. Update dry-run counts for new resources\n5. Add apply loops handling create/update for each resource\n\nIn src/cli/src/commands/edit.ts:\n6. Add 'epic', 'epictask', 'task', 'repo' to validResources array",
"testStrategy": "Unit tests: test apply parses valid YAML for each new kind, test get -o yaml → apply -f round-trip for each resource type.",
"priority": "medium",
"dependencies": [
"137"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "139",
"title": "CLI shell completions for new resources",
"description": "Update completion generation for new resource names and aliases",
"details": "In scripts/generate-completions.ts:\n1. Add to CANONICAL_RESOURCES: 'epics', 'epictasks', 'tasks', 'repos', 'sessions'\n2. Add to ALIAS_ENTRIES: epic→epics, epictask→epictasks, et→epictasks, task→tasks, repo→repos, repository→repos, repositories→repos, session→sessions\n3. Run pnpm completions:generate to regenerate completion scripts\n4. Completions are generated, never hand-edited\n\nIn src/cli/tests/completions.test.ts:\n5. Test assertions already run generator with --check, will fail on drift automatically",
"testStrategy": "Run completions.test.ts which validates generated completions match source of truth. Manual test: source completions in shell, verify tab-completion works for new resources.",
"priority": "low",
"dependencies": [
"138"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "140",
"title": "Extend ContainerSpec for ephemeral pods",
"description": "Add restartPolicy, workdir, volumes, and initContainers to ContainerSpec interface",
"details": "In src/mcpd/src/services/orchestrator.ts:\n1. Add to ContainerSpec interface:\n - restartPolicy?: 'Always' | 'Never' | 'OnFailure'\n - workdir?: string\n - volumes?: Array<{ name: string; mountPath: string; kind: 'emptyDir' }>\n - initContainers?: Array<{ name: string; image: string; command: string[]; env?: Record<string, string>; volumeMounts?: Array<{ name: string; mountPath: string }> }>\n2. These enable ephemeral session pods with workspace volumes and repo-clone init containers",
"testStrategy": "Type tests: verify ContainerSpec accepts all new optional fields, verify existing code still compiles without providing new fields.",
"priority": "high",
"dependencies": [],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "141",
"title": "Kubernetes orchestrator ephemeral pod support",
"description": "Update KubernetesOrchestrator to handle new ContainerSpec fields in generatePodSpec",
"details": "In src/mcpd/src/services/k8s/manifest-generator.ts and KubernetesOrchestrator:\n1. Update generatePodSpec to use spec.restartPolicy if provided (default 'Always' unchanged)\n2. Add workingDir to container spec if workdir provided\n3. Add volumes array for emptyDir volumes\n4. Add volumeMounts to main container\n5. Add initContainers array with their own volumeMounts\n6. Ensure init containers complete before main container starts (Kubernetes handles this)",
"testStrategy": "Unit tests: test generatePodSpec output includes restartPolicy, volumes, initContainers when provided. Integration test against test cluster: create pod with init container, verify init completes before main starts.",
"priority": "high",
"dependencies": [
"140"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "142",
"title": "Docker orchestrator ephemeral container support",
"description": "Update DockerContainerManager to handle new ContainerSpec fields",
"details": "In DockerContainerManager (src/mcpd/src/services/docker/):\n1. Map restartPolicy to Docker restart policy\n2. Set WorkingDir in container config\n3. Create volumes as Docker volumes, add Binds/Mounts\n4. For initContainers: run each sequentially before main container, fail if any init fails\n5. Docker doesn't have native init container support, so implement as sequential container runs that populate shared volume",
"testStrategy": "Unit tests: test container spec translation. Integration test: create container with init, verify volume populated before main container runs.",
"priority": "medium",
"dependencies": [
"140"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "143",
"title": "SessionService for pod provisioning and lifecycle",
"description": "Create SessionService handling AgentSession creation, repo-clone init container, credential resolution, and GC sweep",
"details": "Create src/mcpd/src/services/session.service.ts:\n1. create(agentId, projectId, taskId?, image, expiresAt): create AgentSession row in pending state\n2. provision(sessionId): resolve project's CodeRepo list, resolve credentials via SecretService (fail on resolution error like InstanceService.attemptStart), build ContainerSpec with init container that clones repos to workspace volume, create pod via orchestrator, transition to running\n3. end(sessionId): stop container, mark ended\n4. getById(), listByFilters()\n5. GC sweep: find sessions where now() > expiresAt, stop containers, mark ended. Run in same style as inference-task sweep in main.ts\n6. Note: assumes single mcpd replica (no leader election)",
"testStrategy": "Unit tests: test provision builds correct init container command, test credential resolution failure aborts provision, test GC sweep marks expired sessions ended.",
"priority": "high",
"dependencies": [
"121",
"132",
"141",
"142"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "144",
"title": "Session routes and exec/attach endpoints",
"description": "Create Session routes with CRUD, one-shot exec, and WebSocket attach endpoints",
"details": "Create src/mcpd/src/routes/session.routes.ts:\n1. GET /api/v1/sessions - list with ?project=&agent=&task= filters\n2. POST /api/v1/sessions - create and provision\n3. GET /api/v1/sessions/:id - get\n4. DELETE /api/v1/sessions/:id - end session\n5. POST /api/v1/sessions/:id/exec - one-shot exec, body: { command: string[] }, returns { exitCode, stdout, stderr }\n6. GET /api/v1/sessions/:id/attach - WebSocket upgrade, bidirectional stdio with terminal resize and exit code propagation\n7. Use existing execInContainer, attachInteractive from orchestrator\n8. Register in main.ts",
"testStrategy": "Route tests: test CRUD, test exec returns command output, test attach upgrades to WebSocket. Integration: exec 'echo hello' in session pod, verify output.",
"priority": "high",
"dependencies": [
"143"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "145",
"title": "CLI exec command",
"description": "Add mcpctl exec --project NAME AGENT -- command for interactive session access",
"details": "In src/cli/src/commands/ add exec.ts or extend existing:\n1. Parse: mcpctl exec --project NAME AGENT -- command args\n2. Find or create AgentSession for agent in project\n3. If command provided: call POST /sessions/:id/exec, print output\n4. If no command (or -- bash): attach via WebSocket to /sessions/:id/attach\n5. Handle terminal resize (SIGWINCH), pass to WebSocket\n6. Propagate exit code from session\n7. Per design doc: exec drops human into working environment (cloned repos), NOT the agent's reasoning loop",
"testStrategy": "Manual testing: mcpctl exec --project test myagent -- ls should list repo contents. mcpctl exec --project test myagent -- bash should give interactive shell.",
"priority": "medium",
"dependencies": [
"144"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "146",
"title": "AgentRuntime interface definition",
"description": "Define AgentRuntime adapter interface for swappable agent implementations",
"details": "Create src/mcpd/src/services/agent-runtime.ts:\n1. Define RuntimeSessionOpts: { agentId, projectId, taskId?, image, persona (prompt files) }\n2. Define RuntimeStatus: 'starting' | 'running' | 'completed' | 'failed'\n3. Define RuntimeResult: { branch: string, headCommit: string, summary: string, prUrl?: string }\n4. Define AgentRuntime interface:\n - startSession(opts: RuntimeSessionOpts): Promise<{ sessionId: string }>\n - send(sessionId: string, message: string): Promise<void>\n - status(sessionId: string): Promise<RuntimeStatus>\n - result(sessionId: string): Promise<RuntimeResult>\n - endSession(sessionId: string): Promise<void>\n5. This is an interface, not an implementation - allows swapping runtimes later",
"testStrategy": "Type tests: verify interface can be implemented, verify all methods have correct signatures.",
"priority": "medium",
"dependencies": [],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "147",
"title": "Headless coding agent runtime adapter",
"description": "Implement AgentRuntime adapter that runs a headless coding agent inside the session pod",
"details": "Create src/mcpd/src/services/agent-runtime/headless-adapter.ts:\n1. Implement AgentRuntime interface\n2. startSession: create AgentSession, provision pod with coding agent image, inject persona as prompt files in container\n3. send: exec into container to send message to agent process (implementation depends on chosen agent's IPC)\n4. status: check agent process state via exec or container status\n5. result: read agent output (branch, commit, summary) from known output location\n6. endSession: stop container, update session state\n7. The coding agent handles git, branching, MCP tools, streaming internally\n8. Persona delivered via mounted files the agent reads",
"testStrategy": "Integration tests against test cluster: start session, send simple task, verify branch created and pushed.",
"priority": "medium",
"dependencies": [
"143",
"146"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "148",
"title": "GitProvider interface and Gitea driver",
"description": "Create GitProvider interface and Gitea implementation for PR creation, status check, and merge",
"details": "Create src/mcpd/src/services/git-provider.ts and src/mcpd/src/services/git-provider/gitea.ts:\n1. GitProvider interface: createPullRequest(repo, branch, title, body), getPullRequest(repo, prNumber), getCombinedStatus(repo, ref), mergePullRequest(repo, prNumber, method?)\n2. Gitea driver: implement using Gitea API v1\n - POST /api/v1/repos/:owner/:repo/pulls for createPullRequest\n - GET /api/v1/repos/:owner/:repo/pulls/:id for getPullRequest\n - GET /api/v1/repos/:owner/:repo/commits/:sha/status for getCombinedStatus\n - POST /api/v1/repos/:owner/:repo/pulls/:id/merge for mergePullRequest\n3. Credentials resolved from CodeRepo's Secret via SecretService\n4. Reference pr.sh script for endpoint shapes",
"testStrategy": "Unit tests with mocked HTTP: test each method sends correct request, handles success/error responses. Integration test against local Gitea instance if available.",
"priority": "high",
"dependencies": [
"132"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "149",
"title": "Task PR linkage and human accept gate",
"description": "Integrate GitProvider into TaskService for PR creation on push and merge on accept",
"details": "Update src/mcpd/src/services/task.service.ts:\n1. linkPR(taskId, branch, headCommit): create PR via GitProvider, update Task with prUrl, prNumber\n2. accept(taskId, userId, note):\n - Verify task is in awaiting_review state\n - Check PR combined status is success (optional gate based on project config)\n - Call gitProvider.mergePullRequest\n - Transition to merged state\n - Create TaskEvent\n3. If merge fails, keep in awaiting_review, surface error\n4. reject: transition to in_progress, clear PR linkage or keep for reference",
"testStrategy": "Unit tests: test linkPR updates task fields, test accept calls merge API, test accept fails if PR status is failing.",
"priority": "high",
"dependencies": [
"130",
"148"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "150",
"title": "QA/Security/SRE stage verdicts",
"description": "Implement risk-scaled verification stages that record commit-pinned verdicts",
"details": "Update TaskService:\n1. recordVerdict(taskId, stage, agentId, commit, passed, summary, findings): create TaskVerdict row\n2. If !passed: transition task back to in_progress, create TaskEvent explaining why\n3. Determine required stages based on Task.risk:\n - trivial: may pass on light self-check (no mandatory QA/Security/SRE)\n - normal: requires qa_review\n - high: requires qa_review + security_review + sre_review\n4. Verdicts are immutable - append only, pinned to commit SHA\n5. Each stage persona decides its own depth (not enforced in code, just recorded)\n6. Transition to done only when all required stages have passing verdicts for current headCommit",
"testStrategy": "Unit tests: test verdict creation, test failed verdict transitions back to in_progress, test risk-based stage requirements.",
"priority": "medium",
"dependencies": [
"130"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "151",
"title": "Git webhook receiver for post-merge failure",
"description": "Create webhook endpoint that reopens tasks when post-merge CI fails",
"details": "Create src/mcpd/src/routes/webhook.routes.ts:\n1. POST /api/v1/webhooks/git/:provider - receive webhook payloads\n2. Validate webhook signature using provider-specific method (Gitea uses HMAC-SHA256 with secret)\n3. Parse payload to identify: repo, commit SHA, status (success/failure/pending)\n4. If status is failure for a merged commit:\n - Find Task with that headCommit and state=merged\n - Call taskService.reopenOnPostMergeFailure(taskId)\n - This transitions merged→reopened and creates TaskEvent\n5. Register route in main.ts\n6. Webhook secret stored in CodeRepo's credential secret",
"testStrategy": "Unit tests: test signature validation, test payload parsing, test reopen triggered on failure status. Integration: simulate Gitea webhook payload.",
"priority": "medium",
"dependencies": [
"130",
"148"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "152",
"title": "Agent membership routes",
"description": "Create API endpoints for managing agent-project memberships",
"details": "Add to existing agent routes or create new file:\n1. GET /api/v1/agents/:name/projects - list projects agent belongs to\n2. POST /api/v1/agents/:name/projects/:project - add membership { role?, llm? }\n3. DELETE /api/v1/agents/:name/projects/:project - remove membership\n4. GET /api/v1/projects/:name/agents - list agents in project\n5. Keep Agent.projectId in sync when membership added/removed (backward compat for one release)\n6. Follow existing route patterns",
"testStrategy": "Route tests: test add membership creates junction row, test remove deletes it, test list returns correct memberships.",
"priority": "medium",
"dependencies": [
"120"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "153",
"title": "CLI tasks accept and reject commands",
"description": "Add mcpctl tasks accept and reject commands for human approval gate",
"details": "In src/cli/src/commands/ add or extend:\n1. mcpctl tasks accept NAME [--note TEXT] - call POST /tasks/:id/accept, triggers merge\n2. mcpctl tasks reject NAME --note TEXT - call POST /tasks/:id/reject, note required\n3. Resolve task name to id via API\n4. Print result: merge URL on success, error message on failure\n5. Accept should not require going to git - the CLI is the approval surface",
"testStrategy": "Unit tests: test accept sends correct API call, test reject requires note flag, test output formatting.",
"priority": "medium",
"dependencies": [
"131",
"149"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "154",
"title": "Documentation for new resources",
"description": "Create docs for epics, tasks, repos, sessions and update README and CLAUDE.md",
"details": "Create documentation files:\n1. docs/epics.md - Epic/EpicTask concepts, CLI usage, API reference\n2. docs/tasks.md - Task lifecycle, states, transitions, verdicts\n3. docs/repos.md - CodeRepo configuration, credential setup\n4. docs/sessions.md - AgentSession lifecycle, exec usage\n5. docs/inference-tasks.md - document the rename from 'tasks' RBAC resource\n6. Update README.md resources table with new resources\n7. Update CLAUDE.md resource cheatsheet with new resources",
"testStrategy": "Manual review: verify docs are accurate, CLI examples work, API endpoints match implementation.",
"priority": "low",
"dependencies": [
"126",
"128",
"131",
"133",
"144",
"152"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "155",
"title": "Smoke tests for Epic/EpicTask/Task CRUD",
"description": "Create smoke tests for vision layer resources against live mcpd",
"details": "Create src/mcplocal/tests/smoke/epic.smoke.test.ts:\n1. Follow personality.smoke.test.ts pattern: Date.now().toString(36) name suffix, healthz() preflight that skips when daemon unreachable, mcpctl --direct shelling, explicit afterAll cleanup\n2. Test Epic create/list/describe/delete\n3. Test EpicTask create with edge dependencies\n4. Test Task create linked to EpicTask\n5. Verify cascade: delete Epic removes EpicTasks and Tasks\n6. When test fails, fix environment not assertion",
"testStrategy": "Run against live mcpd instance. Tests self-document expected behavior.",
"priority": "medium",
"dependencies": [
"126",
"128",
"131"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "156",
"title": "Smoke tests for CodeRepo and Session",
"description": "Create smoke tests for repo and session resources with credential resolution",
"details": "Create src/mcplocal/tests/smoke/repo.smoke.test.ts and session.smoke.test.ts:\n1. repo tests: create CodeRepo with credential reference, list, describe, delete\n2. session tests: provision session pod, confirm repo cloned via exec, verify workspace mounted, verify pod reaped after expiry\n3. Follow smoke test patterns: preflight skip, cleanup in afterAll\n4. Session test requires real cluster access",
"testStrategy": "Run against live mcpd with cluster access. Verify repo credentials resolve, session pod starts and has cloned repos.",
"priority": "medium",
"dependencies": [
"133",
"144"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "157",
"title": "Smoke test for task lifecycle transitions",
"description": "Create smoke test driving a task through full lifecycle including rejected accept-gate bounce",
"details": "Create src/mcplocal/tests/smoke/task-lifecycle.smoke.test.ts:\n1. Create Epic → EpicTask → Task\n2. Transition task: todo → in_progress → building → self_testing → qa_review → done → awaiting_review\n3. Test reject: awaiting_review → in_progress\n4. Advance again to awaiting_review\n5. Test accept: verify merge called (may need mock git provider for smoke)\n6. Verify TaskEvents recorded for all transitions\n7. Follow smoke test patterns",
"testStrategy": "Run against live mcpd. Verify each transition succeeds, events logged, reject bounces state correctly.",
"priority": "medium",
"dependencies": [
"131",
"149",
"153"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "158",
"title": "Deferred: Tier-2 vision critic placeholder",
"description": "Placeholder task for Tier-2 vision critic and Epic-comparison loop - blocked on design questions",
"details": "DEFERRED - DO NOT IMPLEMENT YET\n\nBlocked on docs/agentic-teams.md §15 Q13: does this need render/screenshot infrastructure, or can a design-aware persona judge from a structured artifact?\n\nConcept: A review-only, non-executing design/product persona that judges the assembled result against the Epic in its native medium, producing reopen / new-task / exec outcomes.\n\nExpand this task when the blocking design question is answered.",
"testStrategy": "N/A - placeholder only",
"priority": "low",
"dependencies": [
"131",
"149"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "159",
"title": "Deferred: Collaboration modes placeholder",
"description": "Placeholder task for async standup and exec joint sessions - blocked on design questions",
"details": "DEFERRED - DO NOT IMPLEMENT YET\n\nBlocked on docs/agentic-teams.md §15 Q4 and Q5.\n\nConcepts:\n- mcpctl standup --project NAME: on-demand async standup\n- exec as a workflow rather than just a command\n\nExpand this task when the blocking design questions are answered.",
"testStrategy": "N/A - placeholder only",
"priority": "low",
"dependencies": [
"144",
"145"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "160",
"title": "Deferred: Confidence signal and escalation dashboard placeholder",
"description": "Placeholder task for evidence-anchored confidence and human decision queue - blocked on design questions",
"details": "DEFERRED - DO NOT IMPLEMENT YET\n\nBlocked on docs/agentic-teams.md §15 Q12: web / TUI / CLI?\n\nConcepts:\n- Evidence-anchored confidence: retrieve K similar past tasks with outcomes, assess confidence\n- Thresholds driving autonomy level\n- Single cross-project human decision queue\n- Retrieval quality is the crux - weak retrieval quietly poisons the model\n\nExpand this task when the blocking design question is answered.",
"testStrategy": "N/A - placeholder only",
"priority": "low",
"dependencies": [
"131",
"150"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "161",
"title": "Deferred: Per-agent memory and coverage ledger placeholder",
"description": "Placeholder task for agent memory and commit-pinned coverage ledger - blocked on design questions",
"details": "DEFERRED - DO NOT IMPLEMENT YET\n\nConcepts:\n- Global per-agent memory plus per-project knowledge\n- Commit-pinned coverage ledger enabling delta-verification\n- Non-negotiable: invalidation when covered region changes (or ledger becomes false confidence)\n- Trust boundary: ledger is platform-verified machine fact; agent prose notes are opinion, never the gate\n\nExpand this task when prerequisite infrastructure exists.",
"testStrategy": "N/A - placeholder only",
"priority": "low",
"dependencies": [
"147",
"150"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
},
{
"id": "162",
"title": "Deferred: Script artifacts and baseline scorecard placeholder",
"description": "Placeholder task for reusable script artifacts and baseline rules scorecard - blocked on design questions",
"details": "DEFERRED - DO NOT IMPLEMENT YET\n\nBlocked on docs/agentic-teams.md §15 Q15 and Q16.\n\nConcepts:\n- Reusable executable script artifacts at task, project, and agent scope\n- Provisioned baseline-rules scorecard\n- Watch incentive integrity risk: reward reused tools, not tool proliferation\n\nExpand this task when the blocking design questions are answered.",
"testStrategy": "N/A - placeholder only",
"priority": "low",
"dependencies": [
"147"
],
"status": "pending",
"subtasks": [],
"updatedAt": "2026-08-08T08:55:58.627Z"
}
],
"metadata": {
"version": "1.0.0",
"lastModified": "2026-03-07T23:36:15.981Z",
"taskCount": 114,
"completedCount": 96,
"tags": [
"master"
]
"created": "2026-08-08T08:54:31.861Z",
"updated": "2026-08-08T08:54:31.861Z",
"description": "Tasks for master context"
}
}
}