Skip to content

An open-source, faster Devin alternative

TypeScript

feat(security): fan the CVE swarm out into one session per repo × CVE cell

Mohamed Habib via Computerbb0723ded1cc
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 6ecede71..ee67b0df 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -1963,12 +1963,22 @@ export async function getManagedAgentDeployments(agentId: string) {
* continue with the same filters.
*/
export function getManagedAgentSessionsPage(
- options: { agentId?: string; projectId?: string; cursor?: string } = {},
+ options: {
+ agentId?: string
+ projectId?: string
+ cursor?: string
+ // Each entry filters to sessions carrying that label, sent as
+ // `label.<key>=<value>` (the API allows up to three).
+ labels?: Record<string, string>
+ } = {},
) {
const query = new URLSearchParams({ limit: '100' })
if (options.agentId) query.set('agent', options.agentId)
if (options.projectId) query.set('project', options.projectId)
if (options.cursor) query.set('cursor', options.cursor)
+ for (const [key, value] of Object.entries(options.labels ?? {})) {
+ query.set(`label.${key}`, value)
+ }
return apiFetch(
`/managed-agents/sessions?${query.toString()}`,
undefined,
@@ -2642,6 +2652,50 @@ export async function runManagedAgent(
}
}
+/**
+ * Creates a session and queues its first turn without waiting for the run to
+ * finish. This is the fan-out primitive: a swarm launch calls it once per cell
+ * (one repository × one CVE), each with its own findings-document binding and
+ * labels that tie the session back to the run and cell, then returns the
+ * session ids for the grid to poll. Unlike `runManagedAgent` it never blocks on
+ * completion or suspends — the turn is admitted in `queue` mode and runs on the
+ * runtime's own schedule.
+ */
+export async function startManagedAgentSession(
+ agentId: string,
+ input: string,
+ options: {
+ memory?: Record<string, ManagedSessionMemoryBindingInput>
+ labels?: Record<string, string>
+ signal?: AbortSignal
+ } = {},
+) {
+ const hasMemory = options.memory && Object.keys(options.memory).length > 0
+ const hasLabels = options.labels && Object.keys(options.labels).length > 0
+ const created = await apiFetch(
+ '/managed-agents/sessions',
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ agentId,
+ source: 'api',
+ ...(hasMemory ? { memory: options.memory } : {}),
+ ...(hasLabels ? { labels: options.labels } : {}),
+ }),
+ signal: options.signal,
+ },
+ sessionCreateSchema,
+ )
+ const sessionId = created.session.id
+ const turn = await admitManagedAgentInput(
+ sessionId,
+ input,
+ 'queue',
+ options.signal,
+ )
+ return { sessionId, turnId: turn.turnId }
+}
+
export async function continueManagedAgentSession(
sessionId: string,
input: string,
diff --git a/web/src/managed-agents/security/SecurityOnboarding.tsx b/web/src/managed-agents/security/SecurityOnboarding.tsx
index 4a08468b..a9853a3d 100644
--- a/web/src/managed-agents/security/SecurityOnboarding.tsx
+++ b/web/src/managed-agents/security/SecurityOnboarding.tsx
@@ -1,10 +1,10 @@
import { useMemo, useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
-import { useNavigate } from 'react-router-dom'
import {
FolderGit2,
Loader2,
Radar,
+ RotateCcw,
Rocket,
ShieldCheck,
X,
@@ -31,20 +31,28 @@ import {
getManagedTemplateInstallation,
inspectManagedTemplate,
putAgentRuntimeVariable,
+ startManagedAgentSession,
} from '../api'
+import { installedTemplateAgentId } from '../template-continuation'
import {
- installedTemplateAgentId,
- templatePlaygroundPath,
-} from '../template-continuation'
-import {
+ cellDocumentId,
+ cellLabels,
+ composeCellPrompt,
composeLaunchPrompt,
DEFAULT_SWARM_MODEL,
SCAN_DECLARATION,
SECURITY_FINDINGS_RESOURCE,
SECURITY_SWARM_TEMPLATE_REPOSITORY,
SEED_CVES,
+ swarmCells,
+ type SwarmCell,
type SwarmPayload,
} from './catalog'
+import { SwarmGrid } from './SwarmGrid'
+
+// Each cell is one microVM session, so cap the matrix to keep an accidental
+// 20×20 launch from spinning up hundreds of sandboxes at once.
+const MAX_SWARM_CELLS = 24
const STEPS = ['Connect GitHub', 'Deploy swarm', 'Launch swarm'] as const
@@ -64,8 +72,10 @@ async function waitForInstallation(id: string) {
return installation
}
+type SwarmRun = { runId: string; cells: SwarmCell[] }
+
export default function SecurityOnboarding() {
- const navigate = useNavigate()
+ const [run, setRun] = useState<SwarmRun | null>(null)
// Step 1 — GitHub connection. An active install means the boundary is set.
const connections = useQuery({
@@ -157,39 +167,51 @@ export default function SecurityOnboarding() {
onError: (error) => notifyError("Couldn't deploy the CVE Swarm.", error),
})
- // Launch binds a per-run findings document to the session it starts. The
- // document must exist before the session, so a binding to a missing document
- // fails admission; we PUT it first, then navigate with the binding in state
- // for the playground to create the session with.
+ // Launch fans the payload's repository × CVE matrix out into one bound,
+ // labelled session per cell. Each cell gets its own findings document, created
+ // first (a binding to a missing document fails admission), then a session
+ // bound read-write to it with labels that tie it back to the run. The sessions
+ // run in parallel; the grid below polls them by `swarmRun` label.
const launch = useMutation({
- mutationFn: async (payload: SwarmPayload) => {
+ mutationFn: async (payload: SwarmPayload): Promise<SwarmRun> => {
if (!deployed) throw new Error('Deploy the swarm before launching.')
+ const cells = swarmCells(payload)
+ if (cells.length === 0) {
+ throw new Error('Add at least one repository and one CVE to swarm.')
+ }
+ if (cells.length > MAX_SWARM_CELLS) {
+ throw new Error(
+ `That is ${cells.length} cells (repos × CVEs). Trim to ${MAX_SWARM_CELLS} or fewer — each cell is its own sandbox.`,
+ )
+ }
const runId = `run-${crypto.randomUUID()}`
- await createManagedMemoryDocument({
- projectId: deployed.projectId,
- resource: SECURITY_FINDINGS_RESOURCE,
- environment: 'default',
- id: runId,
- title: `CVE swarm ${runId}`,
- text: '{}',
- })
- return { prompt: composeLaunchPrompt(payload), runId }
- },
- onSuccess: ({ prompt, runId }) => {
- if (!deployed) return
- void navigate(templatePlaygroundPath(deployed), {
- state: {
- templateFirstRunPrompt: prompt,
- templateFirstRunMemory: {
- [SECURITY_FINDINGS_RESOURCE]: {
- scope: 'document',
- id: runId,
- access: 'read-write',
+ const agentId = `${deployed.projectAgentId}@default`
+ await Promise.all(
+ cells.map(async (cell) => {
+ const id = cellDocumentId(runId, cell)
+ await createManagedMemoryDocument({
+ projectId: deployed.projectId,
+ resource: SECURITY_FINDINGS_RESOURCE,
+ environment: 'default',
+ id,
+ title: `${cell.repository} · ${cell.cveId}`,
+ text: '{}',
+ })
+ await startManagedAgentSession(agentId, composeCellPrompt(payload, cell), {
+ memory: {
+ [SECURITY_FINDINGS_RESOURCE]: {
+ scope: 'document',
+ id,
+ access: 'read-write',
+ },
},
- },
- },
- })
+ labels: cellLabels(runId, cell),
+ })
+ }),
+ )
+ return { runId, cells }
},
+ onSuccess: (started) => setRun(started),
onError: (error) => notifyError("Couldn't start the swarm.", error),
})
@@ -287,14 +309,32 @@ export default function SecurityOnboarding() {
index={2}
current={step}
icon={Radar}
- title="Launch swarm from payload"
+ title={run ? 'Swarm running' : 'Launch swarm from payload'}
done={false}
>
- <PayloadBuilder
- canLaunch={!!deployed}
- launching={launch.isPending}
- onLaunch={(payload) => launch.mutate(payload)}
- />
+ {run && deployed ? (
+ <div className="space-y-4">
+ <SwarmGrid
+ projectId={deployed.projectId}
+ runId={run.runId}
+ cells={run.cells}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setRun(null)}
+ >
+ <RotateCcw />
+ New swarm
+ </Button>
+ </div>
+ ) : (
+ <PayloadBuilder
+ canLaunch={!!deployed}
+ launching={launch.isPending}
+ onLaunch={(payload) => launch.mutate(payload)}
+ />
+ )}
</StepCard>
</div>
</div>
@@ -423,7 +463,12 @@ function PayloadBuilder({
// of "this web application" — so a launch needs a real https(s) URL. An empty
// or malformed target blocks the button.
const targetValid = /^https?:\/\/.+/i.test(payload.target)
- const ready = declaration && cveIds.length > 0 && targetValid
+ // Fan-out needs explicit repositories: one session per repository × CVE cell.
+ const ready =
+ declaration &&
+ cveIds.length > 0 &&
+ repositories.length > 0 &&
+ targetValid
function addRepo() {
const value = repoInput.trim().replace(/^https?:\/\/github\.com\//i, '')
@@ -454,7 +499,7 @@ function PayloadBuilder({
<Field
label="Repositories"
- hint="Repos from your GitHub install to swarm. Leave empty to scan every connected repository."
+ hint="Repos from your GitHub install to swarm. Each repository is checked against each CVE as its own parallel cell."
>
<div className="flex gap-2">
<Input
@@ -574,6 +619,12 @@ function PayloadBuilder({
<span className="text-muted-foreground text-xs">
Deploy the swarm above to launch.
</span>
+ ) : ready ? (
+ <span className="text-muted-foreground text-xs">
+ {repositories.length} × {cveIds.length} ={' '}
+ {repositories.length * cveIds.length} parallel cell
+ {repositories.length * cveIds.length === 1 ? '' : 's'}
+ </span>
) : null}
</div>
diff --git a/web/src/managed-agents/security/SwarmGrid.tsx b/web/src/managed-agents/security/SwarmGrid.tsx
new file mode 100644
index 00000000..1a5b7c95
--- /dev/null
+++ b/web/src/managed-agents/security/SwarmGrid.tsx
@@ -0,0 +1,289 @@
+import { useMemo } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { ExternalLink, Loader2, ShieldAlert, ShieldCheck, ShieldQuestion } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import {
+ getManagedAgentSessionsPage,
+ getManagedMemoryDocument,
+} from '../api'
+import {
+ cellDocumentId,
+ cellLabels,
+ parseCellFinding,
+ SECURITY_FINDINGS_RESOURCE,
+ SWARM_CELL_LABEL,
+ SWARM_RUN_LABEL,
+ type CellFinding,
+ type CveDisposition,
+ type SwarmCell,
+} from './catalog'
+
+// A cell is settled when its worker has either saved a verdict or its session
+// has stopped without one. We poll both the run's sessions (for liveness) and
+// each cell's findings document (for the verdict) until every cell settles.
+type CellState = {
+ cell: SwarmCell
+ sessionStatus?: string
+ finding: CellFinding | null
+}
+
+function isSessionSettled(status: string | undefined): boolean {
+ return status === 'ended' || status === 'failed' || status === 'cancelled'
+}
+
+function cellPhase(state: CellState): 'done' | 'failed' | 'running' | 'queued' {
+ if (state.finding) return 'done'
+ if (isSessionSettled(state.sessionStatus)) return 'failed'
+ if (state.sessionStatus === 'running' || state.sessionStatus === 'idle')
+ return 'running'
+ return 'queued'
+}
+
+const DISPOSITION_META: Record<
+ CveDisposition,
+ { label: string; icon: typeof ShieldAlert; className: string }
+> = {
+ exposed: {
+ label: 'Exposed',
+ icon: ShieldAlert,
+ className: 'text-destructive border-destructive/40 bg-destructive/10',
+ },
+ 'not-exposed': {
+ label: 'Not exposed',
+ icon: ShieldCheck,
+ className: 'text-status-running border-status-running/40 bg-status-running/10',
+ },
+ 'needs-review': {
+ label: 'Needs review',
+ icon: ShieldQuestion,
+ className: 'text-amber-600 border-amber-500/40 bg-amber-500/10',
+ },
+}
+
+export function SwarmGrid({
+ projectId,
+ runId,
+ cells,
+}: {
+ projectId: string
+ runId: string
+ cells: readonly SwarmCell[]
+}) {
+ // The run's live sessions, keyed by their per-cell label so each tile can show
+ // whether its worker is queued, running, or stopped.
+ const sessions = useQuery({
+ queryKey: ['swarm-sessions', projectId, runId],
+ queryFn: async () => {
+ const page = await getManagedAgentSessionsPage({
+ projectId,
+ labels: { [SWARM_RUN_LABEL]: runId },
+ })
+ return page.sessions
+ },
+ refetchInterval: (query) => {
+ const data = query.state.data
+ if (!data) return 3_000
+ const allSettled = data.every((s) => isSessionSettled(s.status))
+ return allSettled ? false : 3_000
+ },
+ })
+
+ // Each cell's findings document. These are created up front by the launch, so
+ // they always exist; the worker replaces the empty placeholder when it saves.
+ const findings = useQuery({
+ queryKey: ['swarm-findings', projectId, runId],
+ queryFn: async () => {
+ const entries = await Promise.all(
+ cells.map(async (cell) => {
+ const read = await getManagedMemoryDocument({
+ projectId,
+ resource: SECURITY_FINDINGS_RESOURCE,
+ environment: 'default',
+ id: cellDocumentId(runId, cell),
+ })
+ return [
+ cellDocumentId(runId, cell),
+ parseCellFinding(read.document.text),
+ ] as const
+ }),
+ )
+ return Object.fromEntries(entries)
+ },
+ refetchInterval: (query) => {
+ const data = query.state.data
+ if (!data) return 4_000
+ const allFound = cells.every((cell) => data[cellDocumentId(runId, cell)])
+ return allFound ? false : 4_000
+ },
+ })
+
+ const sessionByCell = useMemo(() => {
+ const map = new Map<string, string>()
+ for (const session of sessions.data ?? []) {
+ const key = session.labels[SWARM_CELL_LABEL]
+ if (key) map.set(key, session.status)
+ }
+ return map
+ }, [sessions.data])
+
+ const states: CellState[] = cells.map((cell) => {
+ const cellKey = cellLabels(runId, cell)[SWARM_CELL_LABEL]
+ return {
+ cell,
+ sessionStatus: sessionByCell.get(cellKey),
+ finding: findings.data?.[cellDocumentId(runId, cell)] ?? null,
+ }
+ })
+
+ const counts = states.reduce(
+ (acc, state) => {
+ const phase = cellPhase(state)
+ if (phase === 'done' && state.finding)
+ acc[state.finding.disposition] += 1
+ else if (phase === 'failed') acc.failed += 1
+ else acc.pending += 1
+ return acc
+ },
+ { exposed: 0, 'not-exposed': 0, 'needs-review': 0, failed: 0, pending: 0 },
+ )
+ const settled = counts.pending === 0
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center gap-2 text-sm">
+ {settled ? (
+ <span className="text-muted-foreground">
+ {cells.length} cell{cells.length === 1 ? '' : 's'} complete
+ </span>
+ ) : (
+ <span className="text-muted-foreground inline-flex items-center gap-1.5">
+ <Loader2 className="size-3.5 animate-spin" />
+ {counts.pending} of {cells.length} still running
+ </span>
+ )}
+ <SummaryPill label="Exposed" count={counts.exposed} tone="exposed" />
+ <SummaryPill
+ label="Not exposed"
+ count={counts['not-exposed']}
+ tone="not-exposed"
+ />
+ <SummaryPill
+ label="Needs review"
+ count={counts['needs-review']}
+ tone="needs-review"
+ />
+ {counts.failed > 0 ? (
+ <SummaryPill label="Failed" count={counts.failed} tone="failed" />
+ ) : null}
+ </div>
+
+ <div className="grid gap-2.5 sm:grid-cols-2">
+ {states.map((state) => (
+ <CellTile
+ key={cellDocumentId(runId, state.cell)}
+ state={state}
+ />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+function SummaryPill({
+ label,
+ count,
+ tone,
+}: {
+ label: string
+ count: number
+ tone: CveDisposition | 'failed'
+}) {
+ const className =
+ tone === 'failed'
+ ? 'text-muted-foreground border-border bg-muted'
+ : DISPOSITION_META[tone].className
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium',
+ className,
+ )}
+ >
+ {count} {label}
+ </span>
+ )
+}
+
+function CellTile({ state }: { state: CellState }) {
+ const phase = cellPhase(state)
+ const [owner, name] = state.cell.repository.split('/')
+ return (
+ <div className="rounded-lg border p-3">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <div className="truncate font-mono text-xs">
+ <span className="text-muted-foreground">{owner}/</span>
+ {name}
+ </div>
+ <div className="text-muted-foreground mt-0.5 font-mono text-xs">
+ {state.cell.cveId}
+ </div>
+ </div>
+ <CellBadge state={state} phase={phase} />
+ </div>
+ {state.finding?.reasoning ? (
+ <p className="text-muted-foreground mt-2 line-clamp-3 text-xs leading-5">
+ {state.finding.reasoning}
+ </p>
+ ) : null}
+ {state.finding?.pullRequest ? (
+ <a
+ href={state.finding.pullRequest}
+ target="_blank"
+ rel="noreferrer"
+ className="text-status-running mt-2 inline-flex items-center gap-1 text-xs hover:underline"
+ >
+ <ExternalLink className="size-3" />
+ Fix pull request
+ </a>
+ ) : null}
+ </div>
+ )
+}
+
+function CellBadge({
+ state,
+ phase,
+}: {
+ state: CellState
+ phase: ReturnType<typeof cellPhase>
+}) {
+ if (phase === 'done' && state.finding) {
+ const meta = DISPOSITION_META[state.finding.disposition]
+ const Icon = meta.icon
+ return (
+ <span
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium',
+ meta.className,
+ )}
+ >
+ <Icon className="size-3" />
+ {meta.label}
+ </span>
+ )
+ }
+ if (phase === 'failed') {
+ return (
+ <span className="text-muted-foreground border-border inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-xs">
+ Stopped
+ </span>
+ )
+ }
+ return (
+ <span className="text-muted-foreground inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs">
+ <Loader2 className="size-3 animate-spin" />
+ {phase === 'running' ? 'Running' : 'Queued'}
+ </span>
+ )
+}
diff --git a/web/src/managed-agents/security/catalog.test.ts b/web/src/managed-agents/security/catalog.test.ts
new file mode 100644
index 00000000..86fa24a5
--- /dev/null
+++ b/web/src/managed-agents/security/catalog.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest'
+import {
+ cellDocumentId,
+ cellLabels,
+ composeCellPrompt,
+ parseCellFinding,
+ swarmCells,
+ SWARM_CELL_LABEL,
+ SWARM_RUN_LABEL,
+ type SwarmPayload,
+} from './catalog'
+
+const payload: SwarmPayload = {
+ target: 'https://app.example.com',
+ declarationAccepted: true,
+ repositories: ['acme/web', 'acme/api'],
+ cveIds: ['CVE-2026-1', 'CVE-2026-2'],
+ model: 'GLM-5.3',
+}
+
+describe('swarm fan-out', () => {
+ it('expands the repository × CVE matrix into one cell per pair', () => {
+ expect(swarmCells(payload)).toEqual([
+ { repository: 'acme/web', cveId: 'CVE-2026-1' },
+ { repository: 'acme/web', cveId: 'CVE-2026-2' },
+ { repository: 'acme/api', cveId: 'CVE-2026-1' },
+ { repository: 'acme/api', cveId: 'CVE-2026-2' },
+ ])
+ })
+
+ it('is empty when either dimension is empty', () => {
+ expect(swarmCells({ ...payload, repositories: [] })).toEqual([])
+ expect(swarmCells({ ...payload, cveIds: [] })).toEqual([])
+ })
+
+ it('builds a stable, slash-free document id unique per cell', () => {
+ const run = 'run-abc'
+ const first = cellDocumentId(run, { repository: 'acme/web', cveId: 'CVE-2026-1' })
+ const second = cellDocumentId(run, { repository: 'acme/api', cveId: 'CVE-2026-1' })
+ expect(first).toBe('run-abc__acme-web__cve-2026-1')
+ expect(first).not.toContain('/')
+ expect(first).not.toBe(second)
+ })
+
+ it('labels every cell with the run and a cell key', () => {
+ const labels = cellLabels('run-abc', {
+ repository: 'acme/web',
+ cveId: 'CVE-2026-1',
+ })
+ expect(labels[SWARM_RUN_LABEL]).toBe('run-abc')
+ expect(labels[SWARM_CELL_LABEL]).toBe('acme-web-cve-2026-1')
+ })
+
+ it('narrows the prompt to a single repository and CVE', () => {
+ const prompt = composeCellPrompt(payload, {
+ repository: 'acme/web',
+ cveId: 'CVE-2026-1',
+ })
+ expect(prompt).toContain('Repository: acme/web')
+ expect(prompt).toContain('CVE: CVE-2026-1')
+ expect(prompt).toContain('scan_surface')
+ expect(prompt).not.toContain('acme/api')
+ })
+})
+
+describe('parseCellFinding', () => {
+ it('returns null for the empty placeholder', () => {
+ expect(parseCellFinding('{}')).toBeNull()
+ expect(parseCellFinding('')).toBeNull()
+ expect(parseCellFinding('not json')).toBeNull()
+ })
+
+ it('reads the first finding as the cell verdict', () => {
+ const text = JSON.stringify({
+ summary: { exposed: 1, notExposed: 0, needsReview: 0 },
+ findings: [
+ {
+ repository: 'acme/web',
+ cve: 'CVE-2026-1',
+ disposition: 'exposed',
+ reasoning: 'Pinned in lockfile and served.',
+ pullRequest: 'https://github.com/acme/web/pull/7',
+ },
+ ],
+ })
+ expect(parseCellFinding(text)).toEqual({
+ disposition: 'exposed',
+ reasoning: 'Pinned in lockfile and served.',
+ pullRequest: 'https://github.com/acme/web/pull/7',
+ })
+ })
+
+ it('rejects an unknown disposition', () => {
+ const text = JSON.stringify({ findings: [{ disposition: 'maybe' }] })
+ expect(parseCellFinding(text)).toBeNull()
+ })
+
+ it('omits an empty pull request', () => {
+ const text = JSON.stringify({
+ findings: [{ disposition: 'not-exposed', reasoning: 'Not installed.' }],
+ })
+ expect(parseCellFinding(text)).toEqual({
+ disposition: 'not-exposed',
+ reasoning: 'Not installed.',
+ })
+ })
+})
diff --git a/web/src/managed-agents/security/catalog.ts b/web/src/managed-agents/security/catalog.ts
index 4445ae12..ac3c572a 100644
--- a/web/src/managed-agents/security/catalog.ts
+++ b/web/src/managed-agents/security/catalog.ts
@@ -78,6 +78,126 @@ export type SwarmPayload = {
readonly model: string
}
+// A single unit of swarm work: one repository checked against one CVE. The
+// launch fans the payload's repository × CVE matrix into one cell per pair, and
+// starts one bound, labelled session for each so they run in parallel and each
+// writes its own findings document.
+export type SwarmCell = {
+ readonly repository: string
+ readonly cveId: string
+}
+
+// Expand the payload into the matrix of cells. Fan-out needs explicit
+// repositories and CVEs — the "all connected repositories" / "full feed"
+// shorthands only make sense for the single-session controller, so a caller
+// that means to fan out must resolve those to concrete lists first.
+export function swarmCells(payload: SwarmPayload): SwarmCell[] {
+ const cells: SwarmCell[] = []
+ for (const repository of payload.repositories) {
+ for (const cveId of payload.cveIds) {
+ cells.push({ repository, cveId })
+ }
+ }
+ return cells
+}
+
+// Reduce a free-form identifier to the characters a memory document id and a
+// label value share safely: lower-case alphanumerics and dashes. Keeps the
+// id/label stable and collision-resistant without depending on slash handling.
+function slug(value: string): string {
+ return value
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+}
+
+// The per-cell findings document id, unique within the run. Each worker binds
+// this document read-write and saves the one finding it proves; the reducer
+// reads them all back as a collection.
+export function cellDocumentId(runId: string, cell: SwarmCell): string {
+ return `${runId}__${slug(cell.repository)}__${slug(cell.cveId)}`
+}
+
+// Labels every cell session carries, so the grid can list a run's sessions with
+// `label.swarmRun=<runId>` and map each back to its cell.
+export const SWARM_RUN_LABEL = 'swarmRun'
+export const SWARM_CELL_LABEL = 'swarmCell'
+
+export function cellLabels(
+ runId: string,
+ cell: SwarmCell,
+): Record<string, string> {
+ return {
+ [SWARM_RUN_LABEL]: runId,
+ [SWARM_CELL_LABEL]: slug(`${cell.repository}--${cell.cveId}`),
+ }
+}
+
+// One cell's first-run input: a single repository checked against a single CVE.
+// The worker agent already collapses to a 1×1 matrix when the payload names one
+// of each, so this is the launch prompt narrowed to the cell.
+export function composeCellPrompt(payload: SwarmPayload, cell: SwarmCell): string {
+ const lines = [
+ 'Launch a CVE swarm cell against my own assets.',
+ '',
+ `Declaration: ${SCAN_DECLARATION}`,
+ payload.target
+ ? `Target endpoint (passive scan only): ${payload.target}`
+ : null,
+ `Repository: ${cell.repository}`,
+ `CVE: ${cell.cveId}`,
+ `Model: ${payload.model}`,
+ '',
+ payload.target
+ ? 'Run scan_surface on the target once to fingerprint it passively, then prove whether this CVE is reachable in this repository by reading the clone, then save the one finding with memory_save.'
+ : 'Prove whether this CVE is reachable in this repository by reading the clone, then save the one finding with memory_save.',
+ 'If the verdict is EXPOSED, open_fix_pull_request (dependency-only, single pin). Honor PUBLISH_ENABLED — dry run unless it is enabled.',
+ ].filter((line): line is string => line !== null)
+ return lines.join('\n')
+}
+
+export type CveDisposition = 'exposed' | 'not-exposed' | 'needs-review'
+
+export type CellFinding = {
+ readonly disposition: CveDisposition
+ readonly reasoning?: string
+ readonly pullRequest?: string
+}
+
+// Read the one finding a cell worker saved to its findings document. The worker
+// writes { summary, findings: [...] }; a 1×1 cell has a single finding, which
+// is the cell's verdict. Returns null while the document is still the empty
+// placeholder (the worker has not saved yet) or if the text is not the expected
+// shape — the grid treats both as "no verdict yet".
+export function parseCellFinding(text: string): CellFinding | null {
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(text)
+ } catch {
+ return null
+ }
+ if (!parsed || typeof parsed !== 'object') return null
+ const findings = (parsed as { findings?: unknown }).findings
+ if (!Array.isArray(findings) || findings.length === 0) return null
+ const first: unknown = (findings as unknown[])[0]
+ if (!first || typeof first !== 'object') return null
+ const disposition = (first as { disposition?: unknown }).disposition
+ if (
+ disposition !== 'exposed' &&
+ disposition !== 'not-exposed' &&
+ disposition !== 'needs-review'
+ ) {
+ return null
+ }
+ const reasoning = (first as { reasoning?: unknown }).reasoning
+ const pullRequest = (first as { pullRequest?: unknown }).pullRequest
+ return {
+ disposition,
+ ...(typeof reasoning === 'string' ? { reasoning } : {}),
+ ...(typeof pullRequest === 'string' && pullRequest ? { pullRequest } : {}),
+ }
+}
+
// Compose the controller's first-run input from the payload. This is exactly
// what the swarm agent receives as its opening instruction when the session
// starts — the scan → prove → report pipeline, with fixes gated by the