diff --git a/src/automation/autonomousRunner.ts b/src/automation/autonomousRunner.ts index 5fcdc2d8..95b9a902 100644 --- a/src/automation/autonomousRunner.ts +++ b/src/automation/autonomousRunner.ts @@ -155,52 +155,24 @@ import { globalRateLimit } from './rateLimitBackoff.js'; export { setNotifier, setTaskSource } from './runnerExecution.js'; export type { AutonomousConfig, RunnerState } from './runnerTypes.js'; export type { ProjectInfo } from './runnerState.js'; +export { + decisionSelectionBudget, + effectiveProjectConcurrency, + failClosedConflictFallback, + worktreeFanoutEnabled, + type RunnableCandidate, +} from './runnerAdmissionPolicy.js'; +import { + decisionSelectionBudget, + describeConflictCause, + effectiveProjectConcurrency, + failClosedConflictFallback, + taskLabel, + worktreeFanoutEnabled, + type RunnableCandidate, +} from './runnerAdmissionPolicy.js'; let runnerInstance: AutonomousRunner | null = null; -const DECISION_SELECTION_OVERSAMPLE = 3; - -/** One source of truth for scheduler, heartbeat, and durable admission. */ -export function effectiveProjectConcurrency(config: Pick): number { - const globalCap = Math.max(1, Math.floor(config.maxConcurrentTasks ?? 1)); - const parallel = worktreeFanoutEnabled(config); - if (!parallel) return 1; - // Match `openswarm review`: fill the available global pool. File-scope - // conflict analysis and durable admission remain the safety boundary; an - // omitted per-project setting must not impose a hidden throughput cap. - const requested = Math.floor(config.maxConcurrentPerProject ?? globalCap); - return Math.max(1, Math.min(requested, globalCap)); -} - -/** Worktrees isolate filesystem writes; file-scope admission still protects integration. */ -export function worktreeFanoutEnabled(config: Pick): boolean { - return (config.allowSameProjectConcurrent ?? true) && (config.worktreeMode ?? false); -} - -/** Short, stable label for a task in operator-facing logs. */ -function taskLabel(task: TaskItem): string { - return task.issueIdentifier || task.id.slice(0, 8); -} - -/** - * One-line cause for a deferral log. Without this the operator only sees that a - * candidate was deferred, not whether a scope was unknown or which files - * actually collided — the gap that made AGT-4233 need a ledger dig to diagnose. - * The file list is capped so one blocked heartbeat cannot flood the log. - */ -function describeConflictCause(reason: ScopeConflictReason, activeLabel: string): string { - if (reason.kind === 'unknown-candidate') return 'candidate write scope unknown'; - if (reason.kind === 'unknown-active') return `${activeLabel} write scope unknown`; - if (reason.shared.length === 0) return `overlaps ${activeLabel}`; - const shown = reason.shared.slice(0, 3); - const rest = reason.shared.length - shown.length; - return `overlaps ${activeLabel} on ${shown.join(', ')}${rest > 0 ? ` +${rest} more` : ''}`; -} - -export type RunnableCandidate = { task: TaskItem; projectPath: string }; type CachedDraftScope = { fingerprint: string; @@ -214,22 +186,6 @@ type CachedDraftScope = { // in trackerEffects.ts, shared with the `openswarm work` CLI so the marker // format cannot drift between the two outbox writers. (INT-3387) -/** - * Conflict analysis is an admission safety check. If it is unavailable, allow - * only one candidate from that repository so uncertainty cannot turn into - * concurrent overlapping edits. Input order already reflects decision priority. - */ -export function failClosedConflictFallback(candidates: readonly RunnableCandidate[]): Set { - return new Set(candidates.length > 0 ? [candidates[0].task.id] : []); -} - -export function decisionSelectionBudget(availableSlots: number, candidateCount: number): number { - const slots = Math.max(0, Math.floor(availableSlots)); - const candidates = Math.max(0, Math.floor(candidateCount)); - if (slots === 0 || candidates === 0) return 0; - return Math.min(candidates, Math.max(slots, slots * DECISION_SELECTION_OVERSAMPLE)); -} - /** * Record, or retire, the stand-in park signal for a task whose park cannot be * carried by the run ledger. diff --git a/src/automation/runnerAdmissionPolicy.test.ts b/src/automation/runnerAdmissionPolicy.test.ts new file mode 100644 index 00000000..1729420f --- /dev/null +++ b/src/automation/runnerAdmissionPolicy.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest'; +import type { TaskItem } from '../orchestration/decisionEngine.js'; +import * as runner from './autonomousRunner.js'; +import { + decisionSelectionBudget, + describeConflictCause, + effectiveProjectConcurrency, + failClosedConflictFallback, + taskLabel, + worktreeFanoutEnabled, +} from './runnerAdmissionPolicy.js'; + +const task = (id: string, issueIdentifier?: string) => ({ id, issueIdentifier, title: id }) as unknown as TaskItem; + +describe('runnerAdmissionPolicy (AGT-4867 slice 1)', () => { + it('fans out only with worktrees and same-project concurrency both on', () => { + expect(worktreeFanoutEnabled({ worktreeMode: true })).toBe(true); + expect(worktreeFanoutEnabled({ worktreeMode: false })).toBe(false); + expect(worktreeFanoutEnabled({ worktreeMode: true, allowSameProjectConcurrent: false })).toBe(false); + expect(worktreeFanoutEnabled({})).toBe(false); + }); + + it('caps per-project concurrency at the global pool, 1 without fan-out', () => { + expect(effectiveProjectConcurrency({ worktreeMode: false, maxConcurrentTasks: 6 })).toBe(1); + expect(effectiveProjectConcurrency({ worktreeMode: true, maxConcurrentTasks: 6 })).toBe(6); + expect(effectiveProjectConcurrency({ worktreeMode: true, maxConcurrentTasks: 6, maxConcurrentPerProject: 2 })).toBe(2); + expect(effectiveProjectConcurrency({ worktreeMode: true, maxConcurrentTasks: 3, maxConcurrentPerProject: 9 })).toBe(3); + expect(effectiveProjectConcurrency({ worktreeMode: true, maxConcurrentTasks: 0 })).toBe(1); + }); + + it('oversamples decisions 3x the free slots, bounded by the candidates', () => { + expect(decisionSelectionBudget(2, 50)).toBe(6); + expect(decisionSelectionBudget(2, 4)).toBe(4); + expect(decisionSelectionBudget(0, 4)).toBe(0); + }); + + it('admits only the first candidate when conflict analysis is unavailable', () => { + expect(failClosedConflictFallback([ + { task: task('a'), projectPath: '/p' }, + { task: task('b'), projectPath: '/p' }, + ])).toEqual(new Set(['a'])); + expect(failClosedConflictFallback([])).toEqual(new Set()); + }); + + it('labels tasks by identifier, else a short id', () => { + expect(taskLabel(task('0123456789abcdef', 'AGT-1'))).toBe('AGT-1'); + expect(taskLabel(task('0123456789abcdef'))).toBe('01234567'); + }); + + it('names the conflict cause, capping the file list at three', () => { + expect(describeConflictCause({ kind: 'unknown-candidate' } as never, 'AGT-1')).toBe('candidate write scope unknown'); + expect(describeConflictCause({ kind: 'unknown-active' } as never, 'AGT-1')).toBe('AGT-1 write scope unknown'); + expect(describeConflictCause({ kind: 'overlap', shared: [] } as never, 'AGT-1')).toBe('overlaps AGT-1'); + expect(describeConflictCause({ kind: 'overlap', shared: ['a', 'b', 'c', 'd', 'e'] } as never, 'AGT-1')) + .toBe('overlaps AGT-1 on a, b, c +2 more'); + }); + + it('stays re-exported from autonomousRunner for existing importers', () => { + expect(runner.decisionSelectionBudget).toBe(decisionSelectionBudget); + expect(runner.effectiveProjectConcurrency).toBe(effectiveProjectConcurrency); + expect(runner.failClosedConflictFallback).toBe(failClosedConflictFallback); + expect(runner.worktreeFanoutEnabled).toBe(worktreeFanoutEnabled); + }); +}); diff --git a/src/automation/runnerAdmissionPolicy.ts b/src/automation/runnerAdmissionPolicy.ts new file mode 100644 index 00000000..1384ccd2 --- /dev/null +++ b/src/automation/runnerAdmissionPolicy.ts @@ -0,0 +1,74 @@ +// ============================================ +// OpenSwarm — AutonomousRunner admission policy (AGT-4867, slice 1) +// ============================================ +// +// Pure rules the runner applies when deciding how many candidates may run and +// how a deferral is described: per-project concurrency, worktree fan-out, the +// decision oversampling budget and the fail-closed conflict fallback. Split out +// of autonomousRunner.ts, which re-exports the public ones so existing imports +// keep working. + +import type { TaskItem } from '../orchestration/decisionEngine.js'; +import type { ScopeConflictReason } from '../orchestration/conflictDetector.js'; +import type { AutonomousConfig } from './runnerTypes.js'; + +const DECISION_SELECTION_OVERSAMPLE = 3; + +/** One source of truth for scheduler, heartbeat, and durable admission. */ +export function effectiveProjectConcurrency(config: Pick): number { + const globalCap = Math.max(1, Math.floor(config.maxConcurrentTasks ?? 1)); + const parallel = worktreeFanoutEnabled(config); + if (!parallel) return 1; + // Match `openswarm review`: fill the available global pool. File-scope + // conflict analysis and durable admission remain the safety boundary; an + // omitted per-project setting must not impose a hidden throughput cap. + const requested = Math.floor(config.maxConcurrentPerProject ?? globalCap); + return Math.max(1, Math.min(requested, globalCap)); +} + +/** Worktrees isolate filesystem writes; file-scope admission still protects integration. */ +export function worktreeFanoutEnabled(config: Pick): boolean { + return (config.allowSameProjectConcurrent ?? true) && (config.worktreeMode ?? false); +} + +/** Short, stable label for a task in operator-facing logs. */ +export function taskLabel(task: TaskItem): string { + return task.issueIdentifier || task.id.slice(0, 8); +} + +/** + * One-line cause for a deferral log. Without this the operator only sees that a + * candidate was deferred, not whether a scope was unknown or which files + * actually collided — the gap that made AGT-4233 need a ledger dig to diagnose. + * The file list is capped so one blocked heartbeat cannot flood the log. + */ +export function describeConflictCause(reason: ScopeConflictReason, activeLabel: string): string { + if (reason.kind === 'unknown-candidate') return 'candidate write scope unknown'; + if (reason.kind === 'unknown-active') return `${activeLabel} write scope unknown`; + if (reason.shared.length === 0) return `overlaps ${activeLabel}`; + const shown = reason.shared.slice(0, 3); + const rest = reason.shared.length - shown.length; + return `overlaps ${activeLabel} on ${shown.join(', ')}${rest > 0 ? ` +${rest} more` : ''}`; +} + +export type RunnableCandidate = { task: TaskItem; projectPath: string }; + +/** + * Conflict analysis is an admission safety check. If it is unavailable, allow + * only one candidate from that repository so uncertainty cannot turn into + * concurrent overlapping edits. Input order already reflects decision priority. + */ +export function failClosedConflictFallback(candidates: readonly RunnableCandidate[]): Set { + return new Set(candidates.length > 0 ? [candidates[0].task.id] : []); +} + +export function decisionSelectionBudget(availableSlots: number, candidateCount: number): number { + const slots = Math.max(0, Math.floor(availableSlots)); + const candidates = Math.max(0, Math.floor(candidateCount)); + if (slots === 0 || candidates === 0) return 0; + return Math.min(candidates, Math.max(slots, slots * DECISION_SELECTION_OVERSAMPLE)); +}