PBI-8: Sprint-flow MCP-orkestratie + verifier-fix

Schema sync vanaf upstream Scrum4Me (v77617e8): FAILED toegevoegd aan
Task/Story/Pbi/SprintStatus, nieuw SprintRunStatus + PrStrategy enums,
SprintRun model, ClaudeJob.sprint_run_id, Product.pr_strategy.

T-18 — propagateStatusUpwards in src/lib/tasks-status-update.ts.
Real-time cascade Task → Story → PBI → Sprint → SprintRun bij elke
task-statuswijziging. Bij FAILED cancelt sibling-jobs in dezelfde
SprintRun. PBI-status BLOCKED blijft handmatig. Houd deze helper bit-
voor-bit synchroon met Scrum4Me/lib/tasks-status-update.ts.
updateTaskStatusWithStoryPromotion blijft als BC-wrapper.

T-19 — wait-for-job.ts claim-filter. Task-jobs worden alleen geclaimd
als hun SprintRun status QUEUED of RUNNING heeft. Idea-jobs blijven
ongefilterd. Bij eerste claim van een QUEUED SprintRun → RUNNING
binnen dezelfde tx (race-safe).

T-20 — update-job-status.ts roept propagateStatusUpwards aan na elke
task DONE/FAILED. Bestaande cancelPbiOnFailure-aanroep blijft voor
PR-cleanup; sibling-cancellation overlap is harmless (idempotent).

T-21 — classify.ts (verifier) leest nu ook "--- a/<path>" zodat
delete-only commits niet meer als EMPTY worden geclassificeerd.
Bug had eerder geleid tot ten onrechte FAILED-status op cmotto5h en
cmotto5i (06-05-2026); zou met cascade-flow een hele sprint laten
falen.

Cleanup: create-todo.ts en open_todos in get-claude-context.ts
verwijderd (Todo-model is op main gedropt). Endpoint geeft nu
open_ideas terug — ideeën die niet PLANNED zijn.

Status-mappers (src/status.ts) uitgebreid met failed.

Tests: 184/184 groen (180 → 184; vier nieuwe delete-only classify-tests
en herwerkte propagate-status tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Madhura68 2026-05-06 16:59:58 +02:00
parent c63e2c6730
commit 5c5ae20f10
14 changed files with 627 additions and 238 deletions

View file

@ -9,7 +9,6 @@ import { registerUpdateTaskPlanTool } from './tools/update-task-plan.js'
import { registerLogImplementationTool } from './tools/log-implementation.js'
import { registerLogTestResultTool } from './tools/log-test-result.js'
import { registerLogCommitTool } from './tools/log-commit.js'
import { registerCreateTodoTool } from './tools/create-todo.js'
import { registerCreatePbiTool } from './tools/create-pbi.js'
import { registerCreateStoryTool } from './tools/create-story.js'
import { registerCreateTaskTool } from './tools/create-task.js'
@ -71,7 +70,6 @@ async function main() {
registerLogImplementationTool(server)
registerLogTestResultTool(server)
registerLogCommitTool(server)
registerCreateTodoTool(server)
registerCreatePbiTool(server)
registerCreateStoryTool(server)
registerCreateTaskTool(server)

View file

@ -1,9 +1,11 @@
import type { Prisma, TaskStatus } from '@prisma/client'
// **HOUD SYNC** met Scrum4Me/lib/tasks-status-update.ts.
// Beide repos delen dezelfde DB; deze helper moet bit-voor-bit gelijke
// statusovergangen produceren als de Scrum4Me-versie. Bij wijziging hier
// ook in de Scrum4Me-repo updaten en omgekeerd.
import type { Prisma, TaskStatus, StoryStatus, PbiStatus, SprintStatus } from '@prisma/client'
import { prisma } from '../prisma.js'
export type StoryStatusChange = 'promoted' | 'demoted' | null
export interface UpdateTaskStatusResult {
export interface PropagationResult {
task: {
id: string
title: string
@ -11,21 +13,33 @@ export interface UpdateTaskStatusResult {
story_id: string
implementation_plan: string | null
}
storyStatusChange: StoryStatusChange
storyId: string
storyChanged: boolean
pbiChanged: boolean
sprintChanged: boolean
sprintRunChanged: boolean
}
// Update task.status atomically and auto-promote/demote the parent story:
// - All sibling tasks DONE → story.status = DONE
// - Story was DONE and a task moves out of DONE → story.status = IN_SPRINT
// Demote target is IN_SPRINT (not OPEN): OPEN means "back in product backlog",
// which is a sprint-management action, not a status side-effect.
export async function updateTaskStatusWithStoryPromotion(
// Real-time status-propagatie: bij elke task-statuswijziging wordt de keten
// Task → Story → PBI → Sprint → SprintRun herevalueerd binnen één transactie.
//
// Regels:
// Story: ANY task FAILED → FAILED, ELSE ALL DONE → DONE,
// ELSE IN_SPRINT (mits story.sprint_id != null), anders OPEN
// PBI: ANY story FAILED → FAILED, ELSE ALL DONE → DONE, ELSE READY
// (BLOCKED is handmatig en wordt niet overschreven door deze helper)
// Sprint: ANY PBI van een story-in-sprint FAILED → FAILED,
// ELSE ALL PBIs van die stories DONE → COMPLETED,
// ELSE ACTIVE
// SprintRun: Sprint→FAILED → SprintRun=FAILED + cancel openstaand werk +
// zet failed_task_id; Sprint→COMPLETED → SprintRun=DONE; anders
// blijft SprintRun ongewijzigd.
export async function propagateStatusUpwards(
taskId: string,
newStatus: TaskStatus,
client?: Prisma.TransactionClient,
): Promise<UpdateTaskStatusResult> {
const run = async (tx: Prisma.TransactionClient): Promise<UpdateTaskStatusResult> => {
): Promise<PropagationResult> {
const run = async (tx: Prisma.TransactionClient): Promise<PropagationResult> => {
const task = await tx.task.update({
where: { id: taskId },
data: { status: newStatus },
@ -38,35 +52,199 @@ export async function updateTaskStatusWithStoryPromotion(
},
})
// Story herevalueren
const siblings = await tx.task.findMany({
where: { story_id: task.story_id },
select: { status: true },
})
const allDone = siblings.every((s) => s.status === 'DONE')
const anyTaskFailed = siblings.some((s) => s.status === 'FAILED')
const allTasksDone =
siblings.length > 0 && siblings.every((s) => s.status === 'DONE')
const story = await tx.story.findUniqueOrThrow({
where: { id: task.story_id },
select: { status: true },
select: { id: true, status: true, pbi_id: true, sprint_id: true },
})
let storyStatusChange: StoryStatusChange = null
if (newStatus === 'DONE' && allDone && story.status !== 'DONE') {
const defaultActive: StoryStatus = story.sprint_id ? 'IN_SPRINT' : 'OPEN'
let nextStoryStatus: StoryStatus
if (anyTaskFailed) nextStoryStatus = 'FAILED'
else if (allTasksDone) nextStoryStatus = 'DONE'
else nextStoryStatus = defaultActive
let storyChanged = false
if (nextStoryStatus !== story.status) {
await tx.story.update({
where: { id: task.story_id },
data: { status: 'DONE' },
where: { id: story.id },
data: { status: nextStoryStatus },
})
storyStatusChange = 'promoted'
} else if (newStatus !== 'DONE' && story.status === 'DONE') {
await tx.story.update({
where: { id: task.story_id },
data: { status: 'IN_SPRINT' },
})
storyStatusChange = 'demoted'
storyChanged = true
}
return { task, storyStatusChange, storyId: task.story_id }
// PBI herevalueren — BLOCKED met rust laten
const pbi = await tx.pbi.findUniqueOrThrow({
where: { id: story.pbi_id },
select: { id: true, status: true },
})
let pbiChanged = false
if (pbi.status !== 'BLOCKED') {
const pbiStories = await tx.story.findMany({
where: { pbi_id: pbi.id },
select: { status: true },
})
const anyStoryFailed = pbiStories.some((s) => s.status === 'FAILED')
const allStoriesDone =
pbiStories.length > 0 && pbiStories.every((s) => s.status === 'DONE')
let nextPbiStatus: PbiStatus
if (anyStoryFailed) nextPbiStatus = 'FAILED'
else if (allStoriesDone) nextPbiStatus = 'DONE'
else nextPbiStatus = 'READY'
if (nextPbiStatus !== pbi.status) {
await tx.pbi.update({
where: { id: pbi.id },
data: { status: nextPbiStatus },
})
pbiChanged = true
}
}
// Sprint herevalueren — alleen als deze story aan een sprint hangt
let sprintChanged = false
let nextSprintStatus: SprintStatus | null = null
if (story.sprint_id) {
const sprint = await tx.sprint.findUniqueOrThrow({
where: { id: story.sprint_id },
select: { id: true, status: true },
})
const sprintPbiRows = await tx.story.findMany({
where: { sprint_id: sprint.id },
select: { pbi_id: true },
distinct: ['pbi_id'],
})
const sprintPbis = await tx.pbi.findMany({
where: { id: { in: sprintPbiRows.map((s) => s.pbi_id) } },
select: { status: true },
})
const anyPbiFailed = sprintPbis.some((p) => p.status === 'FAILED')
const allPbisDone =
sprintPbis.length > 0 && sprintPbis.every((p) => p.status === 'DONE')
let nextStatus: SprintStatus
if (anyPbiFailed) nextStatus = 'FAILED'
else if (allPbisDone) nextStatus = 'COMPLETED'
else nextStatus = 'ACTIVE'
if (nextStatus !== sprint.status) {
await tx.sprint.update({
where: { id: sprint.id },
data: {
status: nextStatus,
...(nextStatus === 'COMPLETED' ? { completed_at: new Date() } : {}),
},
})
sprintChanged = true
nextSprintStatus = nextStatus
}
}
// SprintRun herevalueren — via ClaudeJob.sprint_run_id van deze task
let sprintRunChanged = false
if (nextSprintStatus === 'FAILED' || nextSprintStatus === 'COMPLETED') {
const job = await tx.claudeJob.findFirst({
where: { task_id: taskId, sprint_run_id: { not: null } },
orderBy: { created_at: 'desc' },
select: { id: true, sprint_run_id: true },
})
if (job?.sprint_run_id) {
const sprintRun = await tx.sprintRun.findUnique({
where: { id: job.sprint_run_id },
select: { id: true, status: true },
})
if (
sprintRun &&
(sprintRun.status === 'QUEUED' ||
sprintRun.status === 'RUNNING' ||
sprintRun.status === 'PAUSED')
) {
if (nextSprintStatus === 'FAILED') {
await tx.sprintRun.update({
where: { id: sprintRun.id },
data: {
status: 'FAILED',
finished_at: new Date(),
failed_task_id: taskId,
},
})
await tx.claudeJob.updateMany({
where: {
sprint_run_id: sprintRun.id,
status: { in: ['QUEUED', 'CLAIMED', 'RUNNING'] },
id: { not: job.id },
},
data: {
status: 'CANCELLED',
finished_at: new Date(),
error: `Cancelled: task ${taskId} failed in same sprint run`,
},
})
sprintRunChanged = true
} else {
// COMPLETED
await tx.sprintRun.update({
where: { id: sprintRun.id },
data: { status: 'DONE', finished_at: new Date() },
})
sprintRunChanged = true
}
}
}
}
return {
task,
storyId: task.story_id,
storyChanged,
pbiChanged,
sprintChanged,
sprintRunChanged,
}
}
if (client) return run(client)
return prisma.$transaction(run)
}
// ─── Backwards-compat wrapper ────────────────────────────────────────────────
// Bestaande tools (update-task-status, log-implementation, etc.) verwachten
// de oude { task, storyStatusChange, storyId } shape. We mappen storyChanged
// op promoted/demoted via een eenvoudige heuristiek op nieuwe TaskStatus.
export type StoryStatusChange = 'promoted' | 'demoted' | null
export interface UpdateTaskStatusResult {
task: PropagationResult['task']
storyStatusChange: StoryStatusChange
storyId: string
}
export async function updateTaskStatusWithStoryPromotion(
taskId: string,
newStatus: TaskStatus,
client?: Prisma.TransactionClient,
): Promise<UpdateTaskStatusResult> {
const result = await propagateStatusUpwards(taskId, newStatus, client)
let storyStatusChange: StoryStatusChange = null
if (result.storyChanged) {
storyStatusChange = newStatus === 'DONE' ? 'promoted' : 'demoted'
}
return {
task: result.task,
storyStatusChange,
storyId: result.storyId,
}
}

View file

@ -5,6 +5,7 @@ const TASK_DB_TO_API = {
IN_PROGRESS: 'in_progress',
REVIEW: 'review',
DONE: 'done',
FAILED: 'failed',
} as const satisfies Record<TaskStatus, string>
const TASK_API_TO_DB: Record<string, TaskStatus> = {
@ -12,18 +13,21 @@ const TASK_API_TO_DB: Record<string, TaskStatus> = {
in_progress: 'IN_PROGRESS',
review: 'REVIEW',
done: 'DONE',
failed: 'FAILED',
}
const STORY_DB_TO_API = {
OPEN: 'open',
IN_SPRINT: 'in_sprint',
DONE: 'done',
FAILED: 'failed',
} as const satisfies Record<StoryStatus, string>
const STORY_API_TO_DB: Record<string, StoryStatus> = {
open: 'OPEN',
in_sprint: 'IN_SPRINT',
done: 'DONE',
failed: 'FAILED',
}
export type TaskStatusApi = (typeof TASK_DB_TO_API)[TaskStatus]

View file

@ -1,42 +0,0 @@
import { z } from 'zod'
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { prisma } from '../prisma.js'
import { requireWriteAccess } from '../auth.js'
import { userCanAccessProduct } from '../access.js'
import { toolError, toolJson, withToolErrors } from '../errors.js'
const inputSchema = z.object({
title: z.string().min(1),
description: z.string().max(2000).optional(),
product_id: z.string().min(1).optional(),
})
export function registerCreateTodoTool(server: McpServer) {
server.registerTool(
'create_todo',
{
title: 'Create todo',
description:
'Add a todo for the authenticated user, optionally scoped to a product. ' +
'Forbidden for demo accounts.',
inputSchema,
},
async ({ title, description, product_id }) =>
withToolErrors(async () => {
const auth = await requireWriteAccess()
if (product_id && !(await userCanAccessProduct(product_id, auth.userId))) {
return toolError(`Product ${product_id} not found or not accessible`)
}
const todo = await prisma.todo.create({
data: {
user_id: auth.userId,
product_id: product_id ?? null,
title,
description: description ?? null,
},
select: { id: true, title: true, description: true, created_at: true },
})
return toolJson(todo)
}),
)
}

View file

@ -99,19 +99,21 @@ export function registerGetClaudeContextTool(server: McpServer) {
}
}
const openTodos = await prisma.todo.findMany({
const openIdeas = await prisma.idea.findMany({
where: {
user_id: auth.userId,
done: false,
archived: false,
status: { not: 'PLANNED' },
OR: [{ product_id: product_id }, { product_id: null }],
},
orderBy: { created_at: 'asc' },
take: 50,
select: {
id: true,
code: true,
title: true,
description: true,
status: true,
created_at: true,
},
})
@ -120,7 +122,7 @@ export function registerGetClaudeContextTool(server: McpServer) {
product,
active_sprint: activeSprint,
next_story: nextStory,
open_todos: openTodos,
open_ideas: openIdeas,
})
}),
)

View file

@ -15,6 +15,7 @@ import { resolveRepoRoot } from './wait-for-job.js'
import { pushBranchForJob } from '../git/push.js'
import { createPullRequest } from '../git/pr.js'
import { cancelPbiOnFailure } from '../cancel/pbi-cascade.js'
import { propagateStatusUpwards } from '../lib/tasks-status-update.js'
const inputSchema = z.object({
job_id: z.string().min(1),
@ -420,6 +421,25 @@ export function registerUpdateJobStatusTool(server: McpServer) {
},
})
// PBI-46 sprint-flow: propageer Task → Story → PBI → Sprint → SprintRun
// bij elke task-statusovergang (DONE of FAILED). De helper handelt ook
// sibling-cancel binnen dezelfde SprintRun af bij FAILED.
// Idea-jobs hebben geen task_id en worden hier overgeslagen.
if (
(actualStatus === 'done' || actualStatus === 'failed') &&
job.kind === 'TASK_IMPLEMENTATION' &&
job.task_id
) {
try {
await propagateStatusUpwards(job.task_id, actualStatus === 'done' ? 'DONE' : 'FAILED')
} catch (err) {
console.warn(
`[update_job_status] propagateStatusUpwards error for task ${job.task_id}:`,
err,
)
}
}
// M12: bij failed voor IDEA_*-jobs: zet idea.status op
// GRILL_FAILED / PLAN_FAILED + log JOB_EVENT. Bij done laten we de
// idea-status met rust — die wordt door update_idea_*_md gezet.

View file

@ -247,29 +247,47 @@ export async function tryClaimJob(
tokenId: string,
productId?: string,
): Promise<string | null> {
// Atomic claim in a single transaction — also captures plan_snapshot from task
// Atomic claim in a single transaction — also captures plan_snapshot from task.
//
// Sprint-flow filter (PBI-46):
// Idea-jobs (task_id IS NULL) blijven onafhankelijk claimable.
// Task-jobs zijn alleen claimable wanneer ze aan een actieve SprintRun
// hangen (status QUEUED of RUNNING). Legacy task-jobs zonder sprint_run_id
// en jobs in PAUSED/FAILED/CANCELLED/DONE SprintRuns worden overgeslagen.
// Bij eerste claim van een nog QUEUED SprintRun → status RUNNING.
const rows = await prisma.$transaction(async (tx) => {
// SELECT FOR UPDATE OF claude_jobs SKIP LOCKED — LEFT JOIN tasks zodat
// idea-jobs (task_id IS NULL, M12) ook gevonden worden. plan_snapshot
// blijft dan NULL/'' voor idea-jobs — niet nodig (geen verify-flow).
const found = productId
? await tx.$queryRaw<Array<{ id: string; implementation_plan: string | null }>>`
SELECT cj.id, t.implementation_plan
? await tx.$queryRaw<
Array<{ id: string; implementation_plan: string | null; sprint_run_id: string | null }>
>`
SELECT cj.id, t.implementation_plan, cj.sprint_run_id
FROM claude_jobs cj
LEFT JOIN tasks t ON t.id = cj.task_id
LEFT JOIN sprint_runs sr ON sr.id = cj.sprint_run_id
WHERE cj.user_id = ${userId}
AND cj.product_id = ${productId}
AND cj.status = 'QUEUED'
AND (
cj.task_id IS NULL
OR (cj.sprint_run_id IS NOT NULL AND sr.status IN ('QUEUED', 'RUNNING'))
)
ORDER BY cj.created_at ASC
LIMIT 1
FOR UPDATE OF cj SKIP LOCKED
`
: await tx.$queryRaw<Array<{ id: string; implementation_plan: string | null }>>`
SELECT cj.id, t.implementation_plan
: await tx.$queryRaw<
Array<{ id: string; implementation_plan: string | null; sprint_run_id: string | null }>
>`
SELECT cj.id, t.implementation_plan, cj.sprint_run_id
FROM claude_jobs cj
LEFT JOIN tasks t ON t.id = cj.task_id
LEFT JOIN sprint_runs sr ON sr.id = cj.sprint_run_id
WHERE cj.user_id = ${userId}
AND cj.status = 'QUEUED'
AND (
cj.task_id IS NULL
OR (cj.sprint_run_id IS NOT NULL AND sr.status IN ('QUEUED', 'RUNNING'))
)
ORDER BY cj.created_at ASC
LIMIT 1
FOR UPDATE OF cj SKIP LOCKED
@ -279,6 +297,7 @@ export async function tryClaimJob(
const jobId = found[0].id
const snapshot = found[0].implementation_plan ?? ''
const sprintRunId = found[0].sprint_run_id
await tx.$executeRaw`
UPDATE claude_jobs
SET status = 'CLAIMED',
@ -287,6 +306,19 @@ export async function tryClaimJob(
plan_snapshot = ${snapshot}
WHERE id = ${jobId}
`
// SprintRun QUEUED → RUNNING bij eerste claim, in dezelfde tx zodat
// concurrent claims dezelfde overgang niet dubbel doen (UPDATE skipt
// rows die al RUNNING zijn).
if (sprintRunId) {
await tx.$executeRaw`
UPDATE sprint_runs
SET status = 'RUNNING',
started_at = COALESCE(started_at, NOW()),
updated_at = NOW()
WHERE id = ${sprintRunId} AND status = 'QUEUED'
`
}
return [{ id: jobId }]
})

View file

@ -5,12 +5,16 @@ export interface ClassifyResult {
reasoning: string
}
// Extract changed file paths from a unified diff ("+++ b/<path>" lines).
// Extract changed file paths from a unified diff. Reads both "+++ b/<path>"
// (created/modified files) and "--- a/<path>" (deleted/modified files), so
// pure-delete commits (where +++ is /dev/null) are still recognised.
function extractDiffPaths(diff: string): string[] {
const paths = new Set<string>()
for (const line of diff.split('\n')) {
const m = line.match(/^\+\+\+ b\/(.+)$/)
if (m && m[1].trim() !== '/dev/null') paths.add(m[1].trim())
const plus = line.match(/^\+\+\+ b\/(.+)$/)
if (plus && plus[1].trim() !== '/dev/null') paths.add(plus[1].trim())
const minus = line.match(/^--- a\/(.+)$/)
if (minus && minus[1].trim() !== '/dev/null') paths.add(minus[1].trim())
}
return [...paths]
}