diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts index d8077ab0..85691135 100644 --- a/packages/core/src/projects.ts +++ b/packages/core/src/projects.ts @@ -70,7 +70,9 @@ export interface GoalPatch { } export async function updateGoal(db: Db, projectId: number, goalId: number, patch: GoalPatch): Promise { - await getGoal(db, projectId, goalId); + const cur = await getGoal(db, projectId, goalId); + // PEP-209: nothing to change → no empty SET (drizzle: «No values to set»). + if (!Object.values(patch).some((v) => v !== undefined)) return cur; const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning(); return row!; } diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index 8b009730..c6b1c709 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -97,6 +97,12 @@ export async function updateSession( id: number, patch: Partial>, ): Promise { + // PEP-209: nothing to change → no empty SET (drizzle: «No values to set»). + if (!Object.values(patch).some((v) => v !== undefined)) { + const [cur] = await db.select().from(sessions).where(eq(sessions.id, id)); + if (!cur) throw new PeppaError(`Session #${id} not found`); + return cur; + } const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning(); if (!row) throw new PeppaError(`Session #${id} not found`); if (patch.status) await notify(db, { type: "session_updated", sessionId: id }); diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index c63406ab..1a920c24 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -219,7 +219,14 @@ export interface TaskPatch { /** `login`: the person who changed it from the web (PEP-32: authors in Activity). */ export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, sessionId?: number, login?: string): Promise { if (patch.goalId != null) await getGoal(db, ref.project.id, patch.goalId); - const [task] = await db.update(tasks).set(patch).where(eq(tasks.id, ref.task.id)).returning(); + // PEP-209: a patch of undefined fields only (MCP update_task with nothing but `status: review` while + // the checks run) — drizzle refuses an empty SET («No values to set»): nothing to write, the story as it is. + const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined)) as TaskPatch; + if (!Object.keys(defined).length) { + const [cur] = await db.select().from(tasks).where(eq(tasks.id, ref.task.id)); + return cur!; + } + const [task] = await db.update(tasks).set(defined).where(eq(tasks.id, ref.task.id)).returning(); const changed = Object.fromEntries( Object.entries(patch).filter(([k, v]) => v !== undefined && ref.task[k as keyof Task] !== v), ); diff --git a/packages/runner/src/platform-delays.ts b/packages/runner/src/platform-delays.ts index 0e774de5..1f533d62 100644 --- a/packages/runner/src/platform-delays.ts +++ b/packages/runner/src/platform-delays.ts @@ -34,7 +34,7 @@ import { wakeOnGreen } from "./ci-feedback.ts"; import { moveTask } from "./flow.ts"; import { LIMIT_REQUEST, limitHintKey, limitOver, TURN_RETRY_MAX, type LimitHint } from "./limit-delay.ts"; import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts"; -import { restartAgent } from "./stuck-tasks.ts"; +import { restartAgent, sharedCopyBusy } from "./stuck-tasks.ts"; import { requestFromLimitAnswer } from "./subscription-request.ts"; type Log = (m: string) => void; @@ -267,6 +267,9 @@ async function sweep(db: Db, d: PlatformDelay, now: number, log: Log, commit: st // platform — the error may be fixed since (Codex `danger-full-access`, `account/read failed`): // the card goes, the restart count is reset and the story is tried again. if (STALE_AFTER_RELEASE.includes(d.reason) && d.exhausted && commit && d.commit !== commit) { + // One agent per shared working copy (PEP-209): the card stays until the copy is free. + const [last] = (await listSessions(db, { taskId: ref.task.id })).sort((a, b) => b.id - a.id); + if (await sharedCopyBusy(db, ref, last ?? null)) return; await clear(); await retryAfterRelease(db, ref, log); return; diff --git a/packages/runner/src/stuck-tasks.ts b/packages/runner/src/stuck-tasks.ts index 56da627c..a8bdc953 100644 --- a/packages/runner/src/stuck-tasks.ts +++ b/packages/runner/src/stuck-tasks.ts @@ -27,6 +27,7 @@ import { pendingQuestions, pendingReview, platformDelay, + resolveRunnerSettings, prGate, setSetting, taskPrNumber, @@ -149,6 +150,20 @@ export async function restartAgent(db: Db, ref: TaskRef, s: SessionView | null, await resumeSession(db, s.id, { prompt }); } +/** + * PEP-209: the agent would run in a working copy another agent of the project works in right now + * (workspace «shared» — QLFW had 8–10 agents switching each other's branches). One agent per copy: + * the healing waits its turn. Idle agents don't touch git; a separate host has its own clone. + */ +export async function sharedCopyBusy(db: Db, ref: TaskRef, s: SessionView | null): Promise { + if (s?.hostId) return false; + const rs = s ? null : await resolveRunnerSettings(db, ref.project.id, ref.task.id); + const shared = s ? !s.workspacePath : rs!.workspace !== "worktree" && rs!.isolation === "none" && !rs!.hosts.length; + if (!shared) return false; + return (await listSessions(db, { active: true, projectId: ref.project.id })).some((x) => x.id !== s?.id && !x.workspacePath && !x.hostId && WORKING.includes(x.status)); +} +const WORKING = ["starting", "running"]; + const STOPPED = ["idle", "waiting_input", "done", "failed"]; /** Delays other than `stuck` whose own path still works on the story. */ const OTHER_PATHS = ["agent", "limit", "checks", "start", "switch", "turn", "accept", "ci"]; @@ -224,6 +239,14 @@ async function healOne(db: Db, ref: TaskRef, delays: Awaited { + test("update_task(status: review) при идущих проверках — без ошибки «No values to set»", async () => { + const t = await stuck({ checks: null }); + gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, `task/${t.tp.taskKey}`), "peppa/test", "pending"); + const [a, b] = InMemoryTransport.createLinkedPair(); + await createAgentServer(db, { defaultKey: t.tp.key }).connect(a); + const client = new Client({ name: "mock-agent", version: "0" }); + await client.connect(b); + const r = await client.callTool({ name: "update_task", arguments: { task: t.tp.taskKey, status: "review" } }); + const text = (r.content as Array<{ text: string }>)[0]!.text; + assert.equal(!!r.isError, false, text); + assert.match(text, /still running/); + assert.ok(await runner.getReviewWanted(db, t.ref.task.id), "the request is remembered"); + // The same at the core: a patch of undefined fields changes nothing and does not throw. + const same = await core.updateTask(db, t.ref, { prUrl: undefined, title: undefined }); + assert.equal(same.id, t.ref.task.id); + await client.close(); + }); + + test("Общая рабочая копия: один агент на копию, вторая задача ждёт очереди", async () => { + const t = await stuck({ checks: "failure" }); + // A second stuck story of the same project, same shared copy. + const other = await core.createTask(db, { projectId: t.proj.id, title: "Вторая" }); + const sha2 = gitea.commit(t.proj.giteaOwner, t.proj.giteaRepo, `task/${other.key}`, { "g.txt": "2" }); + const pr2 = gitea.openPull(t.proj.giteaOwner, t.proj.giteaRepo, `task/${other.key}`); + gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, sha2, "peppa/test", "failure"); + await core.updateTask(db, other, { status: "in_progress", prUrl: `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/pulls/${pr2.number}` }); + const s2 = await core.createSession(db, { projectId: t.proj.id, taskId: other.task.id }); + await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s2.id)); + // Somebody already works in the shared copy. + const busy = await core.createSession(db, { projectId: t.proj.id, taskId: null }); + await db.update(sessions).set({ status: "running" }).where(eq(sessions.id, busy.id)); + await tick(Date.now()); + for (const id of [t.ref.task.id, other.task.id]) { + const d = await core.getPlatformDelay(db, { projectId: t.proj.id, taskId: id }, "stuck"); + assert.equal(d?.state, "queued", "waits for the copy"); + assert.equal(d?.attempts, 0, "not an attempt"); + } + // The copy is free: exactly one agent is relaunched, the other one waits for it. + await db.update(sessions).set({ status: "done" }).where(eq(sessions.id, busy.id)); + await tick(Date.now() + 6 * MIN); + const healed = [await runner.getStuckHeal(db, t.ref.task.id), await runner.getStuckHeal(db, other.task.id)].filter((h) => (h?.attempts ?? 0) > 0); + assert.equal(healed.length, 1, "one agent per shared copy"); + for (const id of [t.sid, s2.id]) { + await waitFor("settled", async () => ((await core.getSession(db, id)).status !== "starting" ? true : null)); + await runner.stopSession(db, id).catch(() => {}); + } + }); +});