@vercel/factory 0.0.12 → 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/api.d.mts +225 -0
- package/dist/api.mjs +312 -0
- package/dist/api.mjs.map +1 -0
- package/dist/{approval-DdvEKLiE.mjs → approval-JX2Px9IC.mjs} +2 -2
- package/dist/{approval-DdvEKLiE.mjs.map → approval-JX2Px9IC.mjs.map} +1 -1
- package/dist/blob/index.d.mts +4 -3
- package/dist/blob/index.mjs +21 -15
- package/dist/blob/index.mjs.map +1 -1
- package/dist/budget-DzSiIA4t.mjs +42 -0
- package/dist/budget-DzSiIA4t.mjs.map +1 -0
- package/dist/build-factory.d.mts +1 -1
- package/dist/build-factory.mjs +1 -1
- package/dist/change-D2U6v7Ek.mjs +554 -0
- package/dist/change-D2U6v7Ek.mjs.map +1 -0
- package/dist/communication-Kd9nU5RP.mjs +30 -0
- package/dist/communication-Kd9nU5RP.mjs.map +1 -0
- package/dist/connectors/index.d.mts +3 -2
- package/dist/connectors/index.mjs +53 -26
- package/dist/connectors/index.mjs.map +1 -1
- package/dist/connectors/slack.d.mts +17 -6
- package/dist/connectors/slack.mjs +99 -32
- package/dist/connectors/slack.mjs.map +1 -1
- package/dist/coordination-Cq08hb1l.mjs +76 -0
- package/dist/coordination-Cq08hb1l.mjs.map +1 -0
- package/dist/dispatch-BaZS3PT8.d.mts +76 -0
- package/dist/{driver-CrZsy7sm.d.mts → driver-BC0Mt5KG.d.mts} +2 -2
- package/dist/driver-Bbd25rNM.mjs.map +1 -1
- package/dist/engine-DFHU2Pe-.d.mts +781 -0
- package/dist/engine-WaUM2cGA.mjs +1068 -0
- package/dist/engine-WaUM2cGA.mjs.map +1 -0
- package/dist/eve/index.d.mts +289 -153
- package/dist/eve/index.mjs +378 -89
- package/dist/eve/index.mjs.map +1 -1
- package/dist/{factory-config-ifd3JxiU.mjs → factory-config-BoRXOw43.mjs} +23 -22
- package/dist/factory-config-BoRXOw43.mjs.map +1 -0
- package/dist/{factory-config-Bu4mklm9.d.mts → factory-config-D2yU3G0c.d.mts} +21 -2
- package/dist/{github-wThBfbm-.d.mts → github-C5HNBN6p.d.mts} +34 -3
- package/dist/github.d.mts +2 -2
- package/dist/github.mjs +61 -1
- package/dist/github.mjs.map +1 -1
- package/dist/{id-DwCihQr4.mjs → id-BLIkCVue.mjs} +4 -2
- package/dist/{id-DwCihQr4.mjs.map → id-BLIkCVue.mjs.map} +1 -1
- package/dist/index-Bw6hggoH.d.mts +40 -0
- package/dist/index.d.mts +291 -61
- package/dist/index.mjs +140 -783
- package/dist/index.mjs.map +1 -1
- package/dist/postgres/index.d.mts +1 -1
- package/dist/task-CcOyOJ3k.mjs +154 -0
- package/dist/task-CcOyOJ3k.mjs.map +1 -0
- package/package.json +5 -1
- package/dist/approval-CIXB8IF8.d.mts +0 -522
- package/dist/change-CFNGXVqD.mjs +0 -230
- package/dist/change-CFNGXVqD.mjs.map +0 -1
- package/dist/factory-config-ifd3JxiU.mjs.map +0 -1
- package/dist/index-Cy4jfXh5.d.mts +0 -67
- package/dist/signal-CHVEmzvI.d.mts +0 -59
package/dist/eve/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/eve/conflict.ts","../../src/eve/finding.ts","../../src/eve/deepsec.ts","../../src/eve/fetch.ts","../../src/eve/invoke.ts","../../src/eve/post-review.ts","../../src/eve/review.ts","../../src/eve/verification.ts","../../src/eve/index.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport { defineTool } from \"eve/tools\";\nimport type { CommandSandbox } from \"./fetch\";\n\nconst gitShaSchema = z.string().regex(/^[0-9a-f]{40}$/);\nconst gitBranchSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).refine((value) => !value.includes(\"..\"));\n\nexport const mergeConflictPayloadSchema = z.strictObject({\n repository: z.string().regex(/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/),\n prNumber: z.number().int().positive(),\n prUrl: z.url(),\n headBranch: gitBranchSchema.refine((value) => value.startsWith(\"factory/\")),\n headSha: gitShaSchema,\n baseBranch: gitBranchSchema,\n baseSha: gitShaSchema,\n});\n\nexport type MergeConflictPayload = z.infer<typeof mergeConflictPayloadSchema>;\n\nexport interface MergeConflictToolOptions<S extends CommandSandbox = CommandSandbox> {\n withCredential: (\n sandbox: S,\n repository: string,\n command: string,\n ) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n repoPath?: string;\n}\n\nexport function mergeConflictTools<S extends CommandSandbox>(\n stores: FactoryStores,\n options: MergeConflictToolOptions<S>,\n) {\n const repoPath = options.repoPath ?? \"repo\";\n\n async function context(taskId: z.infer<typeof taskIdSchema>) {\n const task = await stores.tasks.get(taskId);\n if (task === null) throw new Error(`task ${taskId} does not exist`);\n if (task.kind !== \"merge_conflict\") throw new Error(`task ${taskId} is ${task.kind}, not merge_conflict`);\n if (task.state !== \"running\") throw new Error(`task ${taskId} is ${task.state}, not running`);\n if (task.origin.signalId === undefined) throw new Error(`task ${taskId} has no conflict signal`);\n const signal = await stores.signals.get(task.origin.signalId);\n if (signal === null || signal.source !== \"github_merge_conflict\") {\n throw new Error(`task ${taskId} has no GitHub merge conflict signal`);\n }\n return { task, conflict: mergeConflictPayloadSchema.parse(signal.payload) };\n }\n\n return {\n fetch_merge_conflict: defineTool({\n description:\n \"Fetch the conflicted factory pull request and its current base, check out the PR head, and start the merge. Resolve every file returned in conflictedFiles, then test and commit the merge.\",\n inputSchema: z.object({ taskId: taskIdSchema }),\n async execute({ taskId }, ctx) {\n const { conflict } = await context(taskId);\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const git = `git -C ${repoPath}`;\n const headRef = `refs/remotes/origin/conflict-pr-${conflict.prNumber}`;\n const baseRef = `refs/remotes/origin/conflict-base-${conflict.prNumber}`;\n const fetch = await options.withCredential(\n sandbox,\n conflict.repository,\n `${git} fetch --depth 100 origin +refs/pull/${conflict.prNumber}/head:${headRef} +refs/heads/${conflict.baseBranch}:${baseRef}`,\n );\n if (typeof fetch.exitCode === \"number\" && fetch.exitCode !== 0) {\n throw new Error(`could not fetch pull request: ${(fetch.stderr ?? \"\").trim()}`);\n }\n const fetched = await sandbox.run({\n command: `${git} rev-parse ${headRef} && ${git} rev-parse ${baseRef}`,\n });\n const [headSha, baseSha] = fetched.stdout.trim().split(\"\\n\");\n if (headSha !== conflict.headSha || baseSha !== conflict.baseSha) {\n throw new Error(\"pull request or base changed while conflict resolution was starting; retry from a new task\");\n }\n await sandbox.run({ command: `${git} checkout -B conflict-pr ${headRef}` });\n const merge = await sandbox.run({ command: `${git} merge --no-commit --no-ff ${baseRef}` });\n const conflicts = await sandbox.run({ command: `${git} diff --name-only --diff-filter=U` });\n const conflictedFiles = conflicts.stdout.trim().split(\"\\n\").filter(Boolean);\n if (conflictedFiles.length === 0) {\n throw new Error(\n typeof merge.exitCode === \"number\" && merge.exitCode !== 0\n ? `merge failed without file conflicts: ${(merge.stderr ?? \"\").trim()}`\n : \"pull request no longer has merge conflicts\",\n );\n }\n return { ...conflict, conflictedFiles };\n },\n }),\n publish_merge_resolution: defineTool({\n description:\n \"Publish a tested, committed conflict resolution to the existing pull request branch. Fails if the remote branch changed since this task started.\",\n inputSchema: z.object({\n taskId: taskIdSchema,\n summary: z.string().min(1).max(2000),\n }),\n async execute({ taskId, summary }, ctx) {\n const { conflict } = await context(taskId);\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const git = `git -C ${repoPath}`;\n const clean = await sandbox.run({ command: `${git} status --porcelain` });\n if (clean.stdout.trim() !== \"\") throw new Error(\"commit the conflict resolution before publishing\");\n const unresolved = await sandbox.run({ command: `${git} diff --name-only --diff-filter=U` });\n if (unresolved.stdout.trim() !== \"\") throw new Error(\"merge conflicts remain unresolved\");\n const push = await options.withCredential(\n sandbox,\n conflict.repository,\n `${git} push --force-with-lease=refs/heads/${conflict.headBranch}:${conflict.headSha} origin HEAD:refs/heads/${conflict.headBranch}`,\n );\n if (typeof push.exitCode === \"number\" && push.exitCode !== 0) {\n throw new Error(`could not update pull request branch: ${(push.stderr ?? \"\").trim()}`);\n }\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n await stores.tasks.transition(taskId, \"succeeded\", { reason: summary });\n return { updated: true as const, prNumber: conflict.prNumber, prUrl: conflict.prUrl };\n },\n }),\n };\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { defaultApprovalPolicy, requiresApproval, type ApprovalPolicy } from \"../approval\";\nimport { findingFingerprint, findingSchema, type Finding } from \"../schema/finding\";\nimport { repositoryIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\n// Matched by name, not instanceof: the Blob driver is a separate package entry\n// point, so its error classes are distinct objects from any imported here.\nfunction isLostRaceError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"VersionConflictError\" || error.name === \"InvalidTransitionError\")\n );\n}\n\nexport interface RecordFindingOptions {\n /** Signal source the findings are recorded under. Defaults to security_scan. */\n source?: string;\n /** Which resulting tasks wait for a human. Defaults to the standard policy. */\n approval?: ApprovalPolicy;\n}\n\nexport type RecordFindingResult =\n | { recorded: false; reason: string; duplicate?: true; signalId?: string }\n | { recorded: true; signalId: string; taskId: string; approval: \"required\" | \"not_required\" };\n\n/**\n * Turn one finding into a signal and a fix task. The fingerprint is the\n * signal's delivery id, so the same problem reported twice is a no-op. The\n * signal is accepted on the reporter's own verification (a human gate follows\n * when the approval policy says so), and the task carries the approval\n * decision from the moment it exists. Shared by record_finding and scanner\n * tools that record on the agent's behalf.\n */\nexport async function recordFinding(\n stores: FactoryStores,\n repositoryId: string,\n finding: Finding,\n options: RecordFindingOptions = {},\n): Promise<RecordFindingResult> {\n const source = options.source ?? \"security_scan\";\n const policy = options.approval ?? defaultApprovalPolicy;\n const repository = await stores.repositories.get(repositoryId);\n if (repository === null) {\n return { recorded: false, reason: `repository ${repositoryId} does not exist` };\n }\n\n const fingerprint = findingFingerprint(repositoryId, finding);\n const signal = await stores.signals.create({\n repositoryId,\n source,\n deliveryId: fingerprint,\n replyTo: { channel: \"finding\", address: fingerprint },\n payload: finding,\n });\n if (signal.outcome !== \"pending\") {\n return { recorded: false, duplicate: true, signalId: signal.id, reason: `already recorded as ${signal.id}` };\n }\n\n // Overlapping scanner sessions can record the same finding. The signal is\n // created idempotently by fingerprint; accepting it is the compare-and-swap.\n try {\n await stores.signals.decide(signal.id, \"accepted\", {\n detail: finding.priority,\n reason: `${finding.tool ?? \"scanner\"} reported it, ${finding.verification.level} by ${finding.verification.method}`,\n });\n } catch (error) {\n // Lost the race: if the winner already decided the signal, this is a\n // duplicate; only a still-pending signal is a real failure to re-raise.\n if (isLostRaceError(error)) {\n const current = await stores.signals.get(signal.id);\n if (current !== null && current.outcome !== \"pending\") {\n return { recorded: false, duplicate: true, signalId: signal.id, reason: `already recorded as ${signal.id}` };\n }\n }\n throw error;\n }\n\n const approval = requiresApproval(policy, { source, kind: \"code_change\", priority: finding.priority });\n const task = await stores.tasks.create({\n repositoryIds: [repositoryId],\n kind: \"code_change\",\n origin: { signalId: signal.id },\n replyTo: signal.replyTo,\n ...(approval ? { approval: \"required\" as const } : {}),\n });\n\n return { recorded: true, signalId: signal.id, taskId: task.id, approval: approval ? \"required\" : \"not_required\" };\n}\n\n/**\n * The scanner's outcome tool: turns one finding into a signal and a fix task\n * in a single deterministic step. The finding's fingerprint is the signal's\n * delivery id, so reporting the same problem twice is a no-op. The signal is\n * accepted on the reporter's own verification (a human gate follows when the\n * approval policy says so), and the task carries the approval decision from\n * the moment it exists.\n */\nexport function recordFindingTool(stores: FactoryStores, options: RecordFindingOptions = {}) {\n return defineTool({\n description:\n \"Record one problem you found in the repository. Creates a fix task (which may wait for human approval) unless the same finding was already recorded. Report every finding separately; never batch.\",\n inputSchema: z.object({\n repositoryId: repositoryIdSchema,\n finding: findingSchema,\n }),\n execute({ repositoryId, finding }) {\n return recordFinding(stores, repositoryId, finding, options);\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { findingSchema, type Finding, type FindingPriority } from \"../schema/finding\";\nimport { repositoryIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport type { CommandSandbox } from \"./fetch\";\nimport { recordFinding, type RecordFindingOptions, type RecordFindingResult } from \"./finding\";\n\nexport interface DeepsecScanOptions<S extends CommandSandbox = CommandSandbox> extends RecordFindingOptions {\n /**\n * Runs one shell command with the model credential deepsec's gateway route\n * expects, and removes it again before resolving. Supplied by the app, which\n * owns where the credential comes from: on Vercel it is the deployment's own\n * OIDC identity (VERCEL_OIDC_TOKEN), so nothing has to be configured.\n */\n withModelCredential: (sandbox: S, command: string) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n /** deepsec agent backend: claude, codex, or pi. */\n agent?: \"claude\" | \"codex\" | \"pi\";\n /** Model deepsec's investigation agent uses, through the AI Gateway (e.g. claude-sonnet-4-6). */\n model?: string;\n /** Reasoning effort for the investigation: minimal, low, medium, high, or xhigh. */\n thinkingLevel?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** Parallel investigation batches. */\n concurrency?: number;\n /** deepsec version to install. */\n version?: string;\n /** Repository checkout inside the sandbox. Defaults to `repo`. */\n repoPath?: string;\n /** deepsec workspace inside the sandbox. Defaults to `deepsec`. */\n workspacePath?: string;\n /** Shell run before every deepsec command, e.g. to put a Node 24 on PATH. */\n commandPrefix?: string;\n /**\n * Candidate files investigated per run. deepsec keeps state, so successive\n * scans continue where the last one stopped; the cap keeps one run inside\n * the deployment's time limit on large repositories. Defaults to 40.\n */\n filesPerRun?: number;\n}\n\n/** deepsec's exported finding shape, as far as we depend on it. */\nconst deepsecFindingSchema = z.looseObject({\n title: z.string().min(1),\n description: z.string().min(1),\n severity: z.string().min(1),\n metadata: z\n .looseObject({\n filePath: z.string().min(1).optional(),\n lineNumbers: z.array(z.number().int().min(1)).optional(),\n vulnSlug: z.string().min(1).optional(),\n confidence: z.string().optional(),\n runId: z.string().optional(),\n })\n .optional(),\n});\n\nconst deepsecExportSchema = z.union([\n z.array(deepsecFindingSchema),\n z.looseObject({ findings: z.array(deepsecFindingSchema) }).transform((value) => value.findings),\n]);\n\nconst priorityBySeverity: Record<string, FindingPriority> = {\n CRITICAL: \"P0\",\n HIGH: \"P1\",\n MEDIUM: \"P2\",\n HIGH_BUG: \"P2\",\n BUG: \"P3\",\n LOW: \"P3\",\n};\n\n/** Convert one deepsec finding into the factory's Finding. Pure; exported for tests. */\nexport function findingFromDeepsec(raw: z.infer<typeof deepsecFindingSchema>): Finding {\n const meta = raw.metadata ?? {};\n const confidence = (meta.confidence ?? \"\").toLowerCase();\n const line = meta.lineNumbers?.[0];\n const endLine = meta.lineNumbers === undefined ? undefined : Math.max(...meta.lineNumbers);\n return findingSchema.parse({\n title: raw.title.replace(/^\\[[A-Z_]+\\]\\s*/u, \"\").slice(0, 200),\n body: raw.description.slice(0, 8000),\n ...(meta.filePath === undefined ? {} : { path: meta.filePath.slice(0, 500) }),\n ...(line === undefined ? {} : { line }),\n ...(endLine === undefined || endLine === line ? {} : { endLine }),\n priority: priorityBySeverity[raw.severity.toUpperCase()] ?? \"P3\",\n category: \"security\",\n verification: {\n // deepsec's agent reads the code; it does not run it. Say so.\n level: confidence === \"high\" ? \"supported\" : \"unverified\",\n method: \"static_analysis\",\n summary: `deepsec ${meta.vulnSlug ?? \"finding\"} with ${confidence || \"unknown\"} confidence${meta.runId === undefined ? \"\" : ` (run ${meta.runId})`}.`,\n limitations: \"AI-assisted static analysis of the checkout; not reproduced at runtime.\",\n },\n tool: \"deepsec\",\n ...(meta.vulnSlug === undefined ? {} : { ruleId: meta.vulnSlug }),\n });\n}\n\nconst findingsPath = \"/tmp/deepsec-findings.json\";\n\n/** Parse \"N file(s) with candidates\" out of deepsec scan output; null when absent. */\nfunction candidateCount(output: string): number | null {\n const match = /(\\d+)\\s+file\\(s\\) with candidates/u.exec(output);\n return match?.[1] === undefined ? null : Number(match[1]);\n}\n\n/** The last few meaningful lines of a command's output, ANSI stripped, for a receipt. */\nfunction tail(output: string, lines = 4): string {\n // eslint-disable-next-line no-control-regex -- stripping terminal colour codes\n const ansi = /\\u001b\\[[0-9;]*m/gu;\n return output\n .replaceAll(ansi, \"\")\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line !== \"\")\n .slice(-lines)\n .join(\" | \")\n .slice(0, 600);\n}\n\n/**\n * Runs deepsec (vercel-labs/deepsec) against the sandbox checkout and records\n * what it finds through the same path as record_finding, so every deepsec\n * finding becomes a fix task subject to the approval policy. Trusted code\n * owns the command sequence and the credential; the agent chooses when to\n * scan and reports the outcome.\n */\nexport function deepsecScanTool<S extends CommandSandbox>(stores: FactoryStores, options: DeepsecScanOptions<S>) {\n const repoPath = options.repoPath ?? \"repo\";\n const workspace = options.workspacePath ?? \"deepsec\";\n const version = options.version ?? \"2.3.8\";\n const agent = options.agent ?? \"claude\";\n const model = options.model ?? \"claude-sonnet-4-6\";\n const thinkingLevel = options.thinkingLevel ?? \"medium\";\n const concurrency = options.concurrency ?? 4;\n const prefix = options.commandPrefix === undefined ? [] : [options.commandPrefix];\n const filesPerRun = options.filesPerRun ?? 40;\n\n return defineTool({\n description:\n \"Run deepsec, the AI-powered vulnerability scanner, over the repository checkout and record every finding it reports as a fix task. Takes minutes. Call once per scan; then summarize the result.\",\n inputSchema: z.object({\n repositoryId: repositoryIdSchema,\n limit: z\n .number()\n .int()\n .min(1)\n .max(500)\n .optional()\n .describe(\"Candidate files to investigate this run (default 40; deepsec resumes where it left off next time).\"),\n }),\n async execute({ repositoryId, limit }, ctx) {\n const repository = await stores.repositories.get(repositoryId);\n if (repository === null) {\n return { scanned: false as const, reason: `repository ${repositoryId} does not exist` };\n }\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const projectId = repository.slug.replace(/[^a-z0-9]+/gu, \"-\");\n const startedAt = Date.now();\n\n // One receipt per phase, so the ledger answers \"where is the scan\" while\n // deepsec runs and shows what each phase cost afterwards.\n const phase = async (state: string, reason: string): Promise<void> => {\n await stores.receipts.append({\n repositoryIds: [repositoryId],\n kind: \"deepsec\",\n state,\n phase: \"security_scan\",\n reason: `${reason} (${Math.round((Date.now() - startedAt) / 1000)}s in)`,\n });\n };\n await phase(\"started\", `deepsec ${version} on ${repository.slug}, ${agent}/${model}`);\n\n // Workspace: scaffolded once per sandbox, installed from npm. deepsec\n // needs Node 24; the sandbox bootstrap is expected to provide it.\n const prepare = await sandbox.run({\n command: [\n ...prefix,\n \"set -e\",\n `if [ ! -f ${workspace}/deepsec.config.ts ]; then`,\n ` npx -y deepsec@${version} init ./${workspace} ./${repoPath} --id ${projectId} --scaffold-only --headless --yes --skip-install`,\n ` (cd ${workspace} && npm install --no-audit --no-fund --loglevel=error)`,\n \"fi\",\n // deepsec resolves deepsec.config.ts from the current directory, so\n // every deepsec command runs inside the workspace. No --root: it is a\n // one-off override that skips the project's file records, leaving\n // `process` with nothing to investigate.\n `cd ${workspace}`,\n `./node_modules/.bin/deepsec scan --project-id ${projectId}`,\n ].join(\"\\n\"),\n });\n if (typeof prepare.exitCode === \"number\" && prepare.exitCode !== 0) {\n const detail = (prepare.stderr ?? prepare.stdout).trim().slice(-1500);\n await phase(\"failed\", `scan phase failed: ${detail.slice(-300)}`);\n return { scanned: false as const, reason: `deepsec scan failed: ${detail}` };\n }\n const candidates = candidateCount(prepare.stdout);\n await phase(\n \"scanned\",\n `${candidates === null ? \"scan output\" : `${candidates} files with candidates`}: ${tail(`${prepare.stdout}\\n${prepare.stderr ?? \"\"}`)}`,\n );\n\n // Investigation talks to the model through the AI Gateway (deepsec's\n // default route); this is the only step that needs a credential.\n const investigate = await options.withModelCredential(\n sandbox,\n [\n ...prefix,\n \"set -e\",\n `cd ${workspace}`,\n `./node_modules/.bin/deepsec process --project-id ${projectId} --agent ${agent} --model ${model} --thinking-level ${thinkingLevel} --concurrency ${concurrency} --limit ${limit ?? filesPerRun}`,\n `./node_modules/.bin/deepsec export --project-id ${projectId} --format json --out ${findingsPath}`,\n ].join(\"\\n\"),\n );\n if (typeof investigate.exitCode === \"number\" && investigate.exitCode !== 0) {\n const detail = (investigate.stderr ?? investigate.stdout).trim().slice(-1500);\n await phase(\"failed\", `process phase failed: ${detail.slice(-300)}`);\n return { scanned: false as const, reason: `deepsec process failed: ${detail}` };\n }\n\n const exported = await sandbox.run({ command: `cat ${findingsPath}` });\n let parsed: unknown;\n try {\n parsed = JSON.parse(exported.stdout);\n } catch {\n return { scanned: false as const, reason: \"deepsec export was not valid JSON\" };\n }\n const raw = deepsecExportSchema.safeParse(parsed);\n if (!raw.success) {\n return { scanned: false as const, reason: `deepsec export had an unexpected shape: ${raw.error.issues[0]?.message ?? \"unknown\"}` };\n }\n\n const results: { finding: Finding; result: RecordFindingResult }[] = [];\n for (const entry of raw.data) {\n const finding = findingFromDeepsec(entry);\n results.push({ finding, result: await recordFinding(stores, repositoryId, finding, options) });\n }\n const recorded = results.filter(({ result }) => result.recorded);\n await phase(\n \"completed\",\n `${results.length} findings, ${recorded.length} new. process output: ${tail(`${investigate.stdout}\\n${investigate.stderr ?? \"\"}`, 6)}`,\n );\n return {\n scanned: true as const,\n tool: \"deepsec\",\n found: results.length,\n recorded: recorded.length,\n duplicates: results.length - recorded.length,\n awaitingApproval: recorded.filter(({ result }) => result.recorded && result.approval === \"required\").length,\n findings: results.map(({ finding, result }) => ({\n title: finding.title,\n priority: finding.priority,\n path: finding.path,\n line: finding.line,\n ...(result.recorded ? { taskId: result.taskId, approval: result.approval } : { duplicate: true }),\n })),\n };\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { changeIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\n/** The subset of the eve sandbox handle a credentialed git operation needs. */\nexport interface CommandSandbox {\n run(options: { command: string }): PromiseLike<{\n stdout: string;\n stderr?: string;\n exitCode?: number;\n }>;\n}\n\nexport interface FetchPullRequestOptions<S extends CommandSandbox = CommandSandbox> {\n /**\n * Runs one git command against `slug` with a credential the sandbox does not\n * otherwise have, and removes it again before resolving. Supplied by the\n * app, which owns how credentials are minted and where they are injected;\n * the library only decides what is fetched.\n */\n withCredential: (\n sandbox: S,\n slug: string,\n command: string,\n ) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n /** Path of the checkout inside the sandbox. Defaults to `repo`. */\n repoPath?: string;\n /** Fetch depth for the pull request head. Defaults to 50. */\n depth?: number;\n}\n\nexport type FetchPullRequestResult =\n | { fetched: false; reason: string }\n | { fetched: true; prNumber: number; prUrl: string; branch: string; headSha: string };\n\n/**\n * The verifier's way in to the change under review. The sandbox has no\n * GitHub credential while the agent runs, so trusted code does the one fetch\n * the agent cannot: the pull request number and repository come from the\n * change record, never from the agent, and the credential is gone again\n * before control returns. Mirrors how publication reads commits out of the\n * sandbox instead of letting the agent push.\n */\nexport function fetchPullRequestTool<S extends CommandSandbox>(\n stores: FactoryStores,\n options: FetchPullRequestOptions<S>,\n) {\n const repoPath = options.repoPath ?? \"repo\";\n const depth = options.depth ?? 50;\n return defineTool({\n description:\n \"Fetch the pull request under review into the checkout and check it out as the local branch `pr`. Call this after get_task, before inspecting or testing the change. Returns the PR number, URL, and the commit you are now on.\",\n inputSchema: z.object({\n changeId: changeIdSchema.describe(\"The change under review, from your starting message.\"),\n }),\n async execute({ changeId }, ctx): Promise<FetchPullRequestResult> {\n const change = await stores.changes.get(changeId);\n if (change === null) {\n return { fetched: false, reason: `change ${changeId} does not exist` };\n }\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n return { fetched: false, reason: `change is ${change.state}, not open for review; nothing to fetch` };\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) {\n return { fetched: false, reason: `repository ${change.repositoryId} does not exist` };\n }\n\n // Fetch into a remote-tracking ref (never the checked-out branch, which\n // git refuses to update), then move the local `pr` branch onto it so a\n // repeated call picks up a force-pushed head.\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const tracking = `refs/remotes/origin/pr-${change.prNumber}`;\n const git = `git -C ${repoPath}`;\n const result = await options.withCredential(\n sandbox,\n repository.slug,\n `${git} fetch --depth ${depth} origin +refs/pull/${change.prNumber}/head:${tracking} && ${git} checkout -B pr ${tracking}`,\n );\n if (typeof result.exitCode === \"number\" && result.exitCode !== 0) {\n return {\n fetched: false,\n reason: `git fetch of pull request ${change.prNumber} failed: ${(result.stderr ?? \"\").trim()}`,\n };\n }\n\n const head = await sandbox.run({ command: `${git} rev-parse HEAD` });\n return {\n fetched: true,\n prNumber: change.prNumber,\n prUrl: change.prUrl,\n branch: \"pr\",\n headSha: head.stdout.trim(),\n };\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { dispatchTask } from \"../dispatch\";\nimport { changeIdSchema, repositoryIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { Task } from \"../schema/task\";\nimport type { FactoryStores } from \"../store/engine\";\n\nexport interface InvokeAgentOptions {\n /** The factory task kind the handoff creates, e.g. \"verification\". */\n kind: string;\n /** Model-facing description of what the target agent does and when to invoke it. */\n description: string;\n /**\n * Base URL of the target agent's eve transport, e.g.\n * `https://factory.example.com/eve/agents/verifier`. Resolved at call time so\n * a deployment can derive it from its own origin.\n */\n targetUrl: () => string;\n /** Bearer token for the target agent's eve channel, when it requires auth. */\n token?: () => Promise<string | undefined>;\n /** Extra headers for the session request, e.g. a deployment protection bypass. */\n headers?: (task: Task) => Record<string, string> | Promise<Record<string, string>>;\n fetch?: typeof fetch;\n}\n\n/**\n * A tool that lets one agent hand work to another, NMA-style: the caller\n * decides to invoke; trusted code owns the how. The handoff is recorded as a\n * factory task (single-winner dispatch, receipts), then a fresh session is\n * started on the target agent carrying only the task id — never the caller's\n * context. The session start is create-once on the task id, so a retried\n * tool call cannot start a second session.\n */\nexport function invokeAgentTool(stores: FactoryStores, options: InvokeAgentOptions) {\n const doFetch = options.fetch ?? fetch;\n return defineTool({\n description: `${options.description} Hands the work to a separate agent in a fresh session; you will not see its reasoning. Returns the handoff task id.`,\n inputSchema: z.object({\n repositoryIds: z.array(repositoryIdSchema).min(1),\n parentTaskId: taskIdSchema.optional().describe(\"Your own task, when this work continues it.\"),\n changeId: changeIdSchema.optional().describe(\"The change the target agent should work on.\"),\n channel: z.string().min(1).describe(\"Reply connector, e.g. github.\"),\n address: z.string().min(1).describe(\"Reply address, e.g. acme/web#41.\"),\n brief: z\n .string()\n .min(1)\n .max(4000)\n .describe(\"What the target agent needs to know. Facts and references only, not your reasoning.\"),\n }),\n async execute(input) {\n const task = await stores.tasks.create({\n repositoryIds: input.repositoryIds,\n kind: options.kind,\n origin:\n input.parentTaskId === undefined ? { operator: \"factory\" } : { parentTaskId: input.parentTaskId },\n replyTo: { channel: input.channel, address: input.address },\n });\n\n const running = await dispatchTask(stores, task.id, {\n // Handoffs are launched by the caller, not the sweep, so a refused\n // session must fail now — no sweep would pick a re-queued handoff up.\n maxLaunchAttempts: 1,\n launch: async (dispatched) => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(await options.headers?.(dispatched)),\n };\n const token = await options.token?.();\n if (token !== undefined) {\n headers.authorization = `Bearer ${token}`;\n }\n const message = [\n `You are assigned factory task ${dispatched.id}.`,\n input.changeId === undefined ? null : `Change under review: ${input.changeId}.`,\n `Reply address: ${input.channel} ${input.address}.`,\n \"\",\n input.brief,\n \"\",\n \"Read the task with get_task first, do the work, and record the outcome with your factory tools.\",\n ]\n .filter((line) => line !== null)\n .join(\"\\n\");\n const response = await doFetch(`${options.targetUrl()}/eve/v1/session`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ message, operationId: `factory-task:${dispatched.id}` }),\n });\n if (!response.ok) {\n throw new Error(`target agent refused the session: ${response.status}`);\n }\n },\n });\n\n return { taskId: running.id, kind: running.kind, state: running.state };\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport {\n submitPullRequestReview,\n type PullRequestReviewComment,\n type SubmittedPullRequestReview,\n} from \"../github\";\nimport { changeIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\nexport interface PublishedReview {\n taskId: string;\n changeId: string;\n repository: string;\n headSha: string;\n verdict: \"approve\" | \"request_changes\" | \"comment\";\n summary: string;\n comments: readonly PullRequestReviewComment[];\n review: SubmittedPullRequestReview;\n}\n\nexport interface PostReviewToolOptions {\n tokenForRepository: (repository: string) => Promise<string>;\n onPublished?: (published: PublishedReview) => Promise<void>;\n fetch?: typeof globalThis.fetch;\n}\n\nconst reviewCommentSchema = z.strictObject({\n path: z.string().min(1).max(500).describe(\"Repository-relative file path.\"),\n line: z.number().int().min(1).describe(\"Line in the pull request's new version.\"),\n body: z.string().min(1).max(5000).describe(\"Markdown explaining the finding and a concrete fix.\"),\n});\n\n/**\n * Publish an independent review of an existing pull request and finish the\n * review task without changing the pull request's factory lifecycle.\n */\nexport function postReviewTool(stores: FactoryStores, options: PostReviewToolOptions) {\n return defineTool({\n description:\n \"Publish a completed code review to the existing pull request and finish your code_review task. Use request_changes only for blocking findings.\",\n inputSchema: z.object({\n taskId: taskIdSchema.describe(\"Your code_review task.\"),\n changeId: changeIdSchema.describe(\"The pull request change from your starting message.\"),\n verdict: z.enum([\"approve\", \"request_changes\", \"comment\"]),\n headSha: z.string().regex(/^[0-9a-f]{40}$/).describe(\"Commit returned by fetch_pull_request.\"),\n summary: z.string().min(1).max(5000).describe(\"Markdown summary of what you reviewed and found.\"),\n comments: z.array(reviewCommentSchema).max(50).default([]),\n }),\n async execute({ taskId, changeId, verdict, headSha, summary, comments }) {\n const task = await stores.tasks.get(taskId);\n if (task === null || task.kind !== \"code_review\") {\n return { recorded: false as const, reason: `${taskId} is not a code_review task` };\n }\n if (task.state !== \"running\") {\n return { recorded: false as const, reason: `task is ${task.state}, not running` };\n }\n\n const change = await stores.changes.get(changeId);\n if (change === null) {\n return { recorded: false as const, reason: `change ${changeId} does not exist` };\n }\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n return { recorded: false as const, reason: `change is ${change.state}, not open for review` };\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) {\n return { recorded: false as const, reason: `repository ${change.repositoryId} does not exist` };\n }\n\n const review = await submitPullRequestReview({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commitId: headSha,\n event:\n verdict === \"approve\"\n ? \"APPROVE\"\n : verdict === \"request_changes\"\n ? \"REQUEST_CHANGES\"\n : \"COMMENT\",\n body: summary,\n comments,\n });\n await options.onPublished?.({\n taskId,\n changeId,\n repository: repository.slug,\n headSha,\n verdict,\n summary,\n comments,\n review,\n });\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n const finished = await stores.tasks.transition(taskId, \"succeeded\");\n return {\n recorded: true as const,\n verdict,\n review,\n taskState: finished.state,\n };\n },\n });\n}\n","import { answerReviewComment, readPullRequestHead, readReviewComment } from \"../github\";\nimport { changeIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport type { CommandSandbox } from \"./fetch\";\n\nexport interface ReviewCommentToolOptions<S extends CommandSandbox = CommandSandbox> {\n tokenForRepository: (repository: string) => Promise<string>;\n withCredential?: (\n sandbox: S,\n repository: string,\n command: string,\n ) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n fetch?: typeof globalThis.fetch;\n repoPath?: string;\n}\n\nexport function reviewCommentTools<S extends CommandSandbox>(\n stores: FactoryStores,\n options: ReviewCommentToolOptions<S>,\n) {\n const repoPath = options.repoPath ?? \"repo\";\n const commentInputSchema = z.object({\n changeId: changeIdSchema.describe(\"The change under review, from your starting message.\"),\n commentId: z.number().int().positive().describe(\"The GitHub review comment id.\"),\n });\n\n return {\n read_review_comment: defineTool({\n description:\n \"Read an inline review comment on a change under verification or ready for human review. By default this refuses to return comments from people without write access to the repository.\",\n inputSchema: commentInputSchema,\n async execute({ changeId, commentId }) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n return readReviewComment({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n commentId,\n });\n },\n }),\n answer_review_comment: defineTool({\n description:\n \"Reply to an inline review comment on a change under verification or ready for human review. Use for findings and low-confidence responses, not for a concrete medium- or high-confidence fix.\",\n inputSchema: commentInputSchema.extend({\n body: z.string().min(1).max(5000).describe(\"The Markdown reply to post.\"),\n }),\n async execute({ changeId, commentId, body }) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n return answerReviewComment({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commentId,\n body,\n });\n },\n }),\n suggest_review_fix: defineTool({\n description:\n \"Post a concrete, apply-able GitHub suggested change for a medium-confidence fix. The replacement must cover exactly the lines attached to the inline review comment.\",\n inputSchema: commentInputSchema.extend({\n confidence: z.literal(\"medium\"),\n replacement: z.string().min(1).max(5000).describe(\"Exact replacement text for the commented lines.\"),\n summary: z.string().min(1).max(1000).describe(\"A brief explanation of the suggested fix.\"),\n }),\n async execute({ changeId, commentId, replacement, summary }) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n return answerReviewComment({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commentId,\n body: `${summary}\\n\\n\\`\\`\\`suggestion\\n${replacement}\\n\\`\\`\\``,\n });\n },\n }),\n apply_review_fix: defineTool({\n description:\n \"Publish a tested, committed high-confidence fix to the existing same-repository pull request branch. Fails if the checkout is dirty, the PR changed, or the PR comes from a fork.\",\n inputSchema: commentInputSchema.extend({\n confidence: z.literal(\"high\"),\n summary: z.string().min(1).max(1000).describe(\"What was fixed and verified.\"),\n }),\n async execute({ changeId, commentId, summary }, ctx) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n if (options.withCredential === undefined) {\n throw new Error(\"applying review fixes is not configured\");\n }\n const token = await options.tokenForRepository(repository.slug);\n await readReviewComment({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n commentId,\n });\n const head = await readPullRequestHead({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n });\n if (head.repository !== repository.slug.toLowerCase()) {\n throw new Error(\"cannot apply a fix to a pull request from a fork\");\n }\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const git = `git -C ${repoPath}`;\n const clean = await sandbox.run({ command: `${git} status --porcelain` });\n if (clean.stdout.trim() !== \"\") throw new Error(\"commit the review fix before publishing\");\n const ancestor = await sandbox.run({ command: `${git} merge-base --is-ancestor ${head.sha} HEAD` });\n if (ancestor.exitCode !== 0) {\n throw new Error(\"pull request changed after it was fetched; fetch it again before applying the fix\");\n }\n const localHead = await sandbox.run({ command: `${git} rev-parse HEAD` });\n if (localHead.stdout.trim() === head.sha) throw new Error(\"no committed review fix to publish\");\n const push = await options.withCredential(\n sandbox,\n repository.slug,\n `${git} push --force-with-lease=refs/heads/${head.branch}:${head.sha} origin HEAD:refs/heads/${head.branch}`,\n );\n if (typeof push.exitCode === \"number\" && push.exitCode !== 0) {\n throw new Error(`could not update pull request branch: ${(push.stderr ?? \"\").trim()}`);\n }\n const reply = await answerReviewComment({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commentId,\n body: summary,\n });\n return { updated: true as const, prNumber: change.prNumber, prUrl: change.prUrl, reply };\n },\n }),\n };\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { changeEvidenceSchema, levelSchema } from \"../schema/change\";\nimport { changeIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\n/**\n * The verifier's outcome tool. Writes evidence onto the change and moves it\n * to ready only when the verdict is pass; a failed verdict leaves the change\n * verifying with the evidence recorded, and the verification task itself\n * ends with a receipt either way. The change's own code_change task follows\n * the verdict too: succeeded on pass, failed on fail with the verifier's\n * summary as the reason, so the ledger never shows a verified-and-rejected fix\n * as still in progress. Fail closed: the agent cannot mark a change ready\n * without supplying every evidence field.\n */\nexport function recordVerificationTool(stores: FactoryStores) {\n return defineTool({\n description:\n \"Record the outcome of a verification task: the evidence you gathered and whether the change passed. Pass moves the change to ready for human review; fail keeps it out of review.\",\n inputSchema: z.object({\n taskId: taskIdSchema.describe(\"Your verification task.\"),\n changeId: changeIdSchema.describe(\"The change you verified.\"),\n verdict: z.enum([\"pass\", \"fail\"]),\n evidence: changeEvidenceSchema,\n confidence: levelSchema.describe(\"How certain you are in the verdict.\"),\n summary: z.string().min(1).max(2000).describe(\"What you checked and what you found.\"),\n }),\n async execute({ taskId, changeId, verdict, evidence, confidence, summary }) {\n const change = await stores.changes.get(changeId);\n if (change === null) {\n return { recorded: false as const, reason: `change ${changeId} does not exist` };\n }\n if (change.state !== \"verifying\") {\n return {\n recorded: false as const,\n reason: `change is ${change.state}, not verifying; nothing to record`,\n };\n }\n\n const task = await stores.tasks.get(taskId);\n if (task === null || task.kind !== \"verification\") {\n return { recorded: false as const, reason: `${taskId} is not a verification task` };\n }\n\n let updatedChange = change;\n if (verdict === \"pass\") {\n updatedChange = await stores.changes.transition(changeId, \"ready\", {\n patch: { evidence, confidence },\n reason: summary,\n });\n }\n\n // The task machine has no running -> succeeded edge; a passing\n // verification walks running -> verifying -> succeeded, a failing one\n // ends directly at failed.\n let finished;\n if (verdict === \"pass\") {\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n finished = await stores.tasks.transition(taskId, \"succeeded\");\n } else {\n finished = await stores.tasks.transition(taskId, \"failed\", { reason: summary });\n }\n\n // The fix task that produced the change. It sat in verifying while the\n // verifier worked; settle it the same way. A missing or already-settled\n // parent is not the verifier's problem, so tolerate it.\n if (change.taskId !== undefined) {\n const parent = await stores.tasks.get(change.taskId);\n if (parent?.state === \"verifying\") {\n await stores.tasks\n .transition(\n change.taskId,\n verdict === \"pass\" ? \"succeeded\" : \"failed\",\n verdict === \"pass\" ? {} : { reason: `verification failed: ${summary}` },\n )\n .catch(() => undefined);\n }\n }\n\n return {\n recorded: true as const,\n verdict,\n changeState: updatedChange.state,\n taskState: finished.state,\n };\n },\n });\n}\n","import { defineHook } from \"eve/hooks\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { changeIdSchema, repositoryIdSchema, signalIdSchema, taskIdSchema } from \"../schema/id\";\nimport { levelSchema } from \"../schema/change\";\nimport { vocabularySchema } from \"../schema/common\";\nimport { taskQuestionSchema } from \"../schema/task\";\nimport type { FactoryStores } from \"../store/engine\";\n\nconst decidedOutcomeSchema = z.enum([\n \"accepted\",\n \"duplicate\",\n \"unactionable\",\n \"low_confidence\",\n \"ignored\",\n]);\n\nconst recordChangeInputSchema = z.object({\n taskId: taskIdSchema,\n repositoryId: repositoryIdSchema,\n prNumber: z.number().int().min(1),\n prUrl: z.url(),\n risk: levelSchema.describe(\"Blast radius of the change if it is wrong.\"),\n confidence: levelSchema.describe(\"How certain you are the change is correct.\"),\n summary: z.string().min(1).describe(\"One-sentence description of the change.\"),\n});\n\nexport type RecordChangeInput = z.infer<typeof recordChangeInputSchema>;\n\nexport type GateVerdict = { ok: true } | { ok: false; reason: string };\n\nexport interface FactoryToolsOptions {\n /**\n * Pre-action gate for record_change, run as an eve approval policy before\n * the tool executes. Refusals reach the model as a denial with the reason.\n * Gates must fail closed: when they cannot verify, they refuse.\n */\n recordChangeGate?: (input: RecordChangeInput) => Promise<GateVerdict>;\n}\n\n/**\n * The factory's store operations wrapped as eve tools. Expose a tool to an\n * agent by re-exporting it from a file under agent/tools/, e.g.\n * `export default factoryTools(stores).get_task;`. Every write goes through\n * the engine, so agents inherit transition legality and receipts.\n */\nexport function factoryTools(stores: FactoryStores, options: FactoryToolsOptions = {}) {\n const recordChangeGate = options.recordChangeGate;\n return {\n get_task: defineTool({\n description:\n \"Read one factory task by id: its kind, state, repositories, origin, and results.\",\n inputSchema: z.object({ taskId: taskIdSchema }),\n async execute({ taskId }) {\n const task = await stores.tasks.get(taskId);\n return task ?? { found: false as const, taskId };\n },\n }),\n\n decide_signal: defineTool({\n description:\n \"Record the triage decision for a pending signal. A signal is decided exactly once.\",\n inputSchema: z.object({\n signalId: signalIdSchema,\n outcome: decidedOutcomeSchema,\n reason: z.string().min(1).describe(\"Why this outcome was chosen.\"),\n detail: z\n .string()\n .min(1)\n .optional()\n .describe(\"Severity if accepted, or the duplicate-of signal id.\"),\n }),\n execute({ signalId, outcome, reason, detail }) {\n return stores.signals.decide(signalId, outcome, { reason, detail });\n },\n }),\n\n record_change: defineTool({\n description:\n \"Record the pull request produced for a code_change task. Creates the change, links it to the task, and moves the task to verifying.\",\n inputSchema: recordChangeInputSchema,\n ...(recordChangeGate === undefined\n ? {}\n : {\n approval: async ({ toolInput }: { toolInput?: unknown }) => {\n const parsed = recordChangeInputSchema.safeParse(toolInput);\n if (!parsed.success) {\n return {\n type: \"denied\" as const,\n reason: \"record_change input is malformed; fix the arguments and retry\",\n };\n }\n const verdict = await recordChangeGate(parsed.data);\n return verdict.ok\n ? (\"not-applicable\" as const)\n : { type: \"denied\" as const, reason: verdict.reason };\n },\n }),\n async execute({ taskId, repositoryId, prNumber, prUrl, risk, confidence, summary }) {\n const change = await stores.changes.create({\n repositoryId,\n taskId,\n prNumber,\n prUrl,\n author: \"factory\",\n risk,\n confidence,\n evidence: {\n reproVerified: false,\n testsAdded: 0,\n checksGreen: false,\n attackPassed: false,\n scopeMatches: false,\n },\n });\n const task = await stores.tasks.transition(taskId, \"verifying\", {\n patch: { changeId: change.id },\n reason: summary,\n });\n return { change, task };\n },\n }),\n\n finish_task: defineTool({\n description:\n \"Mark your task finished with a summary, for task kinds that have no other outcome tool (for example a security_scan). Not for code_change or verification tasks: those end with record_change and record_verification.\",\n inputSchema: z.object({\n taskId: taskIdSchema,\n summary: z.string().min(1).max(4000).describe(\"What you did and found, for the ledger.\"),\n }),\n async execute({ taskId, summary }) {\n const task = await stores.tasks.get(taskId);\n if (task === null) {\n return { finished: false as const, reason: `${taskId} does not exist` };\n }\n if (task.kind === \"code_change\" || task.kind === \"verification\") {\n return { finished: false as const, reason: `${task.kind} tasks end with their own outcome tool` };\n }\n if (task.state !== \"running\") {\n return { finished: false as const, reason: `task is ${task.state}, not running` };\n }\n // The task machine has no running -> succeeded edge; walk through verifying.\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n const finished = await stores.tasks.transition(taskId, \"succeeded\", { reason: summary });\n return { finished: true as const, taskState: finished.state };\n },\n }),\n\n report_blocked: defineTool({\n description:\n \"Mark a running task as needing a human because the work cannot continue without help.\",\n inputSchema: z.object({\n taskId: taskIdSchema,\n reason: z.string().min(1).describe(\"What is blocking, written for the human.\"),\n }),\n execute({ taskId, reason }) {\n return stores.tasks.transition(taskId, \"needs_human\", { reason });\n },\n }),\n\n ask_question: defineTool({\n description:\n \"Raise a question a human operator must answer. Creates a question task that waits for the answer.\",\n inputSchema: z.object({\n repositoryIds: z.array(repositoryIdSchema).min(1),\n parentTaskId: taskIdSchema\n .optional()\n .describe(\"Task the answer unblocks, when there is one.\"),\n channel: z.string().min(1).describe(\"Reply connector, e.g. github.\"),\n address: z.string().min(1).describe(\"Reply address, e.g. acme/web#41.\"),\n question: taskQuestionSchema.omit({ answer: true, answeredBy: true }),\n }),\n async execute({ repositoryIds, parentTaskId, channel, address, question }) {\n const task = await stores.tasks.create({\n repositoryIds,\n kind: \"question\",\n origin: parentTaskId === undefined ? { operator: \"factory\" } : { parentTaskId },\n replyTo: { channel, address },\n question,\n });\n return stores.tasks.transition(task.id, \"needs_human\");\n },\n }),\n\n append_receipt: defineTool({\n description:\n \"Append one immutable audit receipt for an event worth remembering. Receipts can never be edited or deleted.\",\n inputSchema: z.object({\n repositoryIds: z.array(repositoryIdSchema).min(1),\n taskId: taskIdSchema.optional(),\n changeId: changeIdSchema.optional(),\n kind: vocabularySchema.describe(\"What the receipt is about, e.g. investigation.\"),\n state: vocabularySchema.describe(\"What happened, e.g. flag_ramped.\"),\n reason: z.string().min(1).max(2000).optional(),\n dedupeKey: z\n .string()\n .min(1)\n .optional()\n .describe(\"Same key twice records one receipt instead of two.\"),\n }),\n execute(input) {\n return stores.receipts.append(input);\n },\n }),\n };\n}\n\nexport type FactoryTools = ReturnType<typeof factoryTools>;\n\n/**\n * Observe-only eve hooks that keep the ledger honest about session outcomes.\n * Mount by re-exporting from agent/hooks/, e.g.\n * `export default factoryHooks(stores).factory;`.\n *\n * turn.completed: a turn that ends while its task is still running means the\n * agent finished talking without recording an outcome; the task moves to\n * needs_human instead of rotting. The task is found by the session's\n * channel address, which dispatch set from the task's replyTo.\n */\nexport function factoryHooks(stores: FactoryStores) {\n return {\n factory: defineHook({\n events: {\n async \"turn.completed\"(_event, ctx) {\n const address = ctx.channel.continuationToken;\n if (address === undefined) {\n return;\n }\n const tasks = await stores.tasks.list();\n const abandoned = tasks.filter(\n (task) => task.state === \"running\" && task.replyTo.address === address,\n );\n for (const task of abandoned) {\n // A hook throw fails the turn, so a lost race here is swallowed;\n // the task either moved legally elsewhere or the sweep catches it.\n await stores.tasks\n .transition(task.id, \"needs_human\", {\n reason: \"agent turn ended without recording an outcome\",\n })\n .catch(() => undefined);\n }\n },\n },\n }),\n };\n}\n\nexport type FactoryHooks = ReturnType<typeof factoryHooks>;\n\nexport {\n mergeConflictPayloadSchema,\n mergeConflictTools,\n type MergeConflictPayload,\n type MergeConflictToolOptions,\n} from \"./conflict\";\nexport { deepsecScanTool, findingFromDeepsec, type DeepsecScanOptions } from \"./deepsec\";\nexport { recordFinding, recordFindingTool, type RecordFindingOptions, type RecordFindingResult } from \"./finding\";\nexport {\n fetchPullRequestTool,\n type CommandSandbox,\n type FetchPullRequestOptions,\n type FetchPullRequestResult,\n} from \"./fetch\";\nexport { invokeAgentTool, type InvokeAgentOptions } from \"./invoke\";\nexport { postReviewTool, type PostReviewToolOptions, type PublishedReview } from \"./post-review\";\nexport { reviewCommentTools, type ReviewCommentToolOptions } from \"./review\";\nexport { recordVerificationTool } from \"./verification\";\n"],"mappings":";;;;;;;;AAMA,MAAM,eAAe,EAAE,OAAO,CAAC,CAAC,MAAM,gBAAgB;AACtD,MAAM,kBAAkB,EAAE,OAAO,CAAC,CAAC,MAAM,+BAA+B,CAAC,CAAC,QAAQ,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC;AAEjH,MAAa,6BAA6B,EAAE,aAAa;CACvD,YAAY,EAAE,OAAO,CAAC,CAAC,MAAM,oCAAoC;CACjE,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CACpC,OAAO,EAAE,IAAI;CACb,YAAY,gBAAgB,QAAQ,UAAU,MAAM,WAAW,UAAU,CAAC;CAC1E,SAAS;CACT,YAAY;CACZ,SAAS;AACX,CAAC;AAaD,SAAgB,mBACd,QACA,SACA;C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,IAAI,CAAC,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,SAAS;IAC7C,WAAW,EACR,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,oDAAoD;GAClE,CAAC;GACD,QAAQ,OAAO;IACb,OAAO,OAAO,SAAS,OAAO,KAAK;GACrC;EACF,CAAC;CACH;AACF;;;;;;;;;;;AAcA,SAAgB,aAAa,QAAuB;CAClD,OAAO,EACL,SAAS,WAAW,EAClB,QAAQ,EACN,MAAM,iBAAiB,QAAQ,KAAK;EAClC,MAAM,UAAU,IAAI,QAAQ;EAC5B,IAAI,YAAY,KAAA,GACd;EAGF,MAAM,aAAY,MADE,OAAO,MAAM,KAAK,EAAA,CACd,QACrB,SAAS,KAAK,UAAU,aAAa,KAAK,QAAQ,YAAY,OACjE;EACA,KAAK,MAAM,QAAQ,WAGjB,MAAM,OAAO,MACV,WAAW,KAAK,IAAI,eAAe,EAClC,QAAQ,gDACV,CAAC,CAAC,CACD,YAAY,KAAA,CAAS;CAE5B,EACF,EACF,CAAC,EACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/eve/conflict.ts","../../src/eve/finding.ts","../../src/eve/deepsec.ts","../../src/eve/fetch.ts","../../src/eve/invoke.ts","../../src/eve/post-review.ts","../../src/eve/review.ts","../../src/eve/verification.ts","../../src/eve/index.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport { defineTool } from \"eve/tools\";\nimport type { CommandSandbox } from \"./fetch\";\n\nconst gitShaSchema = z.string().regex(/^[0-9a-f]{40}$/);\nconst gitBranchSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).refine((value) => !value.includes(\"..\"));\n\nexport const mergeConflictPayloadSchema = z.strictObject({\n repository: z.string().regex(/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/),\n prNumber: z.number().int().positive(),\n prUrl: z.url(),\n headBranch: gitBranchSchema.refine((value) => value.startsWith(\"factory/\")),\n headSha: gitShaSchema,\n baseBranch: gitBranchSchema,\n baseSha: gitShaSchema,\n});\n\nexport type MergeConflictPayload = z.infer<typeof mergeConflictPayloadSchema>;\n\nexport interface MergeConflictToolOptions<S extends CommandSandbox = CommandSandbox> {\n withCredential: (\n sandbox: S,\n repository: string,\n command: string,\n ) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n repoPath?: string;\n}\n\nexport function mergeConflictTools<S extends CommandSandbox>(\n stores: FactoryStores,\n options: MergeConflictToolOptions<S>,\n) {\n const repoPath = options.repoPath ?? \"repo\";\n\n async function context(taskId: z.infer<typeof taskIdSchema>) {\n const task = await stores.tasks.get(taskId);\n if (task === null) throw new Error(`task ${taskId} does not exist`);\n if (task.kind !== \"merge_conflict\") throw new Error(`task ${taskId} is ${task.kind}, not merge_conflict`);\n if (task.state !== \"running\") throw new Error(`task ${taskId} is ${task.state}, not running`);\n if (task.origin.signalId === undefined) throw new Error(`task ${taskId} has no conflict signal`);\n const signal = await stores.signals.get(task.origin.signalId);\n if (signal === null || signal.source !== \"github_merge_conflict\") {\n throw new Error(`task ${taskId} has no GitHub merge conflict signal`);\n }\n return { task, conflict: mergeConflictPayloadSchema.parse(signal.payload) };\n }\n\n return {\n fetch_merge_conflict: defineTool({\n description:\n \"Fetch the conflicted factory pull request and its current base, check out the PR head, and start the merge. Resolve every file returned in conflictedFiles, then test and commit the merge.\",\n inputSchema: z.object({ taskId: taskIdSchema }),\n async execute({ taskId }, ctx) {\n const { conflict } = await context(taskId);\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const git = `git -C ${repoPath}`;\n const headRef = `refs/remotes/origin/conflict-pr-${conflict.prNumber}`;\n const baseRef = `refs/remotes/origin/conflict-base-${conflict.prNumber}`;\n const fetch = await options.withCredential(\n sandbox,\n conflict.repository,\n `${git} fetch --depth 100 origin +refs/pull/${conflict.prNumber}/head:${headRef} +refs/heads/${conflict.baseBranch}:${baseRef}`,\n );\n if (typeof fetch.exitCode === \"number\" && fetch.exitCode !== 0) {\n throw new Error(`could not fetch pull request: ${(fetch.stderr ?? \"\").trim()}`);\n }\n const fetched = await sandbox.run({\n command: `${git} rev-parse ${headRef} && ${git} rev-parse ${baseRef}`,\n });\n const [headSha, baseSha] = fetched.stdout.trim().split(\"\\n\");\n if (headSha !== conflict.headSha || baseSha !== conflict.baseSha) {\n throw new Error(\"pull request or base changed while conflict resolution was starting; retry from a new task\");\n }\n await sandbox.run({ command: `${git} checkout -B conflict-pr ${headRef}` });\n const merge = await sandbox.run({ command: `${git} merge --no-commit --no-ff ${baseRef}` });\n const conflicts = await sandbox.run({ command: `${git} diff --name-only --diff-filter=U` });\n const conflictedFiles = conflicts.stdout.trim().split(\"\\n\").filter(Boolean);\n if (conflictedFiles.length === 0) {\n throw new Error(\n typeof merge.exitCode === \"number\" && merge.exitCode !== 0\n ? `merge failed without file conflicts: ${(merge.stderr ?? \"\").trim()}`\n : \"pull request no longer has merge conflicts\",\n );\n }\n return { ...conflict, conflictedFiles };\n },\n }),\n publish_merge_resolution: defineTool({\n description:\n \"Publish a tested, committed conflict resolution to the existing pull request branch. Fails if the remote branch changed since this task started.\",\n inputSchema: z.object({\n taskId: taskIdSchema,\n summary: z.string().min(1).max(2000),\n }),\n async execute({ taskId, summary }, ctx) {\n const { conflict } = await context(taskId);\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const git = `git -C ${repoPath}`;\n const clean = await sandbox.run({ command: `${git} status --porcelain` });\n if (clean.stdout.trim() !== \"\") throw new Error(\"commit the conflict resolution before publishing\");\n const unresolved = await sandbox.run({ command: `${git} diff --name-only --diff-filter=U` });\n if (unresolved.stdout.trim() !== \"\") throw new Error(\"merge conflicts remain unresolved\");\n const push = await options.withCredential(\n sandbox,\n conflict.repository,\n `${git} push --force-with-lease=refs/heads/${conflict.headBranch}:${conflict.headSha} origin HEAD:refs/heads/${conflict.headBranch}`,\n );\n if (typeof push.exitCode === \"number\" && push.exitCode !== 0) {\n throw new Error(`could not update pull request branch: ${(push.stderr ?? \"\").trim()}`);\n }\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n await stores.tasks.transition(taskId, \"succeeded\", { reason: summary });\n return { updated: true as const, prNumber: conflict.prNumber, prUrl: conflict.prUrl };\n },\n }),\n };\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { defaultApprovalPolicy, requiresApproval, type ApprovalPolicy } from \"../approval\";\nimport { findingFingerprint, findingSchema, type Finding } from \"../schema/finding\";\nimport { repositoryIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\n// Matched by name, not instanceof: the Blob driver is a separate package entry\n// point, so its error classes are distinct objects from any imported here.\nfunction isLostRaceError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"VersionConflictError\" || error.name === \"InvalidTransitionError\")\n );\n}\n\nexport interface RecordFindingOptions {\n /** Signal source the findings are recorded under. Defaults to security_scan. */\n source?: string;\n /** Which resulting tasks wait for a human. Defaults to the standard policy. */\n approval?: ApprovalPolicy;\n}\n\nexport type RecordFindingResult =\n | { recorded: false; reason: string; duplicate?: true; signalId?: string }\n | { recorded: true; signalId: string; taskId: string; approval: \"required\" | \"not_required\" };\n\n/**\n * Turn one finding into a signal and a fix task. The fingerprint is the\n * signal's delivery id, so the same problem reported twice is a no-op. The\n * signal is accepted on the reporter's own verification (a human gate follows\n * when the approval policy says so), and the task carries the approval\n * decision from the moment it exists. Shared by record_finding and scanner\n * tools that record on the agent's behalf.\n */\nexport async function recordFinding(\n stores: FactoryStores,\n repositoryId: string,\n finding: Finding,\n options: RecordFindingOptions = {},\n): Promise<RecordFindingResult> {\n const source = options.source ?? \"security_scan\";\n const policy = options.approval ?? defaultApprovalPolicy;\n const repository = await stores.repositories.get(repositoryId);\n if (repository === null) {\n return { recorded: false, reason: `repository ${repositoryId} does not exist` };\n }\n\n const fingerprint = findingFingerprint(repositoryId, finding);\n const signal = await stores.signals.create({\n repositoryId,\n source,\n deliveryId: fingerprint,\n replyTo: { channel: \"finding\", address: fingerprint },\n payload: finding,\n });\n if (signal.outcome !== \"pending\") {\n return { recorded: false, duplicate: true, signalId: signal.id, reason: `already recorded as ${signal.id}` };\n }\n\n // Overlapping scanner sessions can record the same finding. The signal is\n // created idempotently by fingerprint; accepting it is the compare-and-swap.\n try {\n await stores.signals.decide(signal.id, \"accepted\", {\n detail: finding.priority,\n reason: `${finding.tool ?? \"scanner\"} reported it, ${finding.verification.level} by ${finding.verification.method}`,\n });\n } catch (error) {\n // Lost the race: if the winner already decided the signal, this is a\n // duplicate; only a still-pending signal is a real failure to re-raise.\n if (isLostRaceError(error)) {\n const current = await stores.signals.get(signal.id);\n if (current !== null && current.outcome !== \"pending\") {\n return { recorded: false, duplicate: true, signalId: signal.id, reason: `already recorded as ${signal.id}` };\n }\n }\n throw error;\n }\n\n const approval = requiresApproval(policy, { source, kind: \"code_change\", priority: finding.priority });\n const task = await stores.tasks.create({\n repositoryIds: [repositoryId],\n kind: \"code_change\",\n origin: { signalId: signal.id },\n replyTo: signal.replyTo,\n ...(approval ? { approval: \"required\" as const } : {}),\n });\n\n return { recorded: true, signalId: signal.id, taskId: task.id, approval: approval ? \"required\" : \"not_required\" };\n}\n\n/**\n * The scanner's outcome tool: turns one finding into a signal and a fix task\n * in a single deterministic step. The finding's fingerprint is the signal's\n * delivery id, so reporting the same problem twice is a no-op. The signal is\n * accepted on the reporter's own verification (a human gate follows when the\n * approval policy says so), and the task carries the approval decision from\n * the moment it exists.\n */\nexport function recordFindingTool(stores: FactoryStores, options: RecordFindingOptions = {}) {\n return defineTool({\n description:\n \"Record one problem you found in the repository. Creates a fix task (which may wait for human approval) unless the same finding was already recorded. Report every finding separately; never batch.\",\n inputSchema: z.object({\n repositoryId: repositoryIdSchema,\n finding: findingSchema,\n }),\n execute({ repositoryId, finding }) {\n return recordFinding(stores, repositoryId, finding, options);\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { findingSchema, type Finding, type FindingPriority } from \"../schema/finding\";\nimport { repositoryIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport type { CommandSandbox } from \"./fetch\";\nimport { recordFinding, type RecordFindingOptions, type RecordFindingResult } from \"./finding\";\n\nexport interface DeepsecScanOptions<S extends CommandSandbox = CommandSandbox> extends RecordFindingOptions {\n /**\n * Runs one shell command with the model credential deepsec's gateway route\n * expects, and removes it again before resolving. Supplied by the app, which\n * owns where the credential comes from: on Vercel it is the deployment's own\n * OIDC identity (VERCEL_OIDC_TOKEN), so nothing has to be configured.\n */\n withModelCredential: (sandbox: S, command: string) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n /** deepsec agent backend: claude, codex, or pi. */\n agent?: \"claude\" | \"codex\" | \"pi\";\n /** Model deepsec's investigation agent uses, through the AI Gateway (e.g. claude-sonnet-4-6). */\n model?: string;\n /** Reasoning effort for the investigation: minimal, low, medium, high, or xhigh. */\n thinkingLevel?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** Parallel investigation batches. */\n concurrency?: number;\n /** deepsec version to install. */\n version?: string;\n /** Repository checkout inside the sandbox. Defaults to `repo`. */\n repoPath?: string;\n /** deepsec workspace inside the sandbox. Defaults to `deepsec`. */\n workspacePath?: string;\n /** Shell run before every deepsec command, e.g. to put a Node 24 on PATH. */\n commandPrefix?: string;\n /**\n * Candidate files investigated per run. deepsec keeps state, so successive\n * scans continue where the last one stopped; the cap keeps one run inside\n * the deployment's time limit on large repositories. Defaults to 40.\n */\n filesPerRun?: number;\n}\n\n/** deepsec's exported finding shape, as far as we depend on it. */\nconst deepsecFindingSchema = z.looseObject({\n title: z.string().min(1),\n description: z.string().min(1),\n severity: z.string().min(1),\n metadata: z\n .looseObject({\n filePath: z.string().min(1).optional(),\n lineNumbers: z.array(z.number().int().min(1)).optional(),\n vulnSlug: z.string().min(1).optional(),\n confidence: z.string().optional(),\n runId: z.string().optional(),\n })\n .optional(),\n});\n\nconst deepsecExportSchema = z.union([\n z.array(deepsecFindingSchema),\n z.looseObject({ findings: z.array(deepsecFindingSchema) }).transform((value) => value.findings),\n]);\n\nconst priorityBySeverity: Record<string, FindingPriority> = {\n CRITICAL: \"P0\",\n HIGH: \"P1\",\n MEDIUM: \"P2\",\n HIGH_BUG: \"P2\",\n BUG: \"P3\",\n LOW: \"P3\",\n};\n\n/** Convert one deepsec finding into the factory's Finding. Pure; exported for tests. */\nexport function findingFromDeepsec(raw: z.infer<typeof deepsecFindingSchema>): Finding {\n const meta = raw.metadata ?? {};\n const confidence = (meta.confidence ?? \"\").toLowerCase();\n const line = meta.lineNumbers?.[0];\n const endLine = meta.lineNumbers === undefined ? undefined : Math.max(...meta.lineNumbers);\n return findingSchema.parse({\n title: raw.title.replace(/^\\[[A-Z_]+\\]\\s*/u, \"\").slice(0, 200),\n body: raw.description.slice(0, 8000),\n ...(meta.filePath === undefined ? {} : { path: meta.filePath.slice(0, 500) }),\n ...(line === undefined ? {} : { line }),\n ...(endLine === undefined || endLine === line ? {} : { endLine }),\n priority: priorityBySeverity[raw.severity.toUpperCase()] ?? \"P3\",\n category: \"security\",\n verification: {\n // deepsec's agent reads the code; it does not run it. Say so.\n level: confidence === \"high\" ? \"supported\" : \"unverified\",\n method: \"static_analysis\",\n summary: `deepsec ${meta.vulnSlug ?? \"finding\"} with ${confidence || \"unknown\"} confidence${meta.runId === undefined ? \"\" : ` (run ${meta.runId})`}.`,\n limitations: \"AI-assisted static analysis of the checkout; not reproduced at runtime.\",\n },\n tool: \"deepsec\",\n ...(meta.vulnSlug === undefined ? {} : { ruleId: meta.vulnSlug }),\n });\n}\n\nconst findingsPath = \"/tmp/deepsec-findings.json\";\n\n/** Parse \"N file(s) with candidates\" out of deepsec scan output; null when absent. */\nfunction candidateCount(output: string): number | null {\n const match = /(\\d+)\\s+file\\(s\\) with candidates/u.exec(output);\n return match?.[1] === undefined ? null : Number(match[1]);\n}\n\n/** The last few meaningful lines of a command's output, ANSI stripped, for a receipt. */\nfunction tail(output: string, lines = 4): string {\n // eslint-disable-next-line no-control-regex -- stripping terminal colour codes\n const ansi = /\\u001b\\[[0-9;]*m/gu;\n return output\n .replaceAll(ansi, \"\")\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line !== \"\")\n .slice(-lines)\n .join(\" | \")\n .slice(0, 600);\n}\n\n/**\n * Runs deepsec (vercel-labs/deepsec) against the sandbox checkout and records\n * what it finds through the same path as record_finding, so every deepsec\n * finding becomes a fix task subject to the approval policy. Trusted code\n * owns the command sequence and the credential; the agent chooses when to\n * scan and reports the outcome.\n */\nexport function deepsecScanTool<S extends CommandSandbox>(stores: FactoryStores, options: DeepsecScanOptions<S>) {\n const repoPath = options.repoPath ?? \"repo\";\n const workspace = options.workspacePath ?? \"deepsec\";\n const version = options.version ?? \"2.3.8\";\n const agent = options.agent ?? \"claude\";\n const model = options.model ?? \"claude-sonnet-4-6\";\n const thinkingLevel = options.thinkingLevel ?? \"medium\";\n const concurrency = options.concurrency ?? 4;\n const prefix = options.commandPrefix === undefined ? [] : [options.commandPrefix];\n const filesPerRun = options.filesPerRun ?? 40;\n\n return defineTool({\n description:\n \"Run deepsec, the AI-powered vulnerability scanner, over the repository checkout and record every finding it reports as a fix task. Takes minutes. Call once per scan; then summarize the result.\",\n inputSchema: z.object({\n repositoryId: repositoryIdSchema,\n limit: z\n .number()\n .int()\n .min(1)\n .max(500)\n .optional()\n .describe(\"Candidate files to investigate this run (default 40; deepsec resumes where it left off next time).\"),\n }),\n async execute({ repositoryId, limit }, ctx) {\n const repository = await stores.repositories.get(repositoryId);\n if (repository === null) {\n return { scanned: false as const, reason: `repository ${repositoryId} does not exist` };\n }\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const projectId = repository.slug.replace(/[^a-z0-9]+/gu, \"-\");\n const startedAt = Date.now();\n\n // One receipt per phase, so the ledger answers \"where is the scan\" while\n // deepsec runs and shows what each phase cost afterwards.\n const phase = async (state: string, reason: string): Promise<void> => {\n await stores.receipts.append({\n repositoryIds: [repositoryId],\n kind: \"deepsec\",\n state,\n phase: \"security_scan\",\n reason: `${reason} (${Math.round((Date.now() - startedAt) / 1000)}s in)`,\n });\n };\n await phase(\"started\", `deepsec ${version} on ${repository.slug}, ${agent}/${model}`);\n\n // Workspace: scaffolded once per sandbox, installed from npm. deepsec\n // needs Node 24; the sandbox bootstrap is expected to provide it.\n const prepare = await sandbox.run({\n command: [\n ...prefix,\n \"set -e\",\n `if [ ! -f ${workspace}/deepsec.config.ts ]; then`,\n ` npx -y deepsec@${version} init ./${workspace} ./${repoPath} --id ${projectId} --scaffold-only --headless --yes --skip-install`,\n ` (cd ${workspace} && npm install --no-audit --no-fund --loglevel=error)`,\n \"fi\",\n // deepsec resolves deepsec.config.ts from the current directory, so\n // every deepsec command runs inside the workspace. No --root: it is a\n // one-off override that skips the project's file records, leaving\n // `process` with nothing to investigate.\n `cd ${workspace}`,\n `./node_modules/.bin/deepsec scan --project-id ${projectId}`,\n ].join(\"\\n\"),\n });\n if (typeof prepare.exitCode === \"number\" && prepare.exitCode !== 0) {\n const detail = (prepare.stderr ?? prepare.stdout).trim().slice(-1500);\n await phase(\"failed\", `scan phase failed: ${detail.slice(-300)}`);\n return { scanned: false as const, reason: `deepsec scan failed: ${detail}` };\n }\n const candidates = candidateCount(prepare.stdout);\n await phase(\n \"scanned\",\n `${candidates === null ? \"scan output\" : `${candidates} files with candidates`}: ${tail(`${prepare.stdout}\\n${prepare.stderr ?? \"\"}`)}`,\n );\n\n // Investigation talks to the model through the AI Gateway (deepsec's\n // default route); this is the only step that needs a credential.\n const investigate = await options.withModelCredential(\n sandbox,\n [\n ...prefix,\n \"set -e\",\n `cd ${workspace}`,\n `./node_modules/.bin/deepsec process --project-id ${projectId} --agent ${agent} --model ${model} --thinking-level ${thinkingLevel} --concurrency ${concurrency} --limit ${limit ?? filesPerRun}`,\n `./node_modules/.bin/deepsec export --project-id ${projectId} --format json --out ${findingsPath}`,\n ].join(\"\\n\"),\n );\n if (typeof investigate.exitCode === \"number\" && investigate.exitCode !== 0) {\n const detail = (investigate.stderr ?? investigate.stdout).trim().slice(-1500);\n await phase(\"failed\", `process phase failed: ${detail.slice(-300)}`);\n return { scanned: false as const, reason: `deepsec process failed: ${detail}` };\n }\n\n const exported = await sandbox.run({ command: `cat ${findingsPath}` });\n let parsed: unknown;\n try {\n parsed = JSON.parse(exported.stdout);\n } catch {\n return { scanned: false as const, reason: \"deepsec export was not valid JSON\" };\n }\n const raw = deepsecExportSchema.safeParse(parsed);\n if (!raw.success) {\n return { scanned: false as const, reason: `deepsec export had an unexpected shape: ${raw.error.issues[0]?.message ?? \"unknown\"}` };\n }\n\n const results: { finding: Finding; result: RecordFindingResult }[] = [];\n for (const entry of raw.data) {\n const finding = findingFromDeepsec(entry);\n results.push({ finding, result: await recordFinding(stores, repositoryId, finding, options) });\n }\n const recorded = results.filter(({ result }) => result.recorded);\n await phase(\n \"completed\",\n `${results.length} findings, ${recorded.length} new. process output: ${tail(`${investigate.stdout}\\n${investigate.stderr ?? \"\"}`, 6)}`,\n );\n return {\n scanned: true as const,\n tool: \"deepsec\",\n found: results.length,\n recorded: recorded.length,\n duplicates: results.length - recorded.length,\n awaitingApproval: recorded.filter(({ result }) => result.recorded && result.approval === \"required\").length,\n findings: results.map(({ finding, result }) => ({\n title: finding.title,\n priority: finding.priority,\n path: finding.path,\n line: finding.line,\n ...(result.recorded ? { taskId: result.taskId, approval: result.approval } : { duplicate: true }),\n })),\n };\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { changeIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\n/** The subset of the eve sandbox handle a credentialed git operation needs. */\nexport interface CommandSandbox {\n run(options: { command: string }): PromiseLike<{\n stdout: string;\n stderr?: string;\n exitCode?: number;\n }>;\n}\n\nexport interface FetchPullRequestOptions<S extends CommandSandbox = CommandSandbox> {\n /**\n * Runs one git command against `slug` with a credential the sandbox does not\n * otherwise have, and removes it again before resolving. Supplied by the\n * app, which owns how credentials are minted and where they are injected;\n * the library only decides what is fetched.\n */\n withCredential: (\n sandbox: S,\n slug: string,\n command: string,\n ) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n /** Path of the checkout inside the sandbox. Defaults to `repo`. */\n repoPath?: string;\n /** Fetch depth for the pull request head. Defaults to 50. */\n depth?: number;\n}\n\nexport type FetchPullRequestResult =\n | { fetched: false; reason: string }\n | {\n fetched: true;\n prNumber: number;\n prUrl: string;\n branch: string;\n headSha: string;\n baseBranch: string;\n baseSha: string;\n mergeBaseSha: string;\n diffCommand: string;\n };\n\n/**\n * The verifier's way in to the change under review. The sandbox has no\n * GitHub credential while the agent runs, so trusted code does the one fetch\n * the agent cannot: the pull request number and repository come from the\n * change record, never from the agent, and the credential is gone again\n * before control returns. Mirrors how publication reads commits out of the\n * sandbox instead of letting the agent push.\n */\nexport function fetchPullRequestTool<S extends CommandSandbox>(\n stores: FactoryStores,\n options: FetchPullRequestOptions<S>,\n) {\n const repoPath = options.repoPath ?? \"repo\";\n const depth = options.depth ?? 50;\n return defineTool({\n description:\n \"Fetch the pull request and the repository's current default branch, then check out the pull request as local branch `pr`. Call this after get_task, before inspecting or testing the change. Returns an exact diff command based on their merge base; use it instead of origin/HEAD.\",\n inputSchema: z.object({\n changeId: changeIdSchema.describe(\"The Change linked to your Task, returned by get_task.\"),\n }),\n async execute({ changeId }, ctx): Promise<FetchPullRequestResult> {\n const boundTaskId = taskIdSchema.safeParse(\n ctx.session?.auth.initiator?.attributes.factoryTaskId,\n );\n if (boundTaskId.success) {\n const task = await stores.tasks.get(boundTaskId.data);\n if (task === null) {\n return { fetched: false, reason: `task ${boundTaskId.data} does not exist` };\n }\n if (task.changeId !== undefined && task.changeId !== changeId) {\n return {\n fetched: false,\n reason: `change ${changeId} is not linked to task ${boundTaskId.data}`,\n };\n }\n }\n const change = await stores.changes.get(changeId);\n if (change === null) {\n return { fetched: false, reason: `change ${changeId} does not exist` };\n }\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n return { fetched: false, reason: `change is ${change.state}, not open for review; nothing to fetch` };\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) {\n return { fetched: false, reason: `repository ${change.repositoryId} does not exist` };\n }\n\n // Fetch into a remote-tracking ref (never the checked-out branch, which\n // git refuses to update), then move the local `pr` branch onto it so a\n // repeated call picks up a force-pushed head.\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const tracking = `refs/remotes/origin/pr-${change.prNumber}`;\n const baseTracking = `refs/remotes/origin/${repository.defaultBranch}`;\n const git = `git -C ${repoPath}`;\n const result = await options.withCredential(\n sandbox,\n repository.slug,\n `${git} fetch --depth ${depth} origin +refs/heads/${repository.defaultBranch}:${baseTracking} +refs/pull/${change.prNumber}/head:${tracking} && ${git} checkout -B pr ${tracking}`,\n );\n if (typeof result.exitCode === \"number\" && result.exitCode !== 0) {\n return {\n fetched: false,\n reason: `git fetch of pull request ${change.prNumber} failed: ${(result.stderr ?? \"\").trim()}`,\n };\n }\n\n const head = await sandbox.run({ command: `${git} rev-parse HEAD` });\n const base = await sandbox.run({ command: `${git} rev-parse ${baseTracking}` });\n const mergeBase = await sandbox.run({ command: `${git} merge-base ${baseTracking} pr` });\n if (typeof mergeBase.exitCode === \"number\" && mergeBase.exitCode !== 0) {\n return {\n fetched: false,\n reason: `could not determine the pull request merge base: ${(mergeBase.stderr ?? \"\").trim()}`,\n };\n }\n const mergeBaseSha = mergeBase.stdout.trim();\n return {\n fetched: true,\n prNumber: change.prNumber,\n prUrl: change.prUrl,\n branch: \"pr\",\n headSha: head.stdout.trim(),\n baseBranch: repository.defaultBranch,\n baseSha: base.stdout.trim(),\n mergeBaseSha,\n diffCommand: `${git} diff ${mergeBaseSha}..pr`,\n };\n },\n });\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport type { AgentRoute, AgentRouteRegistry } from \"../agent-routes\";\nimport { createCoordination } from \"../coordination\";\nimport { dispatchTask, type DispatchBudget } from \"../dispatch\";\nimport { changeIdSchema, repositoryIdSchema, signalIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { Task } from \"../schema/task\";\nimport type { FactoryStores } from \"../store/engine\";\n\nexport interface InvokeAgentOptions {\n /** The factory task kind the handoff creates, e.g. \"verification\". */\n kind: string;\n /** Model-facing description of what the target agent does and when to invoke it. */\n description: string;\n /**\n * Base URL of the target agent's eve transport, e.g.\n * `https://factory.example.com/eve/agents/verifier`. Resolved at call time so\n * a deployment can derive it from its own origin.\n */\n targetUrl: () => string;\n /** Bearer token for the target agent's eve channel, when it requires auth. */\n token?: () => Promise<string | undefined>;\n /** Extra headers for the session request, e.g. a deployment protection bypass. */\n headers?: (task: Task) => Record<string, string> | Promise<Record<string, string>>;\n /**\n * Reserve-before-execution limits for the handoff dispatch, resolved at\n * call time. Without it, handoff tasks run outside the budget.\n */\n budget?: () => DispatchBudget | undefined;\n fetch?: typeof fetch;\n}\n\nexport interface DelegateAgentOptions {\n routes: AgentRouteRegistry;\n targetUrl: (route: AgentRoute) => string;\n token?: (route: AgentRoute) => Promise<string | undefined>;\n headers?: (task: Task, route: AgentRoute) => Record<string, string> | Promise<Record<string, string>>;\n budget?: (route: AgentRoute) => DispatchBudget | undefined;\n fetch?: typeof fetch;\n}\n\n/**\n * A tool that lets one agent hand work to another, NMA-style: the caller\n * decides to invoke; trusted code owns the how. The handoff is recorded as a\n * factory task (single-winner dispatch, receipts), then a fresh session is\n * started on the target agent carrying only the task id — never the caller's\n * context. The session start is create-once on the task id, so a retried\n * tool call cannot start a second session.\n */\nexport function invokeAgentTool(stores: FactoryStores, options: InvokeAgentOptions) {\n const doFetch = options.fetch ?? fetch;\n return defineTool({\n description: `${options.description} Hands the work to a separate agent in a fresh session; you will not see its reasoning. Returns the handoff task id.`,\n inputSchema: z.object({\n repositoryIds: z.array(repositoryIdSchema).min(1),\n parentTaskId: taskIdSchema.optional().describe(\"Your own task, when this work continues it.\"),\n changeId: changeIdSchema.optional().describe(\"The change the target agent should work on.\"),\n channel: z.string().min(1).describe(\"Reply connector, e.g. github.\"),\n address: z.string().min(1).describe(\"Reply address, e.g. acme/web#41.\"),\n brief: z\n .string()\n .min(1)\n .max(4000)\n .describe(\"What the target agent needs to know. Facts and references only, not your reasoning.\"),\n }),\n async execute(input) {\n const task = await stores.tasks.create({\n repositoryIds: input.repositoryIds,\n kind: options.kind,\n origin:\n input.parentTaskId === undefined ? { operator: \"factory\" } : { parentTaskId: input.parentTaskId },\n replyTo: { channel: input.channel, address: input.address },\n });\n\n const running = await dispatchTask(stores, task.id, {\n // Handoffs are launched by the caller, not the sweep, so a refused\n // session must fail now — no sweep would pick a re-queued handoff up.\n maxLaunchAttempts: 1,\n budget: options.budget?.(),\n launch: async (dispatched) => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(await options.headers?.(dispatched)),\n };\n const token = await options.token?.();\n if (token !== undefined) {\n headers.authorization = `Bearer ${token}`;\n }\n const message = [\n `You are assigned factory task ${dispatched.id}.`,\n input.changeId === undefined ? null : `Change under review: ${input.changeId}.`,\n `Reply address: ${input.channel} ${input.address}.`,\n \"\",\n input.brief,\n \"\",\n \"Read the task with get_task first, do the work, and record the outcome with your factory tools.\",\n ]\n .filter((line) => line !== null)\n .join(\"\\n\");\n const response = await doFetch(`${options.targetUrl()}/eve/v1/session`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ message, operationId: `factory-task:${dispatched.id}` }),\n });\n if (!response.ok) {\n throw new Error(`target agent refused the session: ${response.status}`);\n }\n },\n });\n\n return { taskId: running.id, kind: running.kind, state: running.state };\n },\n });\n}\n\n/**\n * Give a conversational agent one bounded delegation surface backed by the\n * application's route registry. The caller selects a declared route; trusted\n * code owns task creation, budget enforcement, and the fresh target session.\n */\nexport function delegateAgentTool(stores: FactoryStores, options: DelegateAgentOptions) {\n const doFetch = options.fetch ?? fetch;\n const routeSummary = options.routes.routes\n .map((route) => `${route.id}: ${route.description}`)\n .join(\"\\n\");\n return defineTool({\n description:\n \"Delegate durable work to one registered specialist. Select only a listed route; \" +\n \"the specialist runs independently and reports its result through Factory.\\n\" +\n routeSummary,\n inputSchema: z.object({\n routeId: z.string().min(1).describe(\"One route id listed in this tool's description.\"),\n repositoryIds: z.array(repositoryIdSchema).min(1),\n signalId: signalIdSchema.optional().describe(\"Pending external signal this delegation accepts.\"),\n parentTaskId: taskIdSchema.optional().describe(\"Existing task this work continues.\"),\n changeId: changeIdSchema.optional().describe(\"Existing change the specialist should inspect.\"),\n channel: z.string().min(1).describe(\"Originating conversation channel.\"),\n address: z.string().min(1).describe(\"Originating conversation reply address.\"),\n brief: z.string().min(1).max(4000).describe(\"Facts and desired outcome, without hidden reasoning.\"),\n }),\n async execute(input, ctx) {\n const route = options.routes.get(input.routeId);\n if (route === undefined) {\n throw new Error(`Unknown agent route ${input.routeId}.`);\n }\n const replyTo = { channel: input.channel, address: input.address };\n const attributes = ctx.session.auth.initiator?.attributes;\n const repositoryAttribute = attributes?.factoryRepositoryIds;\n const boundRepositoryIds =\n typeof repositoryAttribute === \"string\"\n ? repositoryAttribute.split(\",\").filter(Boolean)\n : repositoryAttribute;\n if (\n boundRepositoryIds !== undefined &&\n (boundRepositoryIds.length !== input.repositoryIds.length ||\n boundRepositoryIds.some((id) => !input.repositoryIds.includes(id)))\n ) {\n throw new Error(\"Delegation repositories do not match the connector-authenticated context.\");\n }\n if (\n (attributes?.factoryReplyChannel !== undefined && attributes.factoryReplyChannel !== replyTo.channel) ||\n (attributes?.factoryReplyAddress !== undefined && attributes.factoryReplyAddress !== replyTo.address)\n ) {\n throw new Error(\"Delegation reply address does not match the authenticated conversation.\");\n }\n for (const repositoryId of input.repositoryIds) {\n const repository = await stores.repositories.get(repositoryId);\n if (repository === null || !repository.enabled) {\n throw new Error(`Repository ${repositoryId} is not enabled in this factory.`);\n }\n }\n const boundChange = changeIdSchema.safeParse(attributes?.factoryChangeId);\n if (attributes?.factoryChangeId !== undefined && !boundChange.success) {\n throw new Error(\"Connector-authenticated change context is invalid.\");\n }\n if (\n input.changeId !== undefined &&\n boundChange.success &&\n input.changeId !== boundChange.data\n ) {\n throw new Error(\"Delegated change does not match the connector-authenticated context.\");\n }\n const changeId = input.changeId ?? (boundChange.success ? boundChange.data : undefined);\n if (changeId !== undefined) {\n if (input.repositoryIds.length !== 1) {\n throw new Error(\"Delegating work on an existing Change requires exactly one repository.\");\n }\n const change = await stores.changes.get(changeId);\n if (\n change === null ||\n change.repositoryId !== input.repositoryIds[0] ||\n (change.state !== \"verifying\" && change.state !== \"ready\")\n ) {\n throw new Error(`Change ${changeId} is not an open pull request in the selected repository.`);\n }\n }\n if (input.signalId !== undefined) {\n const signal = await stores.signals.get(input.signalId);\n if (signal === null) throw new Error(`Signal ${input.signalId} does not exist.`);\n if (\n !input.repositoryIds.includes(signal.repositoryId) ||\n signal.replyTo.channel !== replyTo.channel ||\n signal.replyTo.address !== replyTo.address\n ) {\n throw new Error(\"Delegation does not match the signal's authenticated repository and reply address.\");\n }\n if (signal.outcome === \"pending\") {\n await stores.signals.decide(signal.id, \"accepted\", { reason: `Foreman selected ${route.id}.` });\n } else if (signal.outcome !== \"accepted\") {\n throw new Error(`Signal ${signal.id} is already ${signal.outcome}.`);\n }\n }\n const initiator = ctx.session.auth.initiator;\n const operator = initiator?.principalId ?? \"foreman\";\n if (route.taskKind === \"code_change\" && input.repositoryIds.length > 1) {\n const [first, second, ...rest] = input.repositoryIds;\n if (first === undefined || second === undefined) throw new Error(\"Coordination requires two repositories.\");\n const coordination = await createCoordination(stores, {\n repositoryIds: [first, second, ...rest],\n replyTo,\n ...(input.signalId === undefined ? {} : { dedupeKey: `route:${input.signalId}:${route.id}` }),\n ...(input.signalId === undefined ? { operator } : { signalId: input.signalId }),\n });\n await Promise.all(coordination.children.filter((child) => child.state === \"queued\").map((child) =>\n dispatchRouteTask(stores, options, doFetch, route, child, changeId, input.brief),\n ));\n return {\n taskId: coordination.parent.id,\n childTaskIds: coordination.children.map(({ id }) => id),\n routeId: route.id,\n agent: route.agent,\n state: coordination.parent.state,\n };\n }\n const task = await stores.tasks.create({\n repositoryIds: input.repositoryIds,\n kind: route.taskKind,\n origin:\n input.signalId !== undefined\n ? { signalId: input.signalId }\n : input.parentTaskId !== undefined\n ? { parentTaskId: input.parentTaskId }\n : { operator },\n replyTo,\n changeId,\n ...(input.signalId === undefined ? {} : { dedupeKey: `route:${input.signalId}:${route.id}` }),\n });\n const running = task.state === \"queued\"\n ? await dispatchRouteTask(\n stores,\n options,\n doFetch,\n route,\n task,\n changeId,\n input.brief,\n )\n : task;\n return { taskId: running.id, routeId: route.id, agent: route.agent, state: running.state };\n },\n });\n}\n\nasync function dispatchRouteTask(\n stores: FactoryStores,\n options: DelegateAgentOptions,\n doFetch: typeof fetch,\n route: AgentRoute,\n task: Task,\n changeId: string | undefined,\n brief: string,\n): Promise<Task> {\n return dispatchTask(stores, task.id, {\n maxLaunchAttempts: 1,\n budget: options.budget?.(route),\n launch: async (dispatched) => {\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n ...(await options.headers?.(dispatched, route)),\n };\n const token = await options.token?.(route);\n if (token !== undefined) headers.authorization = `Bearer ${token}`;\n const message = [\n `You are assigned factory task ${dispatched.id} through route ${route.id}.`,\n changeId === undefined ? null : `Change under review: ${changeId}.`,\n brief,\n \"Read the task first and return exactly one bounded Factory outcome.\",\n ]\n .filter((line) => line !== null)\n .join(\"\\n\\n\");\n const response = await doFetch(`${options.targetUrl(route)}/eve/v1/session`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ message, operationId: `factory-task:${dispatched.id}` }),\n });\n if (!response.ok) throw new Error(`${route.agent} refused the session: ${response.status}`);\n },\n });\n}\n","import { createHash } from \"node:crypto\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport {\n readPullRequestHead,\n submitPullRequestReview,\n type PullRequestReviewComment,\n type SubmittedPullRequestReview,\n} from \"../github\";\nimport { changeIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\nexport interface CompletedReview {\n taskId: string;\n changeId: string;\n repository: string;\n pullRequestNumber: number;\n headSha: string;\n verdict: \"approve\" | \"request_changes\" | \"comment\";\n summary: string;\n comments: readonly CompletedReviewFinding[];\n}\n\nexport interface CompletedReviewFinding extends PullRequestReviewComment {\n fingerprint: string;\n key: string;\n title: string;\n}\n\nexport interface PublishedReview extends CompletedReview {\n review: SubmittedPullRequestReview;\n}\n\nexport interface PostReviewToolOptions {\n tokenForRepository: (repository: string) => Promise<string>;\n publishReviews?: boolean;\n onCompleted?: (completed: CompletedReview) => Promise<void>;\n onPublished?: (published: PublishedReview) => Promise<void>;\n fetch?: typeof globalThis.fetch;\n}\n\nconst reviewCommentSchema = z.strictObject({\n key: z\n .string()\n .min(1)\n .max(80)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)\n .optional()\n .describe(\"Stable kebab-case identity for this defect and cause; keep it unchanged across reruns.\"),\n title: z.string().min(1).max(200).optional().describe(\"Short finding title.\"),\n path: z.string().min(1).max(500).describe(\"Repository-relative file path.\"),\n line: z.number().int().min(1).describe(\"Line in the pull request's new version.\"),\n body: z.string().min(1).max(5000).describe(\"Markdown explaining the finding and a concrete fix.\"),\n});\nconst reviewCommentsSchema = z\n .array(reviewCommentSchema)\n .max(50)\n .default([])\n .superRefine((comments, context) => {\n const seen = new Set<string>();\n comments.forEach((comment, index) => {\n if (comment.key === undefined) return;\n if (seen.has(comment.key)) {\n context.addIssue({ code: \"custom\", message: `duplicate finding key: ${comment.key}`, path: [index, \"key\"] });\n }\n seen.add(comment.key);\n });\n });\n\n/**\n * Publish an independent review of an existing pull request and finish the\n * review task without changing the pull request's factory lifecycle.\n */\nexport function postReviewTool(stores: FactoryStores, options: PostReviewToolOptions) {\n return defineTool({\n description:\n \"Record a completed code review and finish your code_review task. Results may be reported through completion callbacks instead of a GitHub review; use request_changes only for blocking findings.\",\n inputSchema: z.object({\n taskId: taskIdSchema.describe(\"Your code_review task.\"),\n changeId: changeIdSchema.describe(\"The pull request change from your starting message.\"),\n verdict: z.enum([\"approve\", \"request_changes\", \"comment\"]),\n headSha: z.string().regex(/^[0-9a-f]{40}$/).describe(\"Commit returned by fetch_pull_request.\"),\n summary: z.string().min(1).max(5000).describe(\"Markdown summary of what you reviewed and found.\"),\n comments: reviewCommentsSchema,\n }),\n async execute({ taskId, changeId, verdict, headSha, summary, comments }) {\n const task = await stores.tasks.get(taskId);\n if (task === null || task.kind !== \"code_review\") {\n return { recorded: false as const, reason: `${taskId} is not a code_review task` };\n }\n if (task.state !== \"running\") {\n return { recorded: false as const, reason: `task is ${task.state}, not running` };\n }\n\n const change = await stores.changes.get(changeId);\n if (change === null) {\n return { recorded: false as const, reason: `change ${changeId} does not exist` };\n }\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n return { recorded: false as const, reason: `change is ${change.state}, not open for review` };\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) {\n return { recorded: false as const, reason: `repository ${change.repositoryId} does not exist` };\n }\n\n const token = await options.tokenForRepository(repository.slug);\n const completedComments = comments.map((comment) => {\n const key = comment.key ?? legacyFindingKey(comment);\n return {\n ...comment,\n key,\n title: comment.title ?? \"Review finding\",\n fingerprint: createHash(\"sha256\")\n .update(`${repository.slug.toLowerCase()}#${change.prNumber}:${key}`)\n .digest(\"hex\"),\n };\n });\n const completed = {\n taskId,\n changeId,\n repository: repository.slug,\n pullRequestNumber: change.prNumber,\n headSha,\n verdict,\n summary,\n comments: completedComments,\n } satisfies CompletedReview;\n const publish = options.publishReviews !== false;\n let review: SubmittedPullRequestReview | undefined;\n if (publish) {\n review = await submitPullRequestReview({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commitId: headSha,\n event:\n verdict === \"approve\"\n ? \"APPROVE\"\n : verdict === \"request_changes\"\n ? \"REQUEST_CHANGES\"\n : \"COMMENT\",\n body: summary,\n comments: completedComments,\n });\n await options.onPublished?.({ ...completed, review });\n } else {\n const head = await readPullRequestHead({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n });\n if (head.sha !== headSha) {\n throw new Error(`pull request changed after review: expected ${headSha}, found ${head.sha}`);\n }\n }\n await options.onCompleted?.(completed);\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n const finished = await stores.tasks.transition(taskId, \"succeeded\");\n return {\n recorded: true as const,\n verdict,\n published: review !== undefined,\n ...(review === undefined ? {} : { review }),\n taskState: finished.state,\n };\n },\n });\n}\n\nfunction legacyFindingKey(comment: PullRequestReviewComment): string {\n const digest = createHash(\"sha256\")\n .update(`${comment.path}:${comment.line}:${comment.body}`)\n .digest(\"hex\")\n .slice(0, 24);\n return `legacy-${digest}`;\n}\n","import { answerReviewComment, readPullRequestHead, readReviewComment } from \"../github\";\nimport { changeIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport type { CommandSandbox } from \"./fetch\";\n\nexport interface ReviewCommentToolOptions<S extends CommandSandbox = CommandSandbox> {\n tokenForRepository: (repository: string) => Promise<string>;\n withCredential?: (\n sandbox: S,\n repository: string,\n command: string,\n ) => Promise<{ stdout: string; stderr?: string; exitCode?: number }>;\n fetch?: typeof globalThis.fetch;\n repoPath?: string;\n}\n\nexport function reviewCommentTools<S extends CommandSandbox>(\n stores: FactoryStores,\n options: ReviewCommentToolOptions<S>,\n) {\n const repoPath = options.repoPath ?? \"repo\";\n const commentInputSchema = z.object({\n changeId: changeIdSchema.describe(\"The change under review, from your starting message.\"),\n commentId: z.number().int().positive().describe(\"The GitHub review comment id.\"),\n });\n\n return {\n read_review_comment: defineTool({\n description:\n \"Read an inline review comment on a change under verification or ready for human review. By default this refuses to return comments from people without write access to the repository.\",\n inputSchema: commentInputSchema,\n async execute({ changeId, commentId }) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n return readReviewComment({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n commentId,\n });\n },\n }),\n answer_review_comment: defineTool({\n description:\n \"Reply to an inline review comment on a change under verification or ready for human review. Use for findings and low-confidence responses, not for a concrete medium- or high-confidence fix.\",\n inputSchema: commentInputSchema.extend({\n body: z.string().min(1).max(5000).describe(\"The Markdown reply to post.\"),\n }),\n async execute({ changeId, commentId, body }) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n return answerReviewComment({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commentId,\n body,\n });\n },\n }),\n suggest_review_fix: defineTool({\n description:\n \"Post a concrete, apply-able GitHub suggested change for a medium-confidence fix. The replacement must cover exactly the lines attached to the inline review comment.\",\n inputSchema: commentInputSchema.extend({\n confidence: z.literal(\"medium\"),\n replacement: z.string().min(1).max(5000).describe(\"Exact replacement text for the commented lines.\"),\n summary: z.string().min(1).max(1000).describe(\"A brief explanation of the suggested fix.\"),\n }),\n async execute({ changeId, commentId, replacement, summary }) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n return answerReviewComment({\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commentId,\n body: `${summary}\\n\\n\\`\\`\\`suggestion\\n${replacement}\\n\\`\\`\\``,\n });\n },\n }),\n apply_review_fix: defineTool({\n description:\n \"Publish a tested, committed high-confidence fix to the existing same-repository pull request branch. Fails if the checkout is dirty, the PR changed, or the PR comes from a fork.\",\n inputSchema: commentInputSchema.extend({\n confidence: z.literal(\"high\"),\n summary: z.string().min(1).max(1000).describe(\"What was fixed and verified.\"),\n }),\n async execute({ changeId, commentId, summary }, ctx) {\n const change = await stores.changes.get(changeId);\n if (change === null) throw new Error(`change ${changeId} does not exist`);\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n throw new Error(`change is ${change.state}, not open for review`);\n }\n const repository = await stores.repositories.get(change.repositoryId);\n if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);\n if (options.withCredential === undefined) {\n throw new Error(\"applying review fixes is not configured\");\n }\n const token = await options.tokenForRepository(repository.slug);\n await readReviewComment({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n commentId,\n });\n const head = await readPullRequestHead({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n });\n if (head.repository !== repository.slug.toLowerCase()) {\n throw new Error(\"cannot apply a fix to a pull request from a fork\");\n }\n const sandbox = (await ctx.getSandbox()) as unknown as S;\n const git = `git -C ${repoPath}`;\n const clean = await sandbox.run({ command: `${git} status --porcelain` });\n if (clean.stdout.trim() !== \"\") throw new Error(\"commit the review fix before publishing\");\n const ancestor = await sandbox.run({ command: `${git} merge-base --is-ancestor ${head.sha} HEAD` });\n if (ancestor.exitCode !== 0) {\n throw new Error(\"pull request changed after it was fetched; fetch it again before applying the fix\");\n }\n const localHead = await sandbox.run({ command: `${git} rev-parse HEAD` });\n if (localHead.stdout.trim() === head.sha) throw new Error(\"no committed review fix to publish\");\n const push = await options.withCredential(\n sandbox,\n repository.slug,\n `${git} push --force-with-lease=refs/heads/${head.branch}:${head.sha} origin HEAD:refs/heads/${head.branch}`,\n );\n if (typeof push.exitCode === \"number\" && push.exitCode !== 0) {\n throw new Error(`could not update pull request branch: ${(push.stderr ?? \"\").trim()}`);\n }\n const reply = await answerReviewComment({\n repository: repository.slug,\n token,\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n commentId,\n body: summary,\n });\n return { updated: true as const, prNumber: change.prNumber, prUrl: change.prUrl, reply };\n },\n }),\n };\n}\n","import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport { changeEvidenceSchema, levelSchema } from \"../schema/change\";\nimport { changeIdSchema, taskIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\n\nexport interface RecordVerificationOptions {\n presentResult?: (input: {\n taskId: string;\n changeId: string;\n verdict: \"pass\" | \"fail\";\n summary: string;\n }) => Promise<void>;\n}\n\n/**\n * The verifier's outcome tool. Writes evidence onto the change and moves it\n * to ready only when the verdict is pass; a failed verdict leaves the change\n * verifying with the evidence recorded, and the verification task itself\n * ends with a receipt either way. The change's own code_change task follows\n * the verdict too: succeeded on pass, failed on fail with the verifier's\n * summary as the reason, so the ledger never shows a verified-and-rejected fix\n * as still in progress. Fail closed: the agent cannot mark a change ready\n * without supplying every evidence field.\n */\nexport function recordVerificationTool(\n stores: FactoryStores,\n options: RecordVerificationOptions = {},\n) {\n return defineTool({\n description:\n \"Record the outcome of a verification task: the evidence you gathered and whether the change passed. Pass moves the change to ready for human review; fail keeps it out of review.\",\n inputSchema: z.object({\n taskId: taskIdSchema.describe(\"Your verification task.\"),\n changeId: changeIdSchema.describe(\"The change you verified.\"),\n verdict: z.enum([\"pass\", \"fail\"]),\n evidence: changeEvidenceSchema,\n confidence: levelSchema.describe(\"How certain you are in the verdict.\"),\n summary: z.string().min(1).max(2000).describe(\"What you checked and what you found.\"),\n }),\n async execute({ taskId, changeId, verdict, evidence, confidence, summary }) {\n const change = await stores.changes.get(changeId);\n if (change === null) {\n return { recorded: false as const, reason: `change ${changeId} does not exist` };\n }\n if (change.state !== \"verifying\" && change.state !== \"ready\") {\n return {\n recorded: false as const,\n reason: `change is ${change.state}, not open for verification; nothing to record`,\n };\n }\n\n const task = await stores.tasks.get(taskId);\n if (task === null || task.kind !== \"verification\") {\n return { recorded: false as const, reason: `${taskId} is not a verification task` };\n }\n\n let updatedChange = change;\n if (verdict === \"pass\" && change.state === \"verifying\") {\n updatedChange = await stores.changes.transition(changeId, \"ready\", {\n patch: { evidence, confidence },\n reason: summary,\n });\n } else if (verdict === \"fail\" && change.state === \"ready\") {\n updatedChange = await stores.changes.transition(changeId, \"verifying\", {\n reason: summary,\n });\n }\n\n // The task machine has no running -> succeeded edge; a passing\n // verification walks running -> verifying -> succeeded, a failing one\n // ends directly at failed.\n let finished;\n if (verdict === \"pass\") {\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n finished = await stores.tasks.transition(taskId, \"succeeded\");\n } else {\n finished = await stores.tasks.transition(taskId, \"failed\", { reason: summary });\n }\n\n // Verification settles the code_change Task that requested this run.\n // For legacy verification Tasks without a parent, fall back to the Task\n // that originally produced the Change.\n const sourceTaskId = task.origin.parentTaskId ?? change.taskId;\n if (sourceTaskId !== undefined) {\n const parent = await stores.tasks.get(sourceTaskId);\n if (parent?.state === \"verifying\") {\n await stores.tasks\n .transition(\n sourceTaskId,\n verdict === \"pass\" ? \"succeeded\" : \"failed\",\n verdict === \"pass\" ? {} : { reason: `verification failed: ${summary}` },\n )\n .catch(() => undefined);\n }\n }\n\n await options.presentResult?.({ taskId, changeId, verdict, summary });\n\n return {\n recorded: true as const,\n verdict,\n changeState: updatedChange.state,\n taskState: finished.state,\n };\n },\n });\n}\n","import type { SessionContext } from \"eve/context\";\nimport { defineHook } from \"eve/hooks\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\nimport {\n changeIdSchema,\n repositoryIdSchema,\n signalIdSchema,\n taskIdSchema,\n type TaskId,\n} from \"../schema/id\";\nimport { levelSchema } from \"../schema/change\";\nimport { vocabularySchema } from \"../schema/common\";\nimport { taskQuestionSchema, type Task } from \"../schema/task\";\nimport type { FactoryStores } from \"../store/engine\";\n\nconst decidedOutcomeSchema = z.enum([\n \"accepted\",\n \"duplicate\",\n \"unactionable\",\n \"low_confidence\",\n \"ignored\",\n]);\n\nconst recordChangeInputSchema = z.object({\n taskId: taskIdSchema,\n repositoryId: repositoryIdSchema,\n prNumber: z.number().int().min(1),\n prUrl: z.url(),\n risk: levelSchema.describe(\"Blast radius of the change if it is wrong.\"),\n confidence: levelSchema.describe(\"How certain you are the change is correct.\"),\n summary: z.string().min(1).describe(\"One-sentence description of the change.\"),\n});\n\nexport type RecordChangeInput = z.infer<typeof recordChangeInputSchema>;\n\nexport type GateVerdict = { ok: true } | { ok: false; reason: string };\n\nexport interface FactoryToolsOptions {\n /**\n * Pre-action gate for record_change, run as an eve approval policy before\n * the tool executes. Refusals reach the model as a denial with the reason.\n * Gates must fail closed: when they cannot verify, they refuse.\n */\n recordChangeGate?: (input: RecordChangeInput) => Promise<GateVerdict>;\n /** Whether recorded code changes wait for an independent verification task. Default: required. */\n verification?: \"required\" | \"disabled\";\n /** Present the pull request after record_change persists its durable state. */\n presentChange?: (input: {\n taskId: string;\n changeId: string;\n verification: \"required\" | \"disabled\";\n summary: string;\n }) => Promise<void>;\n /** Present a persisted human question through the application's Foreman communication boundary. */\n presentQuestion?: (task: Task) => Promise<void>;\n}\n\ntype PresentQuestion = NonNullable<FactoryToolsOptions[\"presentQuestion\"]>;\n\nasync function createAndPresentQuestion(\n stores: FactoryStores,\n parent: Task,\n question: z.infer<typeof taskQuestionSchema>,\n presentQuestion: PresentQuestion,\n): Promise<Task> {\n const task = await stores.tasks.create({\n repositoryIds: parent.repositoryIds,\n kind: \"question\",\n origin: { parentTaskId: parent.id },\n replyTo: parent.replyTo,\n question,\n });\n const waiting = await stores.tasks.transition(task.id, \"needs_human\");\n try {\n if (parent.state === \"running\") {\n await stores.tasks.transition(parent.id, \"needs_human\", {\n reason: `waiting for answer to question ${waiting.id}`,\n questionTaskId: waiting.id,\n });\n }\n await presentQuestion(waiting);\n } catch (error) {\n const currentParent = await stores.tasks.get(parent.id);\n if (currentParent?.state === \"needs_human\") {\n await stores.tasks.transition(parent.id, \"queued\", {\n reason: `delivery of question ${waiting.id} failed`,\n });\n }\n const currentQuestion = await stores.tasks.get(waiting.id);\n if (currentQuestion?.state === \"needs_human\") {\n await stores.tasks.transition(waiting.id, \"cancelled\", {\n reason: \"question delivery failed\",\n });\n }\n throw error;\n }\n return waiting;\n}\n\n/**\n * The factory's store operations wrapped as eve tools. Expose a tool to an\n * agent by re-exporting it from a file under agent/tools/, e.g.\n * `export default factoryTools(stores).get_task;`. Every write goes through\n * the engine, so agents inherit transition legality and receipts.\n */\nexport function factoryTools(stores: FactoryStores, options: FactoryToolsOptions = {}) {\n const recordChangeGate = options.recordChangeGate;\n const verification = options.verification ?? \"required\";\n return {\n get_task: defineTool({\n description:\n \"Read one factory task by id: its kind, state, repositories, origin, and results.\",\n inputSchema: z.object({ taskId: taskIdSchema }),\n async execute({ taskId }) {\n const task = await stores.tasks.get(taskId);\n return task ?? { found: false as const, taskId };\n },\n }),\n\n decide_signal: defineTool({\n description:\n \"Record the triage decision for a pending signal. A signal is decided exactly once.\",\n inputSchema: z.object({\n signalId: signalIdSchema,\n outcome: decidedOutcomeSchema,\n reason: z.string().min(1).describe(\"Why this outcome was chosen.\"),\n detail: z\n .string()\n .min(1)\n .optional()\n .describe(\"Severity if accepted, or the duplicate-of signal id.\"),\n }),\n execute({ signalId, outcome, reason, detail }) {\n return stores.signals.decide(signalId, outcome, { reason, detail });\n },\n }),\n\n record_change: defineTool({\n description:\n verification === \"required\"\n ? \"Record the pull request produced for a code_change task. Creates the change, links it to the task, and moves the task to verifying.\"\n : \"Record the pull request produced for a code_change task. Creates the change and marks it ready for human review without independent verification.\",\n inputSchema: recordChangeInputSchema,\n ...(recordChangeGate === undefined\n ? {}\n : {\n approval: async ({ toolInput }: { toolInput?: unknown }) => {\n const parsed = recordChangeInputSchema.safeParse(toolInput);\n if (!parsed.success) {\n return {\n type: \"denied\" as const,\n reason: \"record_change input is malformed; fix the arguments and retry\",\n };\n }\n const verdict = await recordChangeGate(parsed.data);\n return verdict.ok\n ? (\"not-applicable\" as const)\n : { type: \"denied\" as const, reason: verdict.reason };\n },\n }),\n async execute({ taskId, repositoryId, prNumber, prUrl, risk, confidence, summary }) {\n const currentTask = await stores.tasks.get(taskId);\n if (currentTask === null) throw new Error(`task ${taskId} does not exist`);\n if (\n currentTask.state !== \"running\" &&\n currentTask.state !== \"verifying\" &&\n currentTask.state !== \"succeeded\"\n ) {\n throw new Error(`task ${taskId} is ${currentTask.state}, not running`);\n }\n const linkedChange =\n currentTask.changeId === undefined\n ? undefined\n : await stores.changes.get(currentTask.changeId);\n if (currentTask.changeId !== undefined && linkedChange === null) {\n throw new Error(`change ${currentTask.changeId} does not exist`);\n }\n let change =\n linkedChange ?? (await stores.changes.list()).find((candidate) => candidate.taskId === taskId);\n\n if (change === undefined) {\n if (currentTask.state !== \"running\") {\n throw new Error(`task ${taskId} has no recorded change`);\n }\n change = await stores.changes.create({\n repositoryId,\n taskId,\n prNumber,\n prUrl,\n author: \"factory\",\n risk,\n confidence,\n evidence: {\n reproVerified: false,\n testsAdded: 0,\n checksGreen: false,\n attackPassed: false,\n scopeMatches: false,\n },\n });\n }\n\n if (currentTask.state === \"running\") {\n await options.presentChange?.({\n taskId,\n changeId: change.id,\n verification,\n summary,\n });\n }\n\n let task = currentTask;\n if (task.state === \"running\") {\n task = await stores.tasks.transition(taskId, \"verifying\", {\n patch: { changeId: change.id },\n reason: summary,\n });\n }\n if (verification === \"required\") return { change, task };\n\n if (change.state === \"verifying\") {\n change = await stores.changes.transition(change.id, \"ready\", {\n reason: \"independent verification is not configured\",\n });\n }\n if (task.state === \"verifying\") {\n task = await stores.tasks.transition(taskId, \"succeeded\", {\n reason: \"change recorded for human review without independent verification\",\n });\n }\n return { change, task };\n },\n }),\n\n finish_task: defineTool({\n description:\n \"Mark your task finished with a summary, for task kinds that have no other outcome tool (for example a security_scan). Not for code_change or verification tasks: those end with record_change and record_verification.\",\n inputSchema: z.object({\n taskId: taskIdSchema,\n summary: z.string().min(1).max(4000).describe(\"What you did and found, for the ledger.\"),\n }),\n async execute({ taskId, summary }) {\n const task = await stores.tasks.get(taskId);\n if (task === null) {\n return { finished: false as const, reason: `${taskId} does not exist` };\n }\n if (task.kind === \"code_change\" || task.kind === \"verification\") {\n return { finished: false as const, reason: `${task.kind} tasks end with their own outcome tool` };\n }\n if (task.state !== \"running\") {\n return { finished: false as const, reason: `task is ${task.state}, not running` };\n }\n // The task machine has no running -> succeeded edge; walk through verifying.\n await stores.tasks.transition(taskId, \"verifying\", { reason: summary });\n const finished = await stores.tasks.transition(taskId, \"succeeded\", { reason: summary });\n return { finished: true as const, taskState: finished.state };\n },\n }),\n\n request_human_input: defineTool({\n description:\n \"Request human input or action and pause your task until the human replies. The parent task determines the repositories and reply destination.\",\n inputSchema: z.object({\n parentTaskId: taskIdSchema.describe(\"Your running task, which the answer will unblock.\"),\n question: taskQuestionSchema.omit({ answer: true, answeredBy: true }),\n }),\n async execute({ parentTaskId, question }) {\n if (options.presentQuestion === undefined) {\n throw new Error(\"request_human_input requires a configured question presenter.\");\n }\n const parent = await stores.tasks.get(parentTaskId);\n if (parent === null) throw new Error(`Parent task ${parentTaskId} does not exist.`);\n if (parent.state !== \"running\" && parent.state !== \"needs_human\") {\n throw new Error(`Parent task ${parentTaskId} is ${parent.state}, not running.`);\n }\n return createAndPresentQuestion(stores, parent, question, options.presentQuestion);\n },\n }),\n\n answer_question: defineTool({\n description:\n \"Record the authenticated user's answer to a waiting question and requeue the parent specialist task. A blocked parent task id is also accepted and resolves its persisted QuestionTask id.\",\n inputSchema: z.object({\n questionTaskId: taskIdSchema,\n answer: z.string().min(1).max(4000),\n }),\n async execute({ questionTaskId, answer }, ctx) {\n const requestedTask = await stores.tasks.get(questionTaskId);\n const resolvedQuestionTaskId =\n requestedTask?.kind === \"question\" ? requestedTask.id : requestedTask?.questionTaskId;\n const questionTask = resolvedQuestionTaskId === undefined\n ? null\n : await stores.tasks.get(resolvedQuestionTaskId);\n if (\n questionTask === null ||\n questionTask.kind !== \"question\" ||\n questionTask.question === undefined\n ) {\n throw new Error(`Question task ${questionTaskId} does not exist.`);\n }\n const attributes = ctx.session.auth.initiator?.attributes;\n if (\n attributes?.factoryReplyChannel !== questionTask.replyTo.channel ||\n attributes.factoryReplyAddress !== questionTask.replyTo.address\n ) {\n throw new Error(\"Question reply does not match the authenticated conversation.\");\n }\n const answeredBy = ctx.session.auth.initiator?.principalId ?? \"operator\";\n return stores.tasks.answerQuestion({\n questionTaskId: questionTask.id,\n answer,\n answeredBy,\n });\n },\n }),\n\n append_receipt: defineTool({\n description:\n \"Append one immutable audit receipt for an event worth remembering. Receipts can never be edited or deleted.\",\n inputSchema: z.object({\n repositoryIds: z.array(repositoryIdSchema).min(1),\n taskId: taskIdSchema.optional(),\n changeId: changeIdSchema.optional(),\n kind: vocabularySchema.describe(\"What the receipt is about, e.g. investigation.\"),\n state: vocabularySchema.describe(\"What happened, e.g. flag_ramped.\"),\n reason: z.string().min(1).max(2000).optional(),\n dedupeKey: z\n .string()\n .min(1)\n .optional()\n .describe(\"Same key twice records one receipt instead of two.\"),\n }),\n execute(input) {\n return stores.receipts.append(input);\n },\n }),\n };\n}\n\nexport type FactoryTools = ReturnType<typeof factoryTools>;\n\nexport interface FactoryHooksOptions {\n /** Session auth attribute naming the task a dispatched session works on. Default `factoryTaskId`. */\n taskIdAttribute?: string;\n /** Present the recovery question created when a task turn ends without an outcome. */\n presentQuestion: PresentQuestion;\n}\n\nconst terminalTaskStates: ReadonlySet<Task[\"state\"]> = new Set([\"succeeded\", \"failed\", \"cancelled\"]);\n\n/**\n * Observe-only eve hooks that keep the ledger honest about session outcomes.\n * Mount by re-exporting from agent/hooks/, e.g.\n * `export default factoryHooks(stores, { presentQuestion }).factory;`.\n *\n * step.completed: records the step's tokens and AI Gateway cost on the bound\n * task. Delivery is at least once; recordUsage dedupes by (turnId, stepIndex).\n *\n * turn.completed: settles the bound task's recorded usage if the task is\n * already terminal (the sweep handles tasks that end later), then moves any\n * still-running task at this session's reply address behind a surfaced human\n * question, because the agent finished talking without recording an outcome.\n *\n * Every store call is swallowed: a hook throw fails the turn.\n */\nexport function factoryHooks(stores: FactoryStores, options: FactoryHooksOptions) {\n const taskIdAttribute = options.taskIdAttribute ?? \"factoryTaskId\";\n\n function boundTaskId(ctx: Pick<SessionContext, \"session\">): TaskId | undefined {\n const parsed = taskIdSchema.safeParse(ctx.session.auth.initiator?.attributes[taskIdAttribute]);\n return parsed.success ? parsed.data : undefined;\n }\n\n async function settleIfTerminal(taskId: TaskId): Promise<void> {\n const task = await stores.tasks.get(taskId);\n if (task?.usage === undefined || task.settledUsd !== undefined || !terminalTaskStates.has(task.state)) {\n return;\n }\n await stores.tasks.settle(task.id, { totalUsd: task.usage.costUsd }, {\n reason: \"measured usage settled at turn end\",\n });\n }\n\n return {\n factory: defineHook({\n events: {\n async \"step.completed\"(event, ctx) {\n const taskId = boundTaskId(ctx);\n const usage = event.data.usage;\n if (taskId === undefined || usage === undefined) {\n return;\n }\n await stores.tasks\n .recordUsage(taskId, { turnId: event.data.turnId, stepIndex: event.data.stepIndex, ...usage })\n .catch(() => undefined);\n },\n async \"turn.completed\"(_event, ctx) {\n const taskId = boundTaskId(ctx);\n if (taskId !== undefined) {\n await settleIfTerminal(taskId).catch(() => undefined);\n }\n const address = ctx.channel.continuationToken;\n if (address === undefined) {\n return;\n }\n const tasks = await stores.tasks.list().catch(() => []);\n const abandoned = tasks.filter(\n (task) => task.state === \"running\" && task.replyTo.address === address,\n );\n for (const task of abandoned) {\n await createAndPresentQuestion(\n stores,\n task,\n {\n text:\n \"The worker stopped without recording an outcome. Please review the task and reply when Factory should retry it.\",\n options: [\"Retry the task\"],\n },\n options.presentQuestion,\n ).catch(() => undefined);\n }\n },\n },\n }),\n };\n}\n\nexport type FactoryHooks = ReturnType<typeof factoryHooks>;\n\nexport {\n mergeConflictPayloadSchema,\n mergeConflictTools,\n type MergeConflictPayload,\n type MergeConflictToolOptions,\n} from \"./conflict\";\nexport { deepsecScanTool, findingFromDeepsec, type DeepsecScanOptions } from \"./deepsec\";\nexport { recordFinding, recordFindingTool, type RecordFindingOptions, type RecordFindingResult } from \"./finding\";\nexport {\n fetchPullRequestTool,\n type CommandSandbox,\n type FetchPullRequestOptions,\n type FetchPullRequestResult,\n} from \"./fetch\";\nexport {\n delegateAgentTool,\n invokeAgentTool,\n type DelegateAgentOptions,\n type InvokeAgentOptions,\n} from \"./invoke\";\nexport {\n postReviewTool,\n type CompletedReview,\n type CompletedReviewFinding,\n type PostReviewToolOptions,\n type PublishedReview,\n} from \"./post-review\";\nexport { reviewCommentTools, type ReviewCommentToolOptions } from \"./review\";\nexport { recordVerificationTool, type RecordVerificationOptions } from \"./verification\";\n"],"mappings":";;;;;;;;;;;AAMA,MAAM,eAAe,EAAE,OAAO,CAAC,CAAC,MAAM,gBAAgB;AACtD,MAAM,kBAAkB,EAAE,OAAO,CAAC,CAAC,MAAM,+BAA+B,CAAC,CAAC,QAAQ,UAAU,CAAC,MAAM,SAAS,IAAI,CAAC;AAEjH,MAAa,6BAA6B,EAAE,aAAa;CACvD,YAAY,EAAE,OAAO,CAAC,CAAC,MAAM,oCAAoC;CACjE,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CACpC,OAAO,EAAE,IAAI;CACb,YAAY,gBAAgB,QAAQ,UAAU,MAAM,WAAW,UAAU,CAAC;CAC1E,SAAS;CACT,YAAY;CACZ,SAAS;AACX,CAAC;AAaD,SAAgB,mBACd,QACA,SACA;CACA,MAAM,WAAW,QAAQ,YAAY;CAErC,eAAe,QAAQ,QAAsC;EAC3D,MAAM,OAAO,MAAM,OAAO,MAAM,IAAI,MAAM;EAC1C,IAAI,SAA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M,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,EAAA,CAC9B,QACrB,SAAS,KAAK,UAAU,aAAa,KAAK,QAAQ,YAAY,OACjE;GACA,KAAK,MAAM,QAAQ,WACjB,MAAM,yBACJ,QACA,MACA;IACE,MACE;IACF,SAAS,CAAC,gBAAgB;GAC5B,GACA,QAAQ,eACV,CAAC,CAAC,YAAY,KAAA,CAAS;EAE3B;CACF,EACF,CAAC,EACH;AACF"}
|
|
@@ -1,23 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as defaultApprovalPolicy, t as approvalPolicySchema } from "./approval-
|
|
1
|
+
import { s as taskKindSchema } from "./task-CcOyOJ3k.mjs";
|
|
2
|
+
import { r as defaultApprovalPolicy, t as approvalPolicySchema } from "./approval-JX2Px9IC.mjs";
|
|
3
|
+
import { a as repositorySlugSchema, t as budgetLimitsSchema } from "./budget-DzSiIA4t.mjs";
|
|
3
4
|
import { z } from "zod";
|
|
4
|
-
//#region src/schema/repository.ts
|
|
5
|
-
const repositorySlugSchema = z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?\/[a-z0-9._-]+$/).describe("owner/name, lowercase, e.g. acme/web.");
|
|
6
|
-
const repositorySchema = z.strictObject({
|
|
7
|
-
schemaVersion: schemaVersionSchema,
|
|
8
|
-
id: repositoryIdSchema,
|
|
9
|
-
slug: repositorySlugSchema,
|
|
10
|
-
defaultBranch: z.string().min(1).describe("Branch changes land on, usually main."),
|
|
11
|
-
enabled: z.boolean().describe("Whether the factory may work on this repository."),
|
|
12
|
-
dependsOn: z.array(repositorySlugSchema).describe("Slugs of repositories this one consumes, for multi-repo work ordering."),
|
|
13
|
-
devbox: z.strictObject({
|
|
14
|
-
projectId: z.string().min(1),
|
|
15
|
-
teamId: z.string().min(1),
|
|
16
|
-
snapshot: z.string().min(1).optional().describe("Prebuilt snapshot to boot from.")
|
|
17
|
-
}).optional().describe("Devbox execution config. Absent when this repository never uses devboxes."),
|
|
18
|
-
connectedAt: isoDateTimeSchema
|
|
19
|
-
});
|
|
20
|
-
//#endregion
|
|
21
5
|
//#region src/schema/factory-config.ts
|
|
22
6
|
const factoryConfigRepositorySchema = z.strictObject({
|
|
23
7
|
slug: repositorySlugSchema.describe("Repository this factory may work on."),
|
|
@@ -28,6 +12,16 @@ const githubConnectorSchema = z.strictObject({
|
|
|
28
12
|
connector: z.string().regex(/^github\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/).describe("Vercel Connect UID installed for this GitHub owner.")
|
|
29
13
|
});
|
|
30
14
|
const slackConnectorSchema = z.strictObject({ connector: z.string().regex(/^slack\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/).describe("Vercel Connect UID installed for this Slack app.") });
|
|
15
|
+
const executionPolicySchema = z.strictObject({
|
|
16
|
+
maxAttempts: z.number().int().min(1).describe("Attempts a task may consume before a stall fails it for good."),
|
|
17
|
+
stallMinutes: z.number().int().min(1).describe("Minutes without progress before a running task is marked stalled."),
|
|
18
|
+
stallMinutesByKind: z.record(taskKindSchema, z.number().int().min(1)).default({}).describe("Per-kind stall windows for long single-step work, e.g. security_scan: 300.")
|
|
19
|
+
});
|
|
20
|
+
const defaultExecutionPolicy = {
|
|
21
|
+
maxAttempts: 3,
|
|
22
|
+
stallMinutes: 45,
|
|
23
|
+
stallMinutesByKind: {}
|
|
24
|
+
};
|
|
31
25
|
const factoryConfigSchema = z.strictObject({
|
|
32
26
|
connectors: z.strictObject({
|
|
33
27
|
github: z.array(githubConnectorSchema).refine((connectors) => new Set(connectors.map(({ owner }) => owner)).size === connectors.length, "GitHub connector owners must be unique."),
|
|
@@ -38,12 +32,19 @@ const factoryConfigSchema = z.strictObject({
|
|
|
38
32
|
}).describe("Provider connections available to this factory."),
|
|
39
33
|
repositories: z.array(factoryConfigRepositorySchema).min(1).describe("Repositories this factory is allowed to inspect and change."),
|
|
40
34
|
operators: z.array(z.string().min(1)).min(1).describe("Provider-qualified identities allowed to operate this factory."),
|
|
41
|
-
approval: approvalPolicySchema.default(defaultApprovalPolicy).describe("Which tasks wait for a human before they run. First match wins.")
|
|
35
|
+
approval: approvalPolicySchema.default(defaultApprovalPolicy).describe("Which tasks wait for a human before they run. First match wins."),
|
|
36
|
+
budget: budgetLimitsSchema.default({
|
|
37
|
+
totalUsd: 500,
|
|
38
|
+
investigationUsd: 100,
|
|
39
|
+
perTaskReservationUsd: 5,
|
|
40
|
+
warningPercent: 80
|
|
41
|
+
}).describe("Monthly spend limits. One non-disableable budget per factory per month."),
|
|
42
|
+
execution: executionPolicySchema.default(defaultExecutionPolicy).describe("Stall detection and retry limits for running tasks.")
|
|
42
43
|
});
|
|
43
44
|
function defineFactory(config) {
|
|
44
45
|
return factoryConfigSchema.parse(config);
|
|
45
46
|
}
|
|
46
47
|
//#endregion
|
|
47
|
-
export {
|
|
48
|
+
export { factoryConfigSchema as a, factoryConfigRepositorySchema as i, defineFactory as n, executionPolicySchema as r, defaultExecutionPolicy as t };
|
|
48
49
|
|
|
49
|
-
//# sourceMappingURL=factory-config-
|
|
50
|
+
//# sourceMappingURL=factory-config-BoRXOw43.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"factory-config-BoRXOw43.mjs","names":[],"sources":["../src/schema/factory-config.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { approvalPolicySchema, defaultApprovalPolicy } from \"../approval\";\nimport { budgetLimitsSchema } from \"./budget\";\nimport { repositorySlugSchema } from \"./repository\";\nimport { taskKindSchema } from \"./task\";\n\nexport const factoryConfigRepositorySchema = z.strictObject({\n slug: repositorySlugSchema.describe(\"Repository this factory may work on.\"),\n dependsOn: z\n .array(repositorySlugSchema)\n .default([])\n .describe(\"Repositories that must land changes before this repository.\"),\n});\n\nconst githubConnectorSchema = z.strictObject({\n owner: z\n .string()\n .regex(/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/)\n .describe(\"GitHub user or organization that owns this connector installation.\"),\n connector: z\n .string()\n .regex(/^github\\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/)\n .describe(\"Vercel Connect UID installed for this GitHub owner.\"),\n});\n\nconst slackConnectorSchema = z.strictObject({\n connector: z\n .string()\n .regex(/^slack\\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/)\n .describe(\"Vercel Connect UID installed for this Slack app.\"),\n});\n\nexport const executionPolicySchema = z.strictObject({\n maxAttempts: z\n .number()\n .int()\n .min(1)\n .describe(\"Attempts a task may consume before a stall fails it for good.\"),\n stallMinutes: z\n .number()\n .int()\n .min(1)\n .describe(\"Minutes without progress before a running task is marked stalled.\"),\n stallMinutesByKind: z\n .record(taskKindSchema, z.number().int().min(1))\n .default({})\n .describe(\"Per-kind stall windows for long single-step work, e.g. security_scan: 300.\"),\n});\n\nexport type ExecutionPolicy = z.infer<typeof executionPolicySchema>;\n\nexport const defaultExecutionPolicy: ExecutionPolicy = {\n maxAttempts: 3,\n stallMinutes: 45,\n stallMinutesByKind: {},\n};\n\nexport const factoryConfigSchema = z.strictObject({\n connectors: z\n .strictObject({\n github: z\n .array(githubConnectorSchema)\n .refine(\n (connectors) => new Set(connectors.map(({ owner }) => owner)).size === connectors.length,\n \"GitHub connector owners must be unique.\",\n ),\n slack: z\n .array(slackConnectorSchema)\n .max(1, \"A factory may configure one Slack connector.\")\n .default([]),\n })\n .default({ github: [], slack: [] })\n .describe(\"Provider connections available to this factory.\"),\n repositories: z\n .array(factoryConfigRepositorySchema)\n .min(1)\n .describe(\"Repositories this factory is allowed to inspect and change.\"),\n operators: z\n .array(z.string().min(1))\n .min(1)\n .describe(\"Provider-qualified identities allowed to operate this factory.\"),\n approval: approvalPolicySchema\n .default(defaultApprovalPolicy)\n .describe(\"Which tasks wait for a human before they run. First match wins.\"),\n budget: budgetLimitsSchema\n .default({\n totalUsd: 500,\n investigationUsd: 100,\n perTaskReservationUsd: 5,\n warningPercent: 80,\n })\n .describe(\"Monthly spend limits. One non-disableable budget per factory per month.\"),\n execution: executionPolicySchema\n .default(defaultExecutionPolicy)\n .describe(\"Stall detection and retry limits for running tasks.\"),\n});\n\nexport type FactoryConfig = z.infer<typeof factoryConfigSchema>;\nexport type FactoryConfigInput = z.input<typeof factoryConfigSchema>;\n\nexport function defineFactory(config: FactoryConfigInput): FactoryConfig {\n return factoryConfigSchema.parse(config);\n}\n"],"mappings":";;;;;AAMA,MAAa,gCAAgC,EAAE,aAAa;CAC1D,MAAM,qBAAqB,SAAS,sCAAsC;CAC1E,WAAW,EACR,MAAM,oBAAoB,CAAC,CAC3B,QAAQ,CAAC,CAAC,CAAC,CACX,SAAS,6DAA6D;AAC3E,CAAC;AAED,MAAM,wBAAwB,EAAE,aAAa;CAC3C,OAAO,EACJ,OAAO,CAAC,CACR,MAAM,mCAAmC,CAAC,CAC1C,SAAS,oEAAoE;CAChF,WAAW,EACR,OAAO,CAAC,CACR,MAAM,2CAA2C,CAAC,CAClD,SAAS,qDAAqD;AACnE,CAAC;AAED,MAAM,uBAAuB,EAAE,aAAa,EAC1C,WAAW,EACR,OAAO,CAAC,CACR,MAAM,0CAA0C,CAAC,CACjD,SAAS,kDAAkD,EAChE,CAAC;AAED,MAAa,wBAAwB,EAAE,aAAa;CAClD,aAAa,EACV,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,+DAA+D;CAC3E,cAAc,EACX,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,mEAAmE;CAC/E,oBAAoB,EACjB,OAAO,gBAAgB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAC/C,QAAQ,CAAC,CAAC,CAAC,CACX,SAAS,4EAA4E;AAC1F,CAAC;AAID,MAAa,yBAA0C;CACrD,aAAa;CACb,cAAc;CACd,oBAAoB,CAAC;AACvB;AAEA,MAAa,sBAAsB,EAAE,aAAa;CAChD,YAAY,EACT,aAAa;EACZ,QAAQ,EACL,MAAM,qBAAqB,CAAC,CAC5B,QACE,eAAe,IAAI,IAAI,WAAW,KAAK,EAAE,YAAY,KAAK,CAAC,CAAC,CAAC,SAAS,WAAW,QAClF,yCACF;EACF,OAAO,EACJ,MAAM,oBAAoB,CAAC,CAC3B,IAAI,GAAG,8CAA8C,CAAC,CACtD,QAAQ,CAAC,CAAC;CACf,CAAC,CAAC,CACD,QAAQ;EAAE,QAAQ,CAAC;EAAG,OAAO,CAAC;CAAE,CAAC,CAAC,CAClC,SAAS,iDAAiD;CAC7D,cAAc,EACX,MAAM,6BAA6B,CAAC,CACpC,IAAI,CAAC,CAAC,CACN,SAAS,6DAA6D;CACzE,WAAW,EACR,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CACxB,IAAI,CAAC,CAAC,CACN,SAAS,gEAAgE;CAC5E,UAAU,qBACP,QAAQ,qBAAqB,CAAC,CAC9B,SAAS,iEAAiE;CAC7E,QAAQ,mBACL,QAAQ;EACP,UAAU;EACV,kBAAkB;EAClB,uBAAuB;EACvB,gBAAgB;CAClB,CAAC,CAAC,CACD,SAAS,yEAAyE;CACrF,WAAW,sBACR,QAAQ,sBAAsB,CAAC,CAC/B,SAAS,qDAAqD;AACnE,CAAC;AAKD,SAAgB,cAAc,QAA2C;CACvE,OAAO,oBAAoB,MAAM,MAAM;AACzC"}
|
|
@@ -4,6 +4,13 @@ declare const factoryConfigRepositorySchema: z.ZodObject<{
|
|
|
4
4
|
slug: z.ZodString;
|
|
5
5
|
dependsOn: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
6
6
|
}, z.core.$strict>;
|
|
7
|
+
declare const executionPolicySchema: z.ZodObject<{
|
|
8
|
+
maxAttempts: z.ZodNumber;
|
|
9
|
+
stallMinutes: z.ZodNumber;
|
|
10
|
+
stallMinutesByKind: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
11
|
+
}, z.core.$strict>;
|
|
12
|
+
type ExecutionPolicy = z.infer<typeof executionPolicySchema>;
|
|
13
|
+
declare const defaultExecutionPolicy: ExecutionPolicy;
|
|
7
14
|
declare const factoryConfigSchema: z.ZodObject<{
|
|
8
15
|
connectors: z.ZodDefault<z.ZodObject<{
|
|
9
16
|
github: z.ZodArray<z.ZodObject<{
|
|
@@ -30,10 +37,22 @@ declare const factoryConfigSchema: z.ZodObject<{
|
|
|
30
37
|
}>>>;
|
|
31
38
|
require: z.ZodBoolean;
|
|
32
39
|
}, z.core.$strict>>>;
|
|
40
|
+
budget: z.ZodDefault<z.ZodObject<{
|
|
41
|
+
totalUsd: z.ZodNumber;
|
|
42
|
+
investigationUsd: z.ZodNumber;
|
|
43
|
+
perTaskReservationUsd: z.ZodNumber;
|
|
44
|
+
warningPercent: z.ZodNumber;
|
|
45
|
+
perRepositoryUsd: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
46
|
+
}, z.core.$strict>>;
|
|
47
|
+
execution: z.ZodDefault<z.ZodObject<{
|
|
48
|
+
maxAttempts: z.ZodNumber;
|
|
49
|
+
stallMinutes: z.ZodNumber;
|
|
50
|
+
stallMinutesByKind: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
51
|
+
}, z.core.$strict>>;
|
|
33
52
|
}, z.core.$strict>;
|
|
34
53
|
type FactoryConfig = z.infer<typeof factoryConfigSchema>;
|
|
35
54
|
type FactoryConfigInput = z.input<typeof factoryConfigSchema>;
|
|
36
55
|
declare function defineFactory(config: FactoryConfigInput): FactoryConfig;
|
|
37
56
|
//#endregion
|
|
38
|
-
export {
|
|
39
|
-
//# sourceMappingURL=factory-config-
|
|
57
|
+
export { defineFactory as a, factoryConfigSchema as c, defaultExecutionPolicy as i, FactoryConfig as n, executionPolicySchema as o, FactoryConfigInput as r, factoryConfigRepositorySchema as s, ExecutionPolicy as t };
|
|
58
|
+
//# sourceMappingURL=factory-config-D2yU3G0c.d.mts.map
|