diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 29425efdc..c6348b571 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -151,12 +151,23 @@ Screenshots open from Hub, not the agent. Hub serves one only while the screensh Hub can check whether a repository's learnings help and suggest updates. Someone who administers Hub or the repository opens it from **Automated evaluations** on the Learnings page. For example, a Hub administrator sets a shared budget of 100 credits per month, and an administrator of `github/checkout` turns on **Evaluate github/checkout**. -- The budget is one monthly credit limit shared by every repository. Only Hub administrators change it, from 0 to 1,000,000 credits. Usage shows as 0 until evaluations run against Builds. +- The budget is one monthly credit limit shared by every repository. Only Hub administrators change it, from 0 to 1,000,000 credits. Usage counts every score attempt since the start of the month in UTC, including attempts that fail. A budget of 0 means nothing is scored. - Each repository is off until one of its administrators turns it on. Hub and repository administration stay separate, so a Hub administrator alone cannot turn on a repository. - **Allow screenshots** lets agents send screenshots with `report_usage` and lets Hub analyze them. It needs evaluations on, and turning evaluations off turns it off too. The page shows who changed it last. Allowing screenshots adds a consent grant in the repository's learning store with who allowed it. Hub records the grant and passes it to every `report_usage` call, and the store refuses screenshots once the grant is withdrawn. Hub keeps a copy of each accepted image in artifact storage only while the grant is still the active one. Turning screenshots off withdraws the grant and queues a job that deletes the copies taken under it. The worker's recovery pass finds every withdrawn grant again, so a failed enqueue or a copy saved during the change is still deleted. Allowing screenshots again makes a new grant. +Turning evaluations on also adds a consent grant that lets the store use the repository's review comments as evaluation evidence. Turning them off stops scoring and withdraws it. Hub keeps the grant's ID until the withdrawal succeeds, so saving again retries a failed one. A repository without this grant isn't scored until an administrator saves its settings again. + +### Scoring applied learnings + +When an agent's `report_usage` call names a commit, Hub remembers it. A later report for the same commit is kept for another pass, even if scoring is already running. Once a successful Build exists for that commit, the worker's recovery pass queues a scoring job. For example, an agent applies the learning "Use the shared empty state" in commit `abc123`, a Build for `abc123` succeeds, and Hub asks the store to score that learning against the commit's diff and any screenshots the agent sent. + +- Each reported use of a learning is scored once. Hub records the attempt and its cost before asking for the next one, so a crash retries the same operation instead of paying twice. +- A failed score is recorded with what it spent and is not retried. A score interrupted by a worker stopping stays running and is retried with the same operation. +- When the budget runs out or Copilot is unavailable, the request waits. The recovery pass tries it again each minute and starts scoring once the budget is raised or the next month begins. Requests that never find a successful Build are dropped after 30 days. +- Scoring holds the learning execution lock for each command, so agent calls may briefly get a busy reply while a score runs. + Repository changes take the learning execution lock. While other learning work runs, they return `409` and the person tries again. Repository denials write security audits. The browser contracts are: - `GET /api/repositories/:repositoryId/learnings/evaluations` diff --git a/hub/schema/learning-evaluation-run.prisma b/hub/schema/learning-evaluation-run.prisma new file mode 100644 index 000000000..900935f11 --- /dev/null +++ b/hub/schema/learning-evaluation-run.prisma @@ -0,0 +1,26 @@ +model LearningEvaluationRun { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + usedLearningId String @map("used_learning_id") @db.VarChar(255) + operationId String @unique @map("operation_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + state LearningRunState @default(RUNNING) + copilotRequests Int @default(0) @map("copilot_requests") + aiCredits Decimal @default(0) @map("ai_credits") @db.Decimal(20, 9) + scoreId String? @map("score_id") @db.VarChar(255) + failureCode String? @map("failure_code") @db.VarChar(60) + finishedAt DateTime? @map("finished_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([repositoryId, usedLearningId]) + @@index([createdAt]) + @@map("learning_evaluation_runs") +} diff --git a/hub/schema/learning-score-request.prisma b/hub/schema/learning-score-request.prisma new file mode 100644 index 000000000..cc6aaa5e1 --- /dev/null +++ b/hub/schema/learning-score-request.prisma @@ -0,0 +1,19 @@ +model LearningScoreRequest { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + commitSha String @map("commit_sha") @db.VarChar(64) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([repositoryId, commitSha]) + @@index([createdAt]) + @@map("learning_score_requests") +} diff --git a/hub/schema/migrations/20261225090000_learning_evaluation_runs/migration.sql b/hub/schema/migrations/20261225090000_learning_evaluation_runs/migration.sql new file mode 100644 index 000000000..acf0d7280 --- /dev/null +++ b/hub/schema/migrations/20261225090000_learning_evaluation_runs/migration.sql @@ -0,0 +1,53 @@ +-- AlterTable +ALTER TABLE "repository_evaluation_settings" ADD COLUMN "evaluation_grant_id" VARCHAR(255); + +-- CreateTable +CREATE TABLE "learning_evaluation_runs" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "used_learning_id" VARCHAR(255) NOT NULL, + "operation_id" UUID NOT NULL, + "state" "LearningRunState" NOT NULL DEFAULT 'RUNNING', + "copilot_requests" INTEGER NOT NULL DEFAULT 0, + "ai_credits" DECIMAL(20,9) NOT NULL DEFAULT 0, + "score_id" VARCHAR(255), + "failure_code" VARCHAR(60), + "finished_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_evaluation_runs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "learning_score_requests" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "commit_sha" VARCHAR(64) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_score_requests_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_evaluation_runs_operation_id_key" ON "learning_evaluation_runs"("operation_id"); + +-- CreateIndex +CREATE INDEX "learning_evaluation_runs_created_at_idx" ON "learning_evaluation_runs"("created_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_evaluation_runs_repository_id_used_learning_id_key" ON "learning_evaluation_runs"("repository_id", "used_learning_id"); + +-- CreateIndex +CREATE INDEX "learning_score_requests_created_at_idx" ON "learning_score_requests"("created_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_score_requests_repository_id_commit_sha_key" ON "learning_score_requests"("repository_id", "commit_sha"); + +-- AddForeignKey +ALTER TABLE "learning_evaluation_runs" ADD CONSTRAINT "learning_evaluation_runs_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_score_requests" ADD CONSTRAINT "learning_score_requests_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/hub/schema/repository-evaluation-setting.prisma b/hub/schema/repository-evaluation-setting.prisma index 616b94c44..33708b472 100644 --- a/hub/schema/repository-evaluation-setting.prisma +++ b/hub/schema/repository-evaluation-setting.prisma @@ -10,6 +10,7 @@ model RepositoryEvaluationSetting { // Attribute columns enabled Boolean @default(false) + evaluationGrantId String? @map("evaluation_grant_id") @db.VarChar(255) screenshotGrantId String? @map("screenshot_grant_id") @db.VarChar(255) screenshotsChangedAt DateTime? @map("screenshots_changed_at") @db.Timestamptz(3) diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index 5598eeb75..b4579fbbb 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -10,6 +10,8 @@ model Repository { learningShares LearningShare[] evaluationSetting RepositoryEvaluationSetting? agentScreenshots AgentScreenshot[] + learningEvaluationRuns LearningEvaluationRun[] + learningScoreRequests LearningScoreRequest[] decisionModelConfiguration DecisionModelConfiguration? decisionReviewSnapshot DecisionReviewSnapshot? decisionTrainingJobs DecisionTrainingJob[] diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts index 4eaedfd2c..1a048a312 100644 --- a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts @@ -222,3 +222,31 @@ it("keeps screenshot bytes only while the repository still allows screenshots", expect(save).toHaveBeenCalledOnce() expect(save).toHaveBeenCalledWith({ grantId: "grant-1", bytes: Buffer.from("image") }) }) + +it("asks Hub to score the commit an agent reports usage for", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockResolvedValueOnce({ recorded: 1 }) + const requestScore = vi.fn() + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(true), + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + learningDatabaseUrl: "postgresql://learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + requestScore, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + await backend.reportUsage({ commitSha: "a".repeat(40), used: [] }) + + expect(requestScore).toHaveBeenCalledWith("a".repeat(40)) +}) diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts index ce40bdaa2..532f537bc 100644 --- a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts @@ -58,6 +58,7 @@ export function createLearningMcpBackend(input: { learning: LearningSettings learningsUrl: string repository: { id: string; githubRepositoryId: bigint } + requestScore?(commitSha: string): Promise serialize(operation: (signal: AbortSignal) => Promise): Promise screenshots?: { grantId(): Promise @@ -179,7 +180,10 @@ export function createLearningMcpBackend(input: { } }, - async reportUsage(report: { used: { before?: Screenshot; after?: Screenshot }[] }) { + async reportUsage(report: { + commitSha?: unknown + used: { before?: Screenshot; after?: Screenshot }[] + }) { const screenshots = report.used.flatMap((item) => [item.before, item.after].filter((shot) => shot !== undefined), ) @@ -199,6 +203,10 @@ export function createLearningMcpBackend(input: { const directory = await storeDirectory() if (!directory) throw toAgentError("not_found", "This repository has no learnings to report on.") + // Asked first so a report that lands is never missed. A request whose report failed + // finds nothing to score and is dropped. + if (typeof report.commitSha === "string" && /^[0-9a-f]{40}$/.test(report.commitSha)) + await input.requestScore?.(report.commitSha) const result = await withPrivateFile(JSON.stringify(report), (file) => run(directory, ["report-usage", file, ...(grantId ? ["--grant", grantId] : [])]), ) diff --git a/hub/server/domains/learning/change-screenshot-consent/index.ts b/hub/server/domains/learning/change-evaluation-consent/index.ts similarity index 71% rename from hub/server/domains/learning/change-screenshot-consent/index.ts rename to hub/server/domains/learning/change-evaluation-consent/index.ts index a0b35b2a2..5134235e4 100644 --- a/hub/server/domains/learning/change-screenshot-consent/index.ts +++ b/hub/server/domains/learning/change-evaluation-consent/index.ts @@ -6,12 +6,20 @@ import { prepareLearningStore } from "../prepare-learning-store/index.ts" const addedGrantSchema = z.object({ id: z.string().min(1).max(255) }).loose() +const bases = { + agent_screenshots: + "A repository administrator allowed agents to take screenshots and Hub to analyze them.", + hub_review_comments: + "A repository administrator turned on automated evaluations of applied learnings.", +} + /** - * Turns a repository's screenshot consent on or off in its learning store. The store keeps - * the grant with who changed it, and refuses screenshots once the grant is withdrawn, so - * Hub's own setting can never allow more than the store does. Returns the active grant. + * Turns one evaluation consent on or off in a repository's learning store: screenshots, or + * the review comments behind learnings an evaluator scores. The store keeps the grant with + * who changed it, and refuses evaluation once it is withdrawn, so Hub's own setting can + * never allow more than the store does. Returns the active grant. */ -export async function changeScreenshotConsent(input: { +export async function changeEvaluationConsent(input: { actor: string allowed: boolean cliPath: string @@ -22,6 +30,7 @@ export async function changeScreenshotConsent(input: { repositoryScope: string root: string signal?: AbortSignal + source: keyof typeof bases staticDirectories: string[] }): Promise { const store = await prepareLearningStore({ @@ -47,9 +56,9 @@ export async function changeScreenshotConsent(input: { "--purpose", "evaluation", "--source", - "agent_screenshots", + input.source, "--basis", - "A repository administrator allowed agents to take screenshots and Hub to analyze them.", + bases[input.source], "--by", input.actor, ...common, diff --git a/hub/server/domains/learning/create-learning-job-processors/index.test.ts b/hub/server/domains/learning/create-learning-job-processors/index.test.ts index c5b4e04c5..d54e8f13b 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.test.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.test.ts @@ -18,6 +18,7 @@ const prisma = { learningDecisionOperation: { findMany: vi.fn() }, repository: { findUnique: vi.fn() }, reviewComment: { findMany: vi.fn(), updateMany: vi.fn() }, + learningScoreRequest: { deleteMany: vi.fn(), findMany: vi.fn() }, } vi.mock("../../../integrations/prisma", () => ({ prisma })) @@ -116,6 +117,7 @@ describe("createLearningJobProcessors()", () => { prisma.agentScreenshot.groupBy.mockResolvedValue([]) prisma.repositoryEvaluationSetting.findMany.mockResolvedValue([]) prisma.learningDecisionOperation.findMany.mockResolvedValue([]) + prisma.learningScoreRequest.findMany.mockResolvedValue([]) prisma.reviewComment.findMany.mockResolvedValue([ { publicId: 101, diff --git a/hub/server/domains/learning/create-learning-job-processors/index.ts b/hub/server/domains/learning/create-learning-job-processors/index.ts index 7e0642e19..abba7e675 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto" import type { Logger } from "pino" +import { readGitHubAppConfiguration } from "../../authentication/read-github-app-configuration/index.ts" import { resolveLocalSignInEnvironment } from "../../authentication/resolve-local-sign-in-environment/index.ts" import { getCopilotConnectionStatus } from "../../copilot-connection/get-copilot-connection-status/index.ts" import { ReviewCommentError } from "../../review-comments/errors.ts" @@ -14,6 +15,8 @@ import { automaticLearningRunPriority } from "../jobs/priorities.ts" import { recoverLearningRunsJob } from "../jobs/recover-learning-runs.ts" import { redactReviewCommentJob } from "../jobs/redact-review-comment.ts" import { scheduleLearningRunsJob } from "../jobs/schedule-learning-runs.ts" +import { scoreAppliedLearningsJob } from "../jobs/score-applied-learnings.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" import { prepareLearningStore } from "../prepare-learning-store/index.ts" import { processLearningRun } from "../process-learning-run/index.ts" import { processReviewCommentRedaction } from "../process-review-comment-redaction/index.ts" @@ -24,6 +27,7 @@ import { recordFinishedLearningRun } from "../record-finished-learning-run/index import { readAutomaticLearningRunsEnabled } from "../read-automatic-learning-runs-enabled/index.ts" import { readLearningConfiguration } from "../read-learning-configuration/index.ts" import { scheduleLearningRuns } from "../schedule-learning-runs/index.ts" +import { scoreAppliedLearnings } from "../score-applied-learnings/index.ts" import { createConfiguredArtifactStorage } from "../../artifacts/create-configured-artifact-storage/index.ts" import { createJobProcessor } from "../../../integrations/bullmq/create-job-processor/index.ts" import { createJobQueue } from "../../../integrations/bullmq/create-job-queue/index.ts" @@ -32,11 +36,21 @@ import type { PrismaClient } from "../../../generated/prisma/client.ts" import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { CopilotCredentialError } from "../../../integrations/github/create-installation-access-token/errors.ts" +import { createGitHubActionsClient } from "../../../integrations/github/create-github-actions-client/index.ts" +import { GitHubCommitLookupError } from "../../../integrations/github/errors.ts" import { withLearningExecutionLock } from "../../../integrations/postgres/with-learning-execution-lock/index.ts" import { deleteAgentScreenshot } from "../../../repositories/agent-screenshots/delete-agent-screenshot/index.ts" +import { findConsentedAgentScreenshots } from "../../../repositories/agent-screenshots/find-consented-agent-screenshots/index.ts" import { listAgentScreenshotGrants } from "../../../repositories/agent-screenshots/list-agent-screenshot-grants/index.ts" import { listGrantAgentScreenshots } from "../../../repositories/agent-screenshots/list-grant-agent-screenshots/index.ts" import { getRepositoryEvaluationSetting } from "../../../repositories/evaluation-settings/get-repository-evaluation-setting/index.ts" +import { initializeEvaluationSetting } from "../../../repositories/evaluation-settings/initialize-evaluation-setting/index.ts" +import { finishLearningEvaluationRun } from "../../../repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts" +import { startLearningEvaluationRun } from "../../../repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts" +import { sumLearningEvaluationCredits } from "../../../repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts" +import { deleteExpiredLearningScoreRequests } from "../../../repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts" +import { deleteLearningScoreRequest } from "../../../repositories/learning-score-requests/delete-learning-score-request/index.ts" +import { listReadyLearningScoreRequests } from "../../../repositories/learning-score-requests/list-ready-learning-score-requests/index.ts" import { getCopilotConnectionState } from "../../../repositories/copilot-connection-states/get-copilot-connection-state/index.ts" import { advanceCopilotConnectionState } from "../../../repositories/copilot-connection-states/advance-copilot-connection-state/index.ts" import { lockCopilotConnectionState } from "../../../repositories/copilot-connection-states/lock-copilot-connection-state/index.ts" @@ -61,6 +75,7 @@ import { listDeletedReviewComments } from "../../../repositories/review-comments import { markReviewCommentLearningRedacted } from "../../../repositories/review-comments/mark-review-comment-learning-redacted/index.ts" import { findRepositoryGitHubId } from "../../../repositories/repository-access/find-repository-github-id/index.ts" import { createSecurityAudit } from "../../../repositories/security-audits/create-security-audit/index.ts" +import { startOfUtcMonth } from "../../../utils/start-of-utc-month/index.ts" export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logger: Logger) { let databaseDependenciesPromise: @@ -323,6 +338,20 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg `learning-screenshots-${screenshots.repositoryId}-${screenshots.grantId}`, ) } + // Agents can report usage before or after the Build for that commit finishes, so + // requests wait here until both exist. Unbuilt ones are dropped after 30 days. + await deleteExpiredLearningScoreRequests( + prisma, + new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), + ) + for (const request of await listReadyLearningScoreRequests(prisma)) { + await enqueueRecoverableJob( + onDemandQueue, + scoreAppliedLearningsJob, + request, + `learning-score-${request.repositoryId}-${request.commitSha}`, + ) + } for (const operation of await listLearningDecisionOperations(prisma)) { try { await reconcileLearningDecisionOperation(operation, { @@ -505,5 +534,104 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg }) }) - return { run, scheduledRun, recover, redact, schedule, deleteScreenshots } + const score = createJobProcessor(scoreAppliedLearningsJob, async (request, context) => { + const { configuration, databaseUrl, prisma } = await dependencies() + const repository = { repositoryId: request.repositoryId, commitSha: request.commitSha } + try { + const result = await scoreAppliedLearnings({ + commitSha: request.commitSha, + credential: async () => { + if (!(await copilotUsable())) return null + return configuration.copilotCredentialProvider.getCredential() + }, + deleteRequest: (reportedBefore) => + deleteLearningScoreRequest(prisma, { ...repository, reportedBefore }), + finish: (runId, input) => finishLearningEvaluationRun(prisma, runId, input), + // Scoring needs the store's evaluation grant, which a repository turned on before + // grants existed gets on its next settings save. + isEnabled: async () => { + const setting = await getRepositoryEvaluationSetting(prisma, request.repositoryId) + return Boolean(setting?.enabled && setting.evaluationGrantId) + }, + now: () => new Date(), + prepare: async () => + learningStoreArguments( + await prepareLearningStore({ + applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, + repositoryKey: request.repositoryId, + repositoryScope: await getLearningRepositoryScope(prisma, request.repositoryId), + root: configuration.root, + staticDirectories: configuration.staticDirectories, + }), + ), + readDiff: async () => { + const credentials = readGitHubAppConfiguration( + resolveLocalSignInEnvironment(environment), + ).appCredentials + const githubRepositoryId = (await findRepositoryGitHubId(prisma, request.repositoryId)) + ?.githubRepositoryId + if (!credentials || !githubRepositoryId) return null + try { + return await createGitHubActionsClient({ + appId: credentials.appId, + installationId: credentials.installationId, + privateKey: credentials.privateKey, + githubRepositoryId: Number(githubRepositoryId), + }).getCommitDiff(request.commitSha) + } catch (error) { + // A commit GitHub no longer has is scored on what remains. + if ( + error instanceof GitHubCommitLookupError && + (error.statusCode === 404 || error.statusCode === 422) + ) + return null + throw error + } + }, + readScreenshot: async (sha256) => { + const consented = await findConsentedAgentScreenshots(prisma, { + repositoryId: request.repositoryId, + sha256s: [sha256], + }) + const storageKey = consented?.storageKeys.get(sha256) + if (!storageKey) return null + const read = await (await artifactStorage()).read(storageKey) + return read.status === "ok" ? read.bytes : null + }, + runCommand: (arguments_, options) => + runLearningCommand(arguments_, { + cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, + nodePath: configuration.nodePath, + ...options, + }), + start: (usedLearningId) => + startLearningEvaluationRun(prisma, { + repositoryId: request.repositoryId, + usedLearningId, + }), + withinBudget: async () => { + const budget = (await initializeEvaluationSetting(prisma)).monthlyBudgetCredits + const used = await sumLearningEvaluationCredits(prisma, startOfUtcMonth(new Date())) + return used ? used.lessThan(budget) : budget.greaterThan(0) + }, + withLock: (operation) => withLearningExecutionLock({ databaseUrl, run: operation }), + }) + if (result === "paused") + logger.info( + repository, + "Applied learning scoring is paused until Copilot or budget returns", + ) + } catch (error) { + if ( + error instanceof Error && + error.message === "Another learning operation is still running." + ) + return await context.defer(30_000) + throw error + } + }) + + return { run, scheduledRun, recover, redact, schedule, deleteScreenshots, score } } diff --git a/hub/server/domains/learning/jobs/score-applied-learnings.ts b/hub/server/domains/learning/jobs/score-applied-learnings.ts new file mode 100644 index 000000000..a415da792 --- /dev/null +++ b/hub/server/domains/learning/jobs/score-applied-learnings.ts @@ -0,0 +1,12 @@ +import { z } from "zod" + +export const scoreAppliedLearningsJob = { + name: "learning.score-applied-learnings", + schema: z + .object({ + repositoryId: z.uuid(), + commitSha: z.string().regex(/^[0-9a-f]{40}$/), + }) + .strict(), + options: { attempts: 3, backoff: { type: "fixed", delay: 60_000 } }, +} diff --git a/hub/server/domains/learning/process-learning-run/index.ts b/hub/server/domains/learning/process-learning-run/index.ts index 79b9329b6..f9f7dabbf 100644 --- a/hub/server/domains/learning/process-learning-run/index.ts +++ b/hub/server/domains/learning/process-learning-run/index.ts @@ -6,6 +6,7 @@ import { z } from "zod" import { classifyPrismaTransactionError } from "../../../integrations/prisma/classify-transaction-error/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { runWithBoundedRetries } from "../../identity/run-with-bounded-retries/index.ts" +import { formatAiCredits } from "../../../utils/format-ai-credits/index.ts" import { learningStoreArguments } from "../learning-store-arguments/index.ts" const grantListSchema = z.array( @@ -51,11 +52,6 @@ const consolidateSchema = z }) .loose() -function credits(nanoAiu: number) { - const padded = nanoAiu.toString().padStart(10, "0") - return `${padded.slice(0, -9)}.${padded.slice(-9)}`.replace(/\.?0+$/, "") || "0" -} - export async function processLearningRun( runId: string, dependencies: { @@ -305,7 +301,7 @@ export async function processLearningRun( commentsLabeled: partial.data.labeled, commentsRemaining: partial.data.remaining, copilotRequests: partial.data.usage.requests, - aiCredits: credits(partial.data.usage.nanoAiu), + aiCredits: formatAiCredits(partial.data.usage.nanoAiu), }) } } @@ -316,7 +312,7 @@ export async function processLearningRun( commentsLabeled: labeled.labeled, commentsRemaining: labeled.remaining, copilotRequests: labeled.usage.requests, - aiCredits: credits(labeled.usage.nanoAiu), + aiCredits: formatAiCredits(labeled.usage.nanoAiu), }) if ( current.scheduled diff --git a/hub/server/domains/learning/score-applied-learnings/index.test.ts b/hub/server/domains/learning/score-applied-learnings/index.test.ts new file mode 100644 index 000000000..11692d77e --- /dev/null +++ b/hub/server/domains/learning/score-applied-learnings/index.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, vi } from "vitest" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors" +import { scoreAppliedLearnings } from "." + +async function withLock(operation: (signal: AbortSignal) => Promise) { + return await operation(new AbortController().signal) +} + +describe("scoreAppliedLearnings", () => { + it("records what a failed score spent and finishes the request", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "usage") { + return Promise.resolve({ reports: [{ used: [{ id: "learning-1" }] }] }) + } + return Promise.reject( + new LearningCommandError("copilot_failed", "Copilot stopped.", { + result: { usage: { requests: 2, nanoAiu: 1_500_000_000 } }, + }), + ) + }) + + const result = await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-25T09:00:00Z"), + prepare: () => Promise.resolve(["--store", "hub"]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("done") + expect(runCommand).toHaveBeenCalledWith( + ["score", "learning-1", "--operation-id", "op-1", "--store", "hub"], + expect.objectContaining({ githubToken: "token" }), + ) + expect(finish).toHaveBeenCalledWith("run-1", { + state: "FAILED", + failureCode: "copilot_failed", + aiCredits: "1.5", + copilotRequests: 2, + finishedAt: new Date("2026-12-25T09:00:00Z"), + }) + expect(deleteRequest).toHaveBeenCalledOnce() + }) + + it("pauses without scoring once the monthly budget is spent", async () => { + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn(() => Promise.resolve({})) + + const result = await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish: () => Promise.resolve(), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(false), + withLock, + }) + + expect(result).toBe("paused") + expect(runCommand).not.toHaveBeenCalled() + expect(deleteRequest).not.toHaveBeenCalled() + }) + + it("leaves an interrupted score running so the next pass retries it", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "usage") { + return Promise.resolve({ reports: [{ used: [{ id: "learning-1" }] }] }) + } + return Promise.reject(new LearningCommandError("cancelled", "The worker stopped.")) + }) + + await expect( + scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + withLock, + }), + ).rejects.toMatchObject({ code: "cancelled" }) + expect(finish).not.toHaveBeenCalled() + expect(deleteRequest).not.toHaveBeenCalled() + }) +}) diff --git a/hub/server/domains/learning/score-applied-learnings/index.ts b/hub/server/domains/learning/score-applied-learnings/index.ts new file mode 100644 index 000000000..bcaaefeb8 --- /dev/null +++ b/hub/server/domains/learning/score-applied-learnings/index.ts @@ -0,0 +1,164 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { resolve } from "node:path" +import { z } from "zod" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { formatAiCredits } from "../../../utils/format-ai-credits/index.ts" + +const screenshotSchema = z.object({ sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/) }).loose() +const usageSchema = z + .object({ + reports: z.array( + z + .object({ + used: z.array( + z + .object({ + // The ID is passed to the package as an argument, so it must never + // read as an option. + id: z + .string() + .min(1) + .max(255) + .refine((id) => !id.startsWith("-")), + before: screenshotSchema.optional(), + after: screenshotSchema.optional(), + }) + .loose(), + ), + }) + .loose(), + ), + }) + .loose() +const spentSchema = z + .object({ + usage: z + .object({ + requests: z.number().int().nonnegative(), + nanoAiu: z.number().int().nonnegative(), + }) + .loose(), + }) + .loose() +const scoredSchema = spentSchema.extend({ + score: z.object({ id: z.string().min(1).max(255) }).loose(), +}) + +/** + * Scores each learning agents said they applied in one built commit, one Copilot call at a + * time, while the shared monthly budget lasts. Each attempt is recorded with what it cost, + * even when it fails, so spending is never undercounted. Returns "paused" when Copilot or + * the budget is unavailable, so the request is kept and tried again later. + */ +export async function scoreAppliedLearnings(dependencies: { + commitSha: string + credential(): Promise<{ githubToken?: string } | null> + deleteRequest(reportedBefore: Date): Promise + finish( + runId: string, + input: { aiCredits: string; copilotRequests: number; finishedAt: Date } & ( + { state: "SUCCEEDED"; scoreId: string } | { state: "FAILED"; failureCode: string } + ), + ): Promise + isEnabled(): Promise + now(): Date + prepare(): Promise + readDiff(): Promise + readScreenshot(sha256: string): Promise + runCommand( + arguments_: string[], + options: { githubToken?: string; signal: AbortSignal; timeoutMs?: number }, + ): Promise + start(usedLearningId: string): Promise<{ id: string; operationId: string; state: string }> + withinBudget(): Promise + withLock(operation: (signal: AbortSignal) => Promise): Promise +}): Promise<"done" | "paused"> { + // Turning evaluations off means nothing more is scored, so the request is dropped. + if (!(await dependencies.isEnabled())) { + await dependencies.deleteRequest(dependencies.now()) + return "done" + } + if (!(await dependencies.withinBudget())) return "paused" + const credential = await dependencies.credential() + if (!credential) return "paused" + const store = await dependencies.prepare() + const readAt = dependencies.now() + const { reports } = usageSchema.parse( + await dependencies.withLock((signal) => + dependencies.runCommand(["usage", "--commit", dependencies.commitSha, ...store], { + signal, + }), + ), + ) + const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-score-")) + try { + let diffFile: string | null | undefined + for (const [index, used] of reports.flatMap((report) => report.used).entries()) { + const run = await dependencies.start(used.id) + if (run.state !== "RUNNING") continue + if (!(await dependencies.withinBudget())) return "paused" + if (diffFile === undefined) { + const diff = await dependencies.readDiff() + diffFile = diff === null ? null : resolve(temporary, "commit.diff") + if (diffFile) await writeFile(diffFile, diff!, { mode: 0o600 }) + } + // A hosted store keeps no screenshot bytes, so Hub hands over the ones whose + // consent still holds as files named by their digest. + const screenshots = resolve(temporary, `screenshots-${index}`) + let hasScreenshots = false + for (const shot of [used.before, used.after]) { + if (!shot) continue + const bytes = await dependencies.readScreenshot(shot.sha256) + if (!bytes) continue + await mkdir(screenshots, { recursive: true, mode: 0o700 }) + await writeFile(resolve(screenshots, `${shot.sha256.slice(7)}.png`), bytes, { + mode: 0o600, + }) + hasScreenshots = true + } + try { + const scored = scoredSchema.parse( + await dependencies.withLock((signal) => + dependencies.runCommand( + [ + "score", + used.id, + "--operation-id", + run.operationId, + ...(diffFile ? ["--diff-file", diffFile] : []), + ...(hasScreenshots ? ["--screenshots", screenshots] : []), + ...store, + ], + { ...credential, signal, timeoutMs: 10 * 60 * 1000 }, + ), + ), + ) + await dependencies.finish(run.id, { + state: "SUCCEEDED", + scoreId: scored.score.id, + aiCredits: formatAiCredits(scored.usage.nanoAiu), + copilotRequests: scored.usage.requests, + finishedAt: dependencies.now(), + }) + } catch (error) { + // An interrupted score stays running, so the next pass retries it with the same + // operation ID and the store doesn't charge twice for a score it already saved. + if (!(error instanceof LearningCommandError) || error.code === "cancelled") throw error + const spent = spentSchema.safeParse(error.result) + await dependencies.finish(run.id, { + state: "FAILED", + failureCode: error.code.slice(0, 60), + aiCredits: spent.success ? formatAiCredits(spent.data.usage.nanoAiu) : "0", + copilotRequests: spent.success ? spent.data.usage.requests : 0, + finishedAt: dependencies.now(), + }) + } + } + } finally { + await rm(temporary, { recursive: true, force: true }) + } + await dependencies.deleteRequest(readAt) + return "done" +} diff --git a/hub/server/integrations/github/create-github-actions-client/index.test.ts b/hub/server/integrations/github/create-github-actions-client/index.test.ts index 41e97a50c..89bcf467b 100644 --- a/hub/server/integrations/github/create-github-actions-client/index.test.ts +++ b/hub/server/integrations/github/create-github-actions-client/index.test.ts @@ -586,6 +586,24 @@ describe("createGitHubActionsClient", () => { await expect(client.getCommitAuthor("a".repeat(40))).rejects.toThrow(GitHubProviderRequestError) }) + it("reads a commit's diff, and nothing when it is too large to read whole", async () => { + const sha = "a".repeat(40) + const diff = "diff --git a/app.tsx b/app.tsx\n" + const fetch = respond((url, init) => { + expect(url.pathname).toBe(`/repositories/56/commits/${sha}`) + expect(init.headers).toMatchObject({ Accept: "application/vnd.github.diff" }) + return new Response(diff) + }) + const oversized = respond( + () => new Response("x", { headers: { "content-length": String(3_000_000) } }), + ) + + await expect(createGitHubActionsClient(input, { fetch }).getCommitDiff(sha)).resolves.toBe(diff) + await expect( + createGitHubActionsClient(input, { fetch: oversized }).getCommitDiff(sha), + ).resolves.toBeNull() + }) + it("downloads from the redirect without forwarding the token", async () => { const fetch = respond((url) => url.hostname === "api.github.com" diff --git a/hub/server/integrations/github/create-github-actions-client/index.ts b/hub/server/integrations/github/create-github-actions-client/index.ts index fce6b986e..ca56b2b53 100644 --- a/hub/server/integrations/github/create-github-actions-client/index.ts +++ b/hub/server/integrations/github/create-github-actions-client/index.ts @@ -159,6 +159,7 @@ export function createGitHubActionsClient( ...init, headers: { Accept: "application/vnd.github+json", + ...(init.headers as Record | undefined), Authorization: `Bearer ${authorization}`, "User-Agent": "Replica-Hub", "X-GitHub-Api-Version": "2022-11-28", @@ -315,6 +316,24 @@ export function createGitHubActionsClient( : null }, + /** + * Reads one commit's changes as a unified diff, for an evaluator judging the work. A diff + * too large to read whole returns null, since a partial one could mislead. + */ + async getCommitDiff(commitSha: string) { + if (!/^[0-9a-f]{40}$/.test(commitSha)) { + throw new GitHubProviderRequestError({ cause: new Error("Invalid commit SHA.") }) + } + const response = await send( + `${repositoryPath}/commits/${commitSha}`, + await installationToken(), + { headers: { Accept: "application/vnd.github.diff" } }, + ) + if (!response.ok) throw new GitHubCommitLookupError(response.status) + const bytes = await readBounded(response, 2_097_152) + return bytes === undefined ? null : bytes.toString("utf8") + }, + /** Lists branch heads without assuming a truncated response is a complete snapshot. */ async listBranchHeads(): Promise<{ branchName: string; commitSha: string }[]> { const heads: { branchName: string; commitSha: string }[] = [] diff --git a/hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts b/hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts index 44b4bb549..df70ccaae 100644 --- a/hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts +++ b/hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts @@ -4,7 +4,7 @@ export function saveRepositoryEvaluationSetting( database: Prisma.TransactionClient, repositoryId: string, data: - | { enabled: boolean } + | { enabled: boolean; evaluationGrantId: string | null } | { screenshotGrantId: string | null screenshotsChangedAt: Date diff --git a/hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts b/hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts new file mode 100644 index 000000000..617ac2cbb --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts @@ -0,0 +1,16 @@ +import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts" + +export function finishLearningEvaluationRun( + database: Pick, + runId: string, + input: { + aiCredits: Prisma.Decimal | string + copilotRequests: number + finishedAt: Date + } & ({ state: "SUCCEEDED"; scoreId: string } | { state: "FAILED"; failureCode: string }), +) { + return database.learningEvaluationRun.updateMany({ + where: { id: runId, state: "RUNNING" }, + data: input, + }) +} diff --git a/hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts b/hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts new file mode 100644 index 000000000..bc9f1f6ce --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts @@ -0,0 +1,18 @@ +import { randomUUID } from "node:crypto" + +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Starts scoring one used learning, or returns its earlier attempt. An attempt that never + * finished keeps its operation ID, so retrying it can't store a second score. + */ +export function startLearningEvaluationRun( + database: Pick, + input: { repositoryId: string; usedLearningId: string }, +) { + return database.learningEvaluationRun.upsert({ + where: { repositoryId_usedLearningId: input }, + create: { ...input, operationId: randomUUID() }, + update: {}, + }) +} diff --git a/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts new file mode 100644 index 000000000..09a7708df --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts @@ -0,0 +1,13 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** Adds up the AI credits every repository's scoring has spent since a moment. */ +export async function sumLearningEvaluationCredits( + database: Pick, + since: Date, +) { + const total = await database.learningEvaluationRun.aggregate({ + where: { createdAt: { gte: since } }, + _sum: { aiCredits: true }, + }) + return total._sum.aiCredits +} diff --git a/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts b/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts new file mode 100644 index 000000000..3ec1cdf59 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts @@ -0,0 +1,8 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function deleteExpiredLearningScoreRequests( + database: Pick, + cutoff: Date, +) { + return database.learningScoreRequest.deleteMany({ where: { createdAt: { lt: cutoff } } }) +} diff --git a/hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts b/hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts new file mode 100644 index 000000000..72639cbaf --- /dev/null +++ b/hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts @@ -0,0 +1,18 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Drops a score request once scoring has read it. Reports that arrive after reportedBefore + * keep the request, so their learnings are scored on the next pass. + */ +export function deleteLearningScoreRequest( + database: Pick, + input: { repositoryId: string; commitSha: string; reportedBefore: Date }, +) { + return database.learningScoreRequest.deleteMany({ + where: { + repositoryId: input.repositoryId, + commitSha: input.commitSha, + updatedAt: { lte: input.reportedBefore }, + }, + }) +} diff --git a/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts new file mode 100644 index 000000000..d638cd112 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { listReadyLearningScoreRequests } from "." + +describe("listReadyLearningScoreRequests", () => { + it("finds built commits past a page of commits that never built", async () => { + const built = "a".repeat(40) + const unbuilt = "b".repeat(40) + const repository = await prisma.repository.create({ + data: { + nameWithOwner: "team/scored", + defaultBranch: "main", + evaluationSetting: { create: { enabled: true, evaluationGrantId: "evaluation_1" } }, + }, + }) + const other = await prisma.repository.create({ + data: { + nameWithOwner: "team/other", + defaultBranch: "main", + evaluationSetting: { create: { enabled: true, evaluationGrantId: "evaluation_1" } }, + }, + }) + const prototype = await prisma.prototype.create({ + data: { repositoryId: repository.id, branchName: "empty-state", name: "Empty state" }, + }) + await prisma.build.create({ + data: { + prototypeId: prototype.id, + number: 1, + state: "successful", + commitSha: built, + startedAt: new Date("2026-12-01T00:00:00Z"), + finishedAt: new Date("2026-12-01T00:01:00Z"), + }, + }) + await prisma.learningScoreRequest.createMany({ + // IDs fix the reading order, so the unbuilt requests fill the first pages. + data: [ + { + id: "00000000-0000-4000-8000-000000000001", + repositoryId: repository.id, + commitSha: unbuilt, + }, + { id: "00000000-0000-4000-8000-000000000002", repositoryId: other.id, commitSha: built }, + { + id: "00000000-0000-4000-8000-000000000003", + repositoryId: repository.id, + commitSha: built, + }, + ], + }) + + await expect(listReadyLearningScoreRequests(prisma, 1)).resolves.toEqual([ + { repositoryId: repository.id, commitSha: built }, + ]) + }) +}) diff --git a/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts new file mode 100644 index 000000000..cf8c4b009 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts @@ -0,0 +1,48 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Lists commits an agent reported learning usage for that are ready to score: their + * repository can still be evaluated, and the commit has a successful Build there. The + * Build can land before or after the report, so either order ends up here. Requests are + * read in pages, so a pile of commits that never build can't hide ones that did. + */ +export async function listReadyLearningScoreRequests( + database: Pick, + limit = 100, +) { + const ready: Array<{ repositoryId: string; commitSha: string }> = [] + let cursor: string | undefined + while (ready.length < limit) { + const requests = await database.learningScoreRequest.findMany({ + where: { + repository: { + evaluationSetting: { enabled: true, evaluationGrantId: { not: null } }, + }, + }, + orderBy: { id: "asc" }, + take: limit, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + select: { id: true, repositoryId: true, commitSha: true }, + }) + if (requests.length === 0) break + cursor = requests.at(-1)!.id + const builds = await database.build.findMany({ + where: { + state: "successful", + commitSha: { in: requests.map((request) => request.commitSha) }, + prototype: { repositoryId: { in: requests.map((request) => request.repositoryId) } }, + }, + select: { commitSha: true, prototype: { select: { repositoryId: true } } }, + }) + const built = new Set( + builds.map((build) => `${build.prototype.repositoryId}:${build.commitSha}`), + ) + for (const request of requests) { + if (built.has(`${request.repositoryId}:${request.commitSha}`)) { + ready.push({ repositoryId: request.repositoryId, commitSha: request.commitSha }) + } + } + if (requests.length < limit) break + } + return ready.slice(0, limit) +} diff --git a/hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts b/hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts new file mode 100644 index 000000000..3c9939502 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts @@ -0,0 +1,16 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Remembers that an agent reported learning usage in a commit. A repeat report moves + * updatedAt forward, so a scoring job already running keeps the request for another pass. + */ +export function recordLearningScoreRequest( + database: Pick, + input: { repositoryId: string; commitSha: string }, +) { + return database.learningScoreRequest.upsert({ + where: { repositoryId_commitSha: input }, + create: input, + update: { updatedAt: new Date() }, + }) +} diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 6a3bd5bdb..3df3321c0 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -23,6 +23,7 @@ import { withLearningExecutionLock } from "../../integrations/postgres/with-lear import { findAgentRepository } from "../../repositories/agent-connections/find-agent-repository/index.ts" import { createAgentScreenshot } from "../../repositories/agent-screenshots/create-agent-screenshot/index.ts" import { getRepositoryEvaluationSetting } from "../../repositories/evaluation-settings/get-repository-evaluation-setting/index.ts" +import { recordLearningScoreRequest } from "../../repositories/learning-score-requests/record-learning-score-request/index.ts" import type { PrismaClient } from "../../generated/prisma/client.ts" import type { AgentConnectionRouteDependencies } from "./types.ts" @@ -206,6 +207,9 @@ export function agentConnectionRoutes( learning, learningsUrl: new URL(`/repositories/${repository.id}/learnings`, applicationOrigin).href, repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, + async requestScore(commitSha) { + await recordLearningScoreRequest(prisma, { repositoryId: repository.id, commitSha }) + }, async serialize(operation) { try { return await withLearningExecutionLock({ diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts index 555747978..89979bed9 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts @@ -1,14 +1,14 @@ import pino from "pino" import { describe, expect, it, vi } from "vitest" -import { changeScreenshotConsent } from "../../../../domains/learning/change-screenshot-consent" +import { changeEvaluationConsent } from "../../../../domains/learning/change-evaluation-consent" import { enqueueJob } from "../../../../integrations/bullmq/enqueue-job" import { prisma } from "../../../../integrations/prisma" import { getDatabaseUrl } from "../../../../../test/database/get-database-url" import { createLearningsRouteDependencies } from "." -vi.mock("../../../../domains/learning/change-screenshot-consent", () => ({ - changeScreenshotConsent: vi.fn(), +vi.mock("../../../../domains/learning/change-evaluation-consent", () => ({ + changeEvaluationConsent: vi.fn(), })) vi.mock("../../../../integrations/bullmq/create-job-queue", () => ({ createJobQueue: vi.fn(() => ({ close: vi.fn() })), @@ -16,7 +16,7 @@ vi.mock("../../../../integrations/bullmq/create-job-queue", () => ({ vi.mock("../../../../integrations/bullmq/enqueue-job", () => ({ enqueueJob: vi.fn() })) describe("evaluation settings", () => { - it("allows screenshots only while evaluations are on and removes them when evaluations stop", async () => { + it("grants evaluation consent while evaluations are on and withdraws it, with screenshots, when they stop", async () => { const provider = await prisma.authenticationProvider.create({ data: { key: "github", enabled: false }, }) @@ -65,15 +65,21 @@ describe("evaluation settings", () => { repositoryId: repository.id, }, }) - vi.mocked(changeScreenshotConsent).mockResolvedValueOnce("grant_1") - // Records what Hub showed at the moment the store grant was withdrawn. + // Records what Hub showed at the moment each store grant was withdrawn. let grantAtWithdrawal: string | null | undefined - vi.mocked(changeScreenshotConsent).mockImplementationOnce(async () => { - grantAtWithdrawal = ( - await prisma.repositoryEvaluationSetting.findUnique({ - where: { repositoryId: repository.id }, - }) - )?.screenshotGrantId + let evaluationAtWithdrawal: unknown + vi.mocked(changeEvaluationConsent).mockImplementation(async ({ allowed, source }) => { + if (allowed) return source === "agent_screenshots" ? "grant_1" : "evaluation_1" + const setting = await prisma.repositoryEvaluationSetting.findUnique({ + where: { repositoryId: repository.id }, + }) + if (source === "agent_screenshots") grantAtWithdrawal = setting?.screenshotGrantId + else { + evaluationAtWithdrawal = { + enabled: setting?.enabled, + evaluationGrantId: setting?.evaluationGrantId, + } + } return null }) const learnings = await createLearningsRouteDependencies( @@ -102,11 +108,22 @@ describe("evaluation settings", () => { enabled: false, screenshots: { allowed: false }, }) - expect(vi.mocked(changeScreenshotConsent).mock.lastCall?.[0]).toMatchObject({ + expect(vi.mocked(changeEvaluationConsent).mock.lastCall?.[0]).toMatchObject({ allowed: false, grantId: "grant_1", }) expect(grantAtWithdrawal).toBeNull() + expect(vi.mocked(changeEvaluationConsent)).toHaveBeenCalledWith( + expect.objectContaining({ + allowed: false, + grantId: "evaluation_1", + source: "hub_review_comments", + }), + ) + expect(evaluationAtWithdrawal).toEqual({ enabled: false, evaluationGrantId: "evaluation_1" }) + await expect( + prisma.repositoryEvaluationSetting.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toMatchObject({ evaluationGrantId: null }) expect(vi.mocked(enqueueJob).mock.lastCall?.[2]).toEqual({ repositoryId: repository.id, grantId: "grant_1", diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts index be0eba9f2..0ac5fedb8 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts @@ -18,9 +18,10 @@ import { learningRunJob } from "../../../../domains/learning/jobs/learning-run.t import { redactReviewCommentJob } from "../../../../domains/learning/jobs/redact-review-comment.ts" import type { ReviewCommentLearningSource } from "../../../../domains/learning/review-comment-learning-source/types.ts" import { readLearningConfiguration } from "../../../../domains/learning/read-learning-configuration/index.ts" -import { changeScreenshotConsent } from "../../../../domains/learning/change-screenshot-consent/index.ts" +import { changeEvaluationConsent } from "../../../../domains/learning/change-evaluation-consent/index.ts" import { deleteAgentScreenshotsJob } from "../../../../domains/learning/jobs/delete-agent-screenshots.ts" import { getRepositoryEvaluationSetting } from "../../../../repositories/evaluation-settings/get-repository-evaluation-setting/index.ts" +import { sumLearningEvaluationCredits } from "../../../../repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts" import { initializeEvaluationSetting } from "../../../../repositories/evaluation-settings/initialize-evaluation-setting/index.ts" import { saveRepositoryEvaluationSetting } from "../../../../repositories/evaluation-settings/save-repository-evaluation-setting/index.ts" import { updateEvaluationBudget } from "../../../../repositories/evaluation-settings/update-evaluation-budget/index.ts" @@ -52,6 +53,7 @@ import type { resolveRepositoryScope } from "../../product/resolve-repository-sc import { LearningsError } from "../errors.ts" import { isDefinitiveDecisionRejection } from "../is-definitive-decision-rejection/index.ts" import { runWithBoundedRetries } from "../../../../domains/identity/run-with-bounded-retries/index.ts" +import { startOfUtcMonth } from "../../../../utils/start-of-utc-month/index.ts" import type { CurrentSessionDependencies } from "../../auth/types.ts" import type { LearningsRouteDependencies } from "../types.ts" @@ -602,9 +604,11 @@ export async function createLearningsRouteDependencies( getEvaluationSettings: async (repositoryId) => { const budget = await initializeEvaluationSetting(prisma) const setting = await getRepositoryEvaluationSetting(prisma, repositoryId) + const used = await sumLearningEvaluationCredits(prisma, startOfUtcMonth(new Date())) return { // toFixed keeps tiny budgets in plain digits instead of forms like 1e-9. monthlyBudgetCredits: budget.monthlyBudgetCredits.toFixed(), + usedCredits: used?.toFixed() ?? "0", enabled: setting?.enabled ?? false, screenshots: { allowed: Boolean(setting?.screenshotGrantId), @@ -669,14 +673,45 @@ export async function createLearningsRouteDependencies( "Turn on automated evaluations before allowing screenshots.", ) } - if (enabled !== (setting?.enabled ?? false)) { - if ( - !(await withAuthority((transaction) => - saveRepositoryEvaluationSetting(transaction, input.repositoryId, { enabled }), - )) - ) { - return deny() - } + const evaluationGrantId = setting?.evaluationGrantId ?? null + function saveEnabled(next: string | null) { + return withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { + enabled, + evaluationGrantId: next, + }), + ) + } + // Scoring reads the review comments behind each learning, so the store must allow + // evaluation of them too. Turning off stops scoring first, but Hub keeps the grant + // until the store withdraws it, so saving again can retry a failed withdrawal. + if (enabled && !evaluationGrantId) { + const grantId = await changeEvaluationConsent({ + ...configuration, + actor: input.actor, + allowed: true, + grantId: null, + repositoryId: input.repositoryId, + repositoryScope, + signal, + source: "hub_review_comments", + }) + if (!(await saveEnabled(grantId))) return deny() + } else if (!enabled && evaluationGrantId) { + if (!(await saveEnabled(evaluationGrantId))) return deny() + await changeEvaluationConsent({ + ...configuration, + actor: input.actor, + allowed: false, + grantId: evaluationGrantId, + repositoryId: input.repositoryId, + repositoryScope, + signal, + source: "hub_review_comments", + }) + if (!(await saveEnabled(null))) return deny() + } else if (enabled !== (setting?.enabled ?? false)) { + if (!(await saveEnabled(evaluationGrantId))) return deny() } if (allowed === Boolean(grantId)) return function saveGrant(screenshotGrantId: string | null) { @@ -692,7 +727,7 @@ export async function createLearningsRouteDependencies( // failed withdrawal can't leave Hub serving them. The cleanup sweep still // deletes them, since their grant is no longer the active one. if (grantId && !allowed && !(await saveGrant(null))) return deny() - const nextGrantId = await changeScreenshotConsent({ + const nextGrantId = await changeEvaluationConsent({ ...configuration, actor: input.actor, allowed, @@ -700,6 +735,7 @@ export async function createLearningsRouteDependencies( repositoryId: input.repositoryId, repositoryScope, signal, + source: "agent_screenshots", }) if (allowed) { if (!(await saveGrant(nextGrantId))) return deny() diff --git a/hub/server/routes/api/learnings/evaluations/get/index.ts b/hub/server/routes/api/learnings/evaluations/get/index.ts index f21288768..fde867d22 100644 --- a/hub/server/routes/api/learnings/evaluations/get/index.ts +++ b/hub/server/routes/api/learnings/evaluations/get/index.ts @@ -55,8 +55,6 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { } response.json({ repository, - // Usage is counted once evaluations run against Builds. - usedCredits: "0", ...settings, permissions: { changeBudget, changeRepository }, }) diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index 2448538d9..561bd1d05 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -68,6 +68,7 @@ function dependencies( share: vi.fn().mockResolvedValue({ notice: "Shared across Hub." }), getEvaluationSettings: vi.fn().mockResolvedValue({ monthlyBudgetCredits: "0", + usedCredits: "0", enabled: false, screenshots: { allowed: false, changedBy: null, changedAt: null }, }), diff --git a/hub/server/routes/api/learnings/types.ts b/hub/server/routes/api/learnings/types.ts index f81ae74ff..43a59763d 100644 --- a/hub/server/routes/api/learnings/types.ts +++ b/hub/server/routes/api/learnings/types.ts @@ -53,6 +53,8 @@ export interface LearningActivityDay { export interface EvaluationSettings { monthlyBudgetCredits: string + /** What scoring has spent this calendar month in UTC, across every repository. */ + usedCredits: string enabled: boolean screenshots: { allowed: boolean; changedBy: string | null; changedAt: string | null } } diff --git a/hub/server/utils/format-ai-credits/index.ts b/hub/server/utils/format-ai-credits/index.ts new file mode 100644 index 000000000..f1285b934 --- /dev/null +++ b/hub/server/utils/format-ai-credits/index.ts @@ -0,0 +1,8 @@ +/** + * Writes Copilot's nano-AIU usage as AI credits in plain digits, so it can be stored and + * summed as a decimal without floating-point rounding. + */ +export function formatAiCredits(nanoAiu: number) { + const padded = nanoAiu.toString().padStart(10, "0") + return `${padded.slice(0, -9)}.${padded.slice(-9)}`.replace(/\.?0+$/, "") || "0" +} diff --git a/hub/server/utils/start-of-utc-month/index.ts b/hub/server/utils/start-of-utc-month/index.ts new file mode 100644 index 000000000..6409fb355 --- /dev/null +++ b/hub/server/utils/start-of-utc-month/index.ts @@ -0,0 +1,4 @@ +/** The first moment of a date's calendar month in UTC, where monthly budgets reset. */ +export function startOfUtcMonth(date: Date) { + return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1)) +} diff --git a/hub/server/workers/configuration.test.ts b/hub/server/workers/configuration.test.ts index 926a52616..0f332f9bc 100644 --- a/hub/server/workers/configuration.test.ts +++ b/hub/server/workers/configuration.test.ts @@ -28,6 +28,7 @@ describe("learning worker configuration", () => { "learning.run", "learning.redact-review-comment", "learning.delete-agent-screenshots", + "learning.score-applied-learnings", "synchronize-local-builds", "import-github-workflow-run", ]) diff --git a/hub/server/workers/configuration.ts b/hub/server/workers/configuration.ts index 8147085ec..6d22c4a3a 100644 --- a/hub/server/workers/configuration.ts +++ b/hub/server/workers/configuration.ts @@ -76,6 +76,7 @@ const jobProcessors: Record = { learning.run, learning.redact, learning.deleteScreenshots, + learning.score, createJobProcessor(getLocalBuildJobDefinition(), async () => { const { runLocalBuilds } = await import("../scripts/run-local-builds/index.ts") return await runLocalBuilds() diff --git a/hub/server/workers/github-recovery.test.ts b/hub/server/workers/github-recovery.test.ts index 679de006f..ca11a7a76 100644 --- a/hub/server/workers/github-recovery.test.ts +++ b/hub/server/workers/github-recovery.test.ts @@ -61,6 +61,7 @@ describe("GitHub recovery workers", () => { isAncestor: vi.fn(() => Promise.resolve(false)), getWorkflowRun: vi.fn(() => Promise.resolve(null)), getCommitAuthor: vi.fn(() => Promise.resolve(null)), + getCommitDiff: vi.fn(() => Promise.resolve(null)), listWorkflowRuns: vi.fn(() => Promise.resolve([])), listRunArtifacts: vi.fn(() => Promise.resolve([])), downloadArtifact: vi.fn(() => Promise.resolve({ status: "gone" as const })),