refactor: reorganize task management imports and update task handling tools

- Updated import paths for task management providers in task-comment, task-create, and task-update tools.
- Removed deprecated task-complete and task-pickup tools, replacing them with work-finish and work-start tools for improved task handling.
- Enhanced work-finish and work-start tools to streamline task completion and pickup processes, including context-aware detection and auto-scheduling features.
- Updated package.json to include build scripts and main entry point.
- Modified tsconfig.json to enable output directory, declaration files, and source maps for better TypeScript support.
This commit is contained in:
Lauren ten Hoor
2026-02-10 21:39:41 +08:00
parent c1c3e09a8e
commit d7178bb8e5
41 changed files with 1704 additions and 3466 deletions

146
lib/services/health.ts Normal file
View File

@@ -0,0 +1,146 @@
/**
* Health service — worker health checks and auto-fix.
*
* Detects: active_no_session, zombie_session, stale_worker, inactive_with_issue.
* Used by both `status` (read-only) and `auto_pickup` (auto-fix).
*/
import type { StateLabel } from "../providers/provider.js";
import {
getSessionForModel,
getWorker,
updateWorker,
type Project,
} from "../projects.js";
export type HealthIssue = {
type: "active_no_session" | "zombie_session" | "stale_worker" | "inactive_with_issue";
severity: "critical" | "warning";
project: string;
groupId: string;
role: "dev" | "qa";
message: string;
model?: string | null;
sessionKey?: string | null;
hoursActive?: number;
issueId?: string | null;
};
export type HealthFix = {
issue: HealthIssue;
fixed: boolean;
labelReverted?: string;
labelRevertFailed?: boolean;
};
export async function checkWorkerHealth(opts: {
workspaceDir: string;
groupId: string;
project: Project;
role: "dev" | "qa";
activeSessions: string[];
autoFix: boolean;
provider: {
transitionLabel(id: number, from: StateLabel, to: StateLabel): Promise<void>;
};
}): Promise<HealthFix[]> {
const { workspaceDir, groupId, project, role, activeSessions, autoFix, provider } = opts;
const fixes: HealthFix[] = [];
const worker = getWorker(project, role);
const sessionKey = worker.model ? getSessionForModel(worker, worker.model) : null;
const revertLabel: StateLabel = role === "dev" ? "To Do" : "To Test";
const currentLabel: StateLabel = role === "dev" ? "Doing" : "Testing";
async function revertIssueLabel(fix: HealthFix) {
if (!worker.issueId) return;
try {
const id = Number(worker.issueId.split(",")[0]);
await provider.transitionLabel(id, currentLabel, revertLabel);
fix.labelReverted = `${currentLabel}${revertLabel}`;
} catch {
fix.labelRevertFailed = true;
}
}
// Check 1: Active but no session key for current model
if (worker.active && !sessionKey) {
const fix: HealthFix = {
issue: {
type: "active_no_session", severity: "critical",
project: project.name, groupId, role,
model: worker.model,
message: `${role.toUpperCase()} active but no session for model "${worker.model}"`,
},
fixed: false,
};
if (autoFix) {
await updateWorker(workspaceDir, groupId, role, { active: false, issueId: null });
fix.fixed = true;
}
fixes.push(fix);
}
// Check 2: Active with session but session is dead (zombie)
if (worker.active && sessionKey && activeSessions.length > 0 && !activeSessions.includes(sessionKey)) {
const fix: HealthFix = {
issue: {
type: "zombie_session", severity: "critical",
project: project.name, groupId, role,
sessionKey, model: worker.model,
message: `${role.toUpperCase()} session not in active sessions list`,
},
fixed: false,
};
if (autoFix) {
await revertIssueLabel(fix);
const sessions = { ...worker.sessions };
if (worker.model) sessions[worker.model] = null;
await updateWorker(workspaceDir, groupId, role, { active: false, issueId: null, sessions });
fix.fixed = true;
}
fixes.push(fix);
}
// Check 3: Inactive but still has issueId
if (!worker.active && worker.issueId) {
const fix: HealthFix = {
issue: {
type: "inactive_with_issue", severity: "warning",
project: project.name, groupId, role,
issueId: worker.issueId,
message: `${role.toUpperCase()} inactive but still has issueId "${worker.issueId}"`,
},
fixed: false,
};
if (autoFix) {
await updateWorker(workspaceDir, groupId, role, { issueId: null });
fix.fixed = true;
}
fixes.push(fix);
}
// Check 4: Active for >2 hours (stale)
if (worker.active && worker.startTime && sessionKey) {
const hours = (Date.now() - new Date(worker.startTime).getTime()) / 3_600_000;
if (hours > 2) {
const fix: HealthFix = {
issue: {
type: "stale_worker", severity: "warning",
project: project.name, groupId, role,
hoursActive: Math.round(hours * 10) / 10,
sessionKey, issueId: worker.issueId,
message: `${role.toUpperCase()} active for ${Math.round(hours * 10) / 10}h — may need attention`,
},
fixed: false,
};
if (autoFix) {
await revertIssueLabel(fix);
await updateWorker(workspaceDir, groupId, role, { active: false, issueId: null });
fix.fixed = true;
}
fixes.push(fix);
}
}
return fixes;
}

123
lib/services/pipeline.ts Normal file
View File

@@ -0,0 +1,123 @@
/**
* Pipeline service — declarative completion rules.
*
* Replaces 7 if-blocks with a data-driven lookup table.
*/
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import type { StateLabel, IssueProvider } from "../providers/provider.js";
import { deactivateWorker } from "../projects.js";
const execFileAsync = promisify(execFile);
export type CompletionRule = {
from: StateLabel;
to: StateLabel;
gitPull?: boolean;
detectPr?: boolean;
closeIssue?: boolean;
reopenIssue?: boolean;
};
export const COMPLETION_RULES: Record<string, CompletionRule> = {
"dev:done": { from: "Doing", to: "To Test", gitPull: true, detectPr: true },
"qa:pass": { from: "Testing", to: "Done", closeIssue: true },
"qa:fail": { from: "Testing", to: "To Improve", reopenIssue: true },
"qa:refine": { from: "Testing", to: "Refining" },
"dev:blocked": { from: "Doing", to: "To Do" },
"qa:blocked": { from: "Testing", to: "To Test" },
};
export const NEXT_STATE: Record<string, string> = {
"dev:done": "QA queue",
"dev:blocked": "returned to queue",
"qa:pass": "Done!",
"qa:fail": "back to DEV",
"qa:refine": "awaiting human decision",
"qa:blocked": "returned to QA queue",
};
const EMOJI: Record<string, string> = {
"dev:done": "✅",
"qa:pass": "🎉",
"qa:fail": "❌",
"qa:refine": "🤔",
"dev:blocked": "🚫",
"qa:blocked": "🚫",
};
export type CompletionOutput = {
labelTransition: string;
announcement: string;
nextState: string;
prUrl?: string;
issueUrl?: string;
issueClosed?: boolean;
issueReopened?: boolean;
};
export function getRule(role: string, result: string): CompletionRule | undefined {
return COMPLETION_RULES[`${role}:${result}`];
}
/**
* Execute the completion side-effects for a role:result pair.
*/
export async function executeCompletion(opts: {
workspaceDir: string;
groupId: string;
role: "dev" | "qa";
result: string;
issueId: number;
summary?: string;
prUrl?: string;
provider: IssueProvider;
repoPath: string;
}): Promise<CompletionOutput> {
const { workspaceDir, groupId, role, result, issueId, summary, provider, repoPath } = opts;
const key = `${role}:${result}`;
const rule = COMPLETION_RULES[key];
if (!rule) throw new Error(`No completion rule for ${key}`);
let prUrl = opts.prUrl;
// Git pull (dev:done)
if (rule.gitPull) {
try {
await execFileAsync("git", ["pull"], { cwd: repoPath, timeout: 30_000 });
} catch { /* best-effort */ }
}
// Auto-detect PR URL (dev:done)
if (rule.detectPr && !prUrl) {
try { prUrl = await provider.getMergedMRUrl(issueId) ?? undefined; } catch { /* ignore */ }
}
// Deactivate worker + transition label
await deactivateWorker(workspaceDir, groupId, role);
await provider.transitionLabel(issueId, rule.from, rule.to);
// Close/reopen
if (rule.closeIssue) await provider.closeIssue(issueId);
if (rule.reopenIssue) await provider.reopenIssue(issueId);
// Build announcement
const issue = await provider.getIssue(issueId);
const emoji = EMOJI[key] ?? "📋";
const label = key.replace(":", " ").toUpperCase();
let announcement = `${emoji} ${label} #${issueId}`;
if (summary) announcement += `${summary}`;
announcement += `\n📋 Issue: ${issue.web_url}`;
if (prUrl) announcement += `\n🔗 PR: ${prUrl}`;
announcement += `\n${NEXT_STATE[key]}.`;
return {
labelTransition: `${rule.from}${rule.to}`,
announcement,
nextState: NEXT_STATE[key],
prUrl,
issueUrl: issue.web_url,
issueClosed: rule.closeIssue,
issueReopened: rule.reopenIssue,
};
}

247
lib/services/queue.ts Normal file
View File

@@ -0,0 +1,247 @@
/**
* Queue service — task sequencing and priority logic.
*
* Pure functions for scanning issue queues, building execution sequences,
* and formatting output. No tool registration or I/O concerns.
*/
import type { Issue } from "../providers/provider.js";
import { createProvider } from "../providers/index.js";
import type { Project } from "../projects.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type QueueLabel = "To Improve" | "To Test" | "To Do";
export type Role = "dev" | "qa";
export interface SequencedTask {
sequence: number;
projectId: string;
projectName: string;
role: Role;
issueId: number;
title: string;
label: QueueLabel;
active: boolean;
}
export interface ProjectTrack {
name: string;
role: Role;
tasks: SequencedTask[];
}
export interface ProjectExecutionConfig {
name: string;
groupId: string;
roleExecution: "parallel" | "sequential";
devActive: boolean;
qaActive: boolean;
devIssueId: string | null;
qaIssueId: string | null;
}
export interface ProjectTaskSequence {
projectId: string;
projectName: string;
roleExecution: "parallel" | "sequential";
tracks: ProjectTrack[];
}
export interface GlobalTaskSequence {
mode: "sequential";
tasks: SequencedTask[];
}
export interface ProjectQueues {
projectId: string;
project: Project;
queues: Record<QueueLabel, Issue[]>;
}
// ---------------------------------------------------------------------------
// Constants & helpers
// ---------------------------------------------------------------------------
export const QUEUE_PRIORITY: Record<QueueLabel, number> = {
"To Improve": 3,
"To Test": 2,
"To Do": 1,
};
export function getTaskPriority(label: QueueLabel, issue: Issue): number {
return QUEUE_PRIORITY[label] * 10000 - issue.iid;
}
export function getRoleForLabel(label: QueueLabel): Role {
return label === "To Test" ? "qa" : "dev";
}
// ---------------------------------------------------------------------------
// Fetching
// ---------------------------------------------------------------------------
export async function fetchProjectQueues(project: Project): Promise<Record<QueueLabel, Issue[]>> {
const { provider } = createProvider({ repo: project.repo });
const labels: QueueLabel[] = ["To Improve", "To Test", "To Do"];
const queues: Record<QueueLabel, Issue[]> = { "To Improve": [], "To Test": [], "To Do": [] };
for (const label of labels) {
try {
const issues = await provider.listIssuesByLabel(label);
queues[label] = issues.sort((a, b) => getTaskPriority(label, b) - getTaskPriority(label, a));
} catch {
queues[label] = [];
}
}
return queues;
}
// ---------------------------------------------------------------------------
// Track building
// ---------------------------------------------------------------------------
export function buildProjectTrack(
projectId: string, projectName: string, role: Role,
queues: Record<QueueLabel, Issue[]>,
isActive: boolean, activeIssueId: string | null,
startSeq: number,
): { track: ProjectTrack; nextSequence: number } {
const tasks: SequencedTask[] = [];
let seq = startSeq;
for (const label of ["To Improve", "To Test", "To Do"] as QueueLabel[]) {
if (getRoleForLabel(label) !== role) continue;
for (const issue of queues[label]) {
tasks.push({
sequence: seq++, projectId, projectName, role,
issueId: issue.iid, title: issue.title, label,
active: isActive && activeIssueId === String(issue.iid),
});
}
}
return { track: { name: role === "dev" ? "DEV Track" : "QA Track", role, tasks }, nextSequence: seq };
}
// ---------------------------------------------------------------------------
// Sequence building
// ---------------------------------------------------------------------------
export function buildParallelProjectSequences(projectQueues: ProjectQueues[]): ProjectTaskSequence[] {
return projectQueues.map(({ projectId, project, queues }) => {
const roleExecution = project.roleExecution ?? "parallel";
const tracks: ProjectTrack[] = [];
if (roleExecution === "sequential") {
// Build alternating DEV/QA sequence
const alternating = buildAlternatingTrack(projectId, project, queues);
if (alternating.tasks.length > 0) tracks.push(alternating);
} else {
const dev = buildProjectTrack(projectId, project.name, "dev", queues, project.dev.active, project.dev.issueId, 1);
const qa = buildProjectTrack(projectId, project.name, "qa", queues, project.qa.active, project.qa.issueId, 1);
if (dev.track.tasks.length > 0) tracks.push(dev.track);
if (qa.track.tasks.length > 0) tracks.push(qa.track);
}
return { projectId, projectName: project.name, roleExecution, tracks };
});
}
function buildAlternatingTrack(
projectId: string, project: Project, queues: Record<QueueLabel, Issue[]>,
): ProjectTrack {
const tasks: SequencedTask[] = [];
const added = new Set<number>();
let seq = 1;
const nextForRole = (role: Role): SequencedTask | null => {
for (const label of ["To Improve", "To Test", "To Do"] as QueueLabel[]) {
if (getRoleForLabel(label) !== role) continue;
for (const issue of queues[label]) {
if (added.has(issue.iid)) continue;
const isActive =
(role === "dev" && project.dev.active && project.dev.issueId === String(issue.iid)) ||
(role === "qa" && project.qa.active && project.qa.issueId === String(issue.iid));
return { sequence: 0, projectId, projectName: project.name, role, issueId: issue.iid, title: issue.title, label, active: isActive };
}
}
return null;
};
// Start with active task
for (const role of ["dev", "qa"] as Role[]) {
const w = project[role];
if (w.active && w.issueId) {
const t = nextForRole(role);
if (t) { t.sequence = seq++; t.active = true; tasks.push(t); added.add(t.issueId); break; }
}
}
// Alternate
let lastRole: Role | null = tasks[0]?.role ?? null;
while (true) {
const next = nextForRole(lastRole === "dev" ? "qa" : "dev");
if (!next) break;
next.sequence = seq++;
tasks.push(next);
added.add(next.issueId);
lastRole = next.role;
}
return { name: "DEV/QA Alternating", role: "dev", tasks };
}
export function buildGlobalTaskSequence(projectQueues: ProjectQueues[]): GlobalTaskSequence {
const all: Array<{ projectId: string; projectName: string; role: Role; label: QueueLabel; issue: Issue; priority: number }> = [];
for (const { projectId, project, queues } of projectQueues) {
for (const label of ["To Improve", "To Test", "To Do"] as QueueLabel[]) {
for (const issue of queues[label]) {
all.push({ projectId, projectName: project.name, role: getRoleForLabel(label), label, issue, priority: getTaskPriority(label, issue) });
}
}
}
all.sort((a, b) => b.priority !== a.priority ? b.priority - a.priority : a.issue.iid - b.issue.iid);
const tasks: SequencedTask[] = [];
const added = new Set<string>();
let seq = 1;
// Active task first
const active = projectQueues.find(({ project }) => project.dev.active || project.qa.active);
if (active) {
const { project, projectId } = active;
for (const [role, w] of [["dev", project.dev], ["qa", project.qa]] as const) {
if (w.active && w.issueId) {
const t = all.find((t) => t.projectId === projectId && t.role === role && String(t.issue.iid) === w.issueId);
if (t) {
const key = `${t.projectId}:${t.issue.iid}`;
tasks.push({ sequence: seq++, projectId: t.projectId, projectName: t.projectName, role: t.role, issueId: t.issue.iid, title: t.issue.title, label: t.label, active: true });
added.add(key);
break;
}
}
}
}
for (const t of all) {
const key = `${t.projectId}:${t.issue.iid}`;
if (added.has(key)) continue;
tasks.push({ sequence: seq++, projectId: t.projectId, projectName: t.projectName, role: t.role, issueId: t.issue.iid, title: t.issue.title, label: t.label, active: false });
added.add(key);
}
return { mode: "sequential", tasks };
}
// ---------------------------------------------------------------------------
// Formatting
// ---------------------------------------------------------------------------
export function formatProjectQueues(queues: Record<QueueLabel, Issue[]>) {
const fmt = (label: QueueLabel) => queues[label].map((i) => ({ id: i.iid, title: i.title, priority: QUEUE_PRIORITY[label] }));
return { toImprove: fmt("To Improve"), toTest: fmt("To Test"), toDo: fmt("To Do") };
}