agent-dealer 1.4.4 → 1.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/server/dist/adapters/github.js +233 -3
- package/bundle/server/dist/adapters/github.test.js +177 -1
- package/bundle/server/dist/adapters/muse-capability.js +81 -8
- package/bundle/server/dist/adapters/muse-capability.test.js +89 -1
- package/bundle/server/dist/coordinator/commands.js +2 -1
- package/bundle/server/dist/coordinator/developer-effect.js +11 -1
- package/bundle/server/dist/coordinator/developer-effect.test.js +26 -1
- package/bundle/server/dist/coordinator/failure-reason.js +3 -0
- package/bundle/server/dist/coordinator/merge-conflict-sync.js +5 -1
- package/bundle/server/dist/coordinator/routing.js +5 -0
- package/bundle/server/dist/coordinator/routing.test.js +32 -0
- package/bundle/server/package.json +2 -2
- package/bundle/server/static-ui/assets/index-2IuALSbV.js +64 -0
- package/bundle/server/static-ui/assets/index-MgimDoh2.css +1 -0
- package/bundle/server/static-ui/index.html +2 -2
- package/bundle/shared/package.json +1 -1
- package/dist/bin.js +0 -0
- package/package.json +2 -3
- package/bundle/server/dist/adapters/authority-lifecycle.js +0 -289
- package/bundle/server/dist/adapters/execution-authority.js +0 -103
- package/bundle/server/dist/adapters/execution-authority.test.js +0 -166
- package/bundle/server/dist/adapters/external.js +0 -20
- package/bundle/server/dist/coordinator/authority-recovery.integration.test.js +0 -661
- package/bundle/server/dist/coordinator/dispatcher.js +0 -58
- package/bundle/server/dist/coordinator/dispatcher.test.js +0 -81
- package/bundle/server/dist/coordinator/intent-forecast.js +0 -13
- package/bundle/server/dist/coordinator/intent-forecast.test.js +0 -34
- package/bundle/server/dist/coordinator/session-lifecycle.integration.test.js +0 -127
- package/bundle/server/dist/coordinator/session-lifecycle.js +0 -280
- package/bundle/server/dist/coordinator/session-lifecycle.test.js +0 -121
- package/bundle/server/dist/db/authority-attempts-stale-at-migration.test.js +0 -65
- package/bundle/server/dist/intake/agent-routing.js +0 -32
- package/bundle/server/dist/queue/answers.test.js +0 -117
- package/bundle/server/dist/queue/dispatcher-recovery.test.js +0 -37
- package/bundle/server/dist/queue/dispatcher.js +0 -597
- package/bundle/server/dist/queue/plan-delegation.js +0 -27
- package/bundle/server/dist/queue/plan-delegation.test.js +0 -61
- package/bundle/server/dist/queue/plan-gate.test.js +0 -55
- package/bundle/server/dist/queue/result-qa.js +0 -66
- package/bundle/server/dist/queue/result-qa.test.js +0 -146
- package/bundle/server/dist/repository/authority-attempts.js +0 -189
- package/bundle/server/dist/repository/result-qa.js +0 -37
- package/bundle/server/dist/runners/codex-args.js +0 -59
- package/bundle/server/dist/runners/codex-args.test.js +0 -72
- package/bundle/server/dist/runners/codex-resume.test.js +0 -19
- package/bundle/server/dist/runners/codex.js +0 -46
- package/bundle/server/dist/runners/muse-code-settings.js +0 -23
- package/bundle/server/dist/runners/muse-code-settings.test.js +0 -18
- package/bundle/server/dist/runners/persist.js +0 -142
- package/bundle/server/dist/runners/qa.js +0 -54
- package/bundle/server/dist/runners/run-context.js +0 -183
- package/bundle/server/dist/runners/stream-json.test.js +0 -95
- package/bundle/server/dist/trace-summary.js +0 -93
- package/bundle/server/dist/usage-summary.js +0 -61
- package/bundle/server/dist/usage-summary.test.js +0 -33
- package/bundle/server/static-ui/assets/index-CHCiztRI.css +0 -1
- package/bundle/server/static-ui/assets/index-CrLQFFpw.js +0 -64
- package/bundle/server/static-ui/fonts/Monaco.ttf +0 -0
- package/bundle/shared/dist/cursor-auth-health.d.ts +0 -12
- package/bundle/shared/dist/cursor-auth-health.js +0 -36
- package/bundle/shared/dist/cursor-auth-health.test.d.ts +0 -1
- package/bundle/shared/dist/cursor-auth-health.test.js +0 -40
- package/bundle/shared/dist/plan-triage.d.ts +0 -317
- package/bundle/shared/dist/plan-triage.js +0 -65
- package/bundle/shared/dist/plan-triage.test.d.ts +0 -1
- package/bundle/shared/dist/plan-triage.test.js +0 -66
- package/bundle/shared/dist/result-qa.d.ts +0 -45
- package/bundle/shared/dist/result-qa.js +0 -25
- package/bundle/shared/dist/result-qa.test.d.ts +0 -1
- package/bundle/shared/dist/result-qa.test.js +0 -60
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { getDb } from "../db/index.js";
|
|
2
|
-
import { listIssues } from "../repository/issues.js";
|
|
3
|
-
import { advanceIssue } from "./session-lifecycle.js";
|
|
4
|
-
import { removeWorktree, isWorktreeClean, pruneWorktrees } from "../adapters/git-worktree.js";
|
|
5
|
-
import { createHumanAction } from "../repository/human-actions.js";
|
|
6
|
-
/** Advances every issue that has a queued session. Safe to call on a timer. */
|
|
7
|
-
export async function pollAndDispatch(deps) {
|
|
8
|
-
const active = listIssues(["ready", "developing", "reviewing", "repairing"]);
|
|
9
|
-
for (const issue of active) {
|
|
10
|
-
await advanceIssue(issue.id, deps).catch((err) => {
|
|
11
|
-
// A single issue's failure must not stop the poll loop from advancing others.
|
|
12
|
-
console.error(`advanceIssue(${issue.id}) failed:`, err);
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
/** Marks `running` worker_sessions with a stale heartbeat as failed — crash recovery. */
|
|
17
|
-
export function reconcileStaleSessions(staleThresholdMs) {
|
|
18
|
-
const db = getDb();
|
|
19
|
-
const cutoff = new Date(Date.now() - staleThresholdMs).toISOString();
|
|
20
|
-
const stale = db
|
|
21
|
-
.prepare("SELECT id FROM worker_sessions WHERE status = 'running' AND (heartbeat_at IS NULL OR heartbeat_at < ?)")
|
|
22
|
-
.all(cutoff);
|
|
23
|
-
const now = new Date().toISOString();
|
|
24
|
-
const reconciled = [];
|
|
25
|
-
for (const row of stale) {
|
|
26
|
-
db.prepare("UPDATE worker_sessions SET status = 'failed', completed_at = ?, updated_at = ?, error_json = ? WHERE id = ?").run(now, now, JSON.stringify({ reason: "stale heartbeat — process presumed dead" }), row.id);
|
|
27
|
-
reconciled.push(row.id);
|
|
28
|
-
}
|
|
29
|
-
return { reconciled };
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Crash recovery for a leftover worktree: a missing path is a no-op, a clean checkout
|
|
33
|
-
* is pruned, a dirty/unpushed developer worktree is preserved and escalated — never
|
|
34
|
-
* force-removed, since it may hold unrecovered work.
|
|
35
|
-
*/
|
|
36
|
-
export async function recoverWorktree(session, issueId) {
|
|
37
|
-
if (!session.worktreePath)
|
|
38
|
-
return "missing";
|
|
39
|
-
const fs = await import("node:fs");
|
|
40
|
-
if (!fs.existsSync(session.worktreePath))
|
|
41
|
-
return "missing";
|
|
42
|
-
const clean = await isWorktreeClean(session.worktreePath).catch(() => false);
|
|
43
|
-
if (clean) {
|
|
44
|
-
await removeWorktree({ repo: session.worktreePath, path: session.worktreePath, force: false }).catch(() => undefined);
|
|
45
|
-
return "removed";
|
|
46
|
-
}
|
|
47
|
-
createHumanAction({
|
|
48
|
-
issueId,
|
|
49
|
-
actionType: "policy_escalation",
|
|
50
|
-
reason: `Recovered a dirty worktree at ${session.worktreePath} from session ${session.id} — preserved, not removed.`,
|
|
51
|
-
question: "This worktree has uncommitted or unpushed changes from a crashed session. Inspect and resolve manually.",
|
|
52
|
-
evidence: { worktreePath: session.worktreePath, sessionId: session.id },
|
|
53
|
-
});
|
|
54
|
-
return "escalated";
|
|
55
|
-
}
|
|
56
|
-
export async function pruneCleanWorktreesForRepo(repo) {
|
|
57
|
-
await pruneWorktrees(repo).catch(() => undefined);
|
|
58
|
-
}
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import { test, before } from "node:test";
|
|
2
|
-
import assert from "node:assert/strict";
|
|
3
|
-
import fs from "node:fs";
|
|
4
|
-
import os from "node:os";
|
|
5
|
-
import path from "node:path";
|
|
6
|
-
process.env.AGENT_DEALER_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "dealer-dispatcher-"));
|
|
7
|
-
const { migrate } = await import("../db/index.js");
|
|
8
|
-
const { BUILTIN_AGENT_CLAUDE_ID, BUILTIN_AGENT_CURSOR_ID } = await import("@agent-dealer/shared");
|
|
9
|
-
const { createIssue, getIssue } = await import("../repository/issues.js");
|
|
10
|
-
const { createWorkerSession, getWorkerSession, listWorkerSessionsForIssue } = await import("../repository/worker-sessions.js");
|
|
11
|
-
const { createHumanAction } = await import("../repository/human-actions.js");
|
|
12
|
-
const { pollAndDispatch, reconcileStaleSessions } = await import("./dispatcher.js");
|
|
13
|
-
const { startIssueWorkflow } = await import("./session-lifecycle.js");
|
|
14
|
-
before(() => {
|
|
15
|
-
migrate();
|
|
16
|
-
});
|
|
17
|
-
function seedIssue() {
|
|
18
|
-
return createIssue({
|
|
19
|
-
title: "Dispatcher issue",
|
|
20
|
-
repo: "/tmp/fake-repo",
|
|
21
|
-
baseBranch: "main",
|
|
22
|
-
developerAgentId: BUILTIN_AGENT_CLAUDE_ID,
|
|
23
|
-
reviewerAgentId: BUILTIN_AGENT_CURSOR_ID,
|
|
24
|
-
maxReviewRounds: 3,
|
|
25
|
-
source: "manual",
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
/** Fake deps: no real git/gh/spawn — mirrors session-lifecycle.test.ts's fakeDeps. */
|
|
29
|
-
function fakeDeps() {
|
|
30
|
-
return {
|
|
31
|
-
worktree: {
|
|
32
|
-
addWorktree: async () => { },
|
|
33
|
-
removeWorktree: async () => { },
|
|
34
|
-
isWorktreeClean: async () => true,
|
|
35
|
-
mergeBase: async () => "base-sha-1",
|
|
36
|
-
},
|
|
37
|
-
github: {
|
|
38
|
-
viewPr: async () => ({ number: 1, url: "https://github.com/x/y/pull/1", headRefOid: "head-sha-1", baseRefName: "main", headRefName: "issue-branch", reviews: [] }),
|
|
39
|
-
publishReview: async () => ({ ok: true, event: "APPROVE" }),
|
|
40
|
-
},
|
|
41
|
-
spawnDeveloper: async () => ({ exitCode: 0, transcript: "done", logPath: "/tmp/log" }),
|
|
42
|
-
spawnReviewer: async () => ({ exitCode: 0, transcript: "reviewed", logPath: "/tmp/log" }),
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
// Reviewer finding #1: nothing previously proved that starting an issue actually gets
|
|
46
|
-
// dispatched — pollAndDispatch (what index.ts wires into the server's poll timer) must
|
|
47
|
-
// pick up the queued round-1 developer session created by startIssueWorkflow and run it.
|
|
48
|
-
test("pollAndDispatch advances a freshly started issue's queued developer session", async () => {
|
|
49
|
-
const issue = seedIssue();
|
|
50
|
-
await startIssueWorkflow(issue.id, fakeDeps());
|
|
51
|
-
const before = listWorkerSessionsForIssue(issue.id);
|
|
52
|
-
assert.equal(before.length, 1);
|
|
53
|
-
assert.equal(before[0].status, "queued");
|
|
54
|
-
await pollAndDispatch(fakeDeps());
|
|
55
|
-
const after = listWorkerSessionsForIssue(issue.id);
|
|
56
|
-
assert.equal(after[0].status, "done");
|
|
57
|
-
assert.equal(after.length, 2);
|
|
58
|
-
assert.equal(after[1].role, "reviewer");
|
|
59
|
-
assert.equal(getIssue(issue.id)?.status, "reviewing");
|
|
60
|
-
});
|
|
61
|
-
test("reconcileStaleSessions marks a stuck running developer session as failed", async () => {
|
|
62
|
-
const issue = seedIssue();
|
|
63
|
-
const session = createWorkerSession({ issueId: issue.id, role: "developer", round: 1, agentId: BUILTIN_AGENT_CLAUDE_ID, runtime: "claude_code" });
|
|
64
|
-
// Simulate: claimed (running) a long time ago, heartbeat stale, process gone.
|
|
65
|
-
const db = (await import("../db/index.js")).getDb();
|
|
66
|
-
const staleTime = new Date(Date.now() - 2 * 60 * 60_000).toISOString();
|
|
67
|
-
db.prepare("UPDATE worker_sessions SET status = 'running', started_at = ?, heartbeat_at = ? WHERE id = ?").run(staleTime, staleTime, session.id);
|
|
68
|
-
const result = reconcileStaleSessions(60 * 60_000);
|
|
69
|
-
assert.ok(result.reconciled.includes(session.id));
|
|
70
|
-
assert.equal(getWorkerSession(session.id)?.status, "failed");
|
|
71
|
-
});
|
|
72
|
-
test("reconcileStaleSessions ignores sessions with a recent heartbeat", async () => {
|
|
73
|
-
const issue = seedIssue();
|
|
74
|
-
const session = createWorkerSession({ issueId: issue.id, role: "developer", round: 1, agentId: BUILTIN_AGENT_CLAUDE_ID, runtime: "claude_code" });
|
|
75
|
-
const db = (await import("../db/index.js")).getDb();
|
|
76
|
-
const now = new Date().toISOString();
|
|
77
|
-
db.prepare("UPDATE worker_sessions SET status = 'running', started_at = ?, heartbeat_at = ? WHERE id = ?").run(now, now, session.id);
|
|
78
|
-
const result = reconcileStaleSessions(60 * 60_000);
|
|
79
|
-
assert.equal(result.reconciled.includes(session.id), false);
|
|
80
|
-
assert.equal(getWorkerSession(session.id)?.status, "running");
|
|
81
|
-
});
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
const FORECASTS = {
|
|
2
|
-
ready: () => ({ now: "Ready to start", next: "Start the developer round" }),
|
|
3
|
-
developing: (i) => ({ now: `Developer implementing round ${i.currentRound}`, next: "Verify the handoff once the session completes" }),
|
|
4
|
-
reviewing: (i) => ({ now: `Reviewer evaluating round ${i.currentRound}`, next: "Route the reviewer's verdict" }),
|
|
5
|
-
repairing: (i) => ({ now: `Developer repairing round ${i.currentRound}`, next: "Verify the handoff once the session completes" }),
|
|
6
|
-
final_review: () => ({ now: "Awaiting final human review", next: "Human resolves: complete, repair, or close" }),
|
|
7
|
-
needs_human: () => ({ now: "Waiting on a human action", next: "Resolve the open action to resume" }),
|
|
8
|
-
done: () => ({ now: "Done", next: "" }),
|
|
9
|
-
closed: () => ({ now: "Closed", next: "" }),
|
|
10
|
-
};
|
|
11
|
-
export function computeIntentForecast(issue) {
|
|
12
|
-
return FORECASTS[issue.status](issue);
|
|
13
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { test } from "node:test";
|
|
2
|
-
import assert from "node:assert/strict";
|
|
3
|
-
import { computeIntentForecast } from "./intent-forecast.js";
|
|
4
|
-
const BASE = {
|
|
5
|
-
id: "i1", source: "manual", externalId: null, externalLabel: null, externalUrl: null,
|
|
6
|
-
title: "T", description: null, acceptanceCriteria: null, repo: "/r", baseBranch: "main",
|
|
7
|
-
status: "ready", currentOwner: "system", currentIntent: null,
|
|
8
|
-
developerAgentId: null, reviewerAgentId: null, maxReviewRounds: 3, currentRound: 1,
|
|
9
|
-
branch: null, baseSha: null, headSha: null, prNumber: null, prUrl: null,
|
|
10
|
-
createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z",
|
|
11
|
-
};
|
|
12
|
-
test("ready issue forecasts starting the developer round", () => {
|
|
13
|
-
const forecast = computeIntentForecast(BASE);
|
|
14
|
-
assert.match(forecast.now, /Ready/i);
|
|
15
|
-
assert.match(forecast.next, /developer/i);
|
|
16
|
-
});
|
|
17
|
-
test("developing issue forecasts handoff verification", () => {
|
|
18
|
-
const forecast = computeIntentForecast({ ...BASE, status: "developing", currentOwner: "developer" });
|
|
19
|
-
assert.match(forecast.now, /Developer/i);
|
|
20
|
-
assert.match(forecast.next, /verify|handoff|pr/i);
|
|
21
|
-
});
|
|
22
|
-
test("reviewing issue mentions the round number", () => {
|
|
23
|
-
const forecast = computeIntentForecast({ ...BASE, status: "reviewing", currentOwner: "reviewer", currentRound: 2 });
|
|
24
|
-
assert.match(forecast.now, /Reviewer/i);
|
|
25
|
-
assert.ok(forecast.now.includes("2") || forecast.next.includes("2"));
|
|
26
|
-
});
|
|
27
|
-
test("needs_human issue forecasts waiting on a decision", () => {
|
|
28
|
-
const forecast = computeIntentForecast({ ...BASE, status: "needs_human", currentOwner: "human" });
|
|
29
|
-
assert.match(forecast.now, /human|action/i);
|
|
30
|
-
});
|
|
31
|
-
test("done issue has no next step", () => {
|
|
32
|
-
const forecast = computeIntentForecast({ ...BASE, status: "done" });
|
|
33
|
-
assert.equal(forecast.next, "");
|
|
34
|
-
});
|
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
// packages/server/src/coordinator/session-lifecycle.integration.test.ts
|
|
2
|
-
//
|
|
3
|
-
// The rest of this package's coordinator tests use fakeDeps() for the git-worktree
|
|
4
|
-
// boundary (see session-lifecycle.test.ts, dispatcher.test.ts) — good for the DI seam,
|
|
5
|
-
// but never proves the real adapter (packages/server/src/adapters/git-worktree.ts)
|
|
6
|
-
// actually round-trips with the coordinator. This file exercises the REAL worktree
|
|
7
|
-
// adapter (addWorktree/removeWorktree/isWorktreeClean/mergeBase) against a real temp
|
|
8
|
-
// git repo. github + spawn stay faked: they need network / a real CLI the test
|
|
9
|
-
// environment may not have.
|
|
10
|
-
import { test, before } from "node:test";
|
|
11
|
-
import assert from "node:assert/strict";
|
|
12
|
-
import { execFile } from "node:child_process";
|
|
13
|
-
import { promisify } from "node:util";
|
|
14
|
-
import fs from "node:fs";
|
|
15
|
-
import os from "node:os";
|
|
16
|
-
import path from "node:path";
|
|
17
|
-
const run = promisify(execFile);
|
|
18
|
-
process.env.AGENT_DEALER_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "dealer-lifecycle-integration-"));
|
|
19
|
-
const { migrate } = await import("../db/index.js");
|
|
20
|
-
const { BUILTIN_AGENT_CLAUDE_ID, BUILTIN_AGENT_CURSOR_ID } = await import("@agent-dealer/shared");
|
|
21
|
-
const { createIssue, getIssue } = await import("../repository/issues.js");
|
|
22
|
-
const { listWorkerSessionsForIssue } = await import("../repository/worker-sessions.js");
|
|
23
|
-
const { listOpenHumanActions } = await import("../repository/human-actions.js");
|
|
24
|
-
const { startIssueWorkflow, advanceIssue } = await import("./session-lifecycle.js");
|
|
25
|
-
const worktreeAdapter = await import("../adapters/git-worktree.js");
|
|
26
|
-
before(() => {
|
|
27
|
-
migrate();
|
|
28
|
-
});
|
|
29
|
-
async function git(cwd, args) {
|
|
30
|
-
const { stdout } = await run("git", args, { cwd });
|
|
31
|
-
return stdout.trim();
|
|
32
|
-
}
|
|
33
|
-
async function initRepo() {
|
|
34
|
-
const repo = fs.mkdtempSync(path.join(os.tmpdir(), "dealer-integration-repo-"));
|
|
35
|
-
await git(repo, ["init", "-b", "main"]);
|
|
36
|
-
await git(repo, ["config", "user.email", "test@example.com"]);
|
|
37
|
-
await git(repo, ["config", "user.name", "Test"]);
|
|
38
|
-
fs.writeFileSync(path.join(repo, "README.md"), "hello\n");
|
|
39
|
-
await git(repo, ["add", "README.md"]);
|
|
40
|
-
await git(repo, ["commit", "-m", "initial"]);
|
|
41
|
-
return repo;
|
|
42
|
-
}
|
|
43
|
-
function seedIssue(repo) {
|
|
44
|
-
return createIssue({
|
|
45
|
-
title: "Integration issue",
|
|
46
|
-
description: "test issue",
|
|
47
|
-
acceptanceCriteria: "works",
|
|
48
|
-
repo,
|
|
49
|
-
baseBranch: "main",
|
|
50
|
-
developerAgentId: BUILTIN_AGENT_CLAUDE_ID,
|
|
51
|
-
reviewerAgentId: BUILTIN_AGENT_CURSOR_ID,
|
|
52
|
-
maxReviewRounds: 3,
|
|
53
|
-
source: "manual",
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
test("a real git worktree carries a developer commit through to review under the real adapter", async () => {
|
|
57
|
-
const repo = await initRepo();
|
|
58
|
-
const issue = seedIssue(repo);
|
|
59
|
-
const branch = `issue-${issue.id}`;
|
|
60
|
-
// Filled in once the fake "developer" has actually committed inside the real worktree.
|
|
61
|
-
let developerHeadSha = "";
|
|
62
|
-
const deps = {
|
|
63
|
-
worktree: {
|
|
64
|
-
addWorktree: worktreeAdapter.addWorktree,
|
|
65
|
-
removeWorktree: worktreeAdapter.removeWorktree,
|
|
66
|
-
isWorktreeClean: worktreeAdapter.isWorktreeClean,
|
|
67
|
-
mergeBase: worktreeAdapter.mergeBase,
|
|
68
|
-
},
|
|
69
|
-
github: {
|
|
70
|
-
viewPr: async () => ({
|
|
71
|
-
number: 1,
|
|
72
|
-
url: "https://github.com/x/y/pull/1",
|
|
73
|
-
headRefOid: developerHeadSha,
|
|
74
|
-
baseRefName: "main",
|
|
75
|
-
headRefName: branch,
|
|
76
|
-
reviews: [],
|
|
77
|
-
}),
|
|
78
|
-
publishReview: async () => ({ ok: true, event: "APPROVE" }),
|
|
79
|
-
},
|
|
80
|
-
spawnDeveloper: async (session) => {
|
|
81
|
-
const worktreePath = session.worktreePath;
|
|
82
|
-
// Prove this is a REAL git worktree: write a file and commit, on disk.
|
|
83
|
-
fs.writeFileSync(path.join(worktreePath, "feature.txt"), "real work\n");
|
|
84
|
-
await git(worktreePath, ["add", "feature.txt"]);
|
|
85
|
-
await git(worktreePath, ["commit", "-m", "add feature"]);
|
|
86
|
-
developerHeadSha = await git(worktreePath, ["rev-parse", "HEAD"]);
|
|
87
|
-
return { exitCode: 0, transcript: "done", logPath: "/tmp/log" };
|
|
88
|
-
},
|
|
89
|
-
spawnReviewer: async () => ({
|
|
90
|
-
exitCode: 0,
|
|
91
|
-
transcript: "```json\n" +
|
|
92
|
-
JSON.stringify({
|
|
93
|
-
verdict: "approved",
|
|
94
|
-
baseSha: (await git(repo, ["rev-parse", "HEAD"])),
|
|
95
|
-
headSha: developerHeadSha,
|
|
96
|
-
acceptanceCriteriaAssessment: "met",
|
|
97
|
-
evidenceAssessment: "ok",
|
|
98
|
-
findings: [],
|
|
99
|
-
risks: [],
|
|
100
|
-
}) +
|
|
101
|
-
"\n```",
|
|
102
|
-
logPath: "/tmp/log",
|
|
103
|
-
}),
|
|
104
|
-
};
|
|
105
|
-
await startIssueWorkflow(issue.id, deps);
|
|
106
|
-
await advanceIssue(issue.id, deps); // developer: real worktree add -> real commit -> real merge-base
|
|
107
|
-
const afterDev = listWorkerSessionsForIssue(issue.id);
|
|
108
|
-
assert.equal(afterDev.length, 2);
|
|
109
|
-
assert.equal(afterDev[0].status, "done");
|
|
110
|
-
assert.equal(afterDev[1].role, "reviewer");
|
|
111
|
-
assert.equal(afterDev[1].inputSha, developerHeadSha);
|
|
112
|
-
assert.ok(developerHeadSha, "developer session must have produced a real commit sha");
|
|
113
|
-
const afterDevIssue = getIssue(issue.id);
|
|
114
|
-
assert.equal(afterDevIssue?.status, "reviewing");
|
|
115
|
-
assert.equal(afterDevIssue?.headSha, developerHeadSha);
|
|
116
|
-
// The developer's worktree must have been cleaned up by the real adapter, but the
|
|
117
|
-
// branch it created must survive in the bare repo for the reviewer worktree to check out.
|
|
118
|
-
const branches = await git(repo, ["branch", "--list", branch]);
|
|
119
|
-
assert.ok(branches.includes(branch));
|
|
120
|
-
await advanceIssue(issue.id, deps); // reviewer: real detached worktree checkout at the developer's real commit
|
|
121
|
-
const afterReview = listWorkerSessionsForIssue(issue.id);
|
|
122
|
-
assert.equal(afterReview.length, 2);
|
|
123
|
-
assert.equal(afterReview[1].status, "done");
|
|
124
|
-
assert.equal(getIssue(issue.id)?.status, "final_review");
|
|
125
|
-
assert.ok(listOpenHumanActions().some((a) => a.issueId === issue.id && a.actionType === "final_review"));
|
|
126
|
-
fs.rmSync(repo, { recursive: true, force: true });
|
|
127
|
-
});
|
|
@@ -1,280 +0,0 @@
|
|
|
1
|
-
// packages/server/src/coordinator/session-lifecycle.ts
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import os from "node:os";
|
|
4
|
-
import fs from "node:fs";
|
|
5
|
-
import { v4 as uuid } from "uuid";
|
|
6
|
-
import { getIssue, transitionIssue, incrementIssueRound } from "../repository/issues.js";
|
|
7
|
-
import { createWorkerSession, claimQueuedSession, completeSession, listWorkerSessionsForIssue, setSessionWorktreePath, } from "../repository/worker-sessions.js";
|
|
8
|
-
import { startWorkflowInstance, appendWorkflowEvent } from "../repository/workflow-events.js";
|
|
9
|
-
import { createHumanAction } from "../repository/human-actions.js";
|
|
10
|
-
import { reconcileFinding, listFindingsForIssue } from "../repository/findings.js";
|
|
11
|
-
import { getAgent } from "../repository/agents.js";
|
|
12
|
-
import { addWorktree, removeWorktree, isWorktreeClean, mergeBase } from "../adapters/git-worktree.js";
|
|
13
|
-
import { viewPr, publishReview } from "../adapters/github.js";
|
|
14
|
-
import { spawnDeveloperSession, spawnReviewerSession } from "./spawn.js";
|
|
15
|
-
import { buildDeveloperPrompt, buildReviewerPrompt } from "./prompts.js";
|
|
16
|
-
import { parseReviewerResult } from "./reviewer-result.js";
|
|
17
|
-
import { routeDeveloperOutcome, routeReviewerOutcome } from "./routing.js";
|
|
18
|
-
export const defaultCoordinatorDeps = {
|
|
19
|
-
worktree: { addWorktree, removeWorktree, isWorktreeClean, mergeBase },
|
|
20
|
-
github: { viewPr, publishReview },
|
|
21
|
-
spawnDeveloper: spawnDeveloperSession,
|
|
22
|
-
spawnReviewer: spawnReviewerSession,
|
|
23
|
-
};
|
|
24
|
-
function worktreePathFor(issue, role, round) {
|
|
25
|
-
return path.join(os.tmpdir(), "agent-dealer-worktrees", issue.id, `${role}-r${round}`);
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Resolves the selected agent profile's effective runtime/model/deck at session-creation
|
|
29
|
-
* time so the recorded worker_session snapshots it (later profile edits don't rewrite
|
|
30
|
-
* history). Falls back to claude_code only when no profile is set at all. Exported so
|
|
31
|
-
* other call sites that create worker_sessions (e.g. the human-action resolve route's
|
|
32
|
-
* repair-round restart) resolve the real profile instead of re-hardcoding a runtime.
|
|
33
|
-
*/
|
|
34
|
-
export function resolveProfile(agentId) {
|
|
35
|
-
const agent = agentId ? getAgent(agentId) : null;
|
|
36
|
-
return {
|
|
37
|
-
runtime: agent?.runtime ?? "claude_code",
|
|
38
|
-
model: agent?.defaultModel ?? agent?.defaultExecuteModel ?? null,
|
|
39
|
-
deckId: agent?.deckId ?? null,
|
|
40
|
-
playbookId: agent?.playbookId ?? null,
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
export async function startIssueWorkflow(issueId, _deps = defaultCoordinatorDeps) {
|
|
44
|
-
const issue = getIssue(issueId);
|
|
45
|
-
if (!issue)
|
|
46
|
-
throw new Error(`Issue not found: ${issueId}`);
|
|
47
|
-
const instance = startWorkflowInstance(issueId, "dev_reviewer_v1");
|
|
48
|
-
appendWorkflowEvent({ issueId, workflowInstanceId: instance.id, type: "workflow.started", actorType: "system", stage: "ready" });
|
|
49
|
-
// Deciding and recording the branch name here (not just on a successful handoff) means
|
|
50
|
-
// every developer round — including a round 1 that fails after creating the branch —
|
|
51
|
-
// agrees on the same name, so repair rounds always check out the right ref.
|
|
52
|
-
const branch = `issue-${issue.id}`;
|
|
53
|
-
const updated = transitionIssue(issueId, "developing", {
|
|
54
|
-
currentOwner: "developer",
|
|
55
|
-
currentIntent: "Developer implementing round 1",
|
|
56
|
-
branch,
|
|
57
|
-
});
|
|
58
|
-
const profile = resolveProfile(issue.developerAgentId);
|
|
59
|
-
const session = createWorkerSession({
|
|
60
|
-
issueId,
|
|
61
|
-
role: "developer",
|
|
62
|
-
round: 1,
|
|
63
|
-
agentId: issue.developerAgentId,
|
|
64
|
-
runtime: profile.runtime,
|
|
65
|
-
model: profile.model,
|
|
66
|
-
});
|
|
67
|
-
appendWorkflowEvent({
|
|
68
|
-
issueId,
|
|
69
|
-
workflowInstanceId: instance.id,
|
|
70
|
-
workerSessionId: session.id,
|
|
71
|
-
type: "worker.started",
|
|
72
|
-
actorType: "system",
|
|
73
|
-
stage: updated.status,
|
|
74
|
-
round: 1,
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
/** Claims and runs exactly one queued session for this issue to completion, then routes the outcome. */
|
|
78
|
-
export async function advanceIssue(issueId, deps = defaultCoordinatorDeps) {
|
|
79
|
-
const issue = getIssue(issueId);
|
|
80
|
-
if (!issue)
|
|
81
|
-
throw new Error(`Issue not found: ${issueId}`);
|
|
82
|
-
const queued = listWorkerSessionsForIssue(issueId).filter((s) => s.status === "queued");
|
|
83
|
-
const session = queued[queued.length - 1];
|
|
84
|
-
if (!session)
|
|
85
|
-
return;
|
|
86
|
-
const claimed = claimQueuedSession(session.id);
|
|
87
|
-
if (!claimed)
|
|
88
|
-
return; // another dispatcher already took it
|
|
89
|
-
const worktreePath = worktreePathFor(issue, claimed.role === "reviewer" ? "reviewer" : "developer", claimed.round);
|
|
90
|
-
if (claimed.role === "developer") {
|
|
91
|
-
await runDeveloperSession(issue, claimed, worktreePath, deps);
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
await runReviewerSession(issue, claimed, worktreePath, deps);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
async function runDeveloperSession(issue, session, worktreePath, deps) {
|
|
98
|
-
const branch = issue.branch ?? `issue-${issue.id}`;
|
|
99
|
-
if (session.round === 1) {
|
|
100
|
-
await deps.worktree.addWorktree({ repo: issue.repo, path: worktreePath, ref: issue.baseBranch, newBranch: branch });
|
|
101
|
-
}
|
|
102
|
-
else {
|
|
103
|
-
// Repair round: the branch already exists from round 1 (git worktree add -b creates
|
|
104
|
-
// the branch in the repo, independent of that worktree's later removal) — check it
|
|
105
|
-
// out as-is so work continues from the prior head instead of restarting from base.
|
|
106
|
-
await deps.worktree.addWorktree({ repo: issue.repo, path: worktreePath, ref: branch });
|
|
107
|
-
}
|
|
108
|
-
const withPath = setSessionWorktreePath(session.id, worktreePath);
|
|
109
|
-
const priorFindings = listFindingsForIssue(issue.id).filter((f) => f.status === "open" || f.status === "recurring");
|
|
110
|
-
const profile = resolveProfile(issue.developerAgentId);
|
|
111
|
-
const prompt = buildDeveloperPrompt({
|
|
112
|
-
taskSnapshot: { title: issue.title, description: issue.description ?? "", acceptanceCriteria: issue.acceptanceCriteria ?? "", repo: issue.repo, baseBranch: issue.baseBranch },
|
|
113
|
-
round: session.round,
|
|
114
|
-
findings: priorFindings.length ? priorFindings : undefined,
|
|
115
|
-
worktreePath,
|
|
116
|
-
deckId: profile.deckId,
|
|
117
|
-
playbookId: profile.playbookId,
|
|
118
|
-
});
|
|
119
|
-
let result;
|
|
120
|
-
try {
|
|
121
|
-
result = await deps.spawnDeveloper(withPath, prompt);
|
|
122
|
-
}
|
|
123
|
-
catch {
|
|
124
|
-
result = { exitCode: 1, transcript: "", logPath: "", timedOut: false };
|
|
125
|
-
}
|
|
126
|
-
const sessionStatus = result.exitCode === 0 && !result.timedOut ? "done" : "failed";
|
|
127
|
-
completeSession(session.id, { status: sessionStatus, exitCode: result.exitCode, logPath: result.logPath });
|
|
128
|
-
appendWorkflowEvent({ issueId: issue.id, workerSessionId: session.id, type: "worker.completed", actorType: "developer", stage: issue.status, round: session.round });
|
|
129
|
-
const outcome = await classifyDeveloperOutcome(issue, worktreePath, sessionStatus, deps);
|
|
130
|
-
const routed = routeDeveloperOutcome(outcome, { currentRound: issue.currentRound, maxReviewRounds: issue.maxReviewRounds });
|
|
131
|
-
if (outcome.kind === "clean_handoff") {
|
|
132
|
-
appendWorkflowEvent({ issueId: issue.id, workerSessionId: session.id, type: "pull_request.opened", actorType: "system", stage: issue.status, round: session.round, payload: { prNumber: outcome.prNumber, prUrl: outcome.prUrl, headSha: outcome.headSha } });
|
|
133
|
-
}
|
|
134
|
-
if (routed.next === "spawn_reviewer" && outcome.kind === "clean_handoff") {
|
|
135
|
-
transitionIssue(issue.id, "reviewing", {
|
|
136
|
-
currentOwner: "reviewer",
|
|
137
|
-
currentIntent: "Reviewer evaluating PR",
|
|
138
|
-
headSha: outcome.headSha,
|
|
139
|
-
baseSha: outcome.baseSha,
|
|
140
|
-
prNumber: outcome.prNumber,
|
|
141
|
-
prUrl: outcome.prUrl,
|
|
142
|
-
});
|
|
143
|
-
const reviewerProfile = resolveProfile(issue.reviewerAgentId);
|
|
144
|
-
createWorkerSession({ issueId: issue.id, role: "reviewer", round: session.round, agentId: issue.reviewerAgentId, runtime: reviewerProfile.runtime, model: reviewerProfile.model, inputSha: outcome.headSha });
|
|
145
|
-
}
|
|
146
|
-
else if (routed.next === "retry_developer") {
|
|
147
|
-
incrementIssueRound(issue.id);
|
|
148
|
-
const next = getIssue(issue.id);
|
|
149
|
-
const developerProfile = resolveProfile(issue.developerAgentId);
|
|
150
|
-
createWorkerSession({ issueId: issue.id, role: "developer", round: next.currentRound, agentId: issue.developerAgentId, runtime: developerProfile.runtime, model: developerProfile.model });
|
|
151
|
-
}
|
|
152
|
-
else if (routed.next === "human_action") {
|
|
153
|
-
transitionIssue(issue.id, "needs_human", { currentOwner: "human" });
|
|
154
|
-
createHumanAction({ issueId: issue.id, actionType: routed.actionType, reason: routed.reason, question: routed.reason });
|
|
155
|
-
}
|
|
156
|
-
if (outcome.kind !== "dirty_worktree") {
|
|
157
|
-
await deps.worktree.removeWorktree({ repo: issue.repo, path: worktreePath, force: false }).catch(() => undefined);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
async function classifyDeveloperOutcome(issue, worktreePath, sessionStatus, deps) {
|
|
161
|
-
if (sessionStatus === "failed")
|
|
162
|
-
return { kind: "session_failed" };
|
|
163
|
-
const clean = await deps.worktree.isWorktreeClean(worktreePath);
|
|
164
|
-
if (!clean)
|
|
165
|
-
return { kind: "dirty_worktree" };
|
|
166
|
-
try {
|
|
167
|
-
const view = await deps.github.viewPr({ cwd: worktreePath });
|
|
168
|
-
const baseSha = await deps.worktree.mergeBase({ repo: worktreePath, base: view.baseRefName, head: view.headRefName });
|
|
169
|
-
return { kind: "clean_handoff", headSha: view.headRefOid, baseSha, prNumber: view.number, prUrl: view.url };
|
|
170
|
-
}
|
|
171
|
-
catch {
|
|
172
|
-
return { kind: "no_pr" };
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
async function runReviewerSession(issue, session, worktreePath, deps) {
|
|
176
|
-
await deps.worktree.addWorktree({ repo: issue.repo, path: worktreePath, ref: session.inputSha ?? issue.headSha ?? issue.baseBranch, detach: true });
|
|
177
|
-
const withPath = setSessionWorktreePath(session.id, worktreePath);
|
|
178
|
-
const reviewerProfile = resolveProfile(issue.reviewerAgentId);
|
|
179
|
-
const prompt = buildReviewerPrompt({
|
|
180
|
-
taskSnapshot: { title: issue.title, description: issue.description ?? "", acceptanceCriteria: issue.acceptanceCriteria ?? "", repo: issue.repo, baseBranch: issue.baseBranch },
|
|
181
|
-
baseSha: issue.baseSha ?? "",
|
|
182
|
-
headSha: session.inputSha ?? issue.headSha ?? "",
|
|
183
|
-
worktreePath,
|
|
184
|
-
deckId: reviewerProfile.deckId,
|
|
185
|
-
playbookId: reviewerProfile.playbookId,
|
|
186
|
-
});
|
|
187
|
-
let result;
|
|
188
|
-
try {
|
|
189
|
-
result = await deps.spawnReviewer(withPath, prompt);
|
|
190
|
-
}
|
|
191
|
-
catch {
|
|
192
|
-
result = { exitCode: 1, transcript: "", logPath: "", timedOut: false };
|
|
193
|
-
}
|
|
194
|
-
const sessionStatus = result.exitCode === 0 && !result.timedOut ? "done" : "failed";
|
|
195
|
-
completeSession(session.id, { status: sessionStatus, exitCode: result.exitCode, logPath: result.logPath });
|
|
196
|
-
appendWorkflowEvent({ issueId: issue.id, workerSessionId: session.id, type: "worker.completed", actorType: "reviewer", stage: issue.status, round: session.round });
|
|
197
|
-
const outcome = await classifyReviewerOutcome(issue, session, worktreePath, sessionStatus, result.transcript, deps);
|
|
198
|
-
const routed = routeReviewerOutcome(outcome, { currentRound: issue.currentRound, maxReviewRounds: issue.maxReviewRounds });
|
|
199
|
-
if (outcome.kind === "verdict") {
|
|
200
|
-
appendWorkflowEvent({ issueId: issue.id, workerSessionId: session.id, type: "review.submitted", actorType: "reviewer", stage: issue.status, round: session.round, payload: outcome.result });
|
|
201
|
-
for (const f of outcome.result.findings) {
|
|
202
|
-
reconcileFinding({ issueId: issue.id, fingerprint: f.fingerprint, severity: f.severity, title: f.title, rationale: f.rationale, file: f.file, line: f.line, round: session.round });
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
if (routed.next === "final_review") {
|
|
206
|
-
transitionIssue(issue.id, "final_review", { currentOwner: "human" });
|
|
207
|
-
createHumanAction({ issueId: issue.id, actionType: "final_review", reason: "Reviewer approved the PR", question: "Accept this work?" });
|
|
208
|
-
}
|
|
209
|
-
else if (routed.next === "retry_developer_with_findings") {
|
|
210
|
-
transitionIssue(issue.id, "repairing", { currentOwner: "developer" });
|
|
211
|
-
incrementIssueRound(issue.id);
|
|
212
|
-
const next = getIssue(issue.id);
|
|
213
|
-
const developerProfile = resolveProfile(issue.developerAgentId);
|
|
214
|
-
createWorkerSession({ issueId: issue.id, role: "developer", round: next.currentRound, agentId: issue.developerAgentId, runtime: developerProfile.runtime, model: developerProfile.model });
|
|
215
|
-
appendWorkflowEvent({ issueId: issue.id, type: "repair.started", actorType: "system", stage: next.status, round: next.currentRound });
|
|
216
|
-
}
|
|
217
|
-
else if (routed.next === "retry_reviewer_at_new_head") {
|
|
218
|
-
// Record the freshly verified head (never re-queue against the stale one) — the issue
|
|
219
|
-
// stays in "reviewing" (self-loop) throughout, it never actually left that stage.
|
|
220
|
-
transitionIssue(issue.id, "reviewing", { headSha: routed.headSha });
|
|
221
|
-
createWorkerSession({ issueId: issue.id, role: "reviewer", round: session.round, agentId: issue.reviewerAgentId, runtime: reviewerProfile.runtime, model: reviewerProfile.model, inputSha: routed.headSha });
|
|
222
|
-
}
|
|
223
|
-
else if (routed.next === "human_action") {
|
|
224
|
-
transitionIssue(issue.id, "needs_human", { currentOwner: "human" });
|
|
225
|
-
createHumanAction({ issueId: issue.id, actionType: routed.actionType, reason: routed.reason, question: routed.reason });
|
|
226
|
-
}
|
|
227
|
-
await deps.worktree.removeWorktree({ repo: issue.repo, path: worktreePath, force: true }).catch(() => undefined);
|
|
228
|
-
}
|
|
229
|
-
/** Renders the coordinator's own normalized review body — never the agent's raw transcript. */
|
|
230
|
-
function renderReviewBody(result) {
|
|
231
|
-
const lines = [
|
|
232
|
-
`**Verdict:** ${result.verdict}`,
|
|
233
|
-
``,
|
|
234
|
-
`**Acceptance criteria:** ${result.acceptanceCriteriaAssessment}`,
|
|
235
|
-
`**Evidence:** ${result.evidenceAssessment}`,
|
|
236
|
-
];
|
|
237
|
-
if (result.findings.length) {
|
|
238
|
-
lines.push(``, `**Findings:**`);
|
|
239
|
-
for (const f of result.findings) {
|
|
240
|
-
const loc = f.file ? ` (${f.file}${f.line ? `:${f.line}` : ""})` : "";
|
|
241
|
-
lines.push(`- [${f.severity}] ${f.title}${loc}: ${f.rationale}`);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
if (result.risks.length) {
|
|
245
|
-
lines.push(``, `**Risks:**`);
|
|
246
|
-
for (const r of result.risks)
|
|
247
|
-
lines.push(`- ${r}`);
|
|
248
|
-
}
|
|
249
|
-
if (result.productScopeQuestion) {
|
|
250
|
-
lines.push(``, `**Product scope question:** ${result.productScopeQuestion}`);
|
|
251
|
-
}
|
|
252
|
-
return lines.join("\n");
|
|
253
|
-
}
|
|
254
|
-
async function classifyReviewerOutcome(issue, session, worktreePath, sessionStatus, transcript, deps) {
|
|
255
|
-
if (sessionStatus === "failed")
|
|
256
|
-
return { kind: "session_failed" };
|
|
257
|
-
const view = await deps.github.viewPr({ cwd: worktreePath }).catch(() => null);
|
|
258
|
-
if (view && session.inputSha && view.headRefOid !== session.inputSha) {
|
|
259
|
-
return { kind: "stale", currentHeadSha: view.headRefOid };
|
|
260
|
-
}
|
|
261
|
-
const parsed = parseReviewerResult(transcript);
|
|
262
|
-
if (!parsed)
|
|
263
|
-
return { kind: "session_failed" };
|
|
264
|
-
// The coordinator is the only component that publishes — the reviewer has no git/GitHub
|
|
265
|
-
// write access (see args.ts), so this is the sole place a review is ever submitted.
|
|
266
|
-
if (issue.prNumber) {
|
|
267
|
-
const event = parsed.verdict === "approved" ? "APPROVE" : parsed.verdict === "changes_requested" ? "REQUEST_CHANGES" : "COMMENT";
|
|
268
|
-
const bodyFile = path.join(os.tmpdir(), `review-${uuid()}.md`);
|
|
269
|
-
fs.writeFileSync(bodyFile, renderReviewBody(parsed));
|
|
270
|
-
try {
|
|
271
|
-
const published = await deps.github.publishReview({ cwd: worktreePath, prNumber: issue.prNumber, event, bodyFilePath: bodyFile });
|
|
272
|
-
if (!published.ok)
|
|
273
|
-
return { kind: "publish_failed" };
|
|
274
|
-
}
|
|
275
|
-
finally {
|
|
276
|
-
fs.unlink(bodyFile, () => undefined);
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
return { kind: "verdict", result: parsed };
|
|
280
|
-
}
|