← Public packages
@kody/kody-factory
Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.
Files
/**
* Sweep / state machine. Prefer one sweep job over one waiting workflow per item.
* At most one stage transition per item per sweep tick.
*/
import { cardLink, hostedBaseUrl } from '../lib/links.ts'
import { scanMergedPrs, type PrScanResult } from '../cards/pr-scan.ts'
import { afterCardTriaged, afterCardsCreated, flushHeldPushes } from '../cards/lifecycle.ts'
import { isNightlyCard } from '../cards/tags.ts'
import type { PrRefDecision } from '../cards/pr-refs.ts'
import { loadJson, saveJson, storageKeys } from '../lib/storage.ts'
import {
emptyLedger,
nowIso,
type Ledger,
type WorkItem,
type WorkItemState,
} from './work-item.ts'
import { nextItem, rankOf, rankGlobalQueue } from './priority-queue.ts'
import { loadSettings } from '../lib/settings.ts'
import { resolveAgentRunner } from '../adapters/agent/index.ts'
import { skillForSource } from '../signals/skills/index.ts'
import { loadProjects, primaryRepoRef } from '../projects/config.ts'
import { triageWorkItem } from './triage.ts'
import {
pruneExpiredLocks,
releaseLock,
sweepTickLockKey,
tryAcquireLock,
workItemLockKey,
} from '../lib/locks.ts'
import { githubProjectsPlanning } from '../adapters/planning/github-projects.ts'
import { inPilotScope } from './scope.ts'
import { activeSessionOverlap, liveIssueState, openPrOverlap, sourceClosedEvent, type OpenPr } from './overlap.ts'
import { withLink } from './work-item.ts'
import type { GithubFetch } from '../lib/github-readonly.ts'
import { ACTIVE_WATCH, advanceWatch, beginWatch, readPrMerge, type PostMergeOutcome } from './post-merge.ts'
import { applyPrLink } from '../exports/link-pr.ts'
import { optionalGithubFetch } from '../lib/github-permissions.ts'
export type SweepDeps = {
/** GitHub read client for open-PR overlap; null skips the check. Default: the @kody/github client when GitHub answers. */
github?: GithubFetch | null
}
/** How the agent hands work back. The finish report goes onto the card, which also notifies the owner. */
export function agentHandoff(cardId: string, baseUrl?: string): string {
const link = cardLink(baseUrl || hostedBaseUrl(), cardId)
return [
'Open one focused pull request for this work item and stop there; a human reviews and merges.',
`Reference the card in the PR body with a closing keyword, for example \`Closes ${link}\`. When the PR merges, the factory marks the card shipped and links the PR. Use a bare \`${link}\` line (no keyword) for cards the PR only relates to.`,
`When the PR is up, call record-outcome for work item ${cardId} with the PR URL (artifacts: [{ kind: "pr", url }]).`,
`When you finish (or park, or get blocked), report it on the factory card: run kody:@kody/kody-factory/cards/report with { cardId: "${cardId}", outcome, summary, prUrl, agent }. The owner gets a notification that opens the card, so that report is the only update needed.`,
'After it merges, the factory may message this session if main CI fails on the merge commit; if it does, open one focused fix PR.',
'For Kody packages use the Kody CLI via npx, e.g. `npx @kodycodes/cli dev check --org <org> --target mock` before pushing, and `npx -y @kodycodes/cli@latest execute --local --org kody --code \'…\'` to run factory exports.',
].join('\n')
}
/** Handoff text with a placeholder card id (docs and tests). */
export const AGENT_HANDOFF = agentHandoff('<card id>')
function transition(
item: WorkItem,
to: WorkItemState,
reason: string,
actor: WorkItem['events'][number]['actor'],
meta?: Record<string, unknown>,
): WorkItem {
const at = nowIso()
return {
...item,
state: to,
updatedAt: at,
rank: rankOf(item.priority, item.needsKent),
events: [...item.events, { at, from: item.state, to, reason, actor, meta }],
}
}
export type SweepResult = {
scanned: number
advanced: Array<{ id: string; from: WorkItemState; to: WorkItemState; reason: string }>
started: Array<{ workItemId: string; runId: string; url?: string }>
polled: Array<{ workItemId: string; runId: string; state: string }>
needsKent: string[]
needsReview: string[]
skipped: string[]
/** Friction and imported-backlog cards, left for the nightly card run. */
nightly?: string[]
/** Held card pushes sent as the morning digest this tick. */
digest?: { sent: number; skipped?: string }
outOfScope: string[]
suppressed: Array<{ workItemId: string; kind: string; url: string }>
postMerge: PostMergeOutcome[]
/** Merged PRs that referenced cards this tick (see src/cards/pr-refs.ts). */
prRefs?: { repos: number; merged: number; changed: string[]; decisions: Array<PrRefDecision & { prUrl: string }> }
shadowMode: boolean
lockHeld: boolean
errors: string[]
}
function countRunning(items: WorkItem[]): number {
return items.filter((i) => i.state === 'running' || i.state === 'verifying').length
}
/**
* Link the PR the runner reports, then ship when the merge is attested or
* GitHub shows it merged (attested as pipeline github-api). Never merges.
*/
async function shipIfMerged(
item: WorkItem,
ledger: Ledger,
result: SweepResult,
status: { pullRequests?: Array<{ url: string }> } | null,
github: GithubFetch | null,
): Promise<boolean> {
let cur = item
if (!cur.pr && cur.repoRef && status?.pullRequests?.length) {
const want = `https://github.com/${cur.repoRef}/pull/`.toLowerCase()
const found = status.pullRequests.find((p) => p.url.toLowerCase().startsWith(want))
if (found) {
cur = applyPrLink(cur, { workItemId: cur.id, prUrl: found.url })
ledger.items[cur.id] = cur
}
}
if (!cur.pr) return false
if (!cur.pr.merged && github) {
const seen = await readPrMerge(github, cur.pr.url)
if (seen.merged) {
cur = applyPrLink(cur, { workItemId: cur.id, prUrl: cur.pr.url, merged: { by: 'pipeline', attestedBy: 'github-api', mergeCommit: seen.mergeCommit! } })
}
}
const pr = cur.pr
if (!pr?.merged) return false
let next = transition(cur, 'shipped', `merge attested by ${pr.merged.attestedBy} (${pr.merged.by})`, 'sweep', { runId: cur.runId, prUrl: pr.url, mergeCommit: pr.merged.mergeCommit })
next = beginWatch(next, pr.merged.mergeCommit)
ledger.items[cur.id] = next
result.advanced.push({ id: cur.id, from: item.state, to: 'shipped', reason: next.events.at(-1)!.reason })
return true
}
async function pollRunningItem(
item: WorkItem,
ledger: Ledger,
result: SweepResult,
shadowMode: boolean,
github: GithubFetch | null = null,
): Promise<boolean> {
if (!item.runId) {
result.skipped.push(item.id)
return false
}
const projects = await loadProjects()
const project = projects.projects[item.projectId]
const runnerId = project?.defaultRunnerId ?? 'devin'
const runner = (await resolveAgentRunner(runnerId)) ?? (await resolveAgentRunner('devin'))
if (!runner) {
result.skipped.push(item.id)
return false
}
let status: Awaited<ReturnType<typeof runner.status>> | null = null
let statusError: unknown = null
try { status = await runner.status(item.runId) } catch (err) { statusError = err }
if (status?.runId && status.runId !== item.runId) {
// The runner reported the real session for a pending start; adopt it here too
// in case the session.started handler's ledger write lost a race with the sweep.
const at = nowIso()
const adopted: WorkItem = {
...item,
runId: status.runId,
links: status.url ? withLink(item.links, { kind: 'session', url: status.url, label: `${runner.id} session`, reason: 'started', at }) : item.links,
events: [...item.events, { at, from: item.state, to: item.state, reason: 'runner session started', actor: 'system', meta: { runId: status.runId, url: status.url, pendingRunId: item.runId } }],
updatedAt: at,
}
ledger.items[item.id] = adopted
item = adopted
}
if (status) result.polled.push({ workItemId: item.id, runId: item.runId!, state: status.state })
// A merged PR ships the item (frees the run slot) and starts the post-merge watch.
const shipped = await shipIfMerged(item, ledger, result, status, github)
if (shipped) return true
if (statusError || !status) throw statusError ?? new Error('runner status unavailable')
item = ledger.items[item.id] ?? item
if (item.state === 'running') {
if (status.state === 'succeeded') {
const next = transition(
item,
'verifying',
status.summary ?? 'agent run succeeded; awaiting verify / merge record',
'sweep',
{ runId: item.runId, url: status.url },
)
ledger.items[item.id] = next
result.advanced.push({
id: item.id,
from: item.state,
to: next.state,
reason: next.events.at(-1)!.reason,
})
return true
}
if (['failed', 'cancelled', 'timed_out'].includes(status.state)) {
const next = transition(
item,
'needs-kent',
`agent ${status.state}: ${status.summary ?? 'see session'}`,
'sweep',
{ runId: item.runId, url: status.url },
)
ledger.items[item.id] = next
result.advanced.push({
id: item.id,
from: item.state,
to: next.state,
reason: next.events.at(-1)!.reason,
})
result.needsKent.push(item.id)
return true
}
result.skipped.push(item.id)
return false
}
if (item.state === 'verifying') {
// Ship only on an explicit merge attestation (link-pr / record-outcome); never on summary text.
if (item.pr?.merged) {
const next = transition(
item,
'shipped',
`merge attested by ${item.pr.merged.attestedBy} (${item.pr.merged.by})`,
'sweep',
{ runId: item.runId, prUrl: item.pr.url, mergeCommit: item.pr.merged.mergeCommit },
)
ledger.items[item.id] = next
result.advanced.push({ id: item.id, from: item.state, to: next.state, reason: next.events.at(-1)!.reason })
return true
}
// Stay in verifying until human record-outcome or clear merge signal.
result.skipped.push(item.id)
return false
}
return false
}
export async function sweep(opts?: {
dryRun?: boolean
limit?: number
/** Narrow further than the pilot scope (never widens it). */
projectId?: string
}, deps: SweepDeps = {}): Promise<SweepResult> {
const settings = await loadSettings()
const linkBase = settings.publicBaseUrl || hostedBaseUrl()
const killSwitch = (settings as Record<string, unknown>).killSwitch === true
const shadowMode = settings.shadowMode || opts?.dryRun === true
const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
const projects = await loadProjects()
const items = Object.values(ledger.items)
// Snapshot for the save merge and the card hooks.
const original = new Map(items.map((i) => [i.id, { updatedAt: i.updatedAt, state: i.state, priority: i.priority, needsKent: i.needsKent, labels: i.labels }]))
const ranked = rankGlobalQueue(items)
const limit = opts?.limit ?? settings.sweepStartLimit ?? 10
const result: SweepResult = {
scanned: ranked.length,
advanced: [],
started: [],
polled: [],
needsKent: [],
needsReview: [],
skipped: [],
outOfScope: [],
suppressed: [],
postMerge: [],
shadowMode,
lockHeld: false,
errors: [],
}
if (killSwitch) {
result.errors.push('kill switch is engaged: no new agent runs or transitions this tick')
return result
}
const scoped = (i: WorkItem) =>
inPilotScope(settings.pilotScope, i.projectId, i.repoRef) && (!opts?.projectId || i.projectId === opts.projectId)
let github: GithubFetch | null | undefined = deps.github
const prCache = new Map<string, OpenPr[]>()
const runUrls: Record<string, string | undefined> = {}
for (const [id, r] of Object.entries((await loadJson<{ runs: Record<string, { url?: string }> }>(storageKeys.RUNS_KEY, { runs: {} })).runs)) runUrls[id] = r.url
await pruneExpiredLocks()
const tickHolder = `sweep:${crypto.randomUUID().slice(0, 8)}`
const gotTick = await tryAcquireLock(sweepTickLockKey(), tickHolder, 13 * 60_000)
if (!gotTick) {
result.errors.push('another sweep tick holds the lock; skipping')
return result
}
result.lockHeld = true
try {
let transitions = 0
const maxTransitions = limit
// First: poll running/verifying (complete previously skipped path).
for (const item of items) {
if (transitions >= maxTransitions) break
if (item.state !== 'running' && item.state !== 'verifying') continue
if (!scoped(item)) { result.outOfScope.push(item.id); continue }
const holder = `${tickHolder}:${item.id}`
const locked = await tryAcquireLock(workItemLockKey(item.id), holder)
if (!locked) {
result.skipped.push(item.id)
continue
}
try {
if (github === undefined) github = await optionalGithubFetch()
const moved = await pollRunningItem(item, ledger, result, shadowMode, github)
if (moved) transitions++
} catch (err) {
result.errors.push(
`poll ${item.id}: ${err instanceof Error ? err.message : String(err)}`,
)
} finally {
await releaseLock(workItemLockKey(item.id), holder)
}
}
// Post-merge watches on shipped items (not bounded by the start budget; at most 5 per tick).
let watched = 0
for (const item of Object.values(ledger.items)) {
if (watched >= 5) break
if (item.state !== 'shipped' || !item.postMerge || !ACTIVE_WATCH.has(item.postMerge.phase)) continue
if (!scoped(item)) continue
if (github === undefined) github = await optionalGithubFetch()
if (!github) break
watched++
const runner = (await resolveAgentRunner(projects.projects[item.projectId]?.defaultRunnerId ?? 'devin')) ?? (await resolveAgentRunner('devin'))
try {
const o = await advanceWatch(ledger, item.id, {
postMergeFixTimeoutMinutes: settings.postMergeFixTimeoutMinutes,
postMergePendingTimeoutMinutes: settings.postMergePendingTimeoutMinutes,
}, {
github,
shadowMode,
notify: async (runId, text) => {
if (!runner?.message) return false
try { return await runner.message(runId, text) } catch { return false }
},
})
if (o) result.postMerge.push(o)
} catch (err) {
result.errors.push(`post-merge ${item.id}: ${err instanceof Error ? err.message : String(err)}`)
}
}
let started = 0
for (const item of ranked) {
if (transitions >= maxTransitions) break
if (!scoped(item)) {
result.outOfScope.push(item.id)
continue
}
if (item.state === 'needs-kent') {
result.needsKent.push(item.id)
continue
}
if (item.state === 'shipped' || item.state === 'dropped') {
continue
}
if (item.state === 'running' || item.state === 'verifying') {
continue
}
if (isNightlyCard(item)) {
;(result.nightly ??= []).push(item.id)
continue
}
const project = projects.projects[item.projectId]
if (project && !project.enabled) {
result.skipped.push(item.id)
continue
}
if (project && (project as Record<string, unknown>).paused === true) {
result.skipped.push(item.id)
continue
}
const holder = `${tickHolder}:${item.id}`
const locked = await tryAcquireLock(workItemLockKey(item.id), holder)
if (!locked) {
result.skipped.push(item.id)
continue
}
try {
// intake → triaged | needs-kent | stay intake as needs-review marker via event
if (item.state === 'intake') {
const verdict = await triageWorkItem(item)
if (verdict.decision === 'needs-review') {
const next = transition(
item,
'needs-kent',
verdict.reason,
'sweep',
{
triage: verdict.decision,
modelUsed: verdict.modelUsed,
modelError: verdict.modelError,
ship: verdict.ship,
},
)
// Use needs-kent for human gate when model unavailable / ambiguous.
ledger.items[item.id] = next
result.advanced.push({
id: item.id,
from: item.state,
to: next.state,
reason: verdict.reason,
})
result.needsReview.push(item.id)
result.needsKent.push(item.id)
transitions++
continue
}
const to: WorkItemState =
verdict.decision === 'triaged' ? 'triaged' : 'needs-kent'
const next = transition(item, to, verdict.reason, 'sweep', {
triage: verdict.decision,
modelUsed: verdict.modelUsed,
ship: verdict.ship,
})
ledger.items[item.id] = next
result.advanced.push({
id: item.id,
from: item.state,
to: next.state,
reason: verdict.reason,
})
if (to === 'needs-kent') result.needsKent.push(item.id)
transitions++
continue
}
// triaged → planned (skill context; planning adapter flagged storage-only)
if (item.state === 'triaged') {
const skill = skillForSource(item.source)
let planNote = 'planning adapter github-projects is storage stub (disabled live writes)'
try {
if (!shadowMode) {
const card = await githubProjectsPlanning.createCard({
projectId: item.projectId,
title: item.title,
body: item.body,
workItemId: item.id,
status: 'Exploring',
dryRun: true,
})
planNote = `plan stub card ${card.id} (dry; live GH Projects disabled)`
}
} catch (err) {
planNote = `plan stub skipped: ${err instanceof Error ? err.message : String(err)}`
}
const reason = skill
? `planned with skill ${skill.id}; ${planNote}`
: `planned without specific skill; ${planNote}`
const next = transition(item, 'planned', reason, 'sweep')
ledger.items[item.id] = next
result.advanced.push({
id: item.id,
from: item.state,
to: next.state,
reason,
})
transitions++
continue
}
// planned → running (start agent) or stay in shadow
if (item.state === 'planned') {
if (countRunning(Object.values(ledger.items)) + started >= settings.maxConcurrentRuns) {
result.skipped.push(item.id)
continue
}
const runnerId =
project?.defaultRunnerId ??
project?.agents.find((a) => a.role === 'implementer' || a.role === 'single')
?.runnerId ??
'devin'
const runner =
(await resolveAgentRunner(runnerId)) ??
(await resolveAgentRunner('devin')) ??
(await resolveAgentRunner('single-agent'))
if (!runner) {
result.skipped.push(item.id)
continue
}
const live = ledger.items[item.id] ?? item
if (github === undefined) github = await optionalGithubFetch()
// Never start on a closed source: recorded close, or the live issue state.
let closed: string | null = live.runId ? null : sourceClosedEvent(live)
if (!closed && !live.runId) {
try { closed = (await liveIssueState(github, live)) === 'closed' ? 'closed' : null } catch (err) {
result.errors.push(`issue state ${item.id}: ${err instanceof Error ? err.message : String(err)}`)
result.skipped.push(item.id)
continue
}
}
if (closed) {
const next = transition(live, 'dropped', `source issue ${closed} before start`, 'sweep', { externalState: closed })
ledger.items[item.id] = next
// Cleanup, not work: does not use up this tick's start budget.
result.advanced.push({ id: item.id, from: item.state, to: next.state, reason: next.events.at(-1)!.reason })
continue
}
const session = activeSessionOverlap(ledger, live, runUrls)
let pr = null
try { pr = session ? null : await openPrOverlap(github, live, prCache) } catch (err) {
result.errors.push(`overlap ${item.id}: ${err instanceof Error ? err.message : String(err)}`)
}
const overlap = session ?? pr
if (overlap) {
const at = nowIso()
const already = live.links?.some((l) => l.url === overlap.url && l.reason === `overlap:${overlap.kind}`)
ledger.items[item.id] = already ? live : {
...live,
links: withLink(live.links, { kind: overlap.kind === 'open-pr' ? 'pr' : 'session', url: overlap.url, label: overlap.label, reason: `overlap:${overlap.kind}`, at }),
updatedAt: at,
events: [...live.events, { at, from: live.state, to: live.state, reason: `start suppressed: ${overlap.label}`, actor: 'sweep', meta: { overlap: overlap.kind, url: overlap.url } }],
}
result.suppressed.push({ workItemId: item.id, kind: overlap.kind, url: overlap.url })
continue
}
const skill = skillForSource(item.source)
const prompt = [
skill?.understandPrompt(item) ?? `Work on: ${item.title}`,
skill?.actPrompt(item) ?? '',
agentHandoff(item.id, linkBase),
].join('\n\n')
const agentDry =
shadowMode || settings.agentDryRunDefault === true || opts?.dryRun === true
const start = await runner.start({
prompt,
projectId: item.projectId,
workItemId: item.id,
repoRef: item.repoRef ?? (project ? primaryRepoRef(project) ?? undefined : undefined),
dryRun: agentDry,
})
let next = transition(
ledger.items[item.id] ?? item,
agentDry ? 'planned' : 'running',
agentDry
? `shadow/dry: would start ${runner.id} run ${start.runId}`
: `started ${runner.id}`,
'sweep',
{ runId: start.runId, url: start.url, runnerId: runner.id },
)
if (!agentDry) {
next = { ...next, runId: start.runId, ...(start.url ? { links: withLink(next.links, { kind: 'session', url: start.url, label: `${runner.id} session`, reason: 'started', at: nowIso() }) } : {}) }
started++
}
ledger.items[item.id] = next
result.started.push({
workItemId: item.id,
runId: start.runId,
url: start.url,
})
if (next.state !== item.state) {
result.advanced.push({
id: item.id,
from: item.state,
to: next.state,
reason: next.events.at(-1)!.reason,
})
transitions++
}
}
} catch (err) {
result.errors.push(
`item ${item.id}: ${err instanceof Error ? err.message : String(err)}`,
)
} finally {
await releaseLock(workItemLockKey(item.id), holder)
}
}
// Merged PRs that reference cards ("Closes <card link>"). Runs last so it
// sees every transition above. With githubEventsMode live the
// @kody/github.pr.merged event does this instead.
let prScan: PrScanResult | null = null
if (settings.githubEventsMode !== 'live') {
try {
if (github === undefined) github = await optionalGithubFetch()
const repos = Object.values(projects.projects)
.filter((p) => p.enabled)
.flatMap((p) => p.repos.filter((r) => r.enabled && r.host === 'github' && inPilotScope(settings.pilotScope, p.id, r.repoRef)).map((r) => r.repoRef))
if (github && repos.length) {
prScan = await scanMergedPrs(ledger, repos, github, { dryRun: opts?.dryRun })
result.prRefs = { repos: prScan.repos, merged: prScan.merged, changed: prScan.changed, decisions: prScan.decisions.filter((d) => d.action !== 'skip' || d.reason !== 'no such card') }
for (const e of prScan.errors) result.errors.push(`pr refs ${e}`)
}
} catch (err) {
result.errors.push(`pr refs: ${err instanceof Error ? err.message : String(err)}`)
}
}
if (!opts?.dryRun) {
// Follow-up cards this tick created (post-merge fallbacks).
const createdHere = Object.values(ledger.items).filter((i) => !original.has(i.id))
// Keep cards written while this tick ran (create, intake, friction
// filing): new ids, and items this tick left alone that changed.
try {
const fresh = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
for (const [id, it] of Object.entries(fresh.items)) {
const was = original.get(id)
const mine = ledger.items[id]
if (!was && !mine) ledger.items[id] = it
else if (was && mine && mine.updatedAt === was.updatedAt && it.updatedAt !== was.updatedAt) ledger.items[id] = it
}
} catch (err) {
result.errors.push(`ledger merge: ${err instanceof Error ? err.message : String(err)}`)
}
await saveJson(storageKeys.LEDGER_KEY, ledger)
if (prScan) {
try { await prScan.persist() } catch (err) { result.errors.push(`pr refs cursor: ${err instanceof Error ? err.message : String(err)}`) }
}
// Card hooks: triage out of intake, and follow-up cards this tick created.
const triaged = result.advanced
.filter((a) => a.from === 'intake' && original.has(a.id) && ledger.items[a.id])
.map((a) => ({ before: original.get(a.id)!, after: ledger.items[a.id]!, reason: a.reason }))
if (triaged.length > 0) await afterCardTriaged(triaged)
if (createdHere.length > 0) await afterCardsCreated(createdHere)
result.digest = await flushHeldPushes()
}
return result
} finally {
await releaseLock(sweepTickLockKey(), tickHolder)
}
}
export async function getNextWorkItem(projectId?: string) {
const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
return nextItem(Object.values(ledger.items), { projectId })
}