agent-dealer 1.4.4 → 1.4.5
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/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/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,597 +0,0 @@
|
|
|
1
|
-
import { canTransition, planGateDecision } from "@agent-dealer/shared";
|
|
2
|
-
import { buildPlanEditedReplanPrompt, buildPlanFeedbackPrompt, buildPlanRevisePrompt, } from "../runners/prompts.js";
|
|
3
|
-
import { addArtifact, countByStatus, getLatestArtifact, getRun, listArtifacts, listRuns, markPlanTriageConsumed, patchRunPhaseBudget, transitionRun, updateRunFields, } from "../repository/runs.js";
|
|
4
|
-
import { runAgent, killRunProcess } from "../runners/claude.js";
|
|
5
|
-
import { persistRunOutput, seedDeliverableFromParent } from "../runners/persist.js";
|
|
6
|
-
import { checkAgentDeckHealth } from "../adapters/agent-deck.js";
|
|
7
|
-
import { pollLinearIssues } from "../adapters/external.js";
|
|
8
|
-
import { syncLinearForRun } from "../adapters/linear-sync.js";
|
|
9
|
-
import { pendingSendCount } from "../repository/outbound-drafts.js";
|
|
10
|
-
import { listAgentsWithHealth } from "../adapters/agent-health.js";
|
|
11
|
-
import { listAgents } from "../repository/agents.js";
|
|
12
|
-
import { runReflect } from "../runners/reflect.js";
|
|
13
|
-
const activeRuns = new Map();
|
|
14
|
-
const activePlanDrafts = new Set();
|
|
15
|
-
const activeReflects = new Set();
|
|
16
|
-
let listeners = [];
|
|
17
|
-
let pollTimer = null;
|
|
18
|
-
let dispatchTimer = null;
|
|
19
|
-
let healthCache = null;
|
|
20
|
-
const HEALTH_CACHE_MS = 15_000;
|
|
21
|
-
const MAX_PLAN_ATTEMPTS = Number(process.env.MAX_PLAN_ATTEMPTS ?? 3);
|
|
22
|
-
const EMPTY_PLAN_ERROR = "Agent did not return a plan";
|
|
23
|
-
function maxConcurrent() {
|
|
24
|
-
return Number(process.env.MAX_CONCURRENT_RUNS ?? 2);
|
|
25
|
-
}
|
|
26
|
-
function runtimeFor(run) {
|
|
27
|
-
return run.runtime ?? "claude_code";
|
|
28
|
-
}
|
|
29
|
-
function needsPlanDraft(run) {
|
|
30
|
-
if (run.status !== "plan_pending" && run.status !== "queued")
|
|
31
|
-
return false;
|
|
32
|
-
if (!run.runtime)
|
|
33
|
-
return false;
|
|
34
|
-
if (getLatestArtifact(run.id, "draft_plan"))
|
|
35
|
-
return false;
|
|
36
|
-
if (activePlanDrafts.has(run.id))
|
|
37
|
-
return false;
|
|
38
|
-
return true;
|
|
39
|
-
}
|
|
40
|
-
function sortQueueFifo(runs) {
|
|
41
|
-
return [...runs].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
42
|
-
}
|
|
43
|
-
function listPlanningPhaseRuns() {
|
|
44
|
-
return sortQueueFifo(listRuns("queued").concat(listRuns("plan_pending")));
|
|
45
|
-
}
|
|
46
|
-
/** Plan written and idle — human review lane (excludes active re-draft). */
|
|
47
|
-
function isReadyForPlanReview(run) {
|
|
48
|
-
return (run.status === "plan_pending" &&
|
|
49
|
-
!!getLatestArtifact(run.id, "draft_plan") &&
|
|
50
|
-
!activePlanDrafts.has(run.id));
|
|
51
|
-
}
|
|
52
|
-
/** Open (unanswered, unconsumed) question count for a plan_pending run. */
|
|
53
|
-
function openQuestionCount(runId) {
|
|
54
|
-
const tri = getLatestArtifact(runId, "plan_triage");
|
|
55
|
-
if (!tri?.contentJson)
|
|
56
|
-
return 0;
|
|
57
|
-
try {
|
|
58
|
-
const c = JSON.parse(tri.contentJson);
|
|
59
|
-
if (c.consumed || !c.questions?.length)
|
|
60
|
-
return 0;
|
|
61
|
-
const ans = getLatestArtifact(runId, "plan_answers");
|
|
62
|
-
if (ans && ans.createdAt > tri.createdAt)
|
|
63
|
-
return 0;
|
|
64
|
-
return c.questions.length;
|
|
65
|
-
}
|
|
66
|
-
catch {
|
|
67
|
-
return 0;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
export function getSnapshot() {
|
|
71
|
-
const all = listRuns();
|
|
72
|
-
const runningRuns = all.filter((r) => r.status === "running");
|
|
73
|
-
const waitingExecution = sortQueueFifo(all.filter((r) => r.status === "plan_approved"));
|
|
74
|
-
const resultReviewRuns = all
|
|
75
|
-
.filter((r) => r.status === "review" || r.status === "failed")
|
|
76
|
-
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
77
|
-
const recentDone = all
|
|
78
|
-
.filter((r) => r.status === "done")
|
|
79
|
-
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
|
|
80
|
-
.slice(0, 10);
|
|
81
|
-
const planningPhase = listPlanningPhaseRuns();
|
|
82
|
-
const awaitingPlanReview = planningPhase.filter(isReadyForPlanReview);
|
|
83
|
-
const planningActiveRuns = planningPhase.filter((r) => activePlanDrafts.has(r.id));
|
|
84
|
-
const planningQueuedRuns = planningPhase.filter((r) => !activePlanDrafts.has(r.id) && !isReadyForPlanReview(r));
|
|
85
|
-
const openQuestionCounts = {};
|
|
86
|
-
for (const run of awaitingPlanReview) {
|
|
87
|
-
const n = openQuestionCount(run.id);
|
|
88
|
-
if (n > 0)
|
|
89
|
-
openQuestionCounts[run.id] = n;
|
|
90
|
-
}
|
|
91
|
-
const awaitingAnswerRuns = awaitingPlanReview.filter((r) => openQuestionCounts[r.id]);
|
|
92
|
-
const pendingSendCounts = {};
|
|
93
|
-
for (const run of resultReviewRuns) {
|
|
94
|
-
const n = pendingSendCount(run.id);
|
|
95
|
-
if (n > 0)
|
|
96
|
-
pendingSendCounts[run.id] = n;
|
|
97
|
-
}
|
|
98
|
-
const autoApprovedRunIds = [...waitingExecution, ...runningRuns]
|
|
99
|
-
.filter((r) => getLatestArtifact(r.id, "approved_plan")?.author === "system")
|
|
100
|
-
.map((r) => r.id);
|
|
101
|
-
const sentRunIds = recentDone
|
|
102
|
-
.filter((r) => getLatestArtifact(r.id, "send_receipt"))
|
|
103
|
-
.map((r) => r.id);
|
|
104
|
-
return {
|
|
105
|
-
planReviewCount: awaitingPlanReview.length,
|
|
106
|
-
resultReviewCount: resultReviewRuns.length,
|
|
107
|
-
maxConcurrent: maxConcurrent(),
|
|
108
|
-
planningActiveRuns,
|
|
109
|
-
planningQueuedRuns,
|
|
110
|
-
runningRuns,
|
|
111
|
-
waitingExecution,
|
|
112
|
-
resultReviewRuns,
|
|
113
|
-
recentDone,
|
|
114
|
-
awaitingPlanReview,
|
|
115
|
-
awaitingAnswerRuns,
|
|
116
|
-
openQuestionCounts,
|
|
117
|
-
pendingSendCounts,
|
|
118
|
-
sentRunIds,
|
|
119
|
-
autoApprovedRunIds,
|
|
120
|
-
runs: all,
|
|
121
|
-
agentDeckOnline: false,
|
|
122
|
-
agents: [],
|
|
123
|
-
agentIssueCount: 0,
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
export async function getSnapshotAsync() {
|
|
127
|
-
const snap = getSnapshot();
|
|
128
|
-
const now = Date.now();
|
|
129
|
-
if (!healthCache || now - healthCache.at > HEALTH_CACHE_MS) {
|
|
130
|
-
healthCache = {
|
|
131
|
-
at: now,
|
|
132
|
-
agentDeckOnline: await checkAgentDeckHealth(),
|
|
133
|
-
agents: await listAgentsWithHealth(listAgents()),
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
snap.agentDeckOnline = healthCache.agentDeckOnline;
|
|
137
|
-
snap.agents = healthCache.agents;
|
|
138
|
-
snap.agentIssueCount = snap.agents.filter((a) => !a.healthy).length;
|
|
139
|
-
return snap;
|
|
140
|
-
}
|
|
141
|
-
/** Fail runs left in `running` after a server restart or crash. */
|
|
142
|
-
export function recoverOrphanedRuns() {
|
|
143
|
-
let count = 0;
|
|
144
|
-
for (const run of listRuns("running")) {
|
|
145
|
-
transitionRun(run.id, "failed");
|
|
146
|
-
addArtifact(run.id, "feedback", { error: "Server restarted mid-run — retry from failed", recoverable: true }, "system");
|
|
147
|
-
count++;
|
|
148
|
-
}
|
|
149
|
-
return count;
|
|
150
|
-
}
|
|
151
|
-
function reconcileOrphanedRunning() {
|
|
152
|
-
for (const run of listRuns("running")) {
|
|
153
|
-
if (activeRuns.has(run.id))
|
|
154
|
-
continue;
|
|
155
|
-
transitionRun(run.id, "failed");
|
|
156
|
-
addArtifact(run.id, "feedback", { error: "Run lost active worker — marked failed", recoverable: true }, "system");
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
function priorEmptyPlanAttempts(runId) {
|
|
160
|
-
return listArtifacts(runId).filter((a) => {
|
|
161
|
-
if (a.kind !== "feedback" || !a.contentJson)
|
|
162
|
-
return false;
|
|
163
|
-
try {
|
|
164
|
-
const c = JSON.parse(a.contentJson);
|
|
165
|
-
return c.error === EMPTY_PLAN_ERROR;
|
|
166
|
-
}
|
|
167
|
-
catch {
|
|
168
|
-
return false;
|
|
169
|
-
}
|
|
170
|
-
}).length;
|
|
171
|
-
}
|
|
172
|
-
export function cancelActiveRun(runId) {
|
|
173
|
-
killRunProcess(runId);
|
|
174
|
-
}
|
|
175
|
-
export function subscribe(listener) {
|
|
176
|
-
listeners.push(listener);
|
|
177
|
-
return () => {
|
|
178
|
-
listeners = listeners.filter((l) => l !== listener);
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
async function notify() {
|
|
182
|
-
const snap = await getSnapshotAsync();
|
|
183
|
-
for (const l of listeners)
|
|
184
|
-
l(snap);
|
|
185
|
-
}
|
|
186
|
-
export function startQueue() {
|
|
187
|
-
const pollMs = Number(process.env.POLL_INTERVAL_MS ?? 30_000);
|
|
188
|
-
if (!pollTimer) {
|
|
189
|
-
pollTimer = setInterval(() => {
|
|
190
|
-
pollLinearIssues().catch((e) => console.error("[linear]", e));
|
|
191
|
-
}, pollMs);
|
|
192
|
-
pollLinearIssues().catch((e) => console.error("[linear]", e));
|
|
193
|
-
}
|
|
194
|
-
if (!dispatchTimer) {
|
|
195
|
-
dispatchTimer = setInterval(() => {
|
|
196
|
-
dispatch().catch((e) => console.error("[queue]", e));
|
|
197
|
-
}, 3000);
|
|
198
|
-
dispatch().catch((e) => console.error("[queue]", e));
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
export function stopQueue() {
|
|
202
|
-
if (pollTimer)
|
|
203
|
-
clearInterval(pollTimer);
|
|
204
|
-
if (dispatchTimer)
|
|
205
|
-
clearInterval(dispatchTimer);
|
|
206
|
-
pollTimer = null;
|
|
207
|
-
dispatchTimer = null;
|
|
208
|
-
}
|
|
209
|
-
/** Fire-and-forget: agent drafts plan after task intake. */
|
|
210
|
-
export function schedulePlanDraft(run) {
|
|
211
|
-
if (!needsPlanDraft(run))
|
|
212
|
-
return;
|
|
213
|
-
if (activePlanDrafts.has(run.id))
|
|
214
|
-
return;
|
|
215
|
-
activePlanDrafts.add(run.id);
|
|
216
|
-
void draftPlan(run)
|
|
217
|
-
.catch((e) => console.error("[plan-draft]", run.id, e))
|
|
218
|
-
.finally(() => {
|
|
219
|
-
activePlanDrafts.delete(run.id);
|
|
220
|
-
notify().catch(console.error);
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
/** Fire-and-forget: post-review playbook reflect (D3 learning loop). */
|
|
224
|
-
export function scheduleReflect(run, opts) {
|
|
225
|
-
if (!run.playbookId || !run.deckId)
|
|
226
|
-
return;
|
|
227
|
-
if (activeReflects.has(run.id))
|
|
228
|
-
return;
|
|
229
|
-
void (async () => {
|
|
230
|
-
const online = await checkAgentDeckHealth();
|
|
231
|
-
if (!online)
|
|
232
|
-
return;
|
|
233
|
-
activeReflects.add(run.id);
|
|
234
|
-
try {
|
|
235
|
-
await runReflect(run, opts);
|
|
236
|
-
}
|
|
237
|
-
catch (e) {
|
|
238
|
-
console.error("[reflect]", run.id, e);
|
|
239
|
-
}
|
|
240
|
-
finally {
|
|
241
|
-
activeReflects.delete(run.id);
|
|
242
|
-
notify().catch(console.error);
|
|
243
|
-
}
|
|
244
|
-
})();
|
|
245
|
-
}
|
|
246
|
-
async function dispatchPlanDrafts() {
|
|
247
|
-
const pending = listRuns("plan_pending").concat(listRuns("queued"));
|
|
248
|
-
const slots = maxConcurrent() - activePlanDrafts.size;
|
|
249
|
-
if (slots <= 0)
|
|
250
|
-
return;
|
|
251
|
-
for (const run of pending) {
|
|
252
|
-
if (!needsPlanDraft(run))
|
|
253
|
-
continue;
|
|
254
|
-
if (activePlanDrafts.size >= maxConcurrent())
|
|
255
|
-
break;
|
|
256
|
-
activePlanDrafts.add(run.id);
|
|
257
|
-
void draftPlan(run)
|
|
258
|
-
.catch((e) => console.error("[plan-draft]", run.id, e))
|
|
259
|
-
.finally(() => {
|
|
260
|
-
activePlanDrafts.delete(run.id);
|
|
261
|
-
notify().catch(console.error);
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
async function dispatch() {
|
|
266
|
-
reconcileOrphanedRunning();
|
|
267
|
-
await dispatchPlanDrafts();
|
|
268
|
-
const running = countByStatus("running");
|
|
269
|
-
const slots = maxConcurrent() - running;
|
|
270
|
-
if (slots <= 0)
|
|
271
|
-
return;
|
|
272
|
-
const approved = sortQueueFifo(listRuns("plan_approved"));
|
|
273
|
-
for (const run of approved.slice(0, slots)) {
|
|
274
|
-
if (activeRuns.has(run.id))
|
|
275
|
-
continue;
|
|
276
|
-
const job = executeRun(run)
|
|
277
|
-
.catch((e) => console.error("[execute]", run.id, e))
|
|
278
|
-
.finally(() => {
|
|
279
|
-
activeRuns.delete(run.id);
|
|
280
|
-
notify().catch(console.error);
|
|
281
|
-
});
|
|
282
|
-
activeRuns.set(run.id, job);
|
|
283
|
-
}
|
|
284
|
-
await notify();
|
|
285
|
-
}
|
|
286
|
-
export async function kickRun(run) {
|
|
287
|
-
if (run.status !== "plan_approved") {
|
|
288
|
-
throw new Error(`Run must be plan_approved to kick, got ${run.status}`);
|
|
289
|
-
}
|
|
290
|
-
await dispatch();
|
|
291
|
-
}
|
|
292
|
-
function priorQuestionRounds(runId, currentTriageArtifactId) {
|
|
293
|
-
return listArtifacts(runId).filter((a) => {
|
|
294
|
-
if (a.kind !== "plan_triage" || a.id === currentTriageArtifactId || !a.contentJson)
|
|
295
|
-
return false;
|
|
296
|
-
try {
|
|
297
|
-
const c = JSON.parse(a.contentJson);
|
|
298
|
-
return (c.questions?.length ?? 0) > 0;
|
|
299
|
-
}
|
|
300
|
-
catch {
|
|
301
|
-
return false;
|
|
302
|
-
}
|
|
303
|
-
}).length;
|
|
304
|
-
}
|
|
305
|
-
/** Self-triage gate after a plan draft persists (PRD F2). Exported for tests. */
|
|
306
|
-
export function applyPlanGate(run) {
|
|
307
|
-
const art = getLatestArtifact(run.id, "plan_triage");
|
|
308
|
-
if (!art?.contentJson)
|
|
309
|
-
return "await_review";
|
|
310
|
-
let triage;
|
|
311
|
-
try {
|
|
312
|
-
triage = JSON.parse(art.contentJson);
|
|
313
|
-
}
|
|
314
|
-
catch {
|
|
315
|
-
return "await_review";
|
|
316
|
-
}
|
|
317
|
-
const decision = planGateDecision({
|
|
318
|
-
triage,
|
|
319
|
-
priorQuestionRounds: priorQuestionRounds(run.id, art.id),
|
|
320
|
-
});
|
|
321
|
-
if (decision !== "auto_approve")
|
|
322
|
-
return decision;
|
|
323
|
-
const fresh = getRun(run.id);
|
|
324
|
-
if (!fresh || fresh.status !== "plan_pending")
|
|
325
|
-
return "await_review";
|
|
326
|
-
const draft = getLatestArtifact(run.id, "draft_plan");
|
|
327
|
-
if (!draft?.contentJson)
|
|
328
|
-
return "await_review";
|
|
329
|
-
let plan;
|
|
330
|
-
try {
|
|
331
|
-
plan = JSON.parse(draft.contentJson);
|
|
332
|
-
}
|
|
333
|
-
catch {
|
|
334
|
-
return "await_review";
|
|
335
|
-
}
|
|
336
|
-
addArtifact(run.id, "approved_plan", { ...plan, autoApproved: true, rationale: triage.rationale }, "system");
|
|
337
|
-
transitionRun(run.id, "plan_approved");
|
|
338
|
-
void forceDispatch();
|
|
339
|
-
return "auto_approve";
|
|
340
|
-
}
|
|
341
|
-
export async function draftPlan(run, opts) {
|
|
342
|
-
if (run.status === "queued") {
|
|
343
|
-
transitionRun(run.id, "plan_pending");
|
|
344
|
-
}
|
|
345
|
-
const updated = getRun(run.id);
|
|
346
|
-
if (!updated.runtime) {
|
|
347
|
-
throw new Error("Select an agent runtime before planning");
|
|
348
|
-
}
|
|
349
|
-
if (!opts?.replace) {
|
|
350
|
-
syncLinearForRun(updated, "planning_started").catch((e) => console.error("[linear-sync] planning_started:", e));
|
|
351
|
-
}
|
|
352
|
-
const rt = runtimeFor(updated);
|
|
353
|
-
try {
|
|
354
|
-
const result = await runAgent(updated, "plan", opts?.revise);
|
|
355
|
-
const persisted = persistRunOutput({
|
|
356
|
-
run: updated,
|
|
357
|
-
phase: "plan",
|
|
358
|
-
runtime: rt,
|
|
359
|
-
exitCode: result.exitCode,
|
|
360
|
-
logPath: result.logPath,
|
|
361
|
-
rawTranscript: result.transcript,
|
|
362
|
-
});
|
|
363
|
-
const after = getRun(run.id);
|
|
364
|
-
if (!after || (after.status !== "plan_pending" && after.status !== "queued")) {
|
|
365
|
-
// Human approved or run moved on while agent was still planning — ignore late result.
|
|
366
|
-
await notify();
|
|
367
|
-
return after ?? updated;
|
|
368
|
-
}
|
|
369
|
-
if (persisted.planMarkdown) {
|
|
370
|
-
addArtifact(updated.id, "draft_plan", { markdown: persisted.planMarkdown, sessionId: persisted.sessionId }, "agent", result.logPath);
|
|
371
|
-
const triage = persisted.planTriage;
|
|
372
|
-
if (triage) {
|
|
373
|
-
addArtifact(updated.id, "plan_triage", {
|
|
374
|
-
verdict: triage.verdict,
|
|
375
|
-
rationale: triage.rationale,
|
|
376
|
-
questions: triage.questions,
|
|
377
|
-
sessionId: persisted.sessionId,
|
|
378
|
-
parseFallback: triage.parseFallback,
|
|
379
|
-
consumed: false,
|
|
380
|
-
}, "agent");
|
|
381
|
-
applyPlanGate(getRun(run.id));
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
else if (!opts?.replace) {
|
|
385
|
-
addArtifact(updated.id, "feedback", { error: EMPTY_PLAN_ERROR }, "system");
|
|
386
|
-
}
|
|
387
|
-
const emptyPlanExhausted = !persisted.planMarkdown &&
|
|
388
|
-
!opts?.replace &&
|
|
389
|
-
priorEmptyPlanAttempts(updated.id) >= MAX_PLAN_ATTEMPTS;
|
|
390
|
-
const planFailed = result.timedOut ||
|
|
391
|
-
emptyPlanExhausted ||
|
|
392
|
-
(!persisted.planMarkdown && result.exitCode !== 0);
|
|
393
|
-
if (planFailed) {
|
|
394
|
-
const stillActive = getRun(run.id);
|
|
395
|
-
if (stillActive && (stillActive.status === "plan_pending" || stillActive.status === "queued")) {
|
|
396
|
-
transitionRun(run.id, "failed");
|
|
397
|
-
addArtifact(run.id, "feedback", {
|
|
398
|
-
error: result.timedOut
|
|
399
|
-
? "Planning timed out"
|
|
400
|
-
: emptyPlanExhausted
|
|
401
|
-
? `Planning failed after ${MAX_PLAN_ATTEMPTS} empty results`
|
|
402
|
-
: "Planning failed",
|
|
403
|
-
exitCode: result.exitCode,
|
|
404
|
-
}, "system");
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
catch (err) {
|
|
409
|
-
const after = getRun(run.id);
|
|
410
|
-
if (after && (after.status === "plan_pending" || after.status === "queued")) {
|
|
411
|
-
transitionRun(run.id, "failed");
|
|
412
|
-
addArtifact(run.id, "feedback", { error: String(err) }, "system");
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
await notify();
|
|
416
|
-
return getRun(run.id);
|
|
417
|
-
}
|
|
418
|
-
/** Answer open plan questions (PRD F3). Structured answers approve + dispatch; free-form revises the plan. */
|
|
419
|
-
export function submitPlanAnswers(runId, input, opts) {
|
|
420
|
-
const run = getRun(runId);
|
|
421
|
-
if (!run)
|
|
422
|
-
return { ok: false, code: 404, error: "Not found" };
|
|
423
|
-
if (run.status !== "plan_pending") {
|
|
424
|
-
return { ok: false, code: 409, error: `No open questions — run is ${run.status}` };
|
|
425
|
-
}
|
|
426
|
-
const triageArt = getLatestArtifact(runId, "plan_triage");
|
|
427
|
-
if (!triageArt?.contentJson)
|
|
428
|
-
return { ok: false, code: 409, error: "No open questions" };
|
|
429
|
-
let triage;
|
|
430
|
-
try {
|
|
431
|
-
triage = JSON.parse(triageArt.contentJson);
|
|
432
|
-
}
|
|
433
|
-
catch {
|
|
434
|
-
return { ok: false, code: 409, error: "No open questions" };
|
|
435
|
-
}
|
|
436
|
-
if (triage.consumed || triage.questions.length === 0) {
|
|
437
|
-
return { ok: false, code: 409, error: "No open questions" };
|
|
438
|
-
}
|
|
439
|
-
const priorAnswers = getLatestArtifact(runId, "plan_answers");
|
|
440
|
-
if (priorAnswers && priorAnswers.createdAt > triageArt.createdAt) {
|
|
441
|
-
return { ok: false, code: 409, error: "Questions already answered" };
|
|
442
|
-
}
|
|
443
|
-
const expected = triage.questions.map((q) => q.id).sort().join(",");
|
|
444
|
-
const got = input.answers.map((a) => a.questionId).sort().join(",");
|
|
445
|
-
if (expected !== got) {
|
|
446
|
-
return { ok: false, code: 400, error: "Answers must cover every open question exactly once" };
|
|
447
|
-
}
|
|
448
|
-
const freeForm = input.answers.some((a) => a.freeText);
|
|
449
|
-
const outcome = freeForm ? "redraft" : "approved";
|
|
450
|
-
addArtifact(runId, "plan_answers", { answers: input.answers, outcome, answeredAt: new Date().toISOString() }, "human");
|
|
451
|
-
if (!freeForm) {
|
|
452
|
-
// null/empty = "Default" — do not wipe a seeded execute_model; only set explicit picks
|
|
453
|
-
if (input.executeModel?.trim()) {
|
|
454
|
-
updateRunFields(runId, { execute_model: input.executeModel.trim() });
|
|
455
|
-
}
|
|
456
|
-
if (input.executeBudget !== undefined) {
|
|
457
|
-
patchRunPhaseBudget(runId, "execute", input.executeBudget);
|
|
458
|
-
}
|
|
459
|
-
markPlanTriageConsumed(runId);
|
|
460
|
-
try {
|
|
461
|
-
transitionRun(runId, "plan_approved");
|
|
462
|
-
}
|
|
463
|
-
catch (e) {
|
|
464
|
-
return { ok: false, code: 409, error: String(e) };
|
|
465
|
-
}
|
|
466
|
-
const draft = getLatestArtifact(runId, "draft_plan");
|
|
467
|
-
let plan = { markdown: "" };
|
|
468
|
-
if (draft?.contentJson) {
|
|
469
|
-
try {
|
|
470
|
-
plan = JSON.parse(draft.contentJson);
|
|
471
|
-
}
|
|
472
|
-
catch {
|
|
473
|
-
return { ok: false, code: 409, error: "Draft plan is unreadable — request a re-draft" };
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
addArtifact(runId, "approved_plan", plan, "human");
|
|
477
|
-
void forceDispatch();
|
|
478
|
-
return { ok: true, outcome, run: getRun(runId) };
|
|
479
|
-
}
|
|
480
|
-
(opts?.onRedraft ?? scheduleRevisePlan)(getRun(runId), triage, input.answers);
|
|
481
|
-
return { ok: true, outcome, run: getRun(runId) };
|
|
482
|
-
}
|
|
483
|
-
function scheduleRevisePlan(run, triage, answers) {
|
|
484
|
-
if (activePlanDrafts.has(run.id))
|
|
485
|
-
return;
|
|
486
|
-
activePlanDrafts.add(run.id);
|
|
487
|
-
void draftPlan(run, {
|
|
488
|
-
replace: true,
|
|
489
|
-
revise: {
|
|
490
|
-
resumeSessionId: triage.sessionId,
|
|
491
|
-
prompt: buildPlanRevisePrompt(run, triage.questions, answers),
|
|
492
|
-
},
|
|
493
|
-
})
|
|
494
|
-
.catch((e) => console.error("[plan-revise]", run.id, e))
|
|
495
|
-
.finally(() => {
|
|
496
|
-
activePlanDrafts.delete(run.id);
|
|
497
|
-
notify().catch(console.error);
|
|
498
|
-
});
|
|
499
|
-
}
|
|
500
|
-
/** Fire-and-forget: human requested a new agent plan (replaces draft). */
|
|
501
|
-
export function scheduleRedraft(run, opts) {
|
|
502
|
-
if (activePlanDrafts.has(run.id))
|
|
503
|
-
return false;
|
|
504
|
-
if (run.status !== "plan_pending" && run.status !== "queued")
|
|
505
|
-
return false;
|
|
506
|
-
if (!run.runtime)
|
|
507
|
-
return false;
|
|
508
|
-
const feedback = opts?.feedback?.trim();
|
|
509
|
-
const editedMarkdown = opts?.editedMarkdown?.trim();
|
|
510
|
-
let revise;
|
|
511
|
-
if (editedMarkdown) {
|
|
512
|
-
const draft = getLatestArtifact(run.id, "draft_plan");
|
|
513
|
-
const sessionId = draft?.contentJson
|
|
514
|
-
? JSON.parse(draft.contentJson).sessionId
|
|
515
|
-
: undefined;
|
|
516
|
-
revise = {
|
|
517
|
-
resumeSessionId: sessionId,
|
|
518
|
-
prompt: buildPlanEditedReplanPrompt(run, editedMarkdown),
|
|
519
|
-
};
|
|
520
|
-
}
|
|
521
|
-
else if (feedback) {
|
|
522
|
-
const draft = getLatestArtifact(run.id, "draft_plan");
|
|
523
|
-
const sessionId = draft?.contentJson
|
|
524
|
-
? JSON.parse(draft.contentJson).sessionId
|
|
525
|
-
: undefined;
|
|
526
|
-
revise = {
|
|
527
|
-
resumeSessionId: sessionId,
|
|
528
|
-
prompt: buildPlanFeedbackPrompt(run, feedback),
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
activePlanDrafts.add(run.id);
|
|
532
|
-
void draftPlan(run, { replace: true, ...(revise ? { revise } : {}) })
|
|
533
|
-
.catch((e) => console.error("[plan-redraft]", run.id, e))
|
|
534
|
-
.finally(() => {
|
|
535
|
-
activePlanDrafts.delete(run.id);
|
|
536
|
-
notify().catch(console.error);
|
|
537
|
-
});
|
|
538
|
-
return true;
|
|
539
|
-
}
|
|
540
|
-
/** Human requested a new agent plan (replaces draft). @deprecated prefer scheduleRedraft */
|
|
541
|
-
export async function redraftPlan(run) {
|
|
542
|
-
return draftPlan(run, { replace: true });
|
|
543
|
-
}
|
|
544
|
-
async function executeRun(run) {
|
|
545
|
-
const rt = runtimeFor(run);
|
|
546
|
-
try {
|
|
547
|
-
seedDeliverableFromParent(run);
|
|
548
|
-
transitionRun(run.id, "running");
|
|
549
|
-
await notify();
|
|
550
|
-
const result = await runAgent(run, "execute");
|
|
551
|
-
const after = getRun(run.id);
|
|
552
|
-
if (!after || after.status === "cancelled") {
|
|
553
|
-
await notify();
|
|
554
|
-
return;
|
|
555
|
-
}
|
|
556
|
-
const persisted = persistRunOutput({
|
|
557
|
-
run,
|
|
558
|
-
phase: "execute",
|
|
559
|
-
runtime: rt,
|
|
560
|
-
exitCode: result.exitCode,
|
|
561
|
-
logPath: result.logPath,
|
|
562
|
-
rawTranscript: result.transcript,
|
|
563
|
-
});
|
|
564
|
-
const current = getRun(run.id);
|
|
565
|
-
if (!current || current.status === "cancelled") {
|
|
566
|
-
await notify();
|
|
567
|
-
return;
|
|
568
|
-
}
|
|
569
|
-
if (result.timedOut) {
|
|
570
|
-
transitionRun(run.id, "failed");
|
|
571
|
-
addArtifact(run.id, "feedback", { error: "Execution timed out", exitCode: result.exitCode, logPath: result.logPath }, "system");
|
|
572
|
-
}
|
|
573
|
-
else if (result.exitCode === 0 && !persisted.blocked) {
|
|
574
|
-
const updated = transitionRun(run.id, "review");
|
|
575
|
-
syncLinearForRun(updated, "review").catch((e) => console.error("[linear-sync] review:", e));
|
|
576
|
-
}
|
|
577
|
-
else if (canTransition(current.status, "failed")) {
|
|
578
|
-
transitionRun(run.id, "failed");
|
|
579
|
-
addArtifact(run.id, "feedback", {
|
|
580
|
-
error: persisted.blocked ? "Execution blocked" : "Execution failed",
|
|
581
|
-
exitCode: result.exitCode,
|
|
582
|
-
blocker: persisted.blockerSummary,
|
|
583
|
-
}, "system");
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
catch (err) {
|
|
587
|
-
const after = getRun(run.id);
|
|
588
|
-
if (after && after.status !== "cancelled" && canTransition(after.status, "failed")) {
|
|
589
|
-
transitionRun(run.id, "failed");
|
|
590
|
-
addArtifact(run.id, "feedback", { error: String(err) }, "system");
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
await notify();
|
|
594
|
-
}
|
|
595
|
-
export async function forceDispatch() {
|
|
596
|
-
await dispatch();
|
|
597
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { addArtifact, getLatestArtifact } from "../repository/runs.js";
|
|
2
|
-
/**
|
|
3
|
-
* Human approved a plan whose triage questions are still open.
|
|
4
|
-
* Record the delegation so the executor sees the questions it must decide itself.
|
|
5
|
-
* Call BEFORE markPlanTriageConsumed — a consumed triage has nothing to delegate.
|
|
6
|
-
*/
|
|
7
|
-
export function recordPlanDelegation(runId) {
|
|
8
|
-
const triageArt = getLatestArtifact(runId, "plan_triage");
|
|
9
|
-
if (!triageArt?.contentJson)
|
|
10
|
-
return false;
|
|
11
|
-
let triage;
|
|
12
|
-
try {
|
|
13
|
-
triage = JSON.parse(triageArt.contentJson);
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
return false;
|
|
17
|
-
}
|
|
18
|
-
if (triage.consumed || triage.questions.length === 0)
|
|
19
|
-
return false;
|
|
20
|
-
// >= not >: createdAt has millisecond precision, and answers for this triage
|
|
21
|
-
// round can tie with it. Answers can never legitimately predate their triage.
|
|
22
|
-
const answers = getLatestArtifact(runId, "plan_answers");
|
|
23
|
-
if (answers && answers.createdAt >= triageArt.createdAt)
|
|
24
|
-
return false;
|
|
25
|
-
addArtifact(runId, "plan_answers", { answers: [], outcome: "delegated", answeredAt: new Date().toISOString() }, "human");
|
|
26
|
-
return true;
|
|
27
|
-
}
|
|
@@ -1,61 +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-delegate-"));
|
|
7
|
-
process.env.MAX_CONCURRENT_RUNS = "0";
|
|
8
|
-
const { migrate } = await import("../db/index.js");
|
|
9
|
-
const { BUILTIN_AGENT_CLAUDE_ID } = await import("@agent-dealer/shared");
|
|
10
|
-
const { updateAgent } = await import("../repository/agents.js");
|
|
11
|
-
const { addArtifact, createRun, getLatestArtifact, markPlanTriageConsumed } = await import("../repository/runs.js");
|
|
12
|
-
const { recordPlanDelegation } = await import("./plan-delegation.js");
|
|
13
|
-
const QUESTIONS = [{ id: "q1", question: "Which backend?", options: [{ label: "SQLite" }, { label: "Postgres" }] }];
|
|
14
|
-
before(() => {
|
|
15
|
-
migrate();
|
|
16
|
-
updateAgent(BUILTIN_AGENT_CLAUDE_ID, { workspaceRoot: process.env.AGENT_DEALER_HOME });
|
|
17
|
-
});
|
|
18
|
-
function seedRun(triage) {
|
|
19
|
-
const run = createRun({
|
|
20
|
-
title: "Delegate test",
|
|
21
|
-
taskCategory: "other",
|
|
22
|
-
status: "plan_pending",
|
|
23
|
-
agentId: BUILTIN_AGENT_CLAUDE_ID,
|
|
24
|
-
});
|
|
25
|
-
addArtifact(run.id, "draft_plan", { markdown: "# Plan" }, "agent");
|
|
26
|
-
if (triage)
|
|
27
|
-
addArtifact(run.id, "plan_triage", triage, "agent");
|
|
28
|
-
return run;
|
|
29
|
-
}
|
|
30
|
-
test("open questions produce a delegated plan_answers record", () => {
|
|
31
|
-
const run = seedRun({ verdict: "needs_review", rationale: "r", questions: QUESTIONS, parseFallback: false, consumed: false });
|
|
32
|
-
assert.equal(recordPlanDelegation(run.id), true);
|
|
33
|
-
const art = getLatestArtifact(run.id, "plan_answers");
|
|
34
|
-
const content = JSON.parse(art.contentJson);
|
|
35
|
-
assert.equal(content.outcome, "delegated");
|
|
36
|
-
assert.deepEqual(content.answers, []);
|
|
37
|
-
assert.equal(art.author, "human");
|
|
38
|
-
});
|
|
39
|
-
test("no triage means nothing to delegate", () => {
|
|
40
|
-
const run = seedRun();
|
|
41
|
-
assert.equal(recordPlanDelegation(run.id), false);
|
|
42
|
-
assert.equal(getLatestArtifact(run.id, "plan_answers"), null);
|
|
43
|
-
});
|
|
44
|
-
test("triage without questions means nothing to delegate", () => {
|
|
45
|
-
const run = seedRun({ verdict: "trivial", rationale: "r", questions: [], parseFallback: false, consumed: false });
|
|
46
|
-
assert.equal(recordPlanDelegation(run.id), false);
|
|
47
|
-
});
|
|
48
|
-
test("consumed triage means nothing to delegate", () => {
|
|
49
|
-
const run = seedRun({ verdict: "needs_review", rationale: "r", questions: QUESTIONS, parseFallback: false, consumed: false });
|
|
50
|
-
markPlanTriageConsumed(run.id);
|
|
51
|
-
assert.equal(recordPlanDelegation(run.id), false);
|
|
52
|
-
});
|
|
53
|
-
test("already-answered questions are not delegated", () => {
|
|
54
|
-
const run = seedRun({ verdict: "needs_review", rationale: "r", questions: QUESTIONS, parseFallback: false, consumed: false });
|
|
55
|
-
addArtifact(run.id, "plan_answers", {
|
|
56
|
-
answers: [{ questionId: "q1", selectedLabel: "SQLite" }],
|
|
57
|
-
outcome: "approved",
|
|
58
|
-
answeredAt: new Date().toISOString(),
|
|
59
|
-
}, "human");
|
|
60
|
-
assert.equal(recordPlanDelegation(run.id), false);
|
|
61
|
-
});
|