scrum4me-mcp/src/tools/verify-task-against-plan.ts
Madhura68 f7f5a487ec PBI-9 + PBI-47: worktree foundation, product-worktrees, P0 fixes, PAUSED flow
Adds two interlocking PBIs:

PBI-9 — Worktree foundation + persistent product-worktrees for idea-jobs
  - src/git/worktree-paths.ts: centralised root + skip-set + lock-path helpers
  - src/git/file-lock.ts: proper-lockfile wrapper, deadlock-safe ordered acquire
  - src/git/product-worktree.ts: detached-HEAD worktree per product, .scratch/
    excluded via git rev-parse --git-path (handles linked .git file)
  - src/git/job-locks.ts: setupProductWorktrees + releaseLocksOnTerminal
  - wait-for-job.ts: idea-branch wires product-worktrees for IDEA_GRILL/MAKE_PLAN
  - update-job-status.ts + pbi-cascade.ts + stale-reset: release on all four
    server-side terminal transitions (DONE/FAILED/CANCELLED/stale)
  - cleanup-my-worktrees: skip _products/ + *.lock
  - README: worktrees section with single-host invariant + advisory-lock path

PBI-47 — Sprint-flow P0 corrections + PAUSED flow with rich pause_context
  - prisma schema: ClaudeJob.{base_sha,head_sha} + SprintRun.pause_context
  - tryClaimJob captures base_sha; prepareDoneUpdate captures head_sha
  - verify-task-against-plan diffs vs base_sha (no more origin/main fallback);
    rejects with MISSING_BASE_SHA when null — fixes per-task verify-scope P0
  - pr.ts: createPullRequest enableAutoMerge default false; new
    enableAutoMergeOnPr with --match-head-commit guard + 5-category typed
    EnableAutoMergeResult — fixes STORY auto-merge timing P0
  - src/flow/{effects,worktree-lease,pr-flow,sprint-run}.ts: pure transition
    modules + idempotent declarative effects executor
  - update-job-status: STORY auto-merge fires only on the last task of the
    story (story.status === DONE), with head_sha as merge guard; MERGE_CONFLICT
    routes to sprint-run flow which produces CREATE_CLAUDE_QUESTION +
    SET_SPRINT_RUN_STATUS effects with rich pause_context

Tests: 31 test files, 242 passing. Pure-transition tests cover STORY 3-tasks
auto-merge timing, SPRINT draft→ready, MERGE_CONFLICT pause/resume, file-lock
deadlock prevention, worktree-lease lifecycle, delete-only verify (ALIGNED),
per-job verify scope (base_sha isolation), 5-category auto-merge errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 21:09:48 +02:00

114 lines
4 KiB
TypeScript

import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { z } from 'zod'
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { prisma } from '../prisma.js'
import { getAuth } from '../auth.js'
import { userCanAccessTask } from '../access.js'
import { toolError, toolJson, withToolErrors } from '../errors.js'
import { classifyDiffAgainstPlan, type VerifyResultValue } from '../verify/classify.js'
const exec = promisify(execFile)
const inputSchema = z.object({
task_id: z.string().min(1),
worktree_path: z.string().min(1),
})
export async function getDiffInWorktree(
worktreePath: string,
baseSha?: string,
): Promise<string> {
// PBI-47 (P0): when base_sha is provided, diff against the per-job base
// captured at claim-time so verify only sees the current task's changes.
// Falls back to origin/main only for legacy callers without base_sha.
const range = baseSha ? `${baseSha}...HEAD` : 'origin/main...HEAD'
const { stdout } = await exec('git', ['diff', range], { cwd: worktreePath })
return stdout
}
export async function saveVerifyResult(jobId: string, result: VerifyResultValue): Promise<void> {
await prisma.claudeJob.update({
where: { id: jobId },
data: { verify_result: result },
})
}
export function registerVerifyTaskAgainstPlanTool(server: McpServer) {
server.registerTool(
'verify_task_against_plan',
{
title: 'Verify task against plan',
description:
'Run `git diff origin/main...HEAD` in the worktree and compare it against the ' +
'frozen plan_snapshot captured at claim time. Returns ALIGNED|PARTIAL|EMPTY|DIVERGENT ' +
'and saves verify_result on the active job. ' +
'Call this BEFORE update_job_status("done"). ' +
'If the result is EMPTY and task.verify_only is false, update_job_status("done") will be rejected.',
inputSchema,
annotations: { readOnlyHint: false },
},
async ({ task_id, worktree_path }) =>
withToolErrors(async () => {
const auth = await getAuth()
if (!auth) return toolError('Unauthorized')
if (!(await userCanAccessTask(task_id, auth.userId))) {
return toolError(`Task ${task_id} not found or not accessible`)
}
const task = await prisma.task.findUnique({
where: { id: task_id },
select: {
id: true,
verify_only: true,
claude_jobs: {
where: { status: { in: ['CLAIMED', 'RUNNING'] } },
orderBy: { created_at: 'desc' },
take: 1,
select: { id: true, plan_snapshot: true, base_sha: true },
},
},
})
if (!task) return toolError(`Task ${task_id} not found`)
const activeJob = task.claude_jobs[0] ?? null
// PBI-47 (P0): require base_sha so diff is scoped to this job's work,
// not the full origin/main...HEAD which would include sibling commits
// on a reused story/sprint branch.
if (activeJob && !activeJob.base_sha) {
return toolError(
'MISSING_BASE_SHA: This claim has no base_sha. '
+ 'Re-claim the task (cancel + wait_for_job) so a fresh base_sha is captured.',
)
}
let diff: string
try {
diff = await getDiffInWorktree(worktree_path, activeJob?.base_sha ?? undefined)
} catch (err) {
return toolError(
`git diff failed in worktree (${worktree_path}): ${(err as Error).message ?? 'unknown error'}`,
)
}
const { result, reasoning } = classifyDiffAgainstPlan({
diff,
plan: activeJob?.plan_snapshot ?? null,
})
if (activeJob) {
await saveVerifyResult(activeJob.id, result)
}
return toolJson({
result: result.toLowerCase() as 'aligned' | 'partial' | 'empty' | 'divergent',
reasoning,
verify_only: task.verify_only,
task_id,
job_id: activeJob?.id ?? null,
})
}),
)
}