Checkpoint: File edits

Automatic checkpoint created by Claude Code
- Branch: v3
- Timestamp: 2026-01-07T20:23:24Z
- Changes: 1 file(s)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
rUvandClaude Opus 4.5 committed 2026-01-07 20:23:24 +00:00
1 parent 9077a5cca3
commit fd498e8800
3 files changed
+1356

No files matched your search

@@ -55,6 +55,8 @@ const commandLoaders: Record<string, CommandLoader> = {
route: () => import('./route.js'),
// Progress Commands
progress: () => import('./progress.js'),
// Issue Claims Commands (ADR-016)
issues: () => import('./issues.js'),
};
// Cache for loaded commands
+633
View File
@@ -0,0 +1,633 @@
/**
* V3 Issues Command
*
* Implements ADR-016: Collaborative Issue Claims for Human-Agent Workflows
*
* Commands:
* - issues list List all claims
* - issues claim Claim an issue
* - issues release Release a claim
* - issues handoff Request handoff
* - issues status Update claim status
* - issues stealable List stealable issues
* - issues steal Steal an issue
* - issues load View agent load
* - issues rebalance Rebalance swarm
* - issues board Visual board view
*/
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
import { createClaimService, type Claimant, type ClaimStatus } from '../services/claim-service.js';
// ============================================================================
// Subcommands
// ============================================================================
const listCommand: Command = {
name: 'list',
aliases: ['ls'],
description: 'List all issue claims',
options: [
{
name: 'status',
short: 's',
description: 'Filter by status',
type: 'string',
choices: ['active', 'paused', 'blocked', 'stealable', 'completed', 'handoff-pending', 'review-requested'],
},
{
name: 'mine',
short: 'm',
description: 'Show only my claims',
type: 'boolean',
default: false,
},
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const service = createClaimService(ctx.cwd);
await service.initialize();
const status = ctx.flags.status as ClaimStatus | undefined;
const claims = status
? await service.getByStatus(status)
: await service.getAllClaims();
if (claims.length === 0) {
output.printInfo('No claims found');
return { success: true, data: { claims: [] } };
}
output.writeln();
output.writeln(output.bold('Issue Claims (ADR-016)'));
output.writeln();
const rows = claims.map(c => ({
Issue: c.issueId,
Claimant: c.claimant.type === 'human'
? `👤 ${c.claimant.name}`
: `🤖 ${c.claimant.agentType}`,
Status: formatStatus(c.status),
Progress: `${c.progress}%`,
Since: formatDuration(Date.now() - c.claimedAt.getTime()),
}));
output.printTable(rows);
if (ctx.flags.format === 'json') {
output.printJson(claims);
}
return { success: true, data: { claims } };
},
};
const claimCommand: Command = {
name: 'claim',
description: 'Claim an issue',
options: [
{
name: 'issue',
short: 'i',
description: 'Issue ID to claim',
type: 'string',
},
{
name: 'agent',
short: 'a',
description: 'Claim as agent (format: type:id)',
type: 'string',
},
{
name: 'user',
short: 'u',
description: 'Claim as user (format: id:name)',
type: 'string',
},
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const issueId = (ctx.flags.issue || ctx.positional[0]) as string;
const agentStr = ctx.flags.agent as string | undefined;
const userStr = ctx.flags.user as string | undefined;
if (!issueId) {
output.printError('Issue ID is required');
return { success: false, exitCode: 1 };
}
if (!agentStr && !userStr) {
output.printError('Must specify --agent or --user');
return { success: false, exitCode: 1 };
}
const claimant: Claimant = agentStr
? {
type: 'agent',
agentType: agentStr.split(':')[0],
agentId: agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`,
}
: {
type: 'human',
userId: userStr!.split(':')[0],
name: userStr!.split(':')[1] || userStr!.split(':')[0],
};
const service = createClaimService(ctx.cwd);
await service.initialize();
const result = await service.claim(issueId, claimant);
if (result.success) {
output.printSuccess(`Claimed issue ${issueId}`);
return { success: true, data: result.claim };
} else {
output.printError(result.error || 'Failed to claim issue');
return { success: false, exitCode: 1 };
}
},
};
const releaseCommand: Command = {
name: 'release',
description: 'Release a claim',
options: [
{
name: 'issue',
short: 'i',
description: 'Issue ID to release',
type: 'string',
},
{
name: 'agent',
short: 'a',
description: 'Release as agent',
type: 'string',
},
{
name: 'user',
short: 'u',
description: 'Release as user',
type: 'string',
},
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const issueId = (ctx.flags.issue || ctx.positional[0]) as string;
const agentStr = ctx.flags.agent as string | undefined;
const userStr = ctx.flags.user as string | undefined;
if (!issueId) {
output.printError('Issue ID is required');
return { success: false, exitCode: 1 };
}
if (!agentStr && !userStr) {
output.printError('Must specify --agent or --user');
return { success: false, exitCode: 1 };
}
const claimant: Claimant = agentStr
? {
type: 'agent',
agentType: agentStr.split(':')[0],
agentId: agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`,
}
: {
type: 'human',
userId: userStr!.split(':')[0],
name: userStr!.split(':')[1] || userStr!.split(':')[0],
};
const service = createClaimService(ctx.cwd);
await service.initialize();
try {
await service.release(issueId, claimant);
output.printSuccess(`Released claim on issue ${issueId}`);
return { success: true };
} catch (error) {
output.printError(error instanceof Error ? error.message : String(error));
return { success: false, exitCode: 1 };
}
},
};
const handoffCommand: Command = {
name: 'handoff',
description: 'Request handoff to another agent/user',
options: [
{ name: 'issue', short: 'i', type: 'string', description: 'Issue ID' },
{ name: 'to', description: 'Target (agent:type:id or user:id:name)', type: 'string', required: true },
{ name: 'from', description: 'Current owner', type: 'string' },
{ name: 'reason', short: 'r', type: 'string', default: 'Handoff requested' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const issueId = (ctx.flags.issue || ctx.positional[0]) as string;
const toStr = ctx.flags.to as string;
const fromStr = ctx.flags.from as string;
const reason = ctx.flags.reason as string;
if (!issueId || !toStr) {
output.printError('Issue ID and --to are required');
return { success: false, exitCode: 1 };
}
const to = parseClaimant(toStr);
if (!to) {
output.printError('Invalid --to format. Use agent:type:id or user:id:name');
return { success: false, exitCode: 1 };
}
const service = createClaimService(ctx.cwd);
await service.initialize();
// Get current claim to find "from"
const claim = await service.getIssueStatus(issueId);
if (!claim) {
output.printError(`Issue ${issueId} is not claimed`);
return { success: false, exitCode: 1 };
}
const from = fromStr ? parseClaimant(fromStr) : claim.claimant;
if (!from) {
output.printError('Could not determine current owner');
return { success: false, exitCode: 1 };
}
try {
await service.requestHandoff(issueId, from, to, reason);
output.printSuccess(`Handoff requested for issue ${issueId}`);
return { success: true };
} catch (error) {
output.printError(error instanceof Error ? error.message : String(error));
return { success: false, exitCode: 1 };
}
},
};
const statusCommand: Command = {
name: 'status',
description: 'Update claim status',
options: [
{ name: 'issue', short: 'i', type: 'string', description: 'Issue ID' },
{ name: 'set', short: 's', type: 'string', choices: ['active', 'paused', 'blocked', 'completed'] },
{ name: 'progress', short: 'p', type: 'number', description: 'Progress (0-100)' },
{ name: 'note', short: 'n', type: 'string', description: 'Status note' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const issueId = (ctx.flags.issue || ctx.positional[0]) as string;
if (!issueId) {
output.printError('Issue ID is required');
return { success: false, exitCode: 1 };
}
const service = createClaimService(ctx.cwd);
await service.initialize();
const newStatus = ctx.flags.set as ClaimStatus | undefined;
const progress = ctx.flags.progress as number | undefined;
const note = ctx.flags.note as string | undefined;
try {
if (newStatus) {
await service.updateStatus(issueId, newStatus, note);
output.printSuccess(`Updated status to ${newStatus}`);
}
if (progress !== undefined) {
await service.updateProgress(issueId, progress);
output.printSuccess(`Updated progress to ${progress}%`);
}
const claim = await service.getIssueStatus(issueId);
if (claim) {
output.writeln();
output.printBox([
`Issue: ${claim.issueId}`,
`Status: ${formatStatus(claim.status)}`,
`Progress: ${claim.progress}%`,
`Claimant: ${formatClaimant(claim.claimant)}`,
].join('\n'), 'Claim Status');
}
return { success: true, data: claim };
} catch (error) {
output.printError(error instanceof Error ? error.message : String(error));
return { success: false, exitCode: 1 };
}
},
};
const stealableCommand: Command = {
name: 'stealable',
description: 'List stealable issues',
options: [
{ name: 'type', short: 't', type: 'string', description: 'Filter by agent type' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const agentType = ctx.flags.type as string | undefined;
const service = createClaimService(ctx.cwd);
await service.initialize();
const stealable = await service.getStealable(agentType);
if (stealable.length === 0) {
output.printInfo('No stealable issues found');
return { success: true, data: { stealable: [] } };
}
output.writeln();
output.writeln(output.bold('🎯 Stealable Issues'));
output.writeln();
for (const c of stealable) {
output.writeln(` ${output.highlight(c.issueId)}`);
output.writeln(` Owner: ${formatClaimant(c.claimant)}`);
output.writeln(` Progress: ${c.progress}%`);
if (c.context) output.writeln(` Context: ${c.context.slice(0, 60)}...`);
output.writeln();
}
return { success: true, data: { stealable } };
},
};
const stealCommand: Command = {
name: 'steal',
description: 'Steal a stealable issue',
options: [
{ name: 'issue', short: 'i', type: 'string', description: 'Issue ID' },
{ name: 'agent', short: 'a', type: 'string', description: 'Steal as agent', required: true },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const issueId = (ctx.flags.issue || ctx.positional[0]) as string;
const agentStr = ctx.flags.agent as string;
if (!issueId) {
output.printError('Issue ID is required');
return { success: false, exitCode: 1 };
}
const stealer: Claimant = {
type: 'agent',
agentType: agentStr.split(':')[0],
agentId: agentStr.split(':')[1] || `${agentStr.split(':')[0]}-1`,
};
const service = createClaimService(ctx.cwd);
await service.initialize();
const result = await service.steal(issueId, stealer);
if (result.success) {
output.printSuccess(`🎯 Stole issue ${issueId}`);
if (result.previousOwner) {
output.printInfo(`Previous: ${formatClaimant(result.previousOwner)}`);
}
if (result.context) {
output.printInfo(`Progress: ${result.context.progress}%`);
}
return { success: true, data: result };
} else {
output.printError(result.error || 'Failed to steal issue');
return { success: false, exitCode: 1 };
}
},
};
const loadCommand: Command = {
name: 'load',
description: 'View agent load distribution',
options: [
{ name: 'agent', short: 'a', type: 'string', description: 'Specific agent ID' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const agentId = ctx.flags.agent as string | undefined;
const service = createClaimService(ctx.cwd);
await service.initialize();
if (agentId) {
const load = await service.getAgentLoad(agentId);
output.writeln();
output.writeln(output.bold(`📊 Load: ${agentId}`));
output.writeln();
output.printList([
`Claims: ${load.claimCount}/${load.maxClaims}`,
`Utilization: ${(load.utilization * 100).toFixed(0)}%`,
`Blocked: ${load.currentBlockedCount}`,
]);
return { success: true, data: load };
}
const claims = await service.getAllClaims();
const agentLoads = new Map<string, { count: number; type: string }>();
for (const claim of claims) {
if (claim.claimant.type === 'agent') {
const id = claim.claimant.agentId;
const existing = agentLoads.get(id);
agentLoads.set(id, {
count: (existing?.count || 0) + 1,
type: claim.claimant.agentType,
});
}
}
output.writeln();
output.writeln(output.bold('📊 Agent Load Distribution'));
output.writeln();
if (agentLoads.size === 0) {
output.printInfo('No agent claims found');
} else {
for (const [id, data] of agentLoads) {
const bar = '█'.repeat(data.count) + '░'.repeat(Math.max(0, 5 - data.count));
output.writeln(` ${id} (${data.type}): ${bar} ${data.count}`);
}
}
return { success: true, data: Object.fromEntries(agentLoads) };
},
};
const rebalanceCommand: Command = {
name: 'rebalance',
description: 'Rebalance work across swarm',
options: [
{ name: 'dry-run', type: 'boolean', default: true, description: 'Preview only' },
{ name: 'apply', type: 'boolean', default: false, description: 'Apply changes' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const apply = ctx.flags.apply as boolean;
const service = createClaimService(ctx.cwd);
await service.initialize();
const result = await service.rebalance('default');
if (result.suggested.length === 0) {
output.printSuccess('⚖️ Swarm is balanced');
return { success: true, data: result };
}
output.writeln();
output.writeln(output.bold(apply ? '⚖️ Rebalancing' : '⚖️ Rebalance Preview'));
output.writeln();
for (const s of result.suggested) {
const from = s.currentOwner.type === 'agent' ? s.currentOwner.agentId : s.currentOwner.name;
const to = s.suggestedOwner.type === 'agent' ? s.suggestedOwner.agentId : (s.suggestedOwner as { name?: string }).name;
output.writeln(` ${s.issueId}: ${from} → ${to}`);
}
if (!apply) {
output.writeln();
output.printInfo('Use --apply to execute');
}
return { success: true, data: result };
},
};
const boardCommand: Command = {
name: 'board',
description: 'Visual board view of claims',
action: async (ctx: CommandContext): Promise<CommandResult> => {
const service = createClaimService(ctx.cwd);
await service.initialize();
const claims = await service.getAllClaims();
const byStatus: Record<string, typeof claims> = {
active: [],
blocked: [],
'review-requested': [],
stealable: [],
completed: [],
};
for (const c of claims) {
const key = c.status in byStatus ? c.status : 'active';
byStatus[key].push(c);
}
output.writeln();
output.writeln(output.bold('📋 Issue Board (ADR-016)'));
output.writeln();
const columns = ['active', 'blocked', 'review-requested', 'stealable', 'completed'];
const headers = ['🔵 Active', '🔴 Blocked', '🟡 Review', '🟢 Stealable', '✅ Done'];
// Print column headers
output.writeln(headers.map(h => h.padEnd(18)).join(''));
output.writeln('─'.repeat(90));
// Find max rows
const maxRows = Math.max(...Object.values(byStatus).map(arr => arr.length), 1);
for (let i = 0; i < maxRows; i++) {
const row = columns.map(col => {
const item = byStatus[col][i];
if (!item) return ''.padEnd(18);
const owner = item.claimant.type === 'agent' ? item.claimant.agentType.slice(0, 6) : item.claimant.name.slice(0, 6);
return `#${item.issueId} (${owner})`.padEnd(18);
});
output.writeln(row.join(''));
}
return { success: true };
},
};
// ============================================================================
// Main Command
// ============================================================================
export const issuesCommand: Command = {
name: 'issues',
description: 'Collaborative issue claims for human-agent workflows (ADR-016)',
subcommands: [
listCommand,
claimCommand,
releaseCommand,
handoffCommand,
statusCommand,
stealableCommand,
stealCommand,
loadCommand,
rebalanceCommand,
boardCommand,
],
examples: [
{ command: 'claude-flow issues list', description: 'List all claims' },
{ command: 'claude-flow issues claim 123 --agent coder:coder-1', description: 'Claim as agent' },
{ command: 'claude-flow issues handoff 123 --to agent:tester:tester-1', description: 'Handoff to tester' },
{ command: 'claude-flow issues stealable', description: 'List stealable' },
{ command: 'claude-flow issues steal 123 --agent coder:coder-2', description: 'Steal issue' },
{ command: 'claude-flow issues board', description: 'Visual board' },
],
action: async (): Promise<CommandResult> => {
output.writeln();
output.writeln(output.bold('📋 Issue Claims (ADR-016)'));
output.writeln(output.dim('Collaborative human-agent issue management'));
output.writeln();
output.writeln('Commands:');
output.printList([
'list - List all claims',
'claim - Claim an issue',
'release - Release a claim',
'handoff - Request handoff',
'status - Update status/progress',
'stealable - List stealable issues',
'steal - Steal an issue',
'load - View agent load',
'rebalance - Rebalance swarm',
'board - Visual board view',
]);
return { success: true };
},
};
// ============================================================================
// Helpers
// ============================================================================
function parseClaimant(str: string): Claimant | null {
const parts = str.split(':');
if (parts[0] === 'agent' && parts.length >= 2) {
return { type: 'agent', agentType: parts[1], agentId: parts[2] || `${parts[1]}-1` };
}
if (parts[0] === 'user' && parts.length >= 2) {
return { type: 'human', userId: parts[1], name: parts[2] || parts[1] };
}
return null;
}
function formatClaimant(c: Claimant): string {
return c.type === 'human' ? `👤 ${c.name}` : `🤖 ${c.agentType}:${c.agentId}`;
}
function formatStatus(status: ClaimStatus): string {
const icons: Record<ClaimStatus, string> = {
active: '🔵',
paused: '⏸️',
blocked: '🔴',
stealable: '🟢',
completed: '✅',
'handoff-pending': '🔄',
'review-requested': '🟡',
};
return `${icons[status] || '❓'} ${status}`;
}
function formatDuration(ms: number): string {
const minutes = Math.floor(ms / 60000);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h`;
return `${Math.floor(hours / 24)}d`;
}
export default issuesCommand;
@@ -0,0 +1,721 @@
/**
* V3 Collaborative Issue Claims Service
*
* Implements ADR-016: Collaborative Issue Claims for Human-Agent Workflows
*
* Features:
* - Issue claiming/releasing for humans and agents
* - Handoff mechanisms between humans and agents
* - Work stealing for idle agents
* - Load balancing across swarm
* - GitHub integration
*
* @see /v3/implementation/adrs/ADR-016-collaborative-issue-claims.md
*/
import { EventEmitter } from 'events';
import * as fs from 'fs';
import * as path from 'path';
// ============================================================================
// Types
// ============================================================================
export type Claimant =
| { type: 'human'; userId: string; name: string }
| { type: 'agent'; agentId: string; agentType: string };
export type ClaimStatus =
| 'active'
| 'paused'
| 'handoff-pending'
| 'review-requested'
| 'blocked'
| 'stealable'
| 'completed';
export type StealReason =
| 'overloaded'
| 'stale'
| 'blocked-timeout'
| 'voluntary';
export interface IssueClaim {
issueId: string;
claimant: Claimant;
claimedAt: Date;
status: ClaimStatus;
statusChangedAt: Date;
expiresAt?: Date;
handoffTo?: Claimant;
handoffReason?: string;
blockReason?: string;
progress: number; // 0-100
context?: string;
}
export interface StealableInfo {
reason: StealReason;
stealableAt: Date;
preferredTypes?: string[];
progress: number;
context?: string;
}
export interface ClaimResult {
success: boolean;
claim?: IssueClaim;
error?: string;
}
export interface StealResult {
success: boolean;
claim?: IssueClaim;
previousOwner?: Claimant;
context?: StealableInfo;
error?: string;
}
export interface AgentLoadInfo {
agentId: string;
agentType: string;
claimCount: number;
maxClaims: number;
utilization: number;
claims: IssueClaim[];
avgCompletionTime: number;
currentBlockedCount: number;
}
export interface RebalanceResult {
moved: Array<{
issueId: string;
from: Claimant;
to: Claimant;
}>;
suggested: Array<{
issueId: string;
currentOwner: Claimant;
suggestedOwner: Claimant;
reason: string;
}>;
}
export interface WorkStealingConfig {
staleThresholdMinutes: number;
blockedThresholdMinutes: number;
overloadThreshold: number;
gracePeriodMinutes: number;
minProgressToProtect: number;
contestWindowMinutes: number;
requireSameType: boolean;
allowCrossTypeSteal: string[][];
}
export interface IssueFilters {
status?: ClaimStatus[];
labels?: string[];
agentTypes?: string[];
priority?: string[];
}
// ============================================================================
// Default Configuration
// ============================================================================
const DEFAULT_CONFIG: WorkStealingConfig = {
staleThresholdMinutes: 30,
blockedThresholdMinutes: 60,
overloadThreshold: 5,
gracePeriodMinutes: 10,
minProgressToProtect: 75,
contestWindowMinutes: 5,
requireSameType: false,
allowCrossTypeSteal: [
['coder', 'debugger'],
['tester', 'reviewer'],
],
};
// ============================================================================
// Claim Events
// ============================================================================
export type ClaimEventType =
| 'issue:claimed'
| 'issue:released'
| 'issue:handoff:requested'
| 'issue:handoff:accepted'
| 'issue:handoff:rejected'
| 'issue:status:changed'
| 'issue:review:requested'
| 'issue:expired'
| 'issue:stealable'
| 'issue:stolen'
| 'issue:steal:contested'
| 'issue:steal:resolved'
| 'swarm:rebalanced'
| 'agent:overloaded'
| 'agent:underloaded';
export interface ClaimEvent {
type: ClaimEventType;
timestamp: Date;
issueId?: string;
claimant?: Claimant;
previousClaimant?: Claimant;
data?: Record<string, unknown>;
}
// ============================================================================
// Claim Service Implementation
// ============================================================================
export class ClaimService extends EventEmitter {
private claims = new Map<string, IssueClaim>();
private stealableInfo = new Map<string, StealableInfo>();
private storagePath: string;
private config: WorkStealingConfig;
private eventLog: ClaimEvent[] = [];
constructor(projectRoot: string, config?: Partial<WorkStealingConfig>) {
super();
this.storagePath = path.join(projectRoot, '.claude-flow', 'claims');
this.config = { ...DEFAULT_CONFIG, ...config };
}
// ==========================================================================
// Initialization
// ==========================================================================
async initialize(): Promise<void> {
// Ensure storage directory exists
if (!fs.existsSync(this.storagePath)) {
fs.mkdirSync(this.storagePath, { recursive: true });
}
// Load existing claims
await this.loadClaims();
}
private async loadClaims(): Promise<void> {
const claimsFile = path.join(this.storagePath, 'claims.json');
if (fs.existsSync(claimsFile)) {
try {
const data = JSON.parse(fs.readFileSync(claimsFile, 'utf-8'));
for (const claim of data.claims || []) {
claim.claimedAt = new Date(claim.claimedAt);
claim.statusChangedAt = new Date(claim.statusChangedAt);
if (claim.expiresAt) claim.expiresAt = new Date(claim.expiresAt);
this.claims.set(claim.issueId, claim);
}
} catch {
// Start fresh if file is corrupted
}
}
}
private async saveClaims(): Promise<void> {
const claimsFile = path.join(this.storagePath, 'claims.json');
const data = {
claims: Array.from(this.claims.values()),
savedAt: new Date().toISOString(),
};
fs.writeFileSync(claimsFile, JSON.stringify(data, null, 2));
}
// ==========================================================================
// Core Claiming
// ==========================================================================
async claim(issueId: string, claimant: Claimant): Promise<ClaimResult> {
// Check if already claimed
const existing = this.claims.get(issueId);
if (existing && existing.status !== 'stealable') {
return {
success: false,
error: `Issue ${issueId} is already claimed by ${this.formatClaimant(existing.claimant)}`,
};
}
const now = new Date();
const claim: IssueClaim = {
issueId,
claimant,
claimedAt: now,
status: 'active',
statusChangedAt: now,
progress: 0,
};
this.claims.set(issueId, claim);
await this.saveClaims();
this.emitEvent({
type: 'issue:claimed',
timestamp: now,
issueId,
claimant,
previousClaimant: existing?.claimant,
});
return { success: true, claim };
}
async release(issueId: string, claimant: Claimant): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
if (!this.isSameClaimant(claim.claimant, claimant)) {
throw new Error(`Issue ${issueId} is not claimed by ${this.formatClaimant(claimant)}`);
}
this.claims.delete(issueId);
this.stealableInfo.delete(issueId);
await this.saveClaims();
this.emitEvent({
type: 'issue:released',
timestamp: new Date(),
issueId,
claimant,
});
}
// ==========================================================================
// Handoffs
// ==========================================================================
async requestHandoff(
issueId: string,
from: Claimant,
to: Claimant,
reason: string
): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
if (!this.isSameClaimant(claim.claimant, from)) {
throw new Error(`Issue ${issueId} is not claimed by ${this.formatClaimant(from)}`);
}
claim.status = 'handoff-pending';
claim.statusChangedAt = new Date();
claim.handoffTo = to;
claim.handoffReason = reason;
await this.saveClaims();
this.emitEvent({
type: 'issue:handoff:requested',
timestamp: new Date(),
issueId,
claimant: from,
data: { to, reason },
});
}
async acceptHandoff(issueId: string, claimant: Claimant): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim || claim.status !== 'handoff-pending') {
throw new Error(`No pending handoff for issue ${issueId}`);
}
if (!claim.handoffTo || !this.isSameClaimant(claim.handoffTo, claimant)) {
throw new Error(`Handoff not addressed to ${this.formatClaimant(claimant)}`);
}
const previousClaimant = claim.claimant;
claim.claimant = claimant;
claim.status = 'active';
claim.statusChangedAt = new Date();
delete claim.handoffTo;
delete claim.handoffReason;
await this.saveClaims();
this.emitEvent({
type: 'issue:handoff:accepted',
timestamp: new Date(),
issueId,
claimant,
previousClaimant,
});
}
async rejectHandoff(issueId: string, claimant: Claimant, reason: string): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim || claim.status !== 'handoff-pending') {
throw new Error(`No pending handoff for issue ${issueId}`);
}
if (!claim.handoffTo || !this.isSameClaimant(claim.handoffTo, claimant)) {
throw new Error(`Handoff not addressed to ${this.formatClaimant(claimant)}`);
}
claim.status = 'active';
claim.statusChangedAt = new Date();
delete claim.handoffTo;
delete claim.handoffReason;
await this.saveClaims();
this.emitEvent({
type: 'issue:handoff:rejected',
timestamp: new Date(),
issueId,
claimant,
data: { reason },
});
}
// ==========================================================================
// Status Updates
// ==========================================================================
async updateStatus(issueId: string, status: ClaimStatus, note?: string): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
const previousStatus = claim.status;
claim.status = status;
claim.statusChangedAt = new Date();
if (status === 'blocked' && note) {
claim.blockReason = note;
}
if (status === 'completed') {
claim.progress = 100;
}
await this.saveClaims();
this.emitEvent({
type: 'issue:status:changed',
timestamp: new Date(),
issueId,
data: { previousStatus, newStatus: status, note },
});
}
async updateProgress(issueId: string, progress: number): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
claim.progress = Math.min(100, Math.max(0, progress));
await this.saveClaims();
}
async requestReview(issueId: string, reviewers: Claimant[]): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
claim.status = 'review-requested';
claim.statusChangedAt = new Date();
await this.saveClaims();
this.emitEvent({
type: 'issue:review:requested',
timestamp: new Date(),
issueId,
claimant: claim.claimant,
data: { reviewers },
});
}
// ==========================================================================
// Work Stealing
// ==========================================================================
async markStealable(issueId: string, info: StealableInfo): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
claim.status = 'stealable';
claim.statusChangedAt = new Date();
claim.context = info.context;
claim.progress = info.progress;
this.stealableInfo.set(issueId, info);
await this.saveClaims();
this.emitEvent({
type: 'issue:stealable',
timestamp: new Date(),
issueId,
claimant: claim.claimant,
data: { info },
});
}
async steal(issueId: string, stealer: Claimant): Promise<StealResult> {
const claim = this.claims.get(issueId);
if (!claim) {
return { success: false, error: `Issue ${issueId} is not claimed` };
}
if (claim.status !== 'stealable') {
return { success: false, error: `Issue ${issueId} is not stealable` };
}
const info = this.stealableInfo.get(issueId);
const previousOwner = claim.claimant;
// Check if steal is allowed
if (this.config.requireSameType && stealer.type === 'agent' && previousOwner.type === 'agent') {
if (stealer.agentType !== previousOwner.agentType) {
const allowed = this.config.allowCrossTypeSteal.some(
pair => pair.includes(stealer.agentType) && pair.includes(previousOwner.agentType)
);
if (!allowed) {
return { success: false, error: `Cross-type steal not allowed` };
}
}
}
// Execute steal
claim.claimant = stealer;
claim.status = 'active';
claim.statusChangedAt = new Date();
claim.claimedAt = new Date();
this.stealableInfo.delete(issueId);
await this.saveClaims();
this.emitEvent({
type: 'issue:stolen',
timestamp: new Date(),
issueId,
claimant: stealer,
previousClaimant: previousOwner,
data: { context: info },
});
return { success: true, claim, previousOwner, context: info };
}
async getStealable(agentType?: string): Promise<IssueClaim[]> {
const stealable: IssueClaim[] = [];
for (const claim of this.claims.values()) {
if (claim.status !== 'stealable') continue;
const info = this.stealableInfo.get(claim.issueId);
if (agentType && info?.preferredTypes?.length) {
if (!info.preferredTypes.includes(agentType)) continue;
}
stealable.push(claim);
}
return stealable;
}
async contestSteal(issueId: string, originalClaimant: Claimant, reason: string): Promise<void> {
const claim = this.claims.get(issueId);
if (!claim) {
throw new Error(`Issue ${issueId} is not claimed`);
}
this.emitEvent({
type: 'issue:steal:contested',
timestamp: new Date(),
issueId,
claimant: originalClaimant,
data: { reason, currentOwner: claim.claimant },
});
// Contest resolution would typically be handled by a coordinator or human
}
// ==========================================================================
// Load Balancing
// ==========================================================================
async getAgentLoad(agentId: string): Promise<AgentLoadInfo> {
const claims: IssueClaim[] = [];
let blockedCount = 0;
for (const claim of this.claims.values()) {
if (claim.claimant.type === 'agent' && claim.claimant.agentId === agentId) {
claims.push(claim);
if (claim.status === 'blocked') blockedCount++;
}
}
const agentType = claims[0]?.claimant.type === 'agent' ? claims[0].claimant.agentType : 'unknown';
return {
agentId,
agentType,
claimCount: claims.length,
maxClaims: this.config.overloadThreshold,
utilization: claims.length / this.config.overloadThreshold,
claims,
avgCompletionTime: 0, // Would need historical data
currentBlockedCount: blockedCount,
};
}
async rebalance(swarmId: string): Promise<RebalanceResult> {
const result: RebalanceResult = { moved: [], suggested: [] };
// Get all agent loads
const agentLoads = new Map<string, AgentLoadInfo>();
const agentTypes = new Set<string>();
for (const claim of this.claims.values()) {
if (claim.claimant.type !== 'agent') continue;
const agentId = claim.claimant.agentId;
if (!agentLoads.has(agentId)) {
const load = await this.getAgentLoad(agentId);
agentLoads.set(agentId, load);
agentTypes.add(load.agentType);
}
}
// For each agent type, calculate average load
for (const agentType of agentTypes) {
const typeLoads = Array.from(agentLoads.values()).filter(l => l.agentType === agentType);
const avgLoad = typeLoads.reduce((sum, l) => sum + l.utilization, 0) / typeLoads.length;
const overloaded = typeLoads.filter(l => l.utilization > avgLoad * 1.5);
const underloaded = typeLoads.filter(l => l.utilization < avgLoad * 0.5);
// Generate suggestions
for (const over of overloaded) {
const lowProgressClaims = over.claims
.filter(c => c.progress < 25)
.sort((a, b) => a.progress - b.progress);
for (const claim of lowProgressClaims) {
const target = underloaded.find(u => u.claimCount < u.maxClaims);
if (target) {
result.suggested.push({
issueId: claim.issueId,
currentOwner: claim.claimant,
suggestedOwner: {
type: 'agent',
agentId: target.agentId,
agentType: target.agentType,
},
reason: 'Load balancing: redistributing work across swarm',
});
}
}
}
}
return result;
}
// ==========================================================================
// Queries
// ==========================================================================
async getClaimedBy(claimant: Claimant): Promise<IssueClaim[]> {
return Array.from(this.claims.values()).filter(c =>
this.isSameClaimant(c.claimant, claimant)
);
}
async getAvailableIssues(_filters?: IssueFilters): Promise<string[]> {
// This would integrate with GitHub API
// For now, return issues that are not claimed
return [];
}
async getIssueStatus(issueId: string): Promise<IssueClaim | null> {
return this.claims.get(issueId) || null;
}
async getAllClaims(): Promise<IssueClaim[]> {
return Array.from(this.claims.values());
}
async getByStatus(status: ClaimStatus): Promise<IssueClaim[]> {
return Array.from(this.claims.values()).filter(c => c.status === status);
}
// ==========================================================================
// Auto-Management
// ==========================================================================
async expireStale(maxAgeMinutes?: number): Promise<IssueClaim[]> {
const threshold = maxAgeMinutes ?? this.config.staleThresholdMinutes;
const now = Date.now();
const expired: IssueClaim[] = [];
for (const claim of this.claims.values()) {
if (claim.status === 'stealable' || claim.status === 'completed') continue;
const age = (now - claim.statusChangedAt.getTime()) / 60000;
if (age > threshold) {
// Mark as stealable
await this.markStealable(claim.issueId, {
reason: 'stale',
stealableAt: new Date(),
progress: claim.progress,
context: `Stale: No activity for ${Math.round(age)} minutes`,
});
expired.push(claim);
}
}
return expired;
}
// ==========================================================================
// Helpers
// ==========================================================================
private formatClaimant(claimant: Claimant): string {
return claimant.type === 'human'
? `human:${claimant.name}`
: `agent:${claimant.agentType}:${claimant.agentId}`;
}
private isSameClaimant(a: Claimant, b: Claimant): boolean {
if (a.type !== b.type) return false;
if (a.type === 'human' && b.type === 'human') {
return a.userId === b.userId;
}
if (a.type === 'agent' && b.type === 'agent') {
return a.agentId === b.agentId;
}
return false;
}
private emitEvent(event: ClaimEvent): void {
this.eventLog.push(event);
if (this.eventLog.length > 1000) {
this.eventLog = this.eventLog.slice(-500);
}
this.emit(event.type, event);
}
getEventLog(limit = 100): ClaimEvent[] {
return this.eventLog.slice(-limit);
}
}
// ============================================================================
// Factory
// ============================================================================
export function createClaimService(
projectRoot: string,
config?: Partial<WorkStealingConfig>
): ClaimService {
return new ClaimService(projectRoot, config);
}
export default ClaimService;