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>
This commit is contained in:
parent
454d96ee04
commit
f7f5a487ec
29 changed files with 1731 additions and 46 deletions
|
|
@ -13,6 +13,7 @@ import {
|
|||
getPullRequestState,
|
||||
} from '../git/pr.js'
|
||||
import { deleteRemoteBranch } from '../git/push.js'
|
||||
import { releaseLocksOnTerminal } from '../git/job-locks.js'
|
||||
|
||||
export type CascadeOutcome = {
|
||||
cancelled_job_ids: string[]
|
||||
|
|
@ -88,6 +89,9 @@ async function runCascade(failedJobId: string): Promise<CascadeOutcome> {
|
|||
error: 'cancelled_by_pbi_failure',
|
||||
},
|
||||
})
|
||||
// PBI-9: release product-worktree locks for cancelled jobs.
|
||||
// No-op for jobs without registered locks (TASK_IMPLEMENTATION).
|
||||
for (const j of eligible) await releaseLocksOnTerminal(j.id)
|
||||
}
|
||||
|
||||
const outcome: CascadeOutcome = {
|
||||
|
|
|
|||
192
src/flow/effects.ts
Normal file
192
src/flow/effects.ts
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
// PBI-9 + PBI-47: declarative effects produced by pure transitions.
|
||||
// Executor handles each effect idempotently; failures are logged, not thrown.
|
||||
|
||||
export type PauseContext = {
|
||||
pause_reason: 'MERGE_CONFLICT'
|
||||
pr_url: string
|
||||
pr_head_sha: string
|
||||
conflict_files: string[]
|
||||
claude_question_id: string
|
||||
resume_instructions: string
|
||||
paused_at: string
|
||||
}
|
||||
|
||||
export type FlowEffect =
|
||||
| { type: 'RELEASE_WORKTREE_LOCKS'; jobId: string }
|
||||
| { type: 'ENABLE_AUTO_MERGE'; prUrl: string; expectedHeadSha: string }
|
||||
| { type: 'MARK_PR_READY'; prUrl: string }
|
||||
| {
|
||||
type: 'CREATE_CLAUDE_QUESTION'
|
||||
sprintRunId: string
|
||||
prUrl: string
|
||||
files: string[]
|
||||
}
|
||||
| { type: 'CLOSE_CLAUDE_QUESTION'; questionId: string }
|
||||
| {
|
||||
type: 'SET_SPRINT_RUN_STATUS'
|
||||
sprintRunId: string
|
||||
status: 'QUEUED' | 'RUNNING' | 'PAUSED' | 'DONE' | 'FAILED' | 'CANCELLED'
|
||||
pauseContextDraft?: Omit<PauseContext, 'claude_question_id'>
|
||||
clearPauseContext?: boolean
|
||||
}
|
||||
|
||||
export type AutoMergeOutcome =
|
||||
| { effect: 'ENABLE_AUTO_MERGE'; ok: true }
|
||||
| {
|
||||
effect: 'ENABLE_AUTO_MERGE'
|
||||
ok: false
|
||||
reason: 'CHECKS_FAILED' | 'MERGE_CONFLICT' | 'GH_AUTH_ERROR' | 'AUTO_MERGE_NOT_ALLOWED' | 'UNKNOWN'
|
||||
stderr: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a list of effects in order. Returns outcome objects only for
|
||||
* effects whose result the caller needs to react to (auto-merge fail
|
||||
* triggers MERGE_CONFLICT-event in update-job-status). Other failures
|
||||
* are logged but swallowed.
|
||||
*
|
||||
* CREATE_CLAUDE_QUESTION → SET_SPRINT_RUN_STATUS chains: the question_id
|
||||
* created in the first effect is injected into the pause_context of the
|
||||
* second.
|
||||
*/
|
||||
export async function executeEffects(
|
||||
effects: FlowEffect[],
|
||||
): Promise<AutoMergeOutcome[]> {
|
||||
const outcomes: AutoMergeOutcome[] = []
|
||||
let lastQuestionId: string | undefined
|
||||
for (const effect of effects) {
|
||||
try {
|
||||
if (effect.type === 'CREATE_CLAUDE_QUESTION') {
|
||||
lastQuestionId = await createOrReuseClaudeQuestion(effect)
|
||||
continue
|
||||
}
|
||||
if (effect.type === 'SET_SPRINT_RUN_STATUS') {
|
||||
await applySprintRunStatus(effect, lastQuestionId)
|
||||
continue
|
||||
}
|
||||
const outcome = await executeEffect(effect)
|
||||
if (outcome) outcomes.push(outcome)
|
||||
} catch (err) {
|
||||
console.warn(`[effects] effect ${effect.type} failed (idempotent skip):`, err)
|
||||
}
|
||||
}
|
||||
return outcomes
|
||||
}
|
||||
|
||||
async function executeEffect(effect: FlowEffect): Promise<AutoMergeOutcome | undefined> {
|
||||
switch (effect.type) {
|
||||
case 'RELEASE_WORKTREE_LOCKS': {
|
||||
const { releaseLocksOnTerminal } = await import('../git/job-locks.js')
|
||||
await releaseLocksOnTerminal(effect.jobId)
|
||||
return undefined
|
||||
}
|
||||
case 'ENABLE_AUTO_MERGE': {
|
||||
const { enableAutoMergeOnPr } = await import('../git/pr.js')
|
||||
const result = await enableAutoMergeOnPr({
|
||||
prUrl: effect.prUrl,
|
||||
expectedHeadSha: effect.expectedHeadSha,
|
||||
})
|
||||
if (result.ok) return { effect: 'ENABLE_AUTO_MERGE', ok: true }
|
||||
return { effect: 'ENABLE_AUTO_MERGE', ok: false, reason: result.reason, stderr: result.stderr }
|
||||
}
|
||||
case 'MARK_PR_READY': {
|
||||
const { markPullRequestReady } = await import('../git/pr.js')
|
||||
const result = await markPullRequestReady({ prUrl: effect.prUrl })
|
||||
if ('error' in result) {
|
||||
console.warn(`[effects] MARK_PR_READY failed for ${effect.prUrl}: ${result.error}`)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
case 'CLOSE_CLAUDE_QUESTION': {
|
||||
const { prisma } = await import('../prisma.js')
|
||||
await prisma.claudeQuestion.updateMany({
|
||||
where: { id: effect.questionId, status: 'open' },
|
||||
data: { status: 'closed' },
|
||||
})
|
||||
return undefined
|
||||
}
|
||||
// CREATE_CLAUDE_QUESTION + SET_SPRINT_RUN_STATUS handled in executeEffects.
|
||||
case 'CREATE_CLAUDE_QUESTION':
|
||||
case 'SET_SPRINT_RUN_STATUS':
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function createOrReuseClaudeQuestion(effect: {
|
||||
sprintRunId: string
|
||||
prUrl: string
|
||||
files: string[]
|
||||
}): Promise<string> {
|
||||
const { prisma } = await import('../prisma.js')
|
||||
|
||||
// Reuse existing open question for the same SprintRun + PR if present.
|
||||
const existing = await prisma.claudeQuestion.findFirst({
|
||||
where: {
|
||||
status: 'open',
|
||||
options: { path: ['sprint_run_id'], equals: effect.sprintRunId } as never,
|
||||
},
|
||||
orderBy: { created_at: 'desc' },
|
||||
select: { id: true },
|
||||
})
|
||||
if (existing) return existing.id
|
||||
|
||||
// Need product_id + asker (user) to create. Resolve via SprintRun.
|
||||
const sprintRun = await prisma.sprintRun.findUnique({
|
||||
where: { id: effect.sprintRunId },
|
||||
select: {
|
||||
started_by_id: true,
|
||||
sprint: { select: { product_id: true } },
|
||||
},
|
||||
})
|
||||
if (!sprintRun) {
|
||||
throw new Error(`SprintRun ${effect.sprintRunId} not found`)
|
||||
}
|
||||
|
||||
const fileList =
|
||||
effect.files.length === 0
|
||||
? '(unknown files — check the PR)'
|
||||
: effect.files.slice(0, 5).join(', ')
|
||||
+ (effect.files.length > 5 ? ` + ${effect.files.length - 5} more` : '')
|
||||
|
||||
const created = await prisma.claudeQuestion.create({
|
||||
data: {
|
||||
product_id: sprintRun.sprint.product_id,
|
||||
asked_by: sprintRun.started_by_id,
|
||||
question:
|
||||
`Merge-conflict on ${effect.prUrl}. Conflict files: ${fileList}. `
|
||||
+ `Resolve on the branch and push, then resume the sprint.`,
|
||||
options: {
|
||||
sprint_run_id: effect.sprintRunId,
|
||||
pr_url: effect.prUrl,
|
||||
conflict_files: effect.files,
|
||||
},
|
||||
status: 'open',
|
||||
expires_at: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
return created.id
|
||||
}
|
||||
|
||||
async function applySprintRunStatus(
|
||||
effect: Extract<FlowEffect, { type: 'SET_SPRINT_RUN_STATUS' }>,
|
||||
lastQuestionId: string | undefined,
|
||||
): Promise<void> {
|
||||
const { prisma, Prisma } = await (async () => {
|
||||
const mod = await import('../prisma.js')
|
||||
const prismaPkg = await import('@prisma/client')
|
||||
return { prisma: mod.prisma, Prisma: prismaPkg.Prisma }
|
||||
})()
|
||||
|
||||
const data: Record<string, unknown> = { status: effect.status }
|
||||
if (effect.pauseContextDraft && lastQuestionId) {
|
||||
data.pause_context = {
|
||||
...effect.pauseContextDraft,
|
||||
claude_question_id: lastQuestionId,
|
||||
}
|
||||
}
|
||||
if (effect.clearPauseContext) {
|
||||
data.pause_context = Prisma.JsonNull
|
||||
}
|
||||
await prisma.sprintRun.update({ where: { id: effect.sprintRunId }, data })
|
||||
}
|
||||
110
src/flow/pr-flow.ts
Normal file
110
src/flow/pr-flow.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import type { FlowEffect } from './effects.js'
|
||||
import type { AutoMergeFailReason } from '../git/pr.js'
|
||||
|
||||
export type PrStrategy = 'STORY' | 'SPRINT'
|
||||
|
||||
export type PrFlowState =
|
||||
| { kind: 'none'; strategy: PrStrategy }
|
||||
| { kind: 'branch_pushed'; strategy: PrStrategy; prUrl?: string }
|
||||
| { kind: 'pr_opened'; strategy: 'STORY'; prUrl: string }
|
||||
| { kind: 'draft_opened'; strategy: 'SPRINT'; prUrl: string }
|
||||
| { kind: 'waiting_for_checks'; strategy: 'STORY'; prUrl: string; headSha: string }
|
||||
| { kind: 'auto_merge_enabled'; strategy: 'STORY'; prUrl: string; headSha: string }
|
||||
| { kind: 'ready_for_review'; strategy: 'SPRINT'; prUrl: string }
|
||||
| { kind: 'merged'; strategy: PrStrategy; prUrl: string }
|
||||
| { kind: 'checks_failed'; strategy: PrStrategy; prUrl: string }
|
||||
| { kind: 'merge_conflict_paused'; strategy: PrStrategy; prUrl: string; headSha: string }
|
||||
|
||||
export type PrFlowEvent =
|
||||
| { type: 'PR_CREATED'; prUrl: string }
|
||||
| { type: 'TASK_DONE'; taskId: string; headSha: string }
|
||||
| { type: 'STORY_COMPLETED'; storyId: string; headSha: string }
|
||||
| { type: 'SPRINT_COMPLETED'; sprintRunId: string }
|
||||
| { type: 'MERGE_RESULT'; reason?: AutoMergeFailReason }
|
||||
|
||||
export type TransitionResult = { nextState: PrFlowState; effects: FlowEffect[] }
|
||||
|
||||
export function transition(state: PrFlowState, event: PrFlowEvent): TransitionResult {
|
||||
if (state.strategy === 'STORY') {
|
||||
switch (state.kind) {
|
||||
case 'none':
|
||||
case 'branch_pushed':
|
||||
if (event.type === 'PR_CREATED') {
|
||||
return {
|
||||
nextState: { kind: 'pr_opened', strategy: 'STORY', prUrl: event.prUrl },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'pr_opened':
|
||||
if (event.type === 'STORY_COMPLETED') {
|
||||
return {
|
||||
nextState: {
|
||||
kind: 'waiting_for_checks',
|
||||
strategy: 'STORY',
|
||||
prUrl: state.prUrl,
|
||||
headSha: event.headSha,
|
||||
},
|
||||
effects: [
|
||||
{ type: 'ENABLE_AUTO_MERGE', prUrl: state.prUrl, expectedHeadSha: event.headSha },
|
||||
],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'waiting_for_checks':
|
||||
if (event.type === 'MERGE_RESULT' && !event.reason) {
|
||||
return {
|
||||
nextState: {
|
||||
kind: 'auto_merge_enabled',
|
||||
strategy: 'STORY',
|
||||
prUrl: state.prUrl,
|
||||
headSha: state.headSha,
|
||||
},
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
if (event.type === 'MERGE_RESULT' && event.reason === 'MERGE_CONFLICT') {
|
||||
return {
|
||||
nextState: {
|
||||
kind: 'merge_conflict_paused',
|
||||
strategy: 'STORY',
|
||||
prUrl: state.prUrl,
|
||||
headSha: state.headSha,
|
||||
},
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
if (event.type === 'MERGE_RESULT' && event.reason === 'CHECKS_FAILED') {
|
||||
return {
|
||||
nextState: { kind: 'checks_failed', strategy: 'STORY', prUrl: state.prUrl },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (state.strategy === 'SPRINT') {
|
||||
switch (state.kind) {
|
||||
case 'none':
|
||||
case 'branch_pushed':
|
||||
if (event.type === 'PR_CREATED') {
|
||||
return {
|
||||
nextState: { kind: 'draft_opened', strategy: 'SPRINT', prUrl: event.prUrl },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'draft_opened':
|
||||
if (event.type === 'SPRINT_COMPLETED') {
|
||||
return {
|
||||
nextState: { kind: 'ready_for_review', strategy: 'SPRINT', prUrl: state.prUrl },
|
||||
effects: [{ type: 'MARK_PR_READY', prUrl: state.prUrl }],
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return { nextState: state, effects: [] }
|
||||
}
|
||||
136
src/flow/sprint-run.ts
Normal file
136
src/flow/sprint-run.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import type { FlowEffect, PauseContext } from './effects.js'
|
||||
|
||||
export type SprintRunStateKind =
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'paused_merge_conflict'
|
||||
| 'done'
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
|
||||
export type SprintRunState = {
|
||||
kind: SprintRunStateKind
|
||||
sprintRunId: string
|
||||
pauseContext?: PauseContext
|
||||
}
|
||||
|
||||
export type SprintRunEvent =
|
||||
| { type: 'CLAIM_FIRST_JOB' }
|
||||
| { type: 'TASK_DONE'; taskId: string }
|
||||
| { type: 'TASK_FAILED'; taskId: string; error: string }
|
||||
| {
|
||||
type: 'MERGE_CONFLICT'
|
||||
prUrl: string
|
||||
prHeadSha: string
|
||||
conflictFiles: string[]
|
||||
resumeInstructions: string
|
||||
}
|
||||
| { type: 'USER_RESUMED' }
|
||||
| { type: 'USER_CANCELLED' }
|
||||
| { type: 'ALL_DONE' }
|
||||
|
||||
export type TransitionResult = { nextState: SprintRunState; effects: FlowEffect[] }
|
||||
|
||||
export function transition(state: SprintRunState, event: SprintRunEvent): TransitionResult {
|
||||
switch (state.kind) {
|
||||
case 'queued':
|
||||
if (event.type === 'CLAIM_FIRST_JOB') {
|
||||
return {
|
||||
nextState: { ...state, kind: 'running' },
|
||||
effects: [
|
||||
{ type: 'SET_SPRINT_RUN_STATUS', sprintRunId: state.sprintRunId, status: 'RUNNING' },
|
||||
],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'running':
|
||||
if (event.type === 'TASK_DONE') {
|
||||
return { nextState: state, effects: [] }
|
||||
}
|
||||
if (event.type === 'TASK_FAILED') {
|
||||
return {
|
||||
nextState: { ...state, kind: 'failed' },
|
||||
effects: [
|
||||
{ type: 'SET_SPRINT_RUN_STATUS', sprintRunId: state.sprintRunId, status: 'FAILED' },
|
||||
],
|
||||
}
|
||||
}
|
||||
if (event.type === 'ALL_DONE') {
|
||||
return {
|
||||
nextState: { ...state, kind: 'done' },
|
||||
effects: [
|
||||
{ type: 'SET_SPRINT_RUN_STATUS', sprintRunId: state.sprintRunId, status: 'DONE' },
|
||||
],
|
||||
}
|
||||
}
|
||||
if (event.type === 'MERGE_CONFLICT') {
|
||||
const pauseContextDraft: Omit<PauseContext, 'claude_question_id'> = {
|
||||
pause_reason: 'MERGE_CONFLICT',
|
||||
pr_url: event.prUrl,
|
||||
pr_head_sha: event.prHeadSha,
|
||||
conflict_files: event.conflictFiles,
|
||||
resume_instructions: event.resumeInstructions,
|
||||
paused_at: new Date().toISOString(),
|
||||
}
|
||||
return {
|
||||
nextState: { ...state, kind: 'paused_merge_conflict' },
|
||||
effects: [
|
||||
{
|
||||
type: 'CREATE_CLAUDE_QUESTION',
|
||||
sprintRunId: state.sprintRunId,
|
||||
prUrl: event.prUrl,
|
||||
files: event.conflictFiles,
|
||||
},
|
||||
{
|
||||
type: 'SET_SPRINT_RUN_STATUS',
|
||||
sprintRunId: state.sprintRunId,
|
||||
status: 'PAUSED',
|
||||
pauseContextDraft,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
if (event.type === 'USER_CANCELLED') {
|
||||
return {
|
||||
nextState: { ...state, kind: 'cancelled' },
|
||||
effects: [
|
||||
{ type: 'SET_SPRINT_RUN_STATUS', sprintRunId: state.sprintRunId, status: 'CANCELLED' },
|
||||
],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'paused_merge_conflict':
|
||||
if (event.type === 'USER_RESUMED') {
|
||||
const closeQuestionEffects: FlowEffect[] = state.pauseContext
|
||||
? [{ type: 'CLOSE_CLAUDE_QUESTION', questionId: state.pauseContext.claude_question_id }]
|
||||
: []
|
||||
return {
|
||||
nextState: { ...state, kind: 'running', pauseContext: undefined },
|
||||
effects: [
|
||||
...closeQuestionEffects,
|
||||
{
|
||||
type: 'SET_SPRINT_RUN_STATUS',
|
||||
sprintRunId: state.sprintRunId,
|
||||
status: 'RUNNING',
|
||||
clearPauseContext: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
if (event.type === 'USER_CANCELLED') {
|
||||
return {
|
||||
nextState: { ...state, kind: 'cancelled', pauseContext: undefined },
|
||||
effects: [
|
||||
{
|
||||
type: 'SET_SPRINT_RUN_STATUS',
|
||||
sprintRunId: state.sprintRunId,
|
||||
status: 'CANCELLED',
|
||||
clearPauseContext: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
return { nextState: state, effects: [] }
|
||||
}
|
||||
103
src/flow/worktree-lease.ts
Normal file
103
src/flow/worktree-lease.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import type { FlowEffect } from './effects.js'
|
||||
|
||||
export type WorktreeLeaseState =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'acquiring_lock'; jobId: string; productIds: string[] }
|
||||
| { kind: 'creating_or_reusing'; jobId: string; productIds: string[] }
|
||||
| { kind: 'syncing'; jobId: string; productIds: string[] }
|
||||
| { kind: 'ready'; jobId: string; productIds: string[] }
|
||||
| { kind: 'releasing'; jobId: string }
|
||||
| { kind: 'released'; jobId: string }
|
||||
| { kind: 'lock_timeout'; jobId: string; productIds: string[] }
|
||||
| { kind: 'sync_failed'; jobId: string; productIds: string[]; error: string }
|
||||
| { kind: 'stale_released'; jobId: string }
|
||||
|
||||
export type WorktreeLeaseEvent =
|
||||
| { type: 'JOB_CLAIMED'; jobId: string; productIds: string[] }
|
||||
| { type: 'LOCK_ACQUIRED' }
|
||||
| { type: 'LOCK_TIMEOUT' }
|
||||
| { type: 'WORKTREE_READY' }
|
||||
| { type: 'SYNC_DONE' }
|
||||
| { type: 'SYNC_FAILED'; error: string }
|
||||
| { type: 'JOB_TERMINAL'; jobId: string }
|
||||
| { type: 'STALE_RESET'; jobId: string }
|
||||
|
||||
export type TransitionResult = {
|
||||
nextState: WorktreeLeaseState
|
||||
effects: FlowEffect[]
|
||||
}
|
||||
|
||||
export function transition(
|
||||
state: WorktreeLeaseState,
|
||||
event: WorktreeLeaseEvent,
|
||||
): TransitionResult {
|
||||
switch (state.kind) {
|
||||
case 'idle':
|
||||
if (event.type === 'JOB_CLAIMED') {
|
||||
return {
|
||||
nextState: { kind: 'acquiring_lock', jobId: event.jobId, productIds: event.productIds },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'acquiring_lock':
|
||||
if (event.type === 'LOCK_ACQUIRED') {
|
||||
return {
|
||||
nextState: { kind: 'creating_or_reusing', jobId: state.jobId, productIds: state.productIds },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
if (event.type === 'LOCK_TIMEOUT') {
|
||||
return {
|
||||
nextState: { kind: 'lock_timeout', jobId: state.jobId, productIds: state.productIds },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'creating_or_reusing':
|
||||
if (event.type === 'WORKTREE_READY') {
|
||||
return {
|
||||
nextState: { kind: 'syncing', jobId: state.jobId, productIds: state.productIds },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'syncing':
|
||||
if (event.type === 'SYNC_DONE') {
|
||||
return {
|
||||
nextState: { kind: 'ready', jobId: state.jobId, productIds: state.productIds },
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
if (event.type === 'SYNC_FAILED') {
|
||||
return {
|
||||
nextState: {
|
||||
kind: 'sync_failed',
|
||||
jobId: state.jobId,
|
||||
productIds: state.productIds,
|
||||
error: event.error,
|
||||
},
|
||||
effects: [{ type: 'RELEASE_WORKTREE_LOCKS', jobId: state.jobId }],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'ready':
|
||||
if (event.type === 'JOB_TERMINAL') {
|
||||
return {
|
||||
nextState: { kind: 'releasing', jobId: state.jobId },
|
||||
effects: [{ type: 'RELEASE_WORKTREE_LOCKS', jobId: state.jobId }],
|
||||
}
|
||||
}
|
||||
if (event.type === 'STALE_RESET') {
|
||||
return {
|
||||
nextState: { kind: 'stale_released', jobId: state.jobId },
|
||||
effects: [{ type: 'RELEASE_WORKTREE_LOCKS', jobId: state.jobId }],
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'releasing':
|
||||
return { nextState: { kind: 'released', jobId: state.jobId }, effects: [] }
|
||||
}
|
||||
// Unknown or forbidden transition — keep current state, no effects
|
||||
return { nextState: state, effects: [] }
|
||||
}
|
||||
38
src/git/file-lock.ts
Normal file
38
src/git/file-lock.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import lockfile from 'proper-lockfile'
|
||||
|
||||
export async function acquireFileLock(lockPath: string): Promise<() => Promise<void>> {
|
||||
const release = await lockfile.lock(lockPath, {
|
||||
realpath: false,
|
||||
stale: 30_000,
|
||||
update: 5_000,
|
||||
retries: { retries: 60, factor: 1, minTimeout: 1_000, maxTimeout: 1_000 },
|
||||
})
|
||||
let released = false
|
||||
return async () => {
|
||||
if (released) return
|
||||
released = true
|
||||
await release()
|
||||
}
|
||||
}
|
||||
|
||||
export async function acquireFileLocksOrdered(
|
||||
lockPaths: string[],
|
||||
): Promise<() => Promise<void>> {
|
||||
const sorted = [...lockPaths].sort()
|
||||
const releases: Array<() => Promise<void>> = []
|
||||
try {
|
||||
for (const p of sorted) {
|
||||
releases.push(await acquireFileLock(p))
|
||||
}
|
||||
} catch (err) {
|
||||
for (const r of releases.reverse()) {
|
||||
await r().catch(() => {})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
return async () => {
|
||||
for (const r of releases.reverse()) {
|
||||
await r().catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
69
src/git/job-locks.ts
Normal file
69
src/git/job-locks.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import * as fs from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import { acquireFileLocksOrdered } from './file-lock.js'
|
||||
import {
|
||||
getProductWorktreeLockPath,
|
||||
getWorktreeRoot,
|
||||
} from './worktree-paths.js'
|
||||
import {
|
||||
getOrCreateProductWorktree,
|
||||
syncProductWorktree,
|
||||
} from './product-worktree.js'
|
||||
|
||||
type JobReleases = Map<string, Array<() => Promise<void>>>
|
||||
const jobReleases: JobReleases = new Map()
|
||||
|
||||
export async function setupProductWorktrees(
|
||||
jobId: string,
|
||||
productIds: string[],
|
||||
resolveRepoRoot: (productId: string) => Promise<string | null>,
|
||||
): Promise<Array<{ productId: string; worktreePath: string }>> {
|
||||
if (productIds.length === 0) return []
|
||||
|
||||
// Ensure parent dir exists so lockfile creation succeeds
|
||||
await fs.mkdir(path.join(getWorktreeRoot(), '_products'), { recursive: true })
|
||||
|
||||
// Lock-first, alphabetically sorted (deadlock prevention for multi-product idea-jobs)
|
||||
const sorted = [...productIds].sort()
|
||||
const lockPaths = sorted.map(getProductWorktreeLockPath)
|
||||
const releaseAll = await acquireFileLocksOrdered(lockPaths)
|
||||
registerJobLockReleases(jobId, [releaseAll])
|
||||
|
||||
// After lock-acquire, create/reuse worktrees and sync
|
||||
const out: Array<{ productId: string; worktreePath: string }> = []
|
||||
for (const productId of sorted) {
|
||||
const repoRoot = await resolveRepoRoot(productId)
|
||||
if (!repoRoot) continue
|
||||
const { worktreePath } = await getOrCreateProductWorktree({ repoRoot, productId })
|
||||
await syncProductWorktree({ worktreePath })
|
||||
out.push({ productId, worktreePath })
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
export function registerJobLockReleases(
|
||||
jobId: string,
|
||||
releases: Array<() => Promise<void>>,
|
||||
): void {
|
||||
const existing = jobReleases.get(jobId) ?? []
|
||||
jobReleases.set(jobId, [...existing, ...releases])
|
||||
}
|
||||
|
||||
export async function releaseLocksOnTerminal(jobId: string): Promise<void> {
|
||||
const releases = jobReleases.get(jobId)
|
||||
if (!releases) return // idempotent — already released or never locked
|
||||
jobReleases.delete(jobId)
|
||||
for (const release of releases) {
|
||||
try {
|
||||
await release()
|
||||
} catch (err) {
|
||||
console.warn(`[job-locks] release failed for job ${jobId}:`, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For tests
|
||||
export function _resetJobReleasesForTest(): void {
|
||||
jobReleases.clear()
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import * as path from 'node:path'
|
||||
import * as os from 'node:os'
|
||||
import { getWorktreeRoot } from './worktree-paths.js'
|
||||
|
||||
const exec = promisify(execFile)
|
||||
|
||||
|
|
@ -12,10 +12,17 @@ export async function createPullRequest(opts: {
|
|||
body: string
|
||||
/** Open as draft PR (mens moet 'm later ready-for-review zetten). Default false. */
|
||||
draft?: boolean
|
||||
/** Schakel auto-merge (squash) in. Default true. Voor sprint-mode: false. */
|
||||
/**
|
||||
* PBI-47 (P0): default changed to false. Auto-merge is now enabled
|
||||
* separately via `enableAutoMergeOnPr` only on the **last task** of a
|
||||
* STORY-mode story, with a head-SHA guard to prevent racing earlier
|
||||
* task merges. Callers may still pass `true` for one-off PRs that
|
||||
* are immediately ready to merge; in that case we use the new typed
|
||||
* helper rather than the previous fire-and-forget gh call.
|
||||
*/
|
||||
enableAutoMerge?: boolean
|
||||
}): Promise<{ url: string } | { error: string }> {
|
||||
const { worktreePath, branchName, title, body, draft = false, enableAutoMerge = true } = opts
|
||||
const { worktreePath, branchName, title, body, draft = false, enableAutoMerge = false } = opts
|
||||
|
||||
let url: string
|
||||
try {
|
||||
|
|
@ -40,21 +47,14 @@ export async function createPullRequest(opts: {
|
|||
return { error: `gh pr create failed: ${msg.slice(0, 300)}` }
|
||||
}
|
||||
|
||||
// Best-effort: enable auto-merge (squash) on the freshly created PR. If the
|
||||
// repo doesn't have "Allow auto-merge" turned on, or the token lacks scope,
|
||||
// gh exits non-zero and we just log. The PR is still valid; auto-merge can
|
||||
// be turned on manually. We do NOT fail the whole createPullRequest call —
|
||||
// the URL was successfully obtained which is the contract this returns.
|
||||
// Bij draft + sprint-flow slaan we dit over: de PR moet eerst handmatig of
|
||||
// via markPullRequestReady ready-for-review worden gezet.
|
||||
// Legacy opt-in: enableAutoMerge=true and not draft → fire the new typed
|
||||
// helper without head-SHA guard (caller didn't supply one). Result is
|
||||
// logged but not propagated — same shape as before.
|
||||
if (enableAutoMerge && !draft) {
|
||||
try {
|
||||
await exec('gh', ['pr', 'merge', '--auto', '--squash', url], { cwd: worktreePath })
|
||||
} catch (err) {
|
||||
const stderr =
|
||||
(err as { stderr?: string }).stderr ?? (err as Error).message ?? ''
|
||||
const result = await enableAutoMergeOnPr({ prUrl: url, cwd: worktreePath })
|
||||
if (!result.ok) {
|
||||
console.warn(
|
||||
`[createPullRequest] auto-merge enable failed for ${url}: ${stderr.slice(0, 200)}`,
|
||||
`[createPullRequest] auto-merge enable failed for ${url}: ${result.reason} ${result.stderr.slice(0, 200)}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -62,6 +62,51 @@ export async function createPullRequest(opts: {
|
|||
return { url }
|
||||
}
|
||||
|
||||
export type AutoMergeFailReason =
|
||||
| 'CHECKS_FAILED'
|
||||
| 'MERGE_CONFLICT'
|
||||
| 'GH_AUTH_ERROR'
|
||||
| 'AUTO_MERGE_NOT_ALLOWED'
|
||||
| 'UNKNOWN'
|
||||
|
||||
export type EnableAutoMergeResult =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: AutoMergeFailReason; stderr: string }
|
||||
|
||||
function classifyAutoMergeError(stderr: string): AutoMergeFailReason {
|
||||
if (/conflict|not in mergeable state|dirty/i.test(stderr)) return 'MERGE_CONFLICT'
|
||||
if (/checks? failed|status check|required check/i.test(stderr)) return 'CHECKS_FAILED'
|
||||
if (/authentication|HTTP 401|HTTP 403|permission|gh auth/i.test(stderr)) return 'GH_AUTH_ERROR'
|
||||
if (/auto-?merge.*not.*allowed|auto-?merge.*disabled/i.test(stderr)) return 'AUTO_MERGE_NOT_ALLOWED'
|
||||
return 'UNKNOWN'
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable auto-merge (squash) on a PR with an optional head-SHA guard.
|
||||
*
|
||||
* PBI-47 (P0): when `expectedHeadSha` is provided we pass `--match-head-commit`
|
||||
* so GitHub only activates auto-merge if the remote head still matches the
|
||||
* SHA the caller observed. This prevents racing late pushes from another
|
||||
* worker triggering a merge of a different commit set.
|
||||
*/
|
||||
export async function enableAutoMergeOnPr(opts: {
|
||||
prUrl: string
|
||||
expectedHeadSha?: string
|
||||
cwd?: string
|
||||
}): Promise<EnableAutoMergeResult> {
|
||||
try {
|
||||
const args = ['pr', 'merge', '--auto', '--squash']
|
||||
if (opts.expectedHeadSha) args.push('--match-head-commit', opts.expectedHeadSha)
|
||||
args.push(opts.prUrl)
|
||||
await exec('gh', args, opts.cwd ? { cwd: opts.cwd } : {})
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
const stderr =
|
||||
(err as { stderr?: string }).stderr ?? (err as Error).message ?? ''
|
||||
return { ok: false, reason: classifyAutoMergeError(stderr), stderr: stderr.slice(0, 500) }
|
||||
}
|
||||
}
|
||||
|
||||
// Zet een draft-PR over naar "ready for review". Gebruikt bij sprint-mode
|
||||
// wanneer alle stories in de SprintRun DONE zijn — mens reviewt en mergt zelf.
|
||||
export async function markPullRequestReady(opts: {
|
||||
|
|
@ -163,8 +208,7 @@ export async function createRevertPullRequest(opts: {
|
|||
pbiCode,
|
||||
} = opts
|
||||
|
||||
const worktreeDir =
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ?? path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
const worktreeDir = getWorktreeRoot()
|
||||
const wtPath = path.join(worktreeDir, `revert-${jobId}`)
|
||||
const revertBranch = `revert/${originalBranch}-${jobId.slice(-8)}`
|
||||
|
||||
|
|
|
|||
66
src/git/product-worktree.ts
Normal file
66
src/git/product-worktree.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import * as fs from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import { getProductWorktreePath } from './worktree-paths.js'
|
||||
|
||||
const exec = promisify(execFile)
|
||||
|
||||
export async function getOrCreateProductWorktree(opts: {
|
||||
repoRoot: string
|
||||
productId: string
|
||||
}): Promise<{ worktreePath: string; created: boolean }> {
|
||||
const worktreePath = getProductWorktreePath(opts.productId)
|
||||
await fs.mkdir(path.dirname(worktreePath), { recursive: true })
|
||||
|
||||
try {
|
||||
await fs.access(worktreePath)
|
||||
return { worktreePath, created: false }
|
||||
} catch {
|
||||
// Path bestaat niet — aanmaken
|
||||
}
|
||||
|
||||
await exec('git', ['fetch', 'origin', '--prune'], { cwd: opts.repoRoot })
|
||||
await exec('git', ['worktree', 'add', '--detach', worktreePath, 'origin/main'], {
|
||||
cwd: opts.repoRoot,
|
||||
})
|
||||
|
||||
// Resolve REAL exclude-pad (linked worktree heeft .git als file, niet directory)
|
||||
const { stdout } = await exec('git', ['rev-parse', '--git-path', 'info/exclude'], {
|
||||
cwd: worktreePath,
|
||||
})
|
||||
const excludePath = path.resolve(worktreePath, stdout.trim())
|
||||
const existing = await fs.readFile(excludePath, 'utf8').catch(() => '')
|
||||
if (!existing.split('\n').includes('.scratch/')) {
|
||||
const sep = existing === '' || existing.endsWith('\n') ? '' : '\n'
|
||||
await fs.appendFile(excludePath, `${sep}.scratch/\n`)
|
||||
}
|
||||
|
||||
return { worktreePath, created: true }
|
||||
}
|
||||
|
||||
export async function syncProductWorktree(opts: { worktreePath: string }): Promise<void> {
|
||||
const { worktreePath } = opts
|
||||
await exec('git', ['fetch', 'origin', '--prune'], { cwd: worktreePath })
|
||||
await exec('git', ['reset', '--hard', 'origin/main'], { cwd: worktreePath })
|
||||
await exec('git', ['clean', '-fd', '-e', '.scratch/'], { cwd: worktreePath })
|
||||
// Wis .scratch/ inhoud, behoud de map
|
||||
const scratch = path.join(worktreePath, '.scratch')
|
||||
await fs.rm(scratch, { recursive: true, force: true })
|
||||
await fs.mkdir(scratch, { recursive: true })
|
||||
}
|
||||
|
||||
export async function removeProductWorktree(opts: {
|
||||
repoRoot: string
|
||||
productId: string
|
||||
}): Promise<{ removed: boolean }> {
|
||||
const worktreePath = getProductWorktreePath(opts.productId)
|
||||
try {
|
||||
await exec('git', ['worktree', 'remove', '--force', worktreePath], {
|
||||
cwd: opts.repoRoot,
|
||||
})
|
||||
return { removed: true }
|
||||
} catch {
|
||||
return { removed: false }
|
||||
}
|
||||
}
|
||||
19
src/git/worktree-paths.ts
Normal file
19
src/git/worktree-paths.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
|
||||
export const SYSTEM_WORKTREE_DIRS = new Set(['_products'])
|
||||
|
||||
export function getWorktreeRoot(): string {
|
||||
return (
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR
|
||||
?? path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
)
|
||||
}
|
||||
|
||||
export function getProductWorktreePath(productId: string): string {
|
||||
return path.join(getWorktreeRoot(), '_products', productId)
|
||||
}
|
||||
|
||||
export function getProductWorktreeLockPath(productId: string): string {
|
||||
return path.join(getWorktreeRoot(), '_products', `${productId}.lock`)
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import * as path from 'node:path'
|
||||
import * as os from 'node:os'
|
||||
import * as fs from 'node:fs/promises'
|
||||
import { getWorktreeRoot } from './worktree-paths.js'
|
||||
|
||||
const exec = promisify(execFile)
|
||||
|
||||
|
|
@ -50,9 +50,7 @@ export async function createWorktreeForJob(opts: {
|
|||
const { repoRoot, jobId, baseRef = 'origin/main', reuseBranch = false } = opts
|
||||
let { branchName } = opts
|
||||
|
||||
const parent =
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ??
|
||||
path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
const parent = getWorktreeRoot()
|
||||
|
||||
await fs.mkdir(parent, { recursive: true })
|
||||
|
||||
|
|
@ -121,9 +119,7 @@ export async function removeWorktreeForJob(opts: {
|
|||
}): Promise<{ removed: boolean }> {
|
||||
const { repoRoot, jobId, keepBranch = false } = opts
|
||||
|
||||
const parent =
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ??
|
||||
path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
const parent = getWorktreeRoot()
|
||||
|
||||
const worktreePath = path.join(parent, jobId)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
import { z } from 'zod'
|
||||
import * as fs from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import * as os from 'node:os'
|
||||
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
||||
import { prisma } from '../prisma.js'
|
||||
import { requireWriteAccess } from '../auth.js'
|
||||
import { toolJson, withToolErrors } from '../errors.js'
|
||||
import { removeWorktreeForJob } from '../git/worktree.js'
|
||||
import { getWorktreeRoot, SYSTEM_WORKTREE_DIRS } from '../git/worktree-paths.js'
|
||||
import { resolveRepoRoot } from './wait-for-job.js'
|
||||
|
||||
const TERMINAL_STATUSES = new Set(['DONE', 'FAILED', 'CANCELLED'])
|
||||
|
|
@ -15,16 +14,20 @@ const ACTIVE_STATUSES = new Set(['QUEUED', 'CLAIMED', 'RUNNING'])
|
|||
const inputSchema = z.object({})
|
||||
|
||||
export async function getWorktreeParent(): Promise<string> {
|
||||
return (
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ??
|
||||
path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
)
|
||||
return getWorktreeRoot()
|
||||
}
|
||||
|
||||
export async function listWorktreeJobIds(worktreeParent: string): Promise<string[]> {
|
||||
try {
|
||||
const entries = await fs.readdir(worktreeParent, { withFileTypes: true })
|
||||
return entries.filter((e) => e.isDirectory()).map((e) => e.name)
|
||||
return entries
|
||||
.filter(
|
||||
(e) =>
|
||||
e.isDirectory()
|
||||
&& !SYSTEM_WORKTREE_DIRS.has(e.name)
|
||||
&& !e.name.endsWith('.lock'),
|
||||
)
|
||||
.map((e) => e.name)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,11 +11,30 @@ import { prisma } from '../prisma.js'
|
|||
import { requireWriteAccess } from '../auth.js'
|
||||
import { toolJson, toolError, withToolErrors } from '../errors.js'
|
||||
import { removeWorktreeForJob } from '../git/worktree.js'
|
||||
import { getWorktreeRoot } from '../git/worktree-paths.js'
|
||||
import { releaseLocksOnTerminal } from '../git/job-locks.js'
|
||||
import { resolveRepoRoot } from './wait-for-job.js'
|
||||
import { pushBranchForJob } from '../git/push.js'
|
||||
import { createPullRequest, markPullRequestReady } from '../git/pr.js'
|
||||
import { cancelPbiOnFailure } from '../cancel/pbi-cascade.js'
|
||||
import { propagateStatusUpwards } from '../lib/tasks-status-update.js'
|
||||
import { transition as prFlowTransition } from '../flow/pr-flow.js'
|
||||
import { transition as sprintRunTransition } from '../flow/sprint-run.js'
|
||||
import { executeEffects } from '../flow/effects.js'
|
||||
import { execFile as execFileCb } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
const execGh = promisify(execFileCb)
|
||||
|
||||
async function fetchConflictFiles(prUrl: string): Promise<string[]> {
|
||||
try {
|
||||
const { stdout } = await execGh('gh', ['pr', 'view', prUrl, '--json', 'files'])
|
||||
const parsed = JSON.parse(stdout) as { files?: Array<{ path: string }> }
|
||||
return parsed.files?.map((f) => f.path) ?? []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const inputSchema = z.object({
|
||||
job_id: z.string().min(1),
|
||||
|
|
@ -85,26 +104,37 @@ export type DoneUpdatePlan = {
|
|||
branchOverride: string | undefined
|
||||
errorOverride: string | undefined
|
||||
skipWorktreeCleanup: boolean
|
||||
headSha: string | undefined
|
||||
}
|
||||
|
||||
export async function prepareDoneUpdate(
|
||||
jobId: string,
|
||||
branch: string | undefined,
|
||||
): Promise<DoneUpdatePlan> {
|
||||
const worktreeDir =
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ?? path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
const worktreeDir = getWorktreeRoot()
|
||||
const worktreePath = path.join(worktreeDir, jobId)
|
||||
const branchName = branch ?? `feat/job-${jobId.slice(-8)}`
|
||||
|
||||
const pushResult = await pushBranchForJob({ worktreePath, branchName })
|
||||
|
||||
if (pushResult.pushed) {
|
||||
let headSha: string | undefined
|
||||
try {
|
||||
const { execFile } = await import('node:child_process')
|
||||
const { promisify } = await import('node:util')
|
||||
const exec = promisify(execFile)
|
||||
const { stdout } = await exec('git', ['rev-parse', 'HEAD'], { cwd: worktreePath })
|
||||
headSha = stdout.trim()
|
||||
} catch (err) {
|
||||
console.warn(`[prepareDoneUpdate] failed to resolve HEAD sha for job ${jobId}:`, err)
|
||||
}
|
||||
return {
|
||||
dbStatus: 'DONE',
|
||||
pushedAt: new Date(),
|
||||
branchOverride: branchName,
|
||||
errorOverride: undefined,
|
||||
skipWorktreeCleanup: false,
|
||||
headSha,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -115,6 +145,7 @@ export async function prepareDoneUpdate(
|
|||
branchOverride: undefined,
|
||||
errorOverride: undefined,
|
||||
skipWorktreeCleanup: false,
|
||||
headSha: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -126,6 +157,7 @@ export async function prepareDoneUpdate(
|
|||
branchOverride: undefined,
|
||||
errorOverride: `push failed (${pushResult.reason}): ${snippet}`,
|
||||
skipWorktreeCleanup: true,
|
||||
headSha: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -376,6 +408,7 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
let branchToWrite = branch
|
||||
let errorToWrite = error
|
||||
let skipWorktreeCleanup = false
|
||||
let headShaToWrite: string | undefined
|
||||
|
||||
if (status === 'done') {
|
||||
// M12: idea-jobs hebben geen task/plan_snapshot/branch — skip de
|
||||
|
|
@ -401,6 +434,7 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
if (plan.branchOverride !== undefined) branchToWrite = plan.branchOverride
|
||||
if (plan.errorOverride !== undefined) errorToWrite = plan.errorOverride
|
||||
skipWorktreeCleanup = plan.skipWorktreeCleanup
|
||||
headShaToWrite = plan.headSha
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -414,9 +448,7 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
job.kind === 'TASK_IMPLEMENTATION' &&
|
||||
job.task_id
|
||||
) {
|
||||
const worktreeDir =
|
||||
process.env.SCRUM4ME_AGENT_WORKTREE_DIR ??
|
||||
path.join(os.homedir(), '.scrum4me-agent-worktrees')
|
||||
const worktreeDir = getWorktreeRoot()
|
||||
prUrl = await maybeCreateAutoPr({
|
||||
jobId: job_id,
|
||||
productId: job.product_id,
|
||||
|
|
@ -443,6 +475,7 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
...(summary !== undefined ? { summary } : {}),
|
||||
...(errorToWrite !== undefined ? { error: errorToWrite } : {}),
|
||||
...(prUrl !== null ? { pr_url: prUrl } : {}),
|
||||
...(headShaToWrite !== undefined ? { head_sha: headShaToWrite } : {}),
|
||||
...(model_id !== undefined ? { model_id } : {}),
|
||||
...(input_tokens !== undefined ? { input_tokens } : {}),
|
||||
...(output_tokens !== undefined ? { output_tokens } : {}),
|
||||
|
|
@ -468,6 +501,7 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
// sibling-cancel binnen dezelfde SprintRun af bij FAILED.
|
||||
// Idea-jobs hebben geen task_id en worden hier overgeslagen.
|
||||
let sprintRunBecameDone = false
|
||||
let storyBecameDone = false
|
||||
if (
|
||||
(actualStatus === 'done' || actualStatus === 'failed') &&
|
||||
job.kind === 'TASK_IMPLEMENTATION' &&
|
||||
|
|
@ -479,6 +513,7 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
actualStatus === 'done' ? 'DONE' : 'FAILED',
|
||||
)
|
||||
sprintRunBecameDone = actualStatus === 'done' && propagation.sprintRunChanged
|
||||
storyBecameDone = actualStatus === 'done' && propagation.storyChanged
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[update_job_status] propagateStatusUpwards error for task ${job.task_id}:`,
|
||||
|
|
@ -487,6 +522,72 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
}
|
||||
}
|
||||
|
||||
// PBI-47 (P0): STORY-mode auto-merge timing fix.
|
||||
// Only enable auto-merge when this DONE was the *last* task of a STORY
|
||||
// (story.status flipped to DONE) and pr_strategy === STORY. The
|
||||
// pr-flow transition emits ENABLE_AUTO_MERGE with the head_sha guard.
|
||||
if (
|
||||
storyBecameDone &&
|
||||
updated.pr_url &&
|
||||
headShaToWrite &&
|
||||
job.kind === 'TASK_IMPLEMENTATION'
|
||||
) {
|
||||
const storyCtx = await prisma.claudeJob.findUnique({
|
||||
where: { id: job_id },
|
||||
select: {
|
||||
task: { select: { story: { select: { status: true } } } },
|
||||
sprint_run: { select: { pr_strategy: true } },
|
||||
},
|
||||
})
|
||||
if (
|
||||
storyCtx?.sprint_run?.pr_strategy === 'STORY'
|
||||
&& storyCtx.task?.story.status === 'DONE'
|
||||
) {
|
||||
const result = prFlowTransition(
|
||||
{ kind: 'pr_opened', strategy: 'STORY', prUrl: updated.pr_url },
|
||||
{
|
||||
type: 'STORY_COMPLETED',
|
||||
storyId: '',
|
||||
headSha: headShaToWrite,
|
||||
},
|
||||
)
|
||||
const outcomes = await executeEffects(result.effects)
|
||||
// PBI-47 (C2): route MERGE_CONFLICT to sprint-run flow → PAUSED.
|
||||
// Other reasons (CHECKS_FAILED, GH_AUTH_ERROR, AUTO_MERGE_NOT_ALLOWED, UNKNOWN)
|
||||
// remain warnings; CHECKS_FAILED is already covered by the task-FAIL cascade.
|
||||
for (const o of outcomes) {
|
||||
if (o.effect === 'ENABLE_AUTO_MERGE' && !o.ok) {
|
||||
console.warn(
|
||||
`[update_job_status] auto-merge fail for ${updated.pr_url}: ${o.reason} ${o.stderr.slice(0, 200)}`,
|
||||
)
|
||||
if (o.reason === 'MERGE_CONFLICT') {
|
||||
const sprintRunId = await prisma.claudeJob
|
||||
.findUnique({
|
||||
where: { id: job_id },
|
||||
select: { sprint_run_id: true },
|
||||
})
|
||||
.then((j) => j?.sprint_run_id)
|
||||
if (sprintRunId) {
|
||||
const conflictFiles = await fetchConflictFiles(updated.pr_url)
|
||||
const conflictResult = sprintRunTransition(
|
||||
{ kind: 'running', sprintRunId },
|
||||
{
|
||||
type: 'MERGE_CONFLICT',
|
||||
prUrl: updated.pr_url,
|
||||
prHeadSha: headShaToWrite ?? '',
|
||||
conflictFiles,
|
||||
resumeInstructions:
|
||||
'Resolve the conflict on this branch, push, then resume the sprint via the UI.',
|
||||
},
|
||||
)
|
||||
await executeEffects(conflictResult.effects)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SPRINT-mode: bij sprint-DONE de draft-PR ready-for-review zetten.
|
||||
// Mens reviewt + mergt zelf — geen auto-merge in deze modus.
|
||||
if (sprintRunBecameDone && updated.pr_url) {
|
||||
|
|
@ -581,6 +682,12 @@ export function registerUpdateJobStatusTool(server: McpServer) {
|
|||
await cancelPbiOnFailure(job_id)
|
||||
}
|
||||
|
||||
// PBI-9: release product-worktree locks on terminal transitions.
|
||||
// No-op for jobs without registered locks (i.e. TASK_IMPLEMENTATION).
|
||||
if (actualStatus === 'done' || actualStatus === 'failed') {
|
||||
await releaseLocksOnTerminal(job_id)
|
||||
}
|
||||
|
||||
const queueCount = await prisma.claudeJob.count({
|
||||
where: { user_id: userId, status: 'QUEUED' },
|
||||
})
|
||||
|
|
|
|||
|
|
@ -15,8 +15,15 @@ const inputSchema = z.object({
|
|||
worktree_path: z.string().min(1),
|
||||
})
|
||||
|
||||
export async function getDiffInWorktree(worktreePath: string): Promise<string> {
|
||||
const { stdout } = await exec('git', ['diff', 'origin/main...HEAD'], { cwd: worktreePath })
|
||||
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
|
||||
}
|
||||
|
||||
|
|
@ -58,7 +65,7 @@ export function registerVerifyTaskAgainstPlanTool(server: McpServer) {
|
|||
where: { status: { in: ['CLAIMED', 'RUNNING'] } },
|
||||
orderBy: { created_at: 'desc' },
|
||||
take: 1,
|
||||
select: { id: true, plan_snapshot: true },
|
||||
select: { id: true, plan_snapshot: true, base_sha: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
|
@ -67,9 +74,19 @@ export function registerVerifyTaskAgainstPlanTool(server: McpServer) {
|
|||
|
||||
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)
|
||||
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'}`,
|
||||
|
|
|
|||
|
|
@ -7,10 +7,15 @@ import { Client } from 'pg'
|
|||
import * as fs from 'node:fs/promises'
|
||||
import * as os from 'node:os'
|
||||
import * as path from 'node:path'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { prisma } from '../prisma.js'
|
||||
|
||||
const execFileP = promisify(execFile)
|
||||
import { requireWriteAccess } from '../auth.js'
|
||||
import { toolJson, toolError, withToolErrors } from '../errors.js'
|
||||
import { createWorktreeForJob } from '../git/worktree.js'
|
||||
import { setupProductWorktrees, releaseLocksOnTerminal } from '../git/job-locks.js'
|
||||
|
||||
/** Parse `https://github.com/<owner>/<name>(.git)?` → `<name>`. */
|
||||
export function repoNameFromUrl(repoUrl: string | null | undefined): string | null {
|
||||
|
|
@ -181,6 +186,26 @@ export async function attachWorktreeToJob(
|
|||
branchName,
|
||||
reuseBranch: reused,
|
||||
})
|
||||
|
||||
// PBI-47 (P0): capture base_sha so verify_task_against_plan can diff
|
||||
// against the claim-time HEAD instead of origin/main. For reused branches
|
||||
// (siblings already pushed), base_sha = SHA of the worktree HEAD now.
|
||||
// For fresh branches, base_sha = origin/main HEAD which createWorktreeForJob
|
||||
// just checked out.
|
||||
let baseSha: string | null = null
|
||||
try {
|
||||
const { stdout } = await execFileP('git', ['rev-parse', 'HEAD'], { cwd: worktreePath })
|
||||
baseSha = stdout.trim()
|
||||
} catch (err) {
|
||||
console.warn(`[attachWorktreeToJob] failed to resolve base_sha for ${jobId}:`, err)
|
||||
}
|
||||
if (baseSha) {
|
||||
await prisma.claudeJob.update({
|
||||
where: { id: jobId },
|
||||
data: { base_sha: baseSha },
|
||||
})
|
||||
}
|
||||
|
||||
return { worktree_path: worktreePath, branch_name: actualBranch, reused_branch: reused }
|
||||
} catch (err) {
|
||||
await rollbackClaim(jobId)
|
||||
|
|
@ -234,6 +259,11 @@ export async function resetStaleClaimedJobs(userId: string): Promise<void> {
|
|||
|
||||
if (failedRows.length === 0 && requeuedRows.length === 0) return
|
||||
|
||||
// PBI-9: release any product-worktree locks held by these stale jobs.
|
||||
// No-op for jobs without registered locks (TASK_IMPLEMENTATION).
|
||||
for (const j of failedRows) await releaseLocksOnTerminal(j.id)
|
||||
for (const j of requeuedRows) await releaseLocksOnTerminal(j.id)
|
||||
|
||||
// Notify UI via SSE for each transition (best-effort)
|
||||
try {
|
||||
const pg = new Client({ connectionString: process.env.DATABASE_URL })
|
||||
|
|
@ -371,6 +401,9 @@ async function getFullJobContext(jobId: string) {
|
|||
idea: {
|
||||
include: {
|
||||
pbi: { select: { id: true, code: true, title: true } },
|
||||
secondary_products: {
|
||||
include: { product: { select: { id: true, repo_url: true } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
product: { select: { id: true, name: true, repo_url: true, definition_of_done: true } },
|
||||
|
|
@ -384,6 +417,21 @@ async function getFullJobContext(jobId: string) {
|
|||
if (!job.idea) return null
|
||||
const { idea } = job
|
||||
const { getIdeaPromptText } = await import('../lib/idea-prompts.js')
|
||||
|
||||
// Setup persistent product-worktrees for this idea-job (PBI-9).
|
||||
// Primary product is gated by repo_url via resolveRepoRoot returning null.
|
||||
// Secondary products from IdeaProduct[] need explicit repo_url filter.
|
||||
const involvedProductIds: string[] = []
|
||||
if (idea.product_id) involvedProductIds.push(idea.product_id)
|
||||
for (const ip of idea.secondary_products ?? []) {
|
||||
if (ip.product?.repo_url && !involvedProductIds.includes(ip.product_id)) {
|
||||
involvedProductIds.push(ip.product_id)
|
||||
}
|
||||
}
|
||||
const worktrees = involvedProductIds.length > 0
|
||||
? await setupProductWorktrees(job.id, involvedProductIds, (pid) => resolveRepoRoot(pid))
|
||||
: []
|
||||
|
||||
return {
|
||||
job_id: job.id,
|
||||
kind: job.kind,
|
||||
|
|
@ -408,6 +456,11 @@ async function getFullJobContext(jobId: string) {
|
|||
repo_url: job.product.repo_url,
|
||||
prompt_text: getIdeaPromptText(job.kind),
|
||||
branch_suggestion: `feat/idea-${idea.code.toLowerCase()}-${job.kind === 'IDEA_GRILL' ? 'grill' : 'plan'}`,
|
||||
product_worktrees: worktrees.map((w) => ({
|
||||
product_id: w.productId,
|
||||
worktree_path: w.worktreePath,
|
||||
})),
|
||||
primary_worktree_path: worktrees[0]?.worktreePath ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue