From 3bd2b727d2559f7d17223467dc6c866869365cf1 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Thu, 26 Nov 2026 02:17:21 -0800 Subject: [PATCH 1/3] feat(hub): store learning update requests and runs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/schema/learning-update-request.prisma | 20 +++++++++ hub/schema/learning-update-run.prisma | 25 +++++++++++ .../migration.sql | 43 +++++++++++++++++++ hub/schema/repository.prisma | 2 + .../index.db.test.ts | 40 +++++++++++++++++ .../sum-learning-evaluation-credits/index.ts | 26 +++++++---- .../index.db.test.ts | 22 ++++++++++ .../delete-learning-update-request/index.ts | 14 ++++++ .../find-learning-update-request/index.ts | 11 +++++ .../list-learning-update-requests/index.ts | 9 ++++ .../record-learning-update-request/index.ts | 16 +++++++ .../index.db.test.ts | 36 ++++++++++++++++ .../index.ts | 15 +++++++ .../finish-learning-update-run/index.ts | 16 +++++++ .../start-learning-update-run/index.ts | 11 +++++ 15 files changed, 298 insertions(+), 8 deletions(-) create mode 100644 hub/schema/learning-update-request.prisma create mode 100644 hub/schema/learning-update-run.prisma create mode 100644 hub/schema/migrations/20261227090000_learning_update_runs/migration.sql create mode 100644 hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts create mode 100644 hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts create mode 100644 hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts create mode 100644 hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts create mode 100644 hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts create mode 100644 hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts create mode 100644 hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts create mode 100644 hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts create mode 100644 hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts create mode 100644 hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts diff --git a/hub/schema/learning-update-request.prisma b/hub/schema/learning-update-request.prisma new file mode 100644 index 00000000..b2f017fb --- /dev/null +++ b/hub/schema/learning-update-request.prisma @@ -0,0 +1,20 @@ +model LearningUpdateRequest { + // 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 + memoryId String @map("memory_id") @db.VarChar(255) + // Raised by each new score, so a check only drops the request version it saw. + revision Int @default(0) + + // 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, memoryId]) + @@map("learning_update_requests") +} diff --git a/hub/schema/learning-update-run.prisma b/hub/schema/learning-update-run.prisma new file mode 100644 index 00000000..43578f2e --- /dev/null +++ b/hub/schema/learning-update-run.prisma @@ -0,0 +1,25 @@ +model LearningUpdateRun { + // 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 + memoryId String @map("memory_id") @db.VarChar(255) + state LearningRunState @default(RUNNING) + result String? @db.VarChar(30) + copilotRequests Int @default(0) @map("copilot_requests") + aiCredits Decimal @default(0) @map("ai_credits") @db.Decimal(20, 9) + 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) + + @@index([createdAt]) + @@index([repositoryId, memoryId, createdAt]) + @@map("learning_update_runs") +} diff --git a/hub/schema/migrations/20261227090000_learning_update_runs/migration.sql b/hub/schema/migrations/20261227090000_learning_update_runs/migration.sql new file mode 100644 index 00000000..59fdfb11 --- /dev/null +++ b/hub/schema/migrations/20261227090000_learning_update_runs/migration.sql @@ -0,0 +1,43 @@ +-- CreateTable +CREATE TABLE "learning_update_requests" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "memory_id" VARCHAR(255) NOT NULL, + "revision" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_update_requests_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "learning_update_runs" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "memory_id" VARCHAR(255) NOT NULL, + "state" "LearningRunState" NOT NULL DEFAULT 'RUNNING', + "result" VARCHAR(30), + "copilot_requests" INTEGER NOT NULL DEFAULT 0, + "ai_credits" DECIMAL(20,9) NOT NULL DEFAULT 0, + "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_update_runs_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_update_requests_repository_id_memory_id_key" ON "learning_update_requests"("repository_id", "memory_id"); + +-- CreateIndex +CREATE INDEX "learning_update_runs_created_at_idx" ON "learning_update_runs"("created_at"); + +-- CreateIndex +CREATE INDEX "learning_update_runs_repository_id_memory_id_created_at_idx" ON "learning_update_runs"("repository_id", "memory_id", "created_at"); + +-- AddForeignKey +ALTER TABLE "learning_update_requests" ADD CONSTRAINT "learning_update_requests_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_update_runs" ADD CONSTRAINT "learning_update_runs_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index 5a20bd19..555707a4 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -13,6 +13,8 @@ model Repository { learningEvaluationRuns LearningEvaluationRun[] learningScoreRequests LearningScoreRequest[] learningVerifications LearningReviewerVerification[] + learningUpdateRequests LearningUpdateRequest[] + learningUpdateRuns LearningUpdateRun[] decisionModelConfiguration DecisionModelConfiguration? decisionReviewSnapshot DecisionReviewSnapshot? decisionTrainingJobs DecisionTrainingJob[] diff --git a/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts new file mode 100644 index 00000000..300cd209 --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { sumLearningEvaluationCredits } from "." + +describe("sumLearningEvaluationCredits", () => { + it("counts update suggestions against the same monthly budget as scoring", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/learning", defaultBranch: "main" }, + }) + const since = new Date("2026-12-01T00:00:00Z") + await prisma.learningEvaluationRun.create({ + data: { + repositoryId: repository.id, + usedLearningId: "used-1", + operationId: "00000000-0000-4000-8000-000000000001", + aiCredits: "1.25", + createdAt: new Date("2026-12-02T00:00:00Z"), + }, + }) + await prisma.learningUpdateRun.createMany({ + data: [ + { + repositoryId: repository.id, + memoryId: "memory-1", + aiCredits: "0.5", + createdAt: new Date("2026-12-03T00:00:00Z"), + }, + { + repositoryId: repository.id, + memoryId: "memory-1", + aiCredits: "9", + createdAt: new Date("2026-11-30T00:00:00Z"), + }, + ], + }) + + expect((await sumLearningEvaluationCredits(prisma, since))?.toString()).toBe("1.75") + }) +}) 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 index 09a7708d..69f05aac 100644 --- 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 @@ -1,13 +1,23 @@ -import type { PrismaClient } from "../../../generated/prisma/client.ts" +import { Prisma, type PrismaClient } from "../../../generated/prisma/client.ts" -/** Adds up the AI credits every repository's scoring has spent since a moment. */ +/** + * Adds up the AI credits every repository's scoring and update suggestions have spent + * since a moment, since both draw on the same monthly budget. + */ export async function sumLearningEvaluationCredits( - database: Pick, + database: Pick, since: Date, ) { - const total = await database.learningEvaluationRun.aggregate({ - where: { createdAt: { gte: since } }, - _sum: { aiCredits: true }, - }) - return total._sum.aiCredits + const [scores, updates] = await Promise.all([ + database.learningEvaluationRun.aggregate({ + where: { createdAt: { gte: since } }, + _sum: { aiCredits: true }, + }), + database.learningUpdateRun.aggregate({ + where: { createdAt: { gte: since } }, + _sum: { aiCredits: true }, + }), + ]) + if (!scores._sum.aiCredits && !updates._sum.aiCredits) return null + return new Prisma.Decimal(scores._sum.aiCredits ?? 0).plus(updates._sum.aiCredits ?? 0) } diff --git a/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts new file mode 100644 index 00000000..39030e60 --- /dev/null +++ b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { recordLearningUpdateRequest } from "../record-learning-update-request" +import { deleteLearningUpdateRequest } from "." + +describe("deleteLearningUpdateRequest", () => { + it("keeps a learning queued when a new score arrives while it is being checked", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/learning", defaultBranch: "main" }, + }) + const request = { repositoryId: repository.id, memoryId: "memory-1" } + const seen = await recordLearningUpdateRequest(prisma, request) + const latest = await recordLearningUpdateRequest(prisma, request) + + await deleteLearningUpdateRequest(prisma, seen) + const kept = await prisma.learningUpdateRequest.count() + await deleteLearningUpdateRequest(prisma, latest) + + expect([kept, await prisma.learningUpdateRequest.count()]).toEqual([1, 0]) + }) +}) diff --git a/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts new file mode 100644 index 00000000..312d1d06 --- /dev/null +++ b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts @@ -0,0 +1,14 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Drops an update request once its check is done. A score that lands during the check + * raises the revision, so the request stays and the learning is checked again. + */ +export function deleteLearningUpdateRequest( + database: Pick, + input: { id: string; revision: number }, +) { + return database.learningUpdateRequest.deleteMany({ + where: { id: input.id, revision: input.revision }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts b/hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts new file mode 100644 index 00000000..52791ae1 --- /dev/null +++ b/hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts @@ -0,0 +1,11 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function findLearningUpdateRequest( + database: Pick, + id: string, +) { + return database.learningUpdateRequest.findUnique({ + where: { id }, + select: { id: true, repositoryId: true, memoryId: true, revision: true }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts b/hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts new file mode 100644 index 00000000..758f7abd --- /dev/null +++ b/hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts @@ -0,0 +1,9 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** Lists learnings with new scores, oldest first, so none waits behind newer ones. */ +export function listLearningUpdateRequests(database: Pick) { + return database.learningUpdateRequest.findMany({ + orderBy: [{ createdAt: "asc" }, { id: "asc" }], + select: { id: true }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts b/hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts new file mode 100644 index 00000000..59bec9e0 --- /dev/null +++ b/hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts @@ -0,0 +1,16 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Remembers that a learning has a new score, so the daily job checks it for a suggested + * update. A repeat raises the revision, so a check already running keeps the request. + */ +export function recordLearningUpdateRequest( + database: Pick, + input: { repositoryId: string; memoryId: string }, +) { + return database.learningUpdateRequest.upsert({ + where: { repositoryId_memoryId: input }, + create: input, + update: { revision: { increment: 1 } }, + }) +} diff --git a/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts new file mode 100644 index 00000000..8a11c2af --- /dev/null +++ b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { closeAbandonedLearningUpdateRuns } from "." + +describe("closeAbandonedLearningUpdateRuns", () => { + it("closes unfinished checks as interrupted and leaves finished ones alone", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/learning", defaultBranch: "main" }, + }) + const stale = await prisma.learningUpdateRun.create({ + data: { repositoryId: repository.id, memoryId: "memory-1" }, + }) + const finished = await prisma.learningUpdateRun.create({ + data: { + repositoryId: repository.id, + memoryId: "memory-2", + state: "SUCCEEDED", + result: "no_change", + }, + }) + const finishedAt = new Date("2026-12-27T03:00:00Z") + + await closeAbandonedLearningUpdateRuns(prisma, finishedAt) + + const runs = await prisma.learningUpdateRun.findMany({ + select: { id: true, state: true, failureCode: true, finishedAt: true }, + }) + expect(runs).toEqual( + expect.arrayContaining([ + { id: stale.id, state: "FAILED", failureCode: "interrupted", finishedAt }, + { id: finished.id, state: "SUCCEEDED", failureCode: null, finishedAt: null }, + ]), + ) + }) +}) diff --git a/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts new file mode 100644 index 00000000..e2154a72 --- /dev/null +++ b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts @@ -0,0 +1,15 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Closes update checks left running by a stopped worker. The package can't resume a + * check, so they are recorded as interrupted. + */ +export function closeAbandonedLearningUpdateRuns( + database: Pick, + finishedAt: Date, +) { + return database.learningUpdateRun.updateMany({ + where: { state: "RUNNING" }, + data: { state: "FAILED", failureCode: "interrupted", finishedAt }, + }) +} diff --git a/hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts b/hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts new file mode 100644 index 00000000..d0ccbc57 --- /dev/null +++ b/hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts @@ -0,0 +1,16 @@ +import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts" + +export function finishLearningUpdateRun( + database: Pick, + runId: string, + input: { + aiCredits: Prisma.Decimal | string + copilotRequests: number + finishedAt: Date + } & ({ state: "SUCCEEDED"; result: string } | { state: "FAILED"; failureCode: string }), +) { + return database.learningUpdateRun.updateMany({ + where: { id: runId, state: "RUNNING" }, + data: input, + }) +} diff --git a/hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts b/hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts new file mode 100644 index 00000000..b3ecdc9d --- /dev/null +++ b/hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts @@ -0,0 +1,11 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function startLearningUpdateRun( + database: Pick, + input: { repositoryId: string; memoryId: string }, +) { + return database.learningUpdateRun.create({ + data: { repositoryId: input.repositoryId, memoryId: input.memoryId }, + select: { id: true }, + }) +} From b06a25528965176d56b3d307bec7a1077f3e4628 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Thu, 26 Nov 2026 02:17:21 -0800 Subject: [PATCH 2/3] feat(hub): suggest learning updates daily Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../create-learning-job-processors/index.ts | 117 +++++++++++++++++- .../learning/jobs/propose-learning-update.ts | 13 ++ .../learning/jobs/propose-learning-updates.ts | 13 ++ .../propose-learning-update/index.test.ts | 104 ++++++++++++++++ .../learning/propose-learning-update/index.ts | 102 +++++++++++++++ .../score-applied-learnings/index.test.ts | 75 +++++++++-- .../learning/score-applied-learnings/index.ts | 53 ++++---- hub/server/workers/configuration.ts | 9 ++ 8 files changed, 452 insertions(+), 34 deletions(-) create mode 100644 hub/server/domains/learning/jobs/propose-learning-update.ts create mode 100644 hub/server/domains/learning/jobs/propose-learning-updates.ts create mode 100644 hub/server/domains/learning/propose-learning-update/index.test.ts create mode 100644 hub/server/domains/learning/propose-learning-update/index.ts 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 32f5fcbb..446097c3 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -12,6 +12,8 @@ import { getLearningRepositoryScope } from "../get-learning-repository-scope/ind import { deleteAgentScreenshotsJob } from "../jobs/delete-agent-screenshots.ts" import { learningRunJob } from "../jobs/learning-run.ts" import { automaticLearningRunPriority } from "../jobs/priorities.ts" +import { proposeLearningUpdateJob } from "../jobs/propose-learning-update.ts" +import { proposeLearningUpdatesJob } from "../jobs/propose-learning-updates.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" @@ -19,6 +21,7 @@ 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 { proposeLearningUpdate } from "../propose-learning-update/index.ts" import { processReviewCommentRedaction } from "../process-review-comment-redaction/index.ts" import { redactLegacyReviewComment } from "../redact-legacy-review-comment/index.ts" import { recoverLearningRunJobs } from "../recover-learning-run-jobs/index.ts" @@ -51,6 +54,13 @@ import { sumLearningEvaluationCredits } from "../../../repositories/learning-eva import { deleteExpiredLearningScoreRequests } from "../../../repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts" import { listLearningReviewerVerifications } from "../../../repositories/learning-reviewer-verifications/list-learning-reviewer-verifications/index.ts" import { deleteLearningScoreRequest } from "../../../repositories/learning-score-requests/delete-learning-score-request/index.ts" +import { deleteLearningUpdateRequest } from "../../../repositories/learning-update-requests/delete-learning-update-request/index.ts" +import { findLearningUpdateRequest } from "../../../repositories/learning-update-requests/find-learning-update-request/index.ts" +import { listLearningUpdateRequests } from "../../../repositories/learning-update-requests/list-learning-update-requests/index.ts" +import { recordLearningUpdateRequest } from "../../../repositories/learning-update-requests/record-learning-update-request/index.ts" +import { closeAbandonedLearningUpdateRuns } from "../../../repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts" +import { finishLearningUpdateRun } from "../../../repositories/learning-update-runs/finish-learning-update-run/index.ts" +import { startLearningUpdateRun } from "../../../repositories/learning-update-runs/start-learning-update-run/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" @@ -535,6 +545,12 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg }) }) + async function withinBudget(prisma: PrismaClient) { + const budget = (await initializeEvaluationSetting(prisma)).monthlyBudgetCredits + const used = await sumLearningEvaluationCredits(prisma, startOfUtcMonth(new Date())) + return used ? used.lessThan(budget) : budget.greaterThan(0) + } + const score = createJobProcessor(scoreAppliedLearningsJob, async (request, context) => { const { configuration, databaseUrl, prisma } = await dependencies() const repository = { repositoryId: request.repositoryId, commitSha: request.commitSha } @@ -600,6 +616,8 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg const read = await (await artifactStorage()).read(storageKey) return read.status === "ok" ? read.bytes : null }, + requestUpdate: (memoryId) => + recordLearningUpdateRequest(prisma, { repositoryId: request.repositoryId, memoryId }), runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, @@ -614,11 +632,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg trigger, }), verifications: () => listLearningReviewerVerifications(prisma, repository), - withinBudget: async () => { - const budget = (await initializeEvaluationSetting(prisma)).monthlyBudgetCredits - const used = await sumLearningEvaluationCredits(prisma, startOfUtcMonth(new Date())) - return used ? used.lessThan(budget) : budget.greaterThan(0) - }, + withinBudget: () => withinBudget(prisma), withLock: (operation) => withLearningExecutionLock({ databaseUrl, run: operation }), }) if (result === "paused") @@ -636,5 +650,96 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg } }) - return { run, scheduledRun, recover, redact, schedule, deleteScreenshots, score } + // The daily job only queues one check per flagged learning, so other scheduled work + // runs between checks and one repository's failure doesn't hold up the rest. + const proposeUpdates = createJobProcessor(proposeLearningUpdatesJob, async () => { + const { databaseUrl, prisma } = await dependencies() + const queue = createJobQueue({ name: "scheduled", databaseUrl, logger }) + try { + for (const request of await listLearningUpdateRequests(prisma)) + await enqueueRecoverableJob( + queue, + proposeLearningUpdateJob, + { requestId: request.id }, + `learning-update-${request.id}`, + { priority: automaticLearningRunPriority }, + ) + } finally { + await queue.close() + } + }) + + const proposeUpdate = createJobProcessor(proposeLearningUpdateJob, async (input, context) => { + const { configuration, databaseUrl, prisma } = await dependencies() + const request = await findLearningUpdateRequest(prisma, input.requestId) + if (!request) return + try { + const result = await proposeLearningUpdate(request, { + closeAbandoned: (finishedAt) => closeAbandonedLearningUpdateRuns(prisma, finishedAt), + credential: async () => { + if (!(await copilotUsable())) return null + return configuration.copilotCredentialProvider.getCredential() + }, + deleteRequest: (observed) => deleteLearningUpdateRequest(prisma, observed), + finish: (runId, finished) => finishLearningUpdateRun(prisma, runId, finished), + // Drafting needs the store's evaluation grant, like scoring, and a repository + // Hub can still reach. + isEnabled: (repositoryId) => + prisma.$transaction(async (transaction) => { + await lockGitHubRepositoryAccessState(transaction) + const setting = await getRepositoryEvaluationSetting(transaction, repositoryId) + return ( + Boolean(setting?.enabled && setting.evaluationGrantId) && + (await isLearningRunRepositoryAvailable(transaction, repositoryId, true)) + ) + }), + now: () => new Date(), + prepare: async (repositoryId) => + learningStoreArguments( + await prepareLearningStore({ + applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, + repositoryKey: repositoryId, + repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), + root: configuration.root, + staticDirectories: configuration.staticDirectories, + }), + ), + runCommand: (arguments_, options) => + runLearningCommand(arguments_, { + cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, + nodePath: configuration.nodePath, + ...options, + }), + start: (started) => startLearningUpdateRun(prisma, started), + withinBudget: () => withinBudget(prisma), + withLock: (operation) => withLearningExecutionLock({ databaseUrl, run: operation }), + }) + if (result === "paused") + logger.info( + { repositoryId: request.repositoryId }, + "Learning update suggestions are 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, + proposeUpdates, + proposeUpdate, + } } diff --git a/hub/server/domains/learning/jobs/propose-learning-update.ts b/hub/server/domains/learning/jobs/propose-learning-update.ts new file mode 100644 index 00000000..09148f53 --- /dev/null +++ b/hub/server/domains/learning/jobs/propose-learning-update.ts @@ -0,0 +1,13 @@ +import { z } from "zod" + +import { automaticLearningRunPriority } from "./priorities.ts" + +export const proposeLearningUpdateJob = { + name: "learning.propose-update", + schema: z.object({ requestId: z.uuid() }).strict(), + options: { + attempts: 3, + backoff: { type: "exponential", delay: 60_000 }, + priority: automaticLearningRunPriority, + }, +} diff --git a/hub/server/domains/learning/jobs/propose-learning-updates.ts b/hub/server/domains/learning/jobs/propose-learning-updates.ts new file mode 100644 index 00000000..72e3eac7 --- /dev/null +++ b/hub/server/domains/learning/jobs/propose-learning-updates.ts @@ -0,0 +1,13 @@ +import { z } from "zod" + +import { automaticLearningRunPriority } from "./priorities.ts" + +export const proposeLearningUpdatesJob = { + name: "learning.propose-updates", + schema: z.object({}).strict(), + options: { + attempts: 3, + backoff: { type: "exponential", delay: 60_000 }, + priority: automaticLearningRunPriority, + }, +} diff --git a/hub/server/domains/learning/propose-learning-update/index.test.ts b/hub/server/domains/learning/propose-learning-update/index.test.ts new file mode 100644 index 00000000..4bc80763 --- /dev/null +++ b/hub/server/domains/learning/propose-learning-update/index.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi } from "vitest" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors" +import { proposeLearningUpdate } from "." + +async function withLock(operation: (signal: AbortSignal) => Promise) { + return await operation(new AbortController().signal) +} + +const request = { id: "request-1", repositoryId: "repository-1", memoryId: "memory-1", revision: 2 } + +describe("proposeLearningUpdate", () => { + it("records the check's result and cost, then drops the flag it saw", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn(() => + Promise.resolve({ state: "proposed", usage: { requests: 1, nanoAiu: 500_000_000 } }), + ) + + const result = await proposeLearningUpdate(request, { + closeAbandoned: () => Promise.resolve(), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-27T03:00:00Z"), + prepare: () => Promise.resolve(["--store", "hub"]), + runCommand, + start: () => Promise.resolve({ id: "run-1" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("done") + expect(runCommand.mock.calls[0]).toEqual([ + ["propose-update", "memory-1", "--store", "hub"], + expect.objectContaining({ githubToken: "token" }), + ]) + expect(finish).toHaveBeenCalledWith("run-1", { + state: "SUCCEEDED", + result: "proposed", + aiCredits: "0.5", + copilotRequests: 1, + finishedAt: new Date("2026-12-27T03:00:00Z"), + }) + expect(deleteRequest).toHaveBeenCalledWith(request) + }) + + it("keeps the flag when Copilot is down, after recording what the attempt spent", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + + const result = await proposeLearningUpdate(request, { + closeAbandoned: () => Promise.resolve(), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-27T03:00:00Z"), + prepare: () => Promise.resolve([]), + runCommand: () => + Promise.reject( + new LearningCommandError("unavailable", "Copilot is unavailable.", { + result: { usage: { requests: 1, nanoAiu: 0 } }, + }), + ), + start: () => Promise.resolve({ id: "run-1" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("paused") + expect(finish).toHaveBeenCalledWith( + "run-1", + expect.objectContaining({ state: "FAILED", failureCode: "unavailable", copilotRequests: 1 }), + ) + expect(deleteRequest).not.toHaveBeenCalled() + }) + + it("closes abandoned checks and drops the flag once evaluations are off", async () => { + const closeAbandoned = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn() + + const result = await proposeLearningUpdate(request, { + closeAbandoned, + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish: () => Promise.resolve(), + isEnabled: () => Promise.resolve(false), + now: () => new Date("2026-12-27T03:00:00Z"), + prepare: () => Promise.resolve([]), + runCommand, + start: () => Promise.resolve({ id: "run-1" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("done") + expect(closeAbandoned).toHaveBeenCalledWith(new Date("2026-12-27T03:00:00Z")) + expect(runCommand).not.toHaveBeenCalled() + expect(deleteRequest).toHaveBeenCalledWith(request) + }) +}) diff --git a/hub/server/domains/learning/propose-learning-update/index.ts b/hub/server/domains/learning/propose-learning-update/index.ts new file mode 100644 index 00000000..a4a5c357 --- /dev/null +++ b/hub/server/domains/learning/propose-learning-update/index.ts @@ -0,0 +1,102 @@ +import { z } from "zod" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { formatAiCredits } from "../../../utils/format-ai-credits/index.ts" + +const spentSchema = z + .object({ + usage: z + .object({ + requests: z.number().int().nonnegative(), + nanoAiu: z.number().int().nonnegative(), + }) + .loose(), + }) + .loose() +const proposedSchema = spentSchema.extend({ + state: z.enum(["insufficient_evidence", "up_to_date", "no_change", "proposed"]), +}) + +type Request = { id: string; repositoryId: string; memoryId: string; revision: number } + +/** + * Checks one flagged learning for a suggested update and records what the check cost, + * even when it fails, so spending is never undercounted. Returns "paused" when Copilot or + * the budget is unavailable, so the flag waits for the next day. + */ +export async function proposeLearningUpdate( + request: Request, + dependencies: { + closeAbandoned(finishedAt: Date): Promise + credential(): Promise<{ githubToken?: string } | null> + deleteRequest(request: Request): Promise + finish( + runId: string, + input: { aiCredits: string; copilotRequests: number; finishedAt: Date } & ( + { state: "SUCCEEDED"; result: string } | { state: "FAILED"; failureCode: string } + ), + ): Promise + isEnabled(repositoryId: string): Promise + now(): Date + prepare(repositoryId: string): Promise + runCommand( + arguments_: string[], + options: { githubToken?: string; signal: AbortSignal; timeoutMs?: number }, + ): Promise + start(input: { repositoryId: string; memoryId: string }): Promise<{ id: string }> + withinBudget(): Promise + withLock(operation: (signal: AbortSignal) => Promise): Promise + }, +): Promise<"done" | "paused"> { + // The ID is passed to the package as an argument, so it must never read as an option. + if (request.memoryId.startsWith("-")) { + await dependencies.deleteRequest(request) + return "done" + } + // Installation tokens expire within an hour, so each check asks for a fresh one. + const credential = await dependencies.credential() + if (!credential) return "paused" + const store = await dependencies.prepare(request.repositoryId) + const outcome = await dependencies.withLock(async (signal) => { + // Runs are only written under this lock, so any still running were abandoned. + await dependencies.closeAbandoned(dependencies.now()) + // Checked under the lock, so turning evaluations off or removing the repository stops + // the check, and a score running at the same time can't overspend the budget. + if (!(await dependencies.isEnabled(request.repositoryId))) return "disabled" + if (!(await dependencies.withinBudget())) return "paused" + const run = await dependencies.start(request) + try { + const proposed = proposedSchema.parse( + await dependencies.runCommand(["propose-update", request.memoryId, ...store], { + ...credential, + signal, + timeoutMs: 10 * 60 * 1000, + }), + ) + await dependencies.finish(run.id, { + state: "SUCCEEDED", + result: proposed.state, + aiCredits: formatAiCredits(proposed.usage.nanoAiu), + copilotRequests: proposed.usage.requests, + finishedAt: dependencies.now(), + }) + return "done" + } catch (error) { + 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(), + }) + // An outage says nothing about the learning, so its flag waits for Copilot. + return error.code === "unavailable" || error.code === "unauthorized" ? "paused" : "done" + } + }) + if (outcome === "paused") return "paused" + // Turning evaluations off means nothing more is suggested, so the flag is dropped too. + await dependencies.deleteRequest(request) + return "done" +} diff --git a/hub/server/domains/learning/score-applied-learnings/index.test.ts b/hub/server/domains/learning/score-applied-learnings/index.test.ts index c4567487..5169b6aa 100644 --- a/hub/server/domains/learning/score-applied-learnings/index.test.ts +++ b/hub/server/domains/learning/score-applied-learnings/index.test.ts @@ -13,7 +13,9 @@ describe("scoreAppliedLearnings", () => { 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.resolve({ + reports: [{ used: [{ id: "learning-1", memoryId: "memory-learning-1" }] }], + }) } return Promise.reject( new LearningCommandError("copilot_failed", "Copilot stopped.", { @@ -32,6 +34,7 @@ describe("scoreAppliedLearnings", () => { prepare: () => Promise.resolve(["--store", "hub"]), readDiff: () => Promise.resolve(null), readScreenshot: () => Promise.resolve(null), + requestUpdate: () => Promise.resolve(), runCommand, start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), withinBudget: () => Promise.resolve(true), @@ -68,6 +71,7 @@ describe("scoreAppliedLearnings", () => { prepare: () => Promise.resolve([]), readDiff: () => Promise.resolve(null), readScreenshot: () => Promise.resolve(null), + requestUpdate: () => Promise.resolve(), runCommand, start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), withinBudget: () => Promise.resolve(false), @@ -85,7 +89,9 @@ describe("scoreAppliedLearnings", () => { 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.resolve({ + reports: [{ used: [{ id: "learning-1", memoryId: "memory-learning-1" }] }], + }) } return Promise.reject(new LearningCommandError("cancelled", "The worker stopped.")) }) @@ -101,6 +107,7 @@ describe("scoreAppliedLearnings", () => { prepare: () => Promise.resolve([]), readDiff: () => Promise.resolve(null), readScreenshot: () => Promise.resolve(null), + requestUpdate: () => Promise.resolve(), runCommand, start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), withinBudget: () => Promise.resolve(true), @@ -113,7 +120,7 @@ describe("scoreAppliedLearnings", () => { }) it("scores a learning once more only with its own prototype's verification", async () => { - const deleteRequest = vi.fn(() => Promise.resolve()) + const requestUpdate = vi.fn(() => Promise.resolve()) const start = vi.fn((usedLearningId: string, trigger: string) => Promise.resolve({ id: `run-${trigger}`, operationId: `op-${trigger}`, state: "RUNNING" }), ) @@ -121,24 +128,34 @@ describe("scoreAppliedLearnings", () => { if (arguments_[0] === "usage") { return Promise.resolve({ reports: [ - { prototypeId: "prototype-2", used: [{ id: "learning-1" }] }, - { prototypeId: "prototype-1", used: [{ id: "learning-2" }] }, + { + prototypeId: "prototype-2", + used: [{ id: "learning-1", memoryId: "memory-learning-1" }], + }, + { + prototypeId: "prototype-1", + used: [{ id: "learning-2", memoryId: "memory-learning-2" }], + }, ], }) } - return Promise.resolve({ score: { id: "score-1" }, usage: { requests: 1, nanoAiu: 0 } }) + return Promise.resolve({ + score: { id: "score-1", memoryId: `memory-${arguments_[1]}` }, + usage: { requests: 1, nanoAiu: 0 }, + }) }) await scoreAppliedLearnings({ commitSha: "a".repeat(40), credential: () => Promise.resolve({ githubToken: "token" }), - deleteRequest, + deleteRequest: () => Promise.resolve(), finish: () => Promise.resolve(), isEnabled: () => Promise.resolve(true), now: () => new Date(), prepare: () => Promise.resolve([]), readDiff: () => Promise.resolve(null), readScreenshot: () => Promise.resolve(null), + requestUpdate, runCommand, start, withinBudget: () => Promise.resolve(true), @@ -165,5 +182,49 @@ describe("scoreAppliedLearnings", () => { ], expect.anything(), ) + // Each new score asks the daily job to check its learning's wording. + expect(requestUpdate.mock.calls).toEqual([ + ["memory-learning-1"], + ["memory-learning-2"], + ["memory-learning-2"], + ]) + }) + + it("keeps the run open when the score names a different learning than the one used", async () => { + const finish = vi.fn(() => Promise.resolve()) + const requestUpdate = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "usage") { + return Promise.resolve({ + reports: [{ used: [{ id: "learning-1", memoryId: "memory-learning-1" }] }], + }) + } + return Promise.resolve({ + score: { id: "score-1", memoryId: "memory-other" }, + usage: { requests: 1, nanoAiu: 0 }, + }) + }) + + await expect( + scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest: () => Promise.resolve(), + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + requestUpdate, + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + verifications: () => Promise.resolve([]), + withLock, + }), + ).rejects.toThrow("different learning") + expect(requestUpdate).not.toHaveBeenCalled() + expect(finish).not.toHaveBeenCalled() }) }) diff --git a/hub/server/domains/learning/score-applied-learnings/index.ts b/hub/server/domains/learning/score-applied-learnings/index.ts index b8965c8a..15a5e0ea 100644 --- a/hub/server/domains/learning/score-applied-learnings/index.ts +++ b/hub/server/domains/learning/score-applied-learnings/index.ts @@ -23,6 +23,7 @@ const usageSchema = z .min(1) .max(255) .refine((id) => !id.startsWith("-")), + memoryId: z.string().min(1).max(255), before: screenshotSchema.optional(), after: screenshotSchema.optional(), }) @@ -44,7 +45,7 @@ const spentSchema = z }) .loose() const scoredSchema = spentSchema.extend({ - score: z.object({ id: z.string().min(1).max(255) }).loose(), + score: z.object({ id: z.string().min(1).max(255), memoryId: z.string().min(1).max(255) }).loose(), }) /** @@ -54,7 +55,8 @@ const scoredSchema = spentSchema.extend({ * the budget is unavailable, so the request is kept and tried again later. When a reviewer * verified the commit, each learning is scored once more with that verification, and the * first score is kept. A report that names a prototype gets only that prototype's - * verification, since two prototypes can share a commit. + * verification, since two prototypes can share a commit. Each new score flags its learning + * so the daily job checks whether its wording should change. */ export async function scoreAppliedLearnings(dependencies: { commitSha: string @@ -71,6 +73,7 @@ export async function scoreAppliedLearnings(dependencies: { prepare(): Promise readDiff(): Promise readScreenshot(sha256: string): Promise + requestUpdate(memoryId: string): Promise runCommand( arguments_: string[], options: { githubToken?: string; signal: AbortSignal; timeoutMs?: number }, @@ -117,7 +120,6 @@ export async function scoreAppliedLearnings(dependencies: { for (const [index, { used, trigger, verifiedAt }] of attempts.entries()) { const run = await dependencies.start(used.id, trigger) 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") @@ -138,24 +140,33 @@ export async function scoreAppliedLearnings(dependencies: { 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] : []), - // The package wants microsecond timestamps. - ...(verifiedAt ? ["--reviewer-verified-at", verifiedAt.toISOString()] : []), - ...store, - ], - { ...credential, signal, timeoutMs: 10 * 60 * 1000 }, - ), - ), - ) + const output = await dependencies.withLock(async (signal) => { + // Checked under the lock, so an update check running at the same time can't + // overspend the budget. + if (!(await dependencies.withinBudget())) return null + return await dependencies.runCommand( + [ + "score", + used.id, + "--operation-id", + run.operationId, + ...(diffFile ? ["--diff-file", diffFile] : []), + ...(hasScreenshots ? ["--screenshots", screenshots] : []), + // The package wants microsecond timestamps. + ...(verifiedAt ? ["--reviewer-verified-at", verifiedAt.toISOString()] : []), + ...store, + ], + { ...credential, signal, timeoutMs: 10 * 60 * 1000 }, + ) + }) + if (output === null) return "paused" + const scored = scoredSchema.parse(output) + // The score must be for the learning that was used, so a wrong ID can't send + // another learning's text to Copilot. Failing leaves the run to be retried. + if (scored.score.memoryId !== used.memoryId) + throw new Error("The score names a different learning than the one used.") + // Flagged before the run closes, since a closed run is never scored again. + await dependencies.requestUpdate(used.memoryId) await dependencies.finish(run.id, { state: "SUCCEEDED", scoreId: scored.score.id, diff --git a/hub/server/workers/configuration.ts b/hub/server/workers/configuration.ts index 6d22c4a3..e5e44c92 100644 --- a/hub/server/workers/configuration.ts +++ b/hub/server/workers/configuration.ts @@ -14,6 +14,7 @@ import { } from "../domains/decision-model/jobs/reconcile-runtime-deletions.ts" import { createLearningJobProcessors } from "../domains/learning/create-learning-job-processors/index.ts" import { scheduledMaintenancePriority } from "../domains/learning/jobs/priorities.ts" +import { proposeLearningUpdatesJob } from "../domains/learning/jobs/propose-learning-updates.ts" import { recoverLearningRunsJob } from "../domains/learning/jobs/recover-learning-runs.ts" import { scheduleLearningRunsJob } from "../domains/learning/jobs/schedule-learning-runs.ts" import { getLocalBuildJobDefinition } from "../domains/local-builds/get-local-build-job-definition/index.ts" @@ -90,6 +91,8 @@ const jobProcessors: Record = { decision.reconcileDeletions, learning.recover, learning.schedule, + learning.proposeUpdates, + learning.proposeUpdate, createJobProcessor(githubInstallationReconciliation, reconcileGitHubInstallation), createJobProcessor(githubBuildImportRetry, retryGitHubBuildsAwaitingImport), createJobProcessor(githubWorkflowRunDiscovery, discoverGitHubWorkflowRunsJob), @@ -148,6 +151,12 @@ export const jobSchedules: { payload: {}, repeat: { pattern: "0 2 * * *", tz: "UTC" }, }, + { + id: "learning-update-daily", + definition: proposeLearningUpdatesJob, + payload: {}, + repeat: { pattern: "0 3 * * *", tz: "UTC" }, + }, { id: "github-installation-reconciliation", definition: githubInstallationReconciliation, From 452ce5201621136d90ef4a238f58496380bee01f Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Thu, 26 Nov 2026 02:17:21 -0800 Subject: [PATCH 3/3] docs(hub): explain daily learning update suggestions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/docs/learning-foundation.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index ee360708..166300c5 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -151,7 +151,7 @@ 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 counts every score attempt since the start of the month in UTC, including attempts that fail. A budget of 0 means nothing is scored. +- 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 and every update check since the start of the month in UTC, including attempts that fail. A budget of 0 means nothing is scored or checked. - 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. @@ -175,6 +175,16 @@ When the person who left review feedback resolves their own thread, Hub treats t - The scorer gets only the time of the verification, never the thread's text. - The re-score follows the same budget, retry, and lock rules as the first score. +### Suggesting learning updates + +Each new score flags its learning for a check. Once a day at 03:00 UTC, a job queues one check per flagged learning, oldest first, at the same low priority as automatic learning runs. Each check runs on its own, so other scheduled work runs in between and one repository's failure doesn't hold up the rest. The learning package decides whether the same issue keeps coming up in enough Builds and, only then, asks Copilot to draft new wording. Hub records each check's result and cost. For example, two Builds score "Use the shared empty state" low because it never says where the empty state goes, so the check keeps a suggestion that names the position. + +- A suggestion only waits for review. Agents keep getting the current wording until someone applies a change. +- Each check runs under the learning execution lock. It confirms evaluations are still on, the repository is still connected, and the budget remains before it starts. +- When the budget runs out or Copilot is unavailable, the check keeps its flag for the next day. A learning scored again during its check stays flagged too. +- Flags for repositories with evaluations off or no longer connected are dropped. +- A check can't be resumed. One interrupted by a worker stopping is recorded as interrupted by the next check, and it may have spent credits Hub didn't see. + ### Observed outcomes An active learning's detail view lists how later Builds did with its current wording, newest first. Each entry reads a score as one result. A score where the agent didn't clearly follow the guidance is "Inconclusive". Otherwise a score of 3 or 4 "Supports the guidance" and 1 or 2 is a "Possible concern". The entry shows the scorer's issue, or its reasoning when there is no issue, and links to the Build it judged. For example, "Possible concern · Automated assessment · Checkout, Build 12" with "The rule did not say where the label goes." A score made after a reviewer verified the work reads "Reviewer-confirmed" instead, and replaces the earlier score for the same use.