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
13 changes: 12 additions & 1 deletion hub/docs/learning-foundation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
26 changes: 26 additions & 0 deletions hub/schema/learning-evaluation-run.prisma
Original file line number Diff line number Diff line change
@@ -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")
}
19 changes: 19 additions & 0 deletions hub/schema/learning-score-request.prisma
Original file line number Diff line number Diff line change
@@ -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")
}
Original file line number Diff line number Diff line change
@@ -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;

1 change: 1 addition & 0 deletions hub/schema/repository-evaluation-setting.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 2 additions & 0 deletions hub/schema/repository.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ model Repository {
learningShares LearningShare[]
evaluationSetting RepositoryEvaluationSetting?
agentScreenshots AgentScreenshot[]
learningEvaluationRuns LearningEvaluationRun[]
learningScoreRequests LearningScoreRequest[]
decisionModelConfiguration DecisionModelConfiguration?
decisionReviewSnapshot DecisionReviewSnapshot?
decisionTrainingJobs DecisionTrainingJob[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function createLearningMcpBackend(input: {
learning: LearningSettings
learningsUrl: string
repository: { id: string; githubRepositoryId: bigint }
requestScore?(commitSha: string): Promise<void>
serialize<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T>
screenshots?: {
grantId(): Promise<string | null>
Expand Down Expand Up @@ -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),
)
Expand All @@ -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)
Comment thread
nshki marked this conversation as resolved.
Resolved
Comment on lines +206 to +209
const result = await withPrivateFile(JSON.stringify(report), (file) =>
run(directory, ["report-usage", file, ...(grantId ? ["--grant", grantId] : [])]),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,6 +30,7 @@ export async function changeScreenshotConsent(input: {
repositoryScope: string
root: string
signal?: AbortSignal
source: keyof typeof bases
staticDirectories: string[]
}): Promise<string | null> {
const store = await prepareLearningStore({
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 }))
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading