Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion hub/docs/learning-foundation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.
Expand Down
20 changes: 20 additions & 0 deletions hub/schema/learning-update-request.prisma
Original file line number Diff line number Diff line change
@@ -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")
}
25 changes: 25 additions & 0 deletions hub/schema/learning-update-run.prisma
Original file line number Diff line number Diff line change
@@ -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")
}
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions hub/schema/repository.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ model Repository {
learningEvaluationRuns LearningEvaluationRun[]
learningScoreRequests LearningScoreRequest[]
learningVerifications LearningReviewerVerification[]
learningUpdateRequests LearningUpdateRequest[]
learningUpdateRuns LearningUpdateRun[]
decisionModelConfiguration DecisionModelConfiguration?
decisionReviewSnapshot DecisionReviewSnapshot?
decisionTrainingJobs DecisionTrainingJob[]
Expand Down
117 changes: 111 additions & 6 deletions hub/server/domains/learning/create-learning-job-processors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@ 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"
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"
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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,
Expand All @@ -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")
Expand All @@ -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,
}
}
13 changes: 13 additions & 0 deletions hub/server/domains/learning/jobs/propose-learning-update.ts
Original file line number Diff line number Diff line change
@@ -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,
},
}
13 changes: 13 additions & 0 deletions hub/server/domains/learning/jobs/propose-learning-updates.ts
Original file line number Diff line number Diff line change
@@ -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,
},
}
Loading
Loading