refactor: replace autoChain with projectTick queue scanning

Remove hard-coded auto-chain dispatch (DEV done→QA, QA fail→DEV) and
replace with a general-purpose projectTick service that scans the queue
and fills free worker slots after every state transition.

- Create lib/services/tick.ts: consolidates shared helpers and core
  projectTick() function from duplicated code in work-start/auto-pickup
- work_finish: replaces auto-chain block with projectTick call
- work_start: adds projectTick after dispatch to fill parallel slots
- auto_pickup: delegates per-project loop to projectTick
- Remove autoChain from Project type, migration code, and project-register
- Remove scheduling config dependency from work_finish
- Net -112 lines: simpler, self-healing pipeline

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Lauren ten Hoor
2026-02-10 21:46:11 +08:00
parent d7178bb8e5
commit 55b062ac76
8 changed files with 246 additions and 171 deletions

View File

@@ -1,51 +1,21 @@
/**
* auto_pickup — Automated task pickup (heartbeat handler).
*
* Health checks → queue scan → fill free worker slots.
* Health checks → projectTick per project → notify.
* Optional projectGroupId for single-project or all-project sweep.
*/
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { jsonResult } from "openclaw/plugin-sdk";
import type { ToolContext } from "../types.js";
import type { Issue, StateLabel } from "../providers/provider.js";
import { createProvider } from "../providers/index.js";
import { selectModel } from "../model-selector.js";
import { getProject, getWorker, getSessionForModel, readProjects, type Project } from "../projects.js";
import { dispatchTask } from "../dispatch.js";
import { detectContext, generateGuardrails } from "../context-guard.js";
import { type Tier } from "../tiers.js";
import { readProjects } from "../projects.js";
import { detectContext } from "../context-guard.js";
import { log as auditLog } from "../audit.js";
import { notify, getNotificationConfig } from "../notify.js";
import { checkWorkerHealth, type HealthFix } from "../services/health.js";
const DEV_LABELS: StateLabel[] = ["To Do", "To Improve"];
const QA_LABELS: StateLabel[] = ["To Test"];
const PRIORITY_ORDER: StateLabel[] = ["To Improve", "To Test", "To Do"];
const TIER_LABELS: Tier[] = ["junior", "medior", "senior", "qa"];
import { projectTick, type TickAction } from "../services/tick.js";
type ExecutionMode = "parallel" | "sequential";
type PickupAction = { project: string; groupId: string; issueId: number; issueTitle: string; role: "dev" | "qa"; model: string; sessionAction: "spawn" | "send"; announcement: string };
function detectTierFromLabels(labels: string[]): Tier | null {
const lower = labels.map((l) => l.toLowerCase());
return TIER_LABELS.find((t) => lower.includes(t)) ?? null;
}
async function findNextIssueForRole(
provider: { listIssuesByLabel(label: StateLabel): Promise<Issue[]> },
role: "dev" | "qa",
): Promise<{ issue: Issue; label: StateLabel } | null> {
const labels = role === "dev"
? PRIORITY_ORDER.filter((l) => DEV_LABELS.includes(l))
: PRIORITY_ORDER.filter((l) => QA_LABELS.includes(l));
for (const label of labels) {
try {
const issues = await provider.listIssuesByLabel(label);
if (issues.length > 0) return { issue: issues[issues.length - 1], label };
} catch { /* continue */ }
}
return null;
}
export function createAutoPickupTool(api: OpenClawPluginApi) {
return (ctx: ToolContext) => ({
@@ -83,7 +53,7 @@ export function createAutoPickupTool(api: OpenClawPluginApi) {
}
const healthFixes: Array<HealthFix & { project: string; role: string }> = [];
const pickups: PickupAction[] = [];
const pickups: Array<TickAction & { project: string }> = [];
const skipped: Array<{ project: string; role?: string; reason: string }> = [];
let globalActiveDev = 0, globalActiveQa = 0, activeProjectCount = 0, pickupCount = 0;
@@ -102,65 +72,31 @@ export function createAutoPickupTool(api: OpenClawPluginApi) {
}
}
// Pass 2: pick up tasks
// Pass 2: projectTick per project
for (const [groupId] of projectEntries) {
const current = (await readProjects(workspaceDir)).projects[groupId];
if (!current) continue;
const { provider } = createProvider({ repo: current.repo });
const roleExecution: ExecutionMode = current.roleExecution ?? "parallel";
const projectActive = current.dev.active || current.qa.active;
// Sequential project guard (needs global state)
if (projectExecution === "sequential" && !projectActive && activeProjectCount >= 1) {
skipped.push({ project: current.name, reason: "Sequential: another project active" });
continue;
}
for (const role of ["dev", "qa"] as const) {
if (maxPickups !== undefined && pickupCount >= maxPickups) { skipped.push({ project: current.name, role, reason: `Max pickups reached` }); continue; }
const worker = getWorker(current, role);
if (worker.active) { skipped.push({ project: current.name, role, reason: `Already active (#${worker.issueId})` }); continue; }
if (roleExecution === "sequential" && getWorker(current, role === "dev" ? "qa" : "dev").active) {
skipped.push({ project: current.name, role, reason: `Sequential: other role active` }); continue;
}
const remaining = maxPickups !== undefined ? maxPickups - pickupCount : undefined;
const result = await projectTick({
workspaceDir, groupId, agentId: ctx.agentId, pluginConfig, sessionKey: ctx.sessionKey,
dryRun, maxPickups: remaining,
});
const next = await findNextIssueForRole(provider, role);
if (!next) continue;
const { issue, label: currentLabel } = next;
const targetLabel: StateLabel = role === "dev" ? "Doing" : "Testing";
// Model selection
let modelAlias: string;
const tier = detectTierFromLabels(issue.labels);
if (tier) {
if (role === "qa" && tier !== "qa") modelAlias = "qa";
else if (role === "dev" && tier === "qa") modelAlias = selectModel(issue.title, issue.description ?? "", role).tier;
else modelAlias = tier;
} else {
modelAlias = selectModel(issue.title, issue.description ?? "", role).tier;
}
if (dryRun) {
pickups.push({ project: current.name, groupId, issueId: issue.iid, issueTitle: issue.title, role, model: modelAlias, sessionAction: getSessionForModel(worker, modelAlias) ? "send" : "spawn", announcement: `[DRY RUN] Would pick up #${issue.iid}` });
} else {
try {
const dr = await dispatchTask({
workspaceDir, agentId: ctx.agentId, groupId, project: current, issueId: issue.iid,
issueTitle: issue.title, issueDescription: issue.description ?? "", issueUrl: issue.web_url,
role, modelAlias, fromLabel: currentLabel, toLabel: targetLabel,
transitionLabel: (id, from, to) => provider.transitionLabel(id, from as StateLabel, to as StateLabel),
pluginConfig, sessionKey: ctx.sessionKey,
});
pickups.push({ project: current.name, groupId, issueId: issue.iid, issueTitle: issue.title, role, model: dr.modelAlias, sessionAction: dr.sessionAction, announcement: dr.announcement });
} catch (err) {
skipped.push({ project: current.name, role, reason: `Dispatch failed: ${(err as Error).message}` });
continue;
}
}
pickupCount++;
if (role === "dev") globalActiveDev++; else globalActiveQa++;
if (!projectActive) activeProjectCount++;
pickups.push(...result.pickups.map((p) => ({ ...p, project: current.name })));
skipped.push(...result.skipped.map((s) => ({ project: current.name, ...s })));
pickupCount += result.pickups.length;
for (const p of result.pickups) {
if (p.role === "dev") globalActiveDev++; else globalActiveQa++;
}
if (result.pickups.length > 0 && !projectActive) activeProjectCount++;
}
await auditLog(workspaceDir, "auto_pickup", {

View File

@@ -204,7 +204,6 @@ export function createProjectRegisterTool(api: OpenClawPluginApi) {
deployUrl,
baseBranch,
deployBranch,
autoChain: false,
channel: context.channel,
roleExecution,
dev: emptyWorkerState([...DEV_TIERS]),

View File

@@ -1,17 +1,16 @@
/**
* work_finish — Complete a task (DEV done, QA pass/fail/refine/blocked).
*
* Delegates side-effects to pipeline service, then handles notifications,
* audit, and optional auto-chain dispatch.
* Delegates side-effects to pipeline service, then ticks the project queue
* to fill free slots, sends notifications, and logs to audit.
*/
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { jsonResult } from "openclaw/plugin-sdk";
import type { ToolContext } from "../types.js";
import type { StateLabel } from "../providers/provider.js";
import { readProjects, getProject, getWorker, resolveRepoPath } from "../projects.js";
import { createProvider } from "../providers/index.js";
import { resolveRepoPath, readProjects, getProject, getWorker, getSessionForModel } from "../projects.js";
import { executeCompletion, getRule, NEXT_STATE } from "../services/pipeline.js";
import { dispatchTask } from "../dispatch.js";
import { projectTick, type TickResult } from "../services/tick.js";
import { log as auditLog } from "../audit.js";
import { notify, getNotificationConfig } from "../notify.js";
@@ -19,7 +18,7 @@ export function createWorkFinishTool(api: OpenClawPluginApi) {
return (ctx: ToolContext) => ({
name: "work_finish",
label: "Work Finish",
description: `Complete a task: DEV done/blocked, QA pass/fail/refine/blocked. Handles label transition, state update, issue close/reopen, notifications, and audit. With auto-scheduling, dispatches the next step automatically.`,
description: `Complete a task: DEV done/blocked, QA pass/fail/refine/blocked. Handles label transition, state update, issue close/reopen, notifications, audit, and auto-ticks the queue to fill free slots.`,
parameters: {
type: "object",
required: ["role", "result", "projectGroupId"],
@@ -74,31 +73,15 @@ export function createWorkFinishTool(api: OpenClawPluginApi) {
...completion,
};
// Auto-chain dispatch
// Tick: fill free slots after completion
const pluginConfig = api.pluginConfig as Record<string, unknown> | undefined;
const scheduling = (pluginConfig?.scheduling as string) ?? "auto";
if (scheduling === "auto") {
const chainRole = result === "done" ? "qa" : result === "fail" ? "dev" : null;
if (chainRole) {
const chainModel = chainRole === "qa" ? "qa" : (getWorker(project, "dev").model ?? "medior");
try {
const issue = await provider.getIssue(issueId);
const chainResult = await dispatchTask({
workspaceDir, agentId: ctx.agentId, groupId, project, issueId,
issueTitle: issue.title, issueDescription: issue.description ?? "", issueUrl: issue.web_url,
role: chainRole, modelAlias: chainModel,
fromLabel: result === "done" ? "To Test" : "To Improve",
toLabel: chainRole === "qa" ? "Testing" : "Doing",
transitionLabel: (id, from, to) => provider.transitionLabel(id, from as StateLabel, to as StateLabel),
pluginConfig, sessionKey: ctx.sessionKey,
});
output.autoChain = { dispatched: true, role: chainRole, model: chainResult.modelAlias, announcement: chainResult.announcement };
} catch (err) {
output.autoChain = { dispatched: false, error: (err as Error).message };
}
}
}
let tickResult: TickResult | null = null;
try {
tickResult = await projectTick({
workspaceDir, groupId, agentId: ctx.agentId, pluginConfig, sessionKey: ctx.sessionKey,
});
} catch { /* non-fatal: tick failure shouldn't break work_finish */ }
if (tickResult?.pickups.length) output.tickPickups = tickResult.pickups;
// Notify
const notifyConfig = getNotificationConfig(pluginConfig);
@@ -111,7 +94,7 @@ export function createWorkFinishTool(api: OpenClawPluginApi) {
await auditLog(workspaceDir, "work_finish", {
project: project.name, groupId, issue: issueId, role, result,
summary: summary ?? null, labelTransition: completion.labelTransition,
autoChain: output.autoChain ?? null,
tickPickups: tickResult?.pickups.length ?? 0,
});
return jsonResult(output);

View File

@@ -3,57 +3,25 @@
*
* Context-aware: ONLY works in project group chats.
* Auto-detects: projectGroupId, role, model, issueId.
* After dispatch, ticks the project queue to fill parallel slots.
*/
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { jsonResult } from "openclaw/plugin-sdk";
import type { ToolContext } from "../types.js";
import type { Issue, StateLabel } from "../providers/provider.js";
import type { StateLabel } from "../providers/provider.js";
import { createProvider } from "../providers/index.js";
import { selectModel } from "../model-selector.js";
import { activateWorker, getProject, getWorker, readProjects } from "../projects.js";
import { dispatchTask } from "../dispatch.js";
import { detectContext, generateGuardrails } from "../context-guard.js";
import { isDevTier, isTier, type Tier } from "../tiers.js";
import { notify, getNotificationConfig } from "../notify.js";
const DEV_LABELS: StateLabel[] = ["To Do", "To Improve"];
const QA_LABELS: StateLabel[] = ["To Test"];
const PRIORITY_ORDER: StateLabel[] = ["To Improve", "To Test", "To Do"];
const TIER_LABELS: Tier[] = ["junior", "medior", "senior", "qa"];
function detectRoleFromLabel(label: StateLabel): "dev" | "qa" | null {
if (DEV_LABELS.includes(label)) return "dev";
if (QA_LABELS.includes(label)) return "qa";
return null;
}
function detectTierFromLabels(labels: string[]): Tier | null {
const lower = labels.map((l) => l.toLowerCase());
return TIER_LABELS.find((t) => lower.includes(t)) ?? null;
}
async function findNextIssue(
provider: { listIssuesByLabel(label: StateLabel): Promise<Issue[]> },
role?: "dev" | "qa",
): Promise<{ issue: Issue; label: StateLabel } | null> {
const labels = role === "dev" ? PRIORITY_ORDER.filter((l) => DEV_LABELS.includes(l))
: role === "qa" ? PRIORITY_ORDER.filter((l) => QA_LABELS.includes(l))
: PRIORITY_ORDER;
for (const label of labels) {
try {
const issues = await provider.listIssuesByLabel(label);
if (issues.length > 0) return { issue: issues[issues.length - 1], label };
} catch { /* continue */ }
}
return null;
}
import { findNextIssue, detectRoleFromLabel, detectTierFromLabels, projectTick, type TickResult } from "../services/tick.js";
export function createWorkStartTool(api: OpenClawPluginApi) {
return (ctx: ToolContext) => ({
name: "work_start",
label: "Work Start",
description: `Pick up a task from the issue queue. ONLY works in project group chats. Handles label transition, tier assignment, session creation, dispatch, and audit.`,
description: `Pick up a task from the issue queue. ONLY works in project group chats. Handles label transition, tier assignment, session creation, dispatch, audit, and ticks the queue to fill parallel slots.`,
parameters: {
type: "object",
properties: {
@@ -92,7 +60,7 @@ export function createWorkStartTool(api: OpenClawPluginApi) {
const { provider } = createProvider({ repo: project.repo });
// Find issue
let issue: Issue;
let issue: { iid: number; title: string; description: string; labels: string[]; web_url: string; state: string };
let currentLabel: StateLabel;
if (issueIdParam !== undefined) {
issue = await provider.getIssue(issueIdParam);
@@ -164,13 +132,25 @@ export function createWorkStartTool(api: OpenClawPluginApi) {
{ workspaceDir, config: notifyConfig, groupId, channel: context.channel },
);
return jsonResult({
// Tick: fill parallel slots
let tickResult: TickResult | null = null;
try {
tickResult = await projectTick({
workspaceDir, groupId, agentId: ctx.agentId, pluginConfig, sessionKey: ctx.sessionKey,
targetRole: role === "dev" ? "qa" : "dev",
});
} catch { /* non-fatal */ }
const output: Record<string, unknown> = {
success: true, project: project.name, groupId, issueId: issue.iid, issueTitle: issue.title,
role, model: dr.modelAlias, fullModel: dr.fullModel, sessionAction: dr.sessionAction,
announcement: dr.announcement, labelTransition: `${currentLabel}${targetLabel}`,
modelReason, modelSource,
autoDetected: { projectGroupId: !groupIdParam, role: !roleParam, issueId: issueIdParam === undefined, model: !modelParam },
});
};
if (tickResult?.pickups.length) output.tickPickups = tickResult.pickups;
return jsonResult(output);
},
});
}