@vercel/factory 0.0.4 → 0.0.6
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/dist/{approval-h5aj8HYN.d.mts → approval-MoiwGpkh.d.mts} +3 -2
- package/dist/connectors/slack.d.mts +43 -0
- package/dist/connectors/slack.mjs +50 -0
- package/dist/connectors/slack.mjs.map +1 -0
- package/dist/eve/index.d.mts +50 -4
- package/dist/eve/index.mjs +94 -18
- package/dist/eve/index.mjs.map +1 -1
- package/dist/{github-5qQPCaXj.d.mts → github-lprHgbx7.d.mts} +30 -2
- package/dist/github.d.mts +2 -2
- package/dist/github.mjs +49 -1
- package/dist/github.mjs.map +1 -1
- package/dist/index.d.mts +15 -3
- package/dist/index.mjs +29 -4
- package/dist/index.mjs.map +1 -1
- package/dist/{task-Cj7Ei9Nh.mjs → task-BxTU3MJb.mjs} +2 -1
- package/dist/task-BxTU3MJb.mjs.map +1 -0
- package/dist/vercel.d.mts +32 -0
- package/dist/vercel.mjs +62 -0
- package/dist/vercel.mjs.map +1 -0
- package/package.json +9 -15
- package/dist/next-page.d.mts +0 -5
- package/dist/next-page.mjs +0 -71
- package/dist/next-page.mjs.map +0 -1
- package/dist/next.d.mts +0 -12
- package/dist/next.mjs +0 -44
- package/dist/next.mjs.map +0 -1
- package/dist/task-Cj7Ei9Nh.mjs.map +0 -1
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/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 { 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?: () => 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?.()),\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 { answerReviewComment, readReviewComment } from \"../github\";\nimport { changeIdSchema } from \"../schema/id\";\nimport type { FactoryStores } from \"../store/engine\";\nimport { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\n\nexport interface ReviewCommentToolOptions {\n tokenForRepository: (repository: string) => Promise<string>;\n fetch?: typeof globalThis.fetch;\n}\n\nexport function reviewCommentTools(stores: FactoryStores, options: ReviewCommentToolOptions) {\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 async function context(changeId: z.infer<typeof changeIdSchema>) {\n const change = await stores.changes.get(changeId);\n if (change === null) {\n throw new Error(`change ${changeId} does not exist`);\n }\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) {\n throw new Error(`repository ${change.repositoryId} does not exist`);\n }\n return {\n repository: repository.slug,\n token: await options.tokenForRepository(repository.slug),\n fetch: options.fetch,\n pullRequestNumber: change.prNumber,\n };\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 return readReviewComment({ ...(await context(changeId)), commentId });\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. The repository and pull request come from the ledger, and the comment author must have write access.\",\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 return answerReviewComment({ ...(await context(changeId)), commentId, body });\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 { 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;CACA,MAAM,WAAW,QAAQ,YAAY;CAErC,eAAe,QAAQ,QAAsC;EAC3D,MAAM,OAAO,MAAM,OAAO,MAAM,IAAI,MAAM;EAC1C,IAAI,SAAS,MAAM,MAAM,IAAI,MAAM,QAAQ,OAAO,gBAAgB;EAClE,IAAI,KAAK,SAAS,kBAAkB,MAAM,IAAI,MAAM,QAAQ,OAAO,MAAM,KAAK,KAAK,qBAAqB;EACxG,IAAI,KAAK,UAAU,WAAW,MAAM,IAAI,MAAM,QAAQ,OAAO,MAAM,KAAK,MAAM,cAAc;EAC5F,IAAI,KAAK,OAAO,aAAa,KAAA,GAAW,MAAM,IAAI,MAAM,QAAQ,OAAO,wBAAwB;EAC/F,MAAM,SAAS,MAAM,OAAO,QAAQ,IAAI,KAAK,OAAO,QAAQ;EAC5D,IAAI,WAAW,QAAQ,OAAO,WAAW,yBACvC,MAAM,IAAI,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":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/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 { 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?: () => 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?.()),\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 { 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 { 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;CACA,MAAM,WAAW,QAAQ,YAAY;CAErC,eAAe,QAAQ,QAAsC;EAC3D,MAAM,OAAO,MAAM,OAAO,MAAM,IAAI,MAAM;EAC1C,IAAI,SAAS,MAAM,MAAM,IAAI,MAAM,QAAQ,OAAO,gBAAgB;EAClE,IAAI,KAAK,SAAS,kBAAkB,MAAM,IAAI,MAAM,QAAQ,OAAO,MAAM,KAAK,KAAK,qBAAqB;EACxG,IAAI,KAAK,UAAU,WAAW,MAAM,IAAI,MAAM,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AAC;IAChD,QAAQ,aAAa,SAAS;IAC9B,UAAU,eAAe,SAAS;IAClC,MAAM,iBAAiB,SAAS,gDAAgD;IAChF,OAAO,iBAAiB,SAAS,kCAAkC;IACnE,QAAQ,EAAE,OAAO,CAAC,CAAC,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"}
|
|
@@ -36,6 +36,14 @@ interface AnswerReviewCommentInput extends GitHubRepositoryRequest, ReviewCommen
|
|
|
36
36
|
commentId: number;
|
|
37
37
|
body: string;
|
|
38
38
|
}
|
|
39
|
+
interface ReadPullRequestHeadInput extends GitHubRepositoryRequest {
|
|
40
|
+
pullRequestNumber: number;
|
|
41
|
+
}
|
|
42
|
+
interface GitHubPullRequestHead {
|
|
43
|
+
branch: string;
|
|
44
|
+
sha: string;
|
|
45
|
+
repository: string;
|
|
46
|
+
}
|
|
39
47
|
interface PullRequestLabelInput extends GitHubRepositoryRequest {
|
|
40
48
|
pullRequestNumber: number;
|
|
41
49
|
label: string;
|
|
@@ -59,6 +67,8 @@ declare function createPullRequest(input: CreatePullRequestInput): Promise<Creat
|
|
|
59
67
|
declare function readReviewComment(input: ReadReviewCommentInput): Promise<GitHubReviewComment>;
|
|
60
68
|
/** Reply to an inline review comment after applying the author policy, which requires write access by default. */
|
|
61
69
|
declare function answerReviewComment(input: AnswerReviewCommentInput): Promise<GitHubReviewComment>;
|
|
70
|
+
/** Read the current head branch and commit of a pull request. */
|
|
71
|
+
declare function readPullRequestHead(input: ReadPullRequestHeadInput): Promise<GitHubPullRequestHead>;
|
|
62
72
|
/** List open, same-repository pull requests by one author that GitHub reports as conflicting. */
|
|
63
73
|
declare function listConflictedPullRequests(input: ListConflictedPullRequestsInput): Promise<ConflictedPullRequest[]>;
|
|
64
74
|
/** Add one label to a pull request. */
|
|
@@ -116,8 +126,26 @@ interface GitHubCIFailureSignal extends NormalizedSignal<"github_ci_failure"> {
|
|
|
116
126
|
* repository id; the payload stays untrusted data.
|
|
117
127
|
*/
|
|
118
128
|
declare function normalizeGitHubIssueOpened(options: WebhookEvent): GitHubIssueSignal | null;
|
|
129
|
+
interface GitHubPullRequestClosed {
|
|
130
|
+
source: "github_pull_request_closed";
|
|
131
|
+
deliveryId: string;
|
|
132
|
+
repositorySlug: string;
|
|
133
|
+
prNumber: number;
|
|
134
|
+
prUrl: string;
|
|
135
|
+
merged: boolean;
|
|
136
|
+
/** The merge commit on the base branch; null when closed without merging. */
|
|
137
|
+
mergeCommitSha: string | null;
|
|
138
|
+
/** The GitHub login that merged the pull request, or closed it without merging. */
|
|
139
|
+
decidedBy: string;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Normalize a closed pull_request webhook so the factory can observe what
|
|
143
|
+
* happened to its change: merged records merged_by (the sender when GitHub
|
|
144
|
+
* omits it), a close without merge records the sender.
|
|
145
|
+
*/
|
|
146
|
+
declare function normalizeGitHubPullRequestClosed(options: WebhookEvent): GitHubPullRequestClosed | null;
|
|
119
147
|
/** Normalize a completed, unsuccessful GitHub Actions run into a CI failure signal. */
|
|
120
148
|
declare function normalizeGitHubWorkflowRunFailure(options: WebhookEvent): GitHubCIFailureSignal | null;
|
|
121
149
|
//#endregion
|
|
122
|
-
export {
|
|
123
|
-
//# sourceMappingURL=github-
|
|
150
|
+
export { normalizeGitHubIssueOpened as C, readReviewComment as D, readPullRequestHead as E, removeLabel as O, normalizeGitHubDefaultBranchPush as S, normalizeGitHubWorkflowRunFailure as T, ReviewCommentAuthorPolicy as _, GitHubCIFailureSignal as a, createPullRequest as b, GitHubPullRequestClosed as c, GitHubReviewComment as d, GitHubReviewCommentAuthorError as f, ReadReviewCommentInput as g, ReadPullRequestHeadInput as h, CreatedPullRequest as i, verifyGitHubSignature as k, GitHubPullRequestHead as l, PullRequestLabelInput as m, ConflictedPullRequest as n, GitHubDefaultBranchPush as o, ListConflictedPullRequestsInput as p, CreatePullRequestInput as r, GitHubIssueSignal as s, AnswerReviewCommentInput as t, GitHubRepositoryRequest as u, addLabel as v, normalizeGitHubPullRequestClosed as w, listConflictedPullRequests as x, answerReviewComment as y };
|
|
151
|
+
//# sourceMappingURL=github-lprHgbx7.d.mts.map
|
package/dist/github.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as removeLabel, S as
|
|
2
|
-
export { AnswerReviewCommentInput, ConflictedPullRequest, CreatePullRequestInput, CreatedPullRequest, GitHubCIFailureSignal, GitHubDefaultBranchPush, GitHubIssueSignal, GitHubRepositoryRequest, GitHubReviewComment, GitHubReviewCommentAuthorError, ListConflictedPullRequestsInput, PullRequestLabelInput, ReadReviewCommentInput, ReviewCommentAuthorPolicy, addLabel, answerReviewComment, createPullRequest, listConflictedPullRequests, normalizeGitHubDefaultBranchPush, normalizeGitHubIssueOpened, normalizeGitHubWorkflowRunFailure, readReviewComment, removeLabel, verifyGitHubSignature };
|
|
1
|
+
import { C as normalizeGitHubIssueOpened, D as readReviewComment, E as readPullRequestHead, O as removeLabel, S as normalizeGitHubDefaultBranchPush, T as normalizeGitHubWorkflowRunFailure, _ as ReviewCommentAuthorPolicy, a as GitHubCIFailureSignal, b as createPullRequest, c as GitHubPullRequestClosed, d as GitHubReviewComment, f as GitHubReviewCommentAuthorError, g as ReadReviewCommentInput, h as ReadPullRequestHeadInput, i as CreatedPullRequest, k as verifyGitHubSignature, l as GitHubPullRequestHead, m as PullRequestLabelInput, n as ConflictedPullRequest, o as GitHubDefaultBranchPush, p as ListConflictedPullRequestsInput, r as CreatePullRequestInput, s as GitHubIssueSignal, t as AnswerReviewCommentInput, u as GitHubRepositoryRequest, v as addLabel, w as normalizeGitHubPullRequestClosed, x as listConflictedPullRequests, y as answerReviewComment } from "./github-lprHgbx7.mjs";
|
|
2
|
+
export { AnswerReviewCommentInput, ConflictedPullRequest, CreatePullRequestInput, CreatedPullRequest, GitHubCIFailureSignal, GitHubDefaultBranchPush, GitHubIssueSignal, GitHubPullRequestClosed, GitHubPullRequestHead, GitHubRepositoryRequest, GitHubReviewComment, GitHubReviewCommentAuthorError, ListConflictedPullRequestsInput, PullRequestLabelInput, ReadPullRequestHeadInput, ReadReviewCommentInput, ReviewCommentAuthorPolicy, addLabel, answerReviewComment, createPullRequest, listConflictedPullRequests, normalizeGitHubDefaultBranchPush, normalizeGitHubIssueOpened, normalizeGitHubPullRequestClosed, normalizeGitHubWorkflowRunFailure, readPullRequestHead, readReviewComment, removeLabel, verifyGitHubSignature };
|
package/dist/github.mjs
CHANGED
|
@@ -7,6 +7,11 @@ const pullRequestSchema = z.object({
|
|
|
7
7
|
number: z.number().int().positive(),
|
|
8
8
|
html_url: z.url()
|
|
9
9
|
});
|
|
10
|
+
const pullRequestHeadSchema = z.object({ head: z.object({
|
|
11
|
+
ref: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).refine((value) => !value.includes("..")),
|
|
12
|
+
sha: z.string().regex(/^[0-9a-f]{40}$/),
|
|
13
|
+
repo: z.object({ full_name: z.string().min(1) })
|
|
14
|
+
}) });
|
|
10
15
|
const reviewCommentSchema = z.object({
|
|
11
16
|
id: z.number().int().positive(),
|
|
12
17
|
body: z.string(),
|
|
@@ -86,6 +91,15 @@ async function answerReviewComment(input) {
|
|
|
86
91
|
body: JSON.stringify({ body: input.body })
|
|
87
92
|
}));
|
|
88
93
|
}
|
|
94
|
+
/** Read the current head branch and commit of a pull request. */
|
|
95
|
+
async function readPullRequestHead(input) {
|
|
96
|
+
const pull = pullRequestHeadSchema.parse(await gitHubRequest(input, `/pulls/${positiveInteger(input.pullRequestNumber, "pullRequestNumber")}`));
|
|
97
|
+
return {
|
|
98
|
+
branch: pull.head.ref,
|
|
99
|
+
sha: pull.head.sha,
|
|
100
|
+
repository: pull.head.repo.full_name.toLowerCase()
|
|
101
|
+
};
|
|
102
|
+
}
|
|
89
103
|
/** List open, same-repository pull requests by one author that GitHub reports as conflicting. */
|
|
90
104
|
async function listConflictedPullRequests(input) {
|
|
91
105
|
const candidates = openPullRequestsSchema.parse(await gitHubRequest(input, `/pulls?state=open&per_page=100`)).filter((pull) => pull.user.type === "Bot" && pull.head.ref.startsWith("factory/") && pull.head.repo.full_name.toLowerCase() === input.repository.toLowerCase());
|
|
@@ -248,6 +262,40 @@ function normalizeGitHubIssueOpened(options) {
|
|
|
248
262
|
payload: options.payload
|
|
249
263
|
};
|
|
250
264
|
}
|
|
265
|
+
const pullRequestClosedSchema = z.looseObject({
|
|
266
|
+
action: z.string(),
|
|
267
|
+
pull_request: z.looseObject({
|
|
268
|
+
number: z.number().int().min(1),
|
|
269
|
+
html_url: z.url(),
|
|
270
|
+
merged: z.boolean(),
|
|
271
|
+
merged_by: z.looseObject({ login: z.string().min(1) }).nullable().optional(),
|
|
272
|
+
merge_commit_sha: z.string().regex(/^[0-9a-f]{40}$/).nullable().optional()
|
|
273
|
+
}),
|
|
274
|
+
repository: z.looseObject({ full_name: z.string().min(1) }),
|
|
275
|
+
sender: z.looseObject({ login: z.string().min(1) })
|
|
276
|
+
});
|
|
277
|
+
/**
|
|
278
|
+
* Normalize a closed pull_request webhook so the factory can observe what
|
|
279
|
+
* happened to its change: merged records merged_by (the sender when GitHub
|
|
280
|
+
* omits it), a close without merge records the sender.
|
|
281
|
+
*/
|
|
282
|
+
function normalizeGitHubPullRequestClosed(options) {
|
|
283
|
+
if (options.event !== "pull_request") return null;
|
|
284
|
+
const parsed = pullRequestClosedSchema.safeParse(options.payload);
|
|
285
|
+
if (!parsed.success || parsed.data.action !== "closed") return null;
|
|
286
|
+
const pr = parsed.data.pull_request;
|
|
287
|
+
const sender = parsed.data.sender.login;
|
|
288
|
+
return {
|
|
289
|
+
source: "github_pull_request_closed",
|
|
290
|
+
deliveryId: options.deliveryId,
|
|
291
|
+
repositorySlug: parsed.data.repository.full_name.toLowerCase(),
|
|
292
|
+
prNumber: pr.number,
|
|
293
|
+
prUrl: pr.html_url,
|
|
294
|
+
merged: pr.merged,
|
|
295
|
+
mergeCommitSha: pr.merged ? pr.merge_commit_sha ?? null : null,
|
|
296
|
+
decidedBy: pr.merged ? pr.merged_by?.login ?? sender : sender
|
|
297
|
+
};
|
|
298
|
+
}
|
|
251
299
|
/** Normalize a completed, unsuccessful GitHub Actions run into a CI failure signal. */
|
|
252
300
|
function normalizeGitHubWorkflowRunFailure(options) {
|
|
253
301
|
if (options.event !== "workflow_run") return null;
|
|
@@ -281,6 +329,6 @@ function normalizeGitHubWorkflowRunFailure(options) {
|
|
|
281
329
|
};
|
|
282
330
|
}
|
|
283
331
|
//#endregion
|
|
284
|
-
export { GitHubReviewCommentAuthorError, addLabel, answerReviewComment, createPullRequest, listConflictedPullRequests, normalizeGitHubDefaultBranchPush, normalizeGitHubIssueOpened, normalizeGitHubWorkflowRunFailure, readReviewComment, removeLabel, verifyGitHubSignature };
|
|
332
|
+
export { GitHubReviewCommentAuthorError, addLabel, answerReviewComment, createPullRequest, listConflictedPullRequests, normalizeGitHubDefaultBranchPush, normalizeGitHubIssueOpened, normalizeGitHubPullRequestClosed, normalizeGitHubWorkflowRunFailure, readPullRequestHead, readReviewComment, removeLabel, verifyGitHubSignature };
|
|
285
333
|
|
|
286
334
|
//# sourceMappingURL=github.mjs.map
|