diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index 9f3a24921..4bd142fdf 100644 --- a/hub/client/application/hub/learnings-contracts/index.ts +++ b/hub/client/application/hub/learnings-contracts/index.ts @@ -4,6 +4,7 @@ import { recordIdentifierSchema, repositorySchema } from "@application/hub/contr import type { AcceptedLearningResponse, + EvaluationSettingsResponse, LearningActivityDayResponse, LearningDecisionInput, LearningEvidenceResponse, @@ -274,3 +275,26 @@ export const learningShareInputSchema = z export const learningMutationResponseSchema = z .object({ notice: z.string().min(1) }) .strict() satisfies z.ZodType + +export const evaluationSettingsResponseSchema = z + .object({ + repository: z + .object({ + id: recordIdentifierSchema, + nameWithOwner: z.string().min(1), + defaultBranch: z.string().min(1), + }) + .strict(), + monthlyBudgetCredits: credits, + usedCredits: credits, + enabled: z.boolean(), + screenshots: z + .object({ + allowed: z.boolean(), + changedBy: z.string().min(1).nullable(), + changedAt: timestamp.nullable(), + }) + .strict(), + permissions: z.object({ changeBudget: z.boolean(), changeRepository: z.boolean() }).strict(), + }) + .strict() satisfies z.ZodType diff --git a/hub/client/application/hub/learnings-contracts/types.ts b/hub/client/application/hub/learnings-contracts/types.ts index f50f39c27..fdf20fc1e 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -153,3 +153,12 @@ export interface LearningShareInput { export interface LearningMutationResponse { notice: string } + +export interface EvaluationSettingsResponse { + repository: { id: string; nameWithOwner: string; defaultBranch: string } + monthlyBudgetCredits: string + usedCredits: string + enabled: boolean + screenshots: { allowed: boolean; changedBy: string | null; changedAt: string | null } + permissions: { changeBudget: boolean; changeRepository: boolean } +} diff --git a/hub/client/application/hub/routes/learning-evaluations/index.tsx b/hub/client/application/hub/routes/learning-evaluations/index.tsx new file mode 100644 index 000000000..05c38d025 --- /dev/null +++ b/hub/client/application/hub/routes/learning-evaluations/index.tsx @@ -0,0 +1,128 @@ +import { useFetcher, useLocation } from "react-router" + +import { canvasActionError } from "@application/hub/canvas-connections/contract" +import { recordIdentifierSchema } from "@application/hub/contracts" +import { FormBoundary } from "@application/hub/form-boundary" +import { + evaluationSettingsResponseSchema, + learningMutationResponseSchema, +} from "@application/hub/learnings-contracts" +import { requestJson } from "@application/hub/requests/request-json" +import { EvaluationSettingsPage } from "@pages/evaluation-settings-page" + +import type { Route } from "./+types/index" +import type { WorkspaceRouteHandle } from "../workspace/types" + +export const handle = { workspaceSection: "learnings" } satisfies WorkspaceRouteHandle + +function repositoryId(value: string | undefined) { + const parsed = recordIdentifierSchema.safeParse(value) + if (!parsed.success) throw new Response("Invalid repository identifier.", { status: 400 }) + return parsed.data +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const id = repositoryId(params.repositoryId) + return requestJson( + new URL(`/api/repositories/${id}/learnings/evaluations`, request.url), + evaluationSettingsResponseSchema, + { signal: request.signal }, + ) +} + +/** Reads an optional on/off field the switches send as text. */ +function readSwitch(form: FormData, name: string) { + const value = form.get(name) + if (value === null) return undefined + if (value !== "true" && value !== "false") { + throw new Response(`A valid ${name} value is required.`, { status: 422 }) + } + return value === "true" +} + +export async function clientAction({ request, params }: Route.ClientActionArgs) { + const id = repositoryId(params.repositoryId) + if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) + const form = await request.formData() + const budget = form.get("monthlyBudgetCredits") + try { + if (typeof budget === "string") { + return await requestJson( + new URL("/api/learnings/evaluation-budget", request.url), + learningMutationResponseSchema, + { + method: "PATCH", + body: JSON.stringify({ monthlyBudgetCredits: budget.trim() }), + signal: request.signal, + }, + ) + } + return await requestJson( + new URL(`/api/repositories/${id}/learnings/evaluations`, request.url), + learningMutationResponseSchema, + { + method: "PATCH", + body: JSON.stringify({ + enabled: readSwitch(form, "enabled"), + screenshots: readSwitch(form, "screenshots"), + }), + signal: request.signal, + }, + ) + } catch (error) { + return canvasActionError(error) + } +} + +export function meta() { + return [{ title: "Automated evaluations - Replica Hub" }] +} + +function dateLabel(value: string) { + return new Date(value).toLocaleDateString() +} + +export default function LearningEvaluations({ loaderData, params }: Route.ComponentProps) { + const fetcher = useFetcher<{ error?: string; notice?: string }>() + const { pathname } = useLocation() + const busy = fetcher.state !== "idle" + const { screenshots } = loaderData + function submit(form: FormData) { + void fetcher.submit(form, { method: "post", action: pathname }) + } + return ( + + { + const form = new FormData() + for (const [name, value] of Object.entries(change)) form.set(name, String(value)) + submit(form) + }} + /> + + ) +} diff --git a/hub/client/application/hub/routes/product-routes.ts b/hub/client/application/hub/routes/product-routes.ts index 1e9875149..d09395078 100644 --- a/hub/client/application/hub/routes/product-routes.ts +++ b/hub/client/application/hub/routes/product-routes.ts @@ -12,6 +12,7 @@ export const repositoryProductRoutes: RouteConfigEntry[] = [ route("analytics", "routes/settings-analytics/index.tsx"), route("learnings", "routes/settings-learnings/index.tsx"), route("learnings/agents", "routes/learning-agents/index.tsx"), + route("learnings/evaluations", "routes/learning-evaluations/index.tsx"), ] export const workspaceProductRoutes: RouteConfigEntry[] = [ diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index 00cf3739e..9759df458 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -338,6 +338,10 @@ export function settingsLearnings( agentsPath: workspace.repositories.find(({ id }) => id === repositoryId)?.capabilities?.local ? null : `/repositories/${repositoryId}/learnings/agents`, + evaluationsPath: + state.capabilities.administerHub || state.capabilities.administerRepository + ? `/repositories/${repositoryId}/learnings/evaluations` + : null, run: { path: `/repositories/${repositoryId}/learnings/runs`, available: state.permissions.requestRun && state.runAvailable, diff --git a/hub/client/pages/evaluation-settings-page/index.test.tsx b/hub/client/pages/evaluation-settings-page/index.test.tsx new file mode 100644 index 000000000..2e1d2dbe5 --- /dev/null +++ b/hub/client/pages/evaluation-settings-page/index.test.tsx @@ -0,0 +1,35 @@ +import { fireEvent, render, screen } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" + +import { HubThemeProvider } from "@hooks/use-hub-theme" + +import { EvaluationSettingsPage } from "." + +describe("EvaluationSettingsPage()", () => { + it("allows screenshots only once the repository is evaluated", () => { + const onChange = vi.fn() + render( + , + { wrapper: HubThemeProvider }, + ) + + fireEvent.click(screen.getByRole("switch", { name: "Evaluate github/prototype" })) + + expect(screen.getByRole("switch", { name: "Allow screenshots" })).toBeDisabled() + expect(onChange).toHaveBeenCalledWith({ enabled: true }) + }) +}) diff --git a/hub/client/pages/evaluation-settings-page/index.tsx b/hub/client/pages/evaluation-settings-page/index.tsx new file mode 100644 index 000000000..45c2e08ad --- /dev/null +++ b/hub/client/pages/evaluation-settings-page/index.tsx @@ -0,0 +1,175 @@ +import { ArrowLeftIcon } from "@primer/octicons-react" +import { Button, Heading, Text, TextInput } from "@primer/react-brand" + +import { HubAlert } from "@components/hub-alert" +import { HubIconButton } from "@components/hub-icon-button" +import { HubSwitch } from "@components/hub-switch" + +import type { EvaluationSettingsChange, EvaluationSettingsPageData } from "./types" +import "./styles.css" + +// Budgets keep up to nine decimal places, so small limits must not round to zero. +function amount(value: number) { + return value.toLocaleString(undefined, { maximumFractionDigits: 9 }) +} + +function credits(value: string) { + const number = Number(value) + return `${amount(number)} ${number === 1 ? "credit" : "credits"}` +} + +/** + * Lets Hub administrators set the shared evaluation budget and repository administrators + * choose whether Hub evaluates this repository and may analyze agent screenshots. + */ +export function EvaluationSettingsPage({ + busy, + data, + onChange, +}: { + busy: boolean + data: EvaluationSettingsPageData + onChange: (change: EvaluationSettingsChange) => void +}) { + const { budget, evaluations } = data + const limit = Number(budget.limitCredits) + const used = Number(budget.usedCredits) + const budgetNotSet = limit === 0 + const budgetReached = !budgetNotSet && used >= limit + + // A bar shows how much of the shared budget is gone at a glance; the label keeps + // the exact numbers for anyone who needs them. + const usage = budgetNotSet ? ( + + Not set + + ) : ( +
+ + {amount(used)} of {credits(budget.limitCredits)} used + + +
+ ) + + return ( +
+
+ + + Automated evaluations + +
+
+ + When enabled, Hub checks whether your learnings are helping and suggests updates when + needed. + + +
+ {budget.editable ? ( +
+ + + + credits per month + + + {usage} + + ) : ( +
+ + Shared Hub budget + + {usage} +
+ )} +
+ +
+ {budgetReached ? ( + + ) : budgetNotSet ? ( + + ) : null} +
+ + Evaluate {data.repositoryName} + + onChange({ enabled })} + size="small" + /> +
+
+ + Allow screenshots + + onChange({ screenshots })} + size="small" + /> + + Agents may capture screenshots for Hub to analyze. Turning this off deletes the ones + Hub keeps. + +
+ {evaluations.screenshotsRecord ? ( + + {evaluations.screenshotsRecord} + + ) : null} + {evaluations.editable ? null : ( + + Only a repository administrator can change these settings. + + )} +
+
+
+ ) +} diff --git a/hub/client/pages/evaluation-settings-page/stories.tsx b/hub/client/pages/evaluation-settings-page/stories.tsx new file mode 100644 index 000000000..e189cf5f0 --- /dev/null +++ b/hub/client/pages/evaluation-settings-page/stories.tsx @@ -0,0 +1,124 @@ +import type { Meta, StoryObj } from "@storybook/react-vite" +import { useState } from "react" + +import { RepositoryWorkspace } from "@features/repository-workspace" +import type { RepositoryWorkspaceData } from "@features/repository-workspace/types" +import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" +import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" + +import { EvaluationSettingsPage } from "." +import type { EvaluationSettingsPageData } from "./types" + +const workspace: RepositoryWorkspaceData = { + ...authenticatedHeaderData, + analyticsLabel: "Analytics", + analyticsPath: "/repositories/2001/analytics", + collapseNavigationLabel: "Collapse sidebar", + expandNavigationLabel: "Expand sidebar", + learningsLabel: "Learnings", + learningsPath: "/repositories/2001/learnings", + navigationLabel: "Repository navigation", + newPrototypeLabel: "Create", + newPrototypePath: "/repositories/2001/new", + prototypesLabel: "Prototypes", + prototypesPath: "/repositories/2001", + repositories: [githubPrototype, githubEmpty], + repositoryMenuLabel: "Repositories", + repositorySelectorLabel: "Choose repository. github/prototype selected", + selectedRepositoryId: "2001", + selectedSection: "learnings", + welcomeLabel: "Welcome", + welcomePath: "/welcome", +} + +const settings: EvaluationSettingsPageData = { + repositoryName: "github/prototype", + learningsPath: "/iframe.html?id=hub-pages-learnings-library--multiple&viewMode=story", + budget: { limitCredits: "100", usedCredits: "42", editable: true }, + evaluations: { + editable: true, + enabled: true, + screenshotsAllowed: true, + screenshotsRecord: "Allowed by @mona on 12/20/2026", + }, +} + +/** Keeps each story's changes in its own state, as Hub would after saving. */ +function EvaluationSettingsStory({ + busy, + data, +}: { + busy: boolean + data: EvaluationSettingsPageData +}) { + const [current, setCurrent] = useState(data) + return ( + // The budget form posts to Hub, so the story saves the value itself instead. +
{ + event.preventDefault() + const limit = new FormData(event.target).get("monthlyBudgetCredits") + if (typeof limit !== "string") return + setCurrent((value) => ({ ...value, budget: { ...value.budget, limitCredits: limit } })) + }} + > + + + setCurrent((value) => ({ + ...value, + evaluations: { + ...value.evaluations, + ...(enabled === undefined ? {} : { enabled }), + ...(screenshots === undefined ? {} : { screenshotsAllowed: screenshots }), + }, + })) + } + /> + +
+ ) +} + +const meta = { + title: "Hub/Pages/Learnings/Evaluation settings", + component: EvaluationSettingsPage, + parameters: { layout: "fullscreen" }, + args: { busy: false, data: settings, onChange: () => {} }, + render: ({ busy, data }) => , +} satisfies Meta + +export default meta +type Story = StoryObj + +export const HubAndRepositoryAdmin: Story = {} +export const RepositoryAdmin: Story = { + args: { data: { ...settings, budget: { ...settings.budget, editable: false } } }, +} +export const HubAdmin: Story = { + args: { + data: { + ...settings, + evaluations: { + editable: false, + enabled: false, + screenshotsAllowed: false, + screenshotsRecord: null, + }, + }, + }, +} +export const BudgetReached: Story = { + args: { data: { ...settings, budget: { ...settings.budget, usedCredits: "100" } } }, +} +export const BudgetNotSet: Story = { + args: { + data: { + ...settings, + budget: { limitCredits: "0", usedCredits: "0", editable: false }, + evaluations: { ...settings.evaluations, enabled: false, screenshotsAllowed: false }, + }, + }, +} diff --git a/hub/client/pages/evaluation-settings-prototype/styles.css b/hub/client/pages/evaluation-settings-page/styles.css similarity index 100% rename from hub/client/pages/evaluation-settings-prototype/styles.css rename to hub/client/pages/evaluation-settings-page/styles.css diff --git a/hub/client/pages/evaluation-settings-page/types.ts b/hub/client/pages/evaluation-settings-page/types.ts new file mode 100644 index 000000000..e8ada8fe8 --- /dev/null +++ b/hub/client/pages/evaluation-settings-page/types.ts @@ -0,0 +1,22 @@ +export interface EvaluationSettingsPageData { + repositoryName: string + learningsPath: string + budget: { + /** Decimal credit strings, kept exact for the form and shown as numbers. */ + limitCredits: string + usedCredits: string + editable: boolean + } + evaluations: { + editable: boolean + enabled: boolean + screenshotsAllowed: boolean + /** Who last changed screenshot permission and when, if anyone has. */ + screenshotsRecord: string | null + } +} + +export interface EvaluationSettingsChange { + enabled?: boolean + screenshots?: boolean +} diff --git a/hub/client/pages/evaluation-settings-prototype/index.test.tsx b/hub/client/pages/evaluation-settings-prototype/index.test.tsx deleted file mode 100644 index e7cae39b7..000000000 --- a/hub/client/pages/evaluation-settings-prototype/index.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -import { fireEvent, render, screen } from "@testing-library/react" -import { describe, expect, it } from "vitest" - -import { HubThemeProvider } from "@hooks/use-hub-theme" - -import { EvaluationSettingsPrototype } from "." -import type { EvaluationSettingsPrototypeData } from "./types" - -function renderPrototype(data: EvaluationSettingsPrototypeData) { - render(, { wrapper: HubThemeProvider }) -} - -describe("EvaluationSettingsPrototype()", () => { - it("lets a Hub admin set the shared cap without going below spend already used", () => { - const data: EvaluationSettingsPrototypeData = { - repositoryName: "github/prototype", - learningsPath: "/repositories/2001/learnings", - canManageHubBudget: true, - canManageRepositorySettings: true, - budgetLimitCredits: 100, - usedCredits: 42, - repositoryEnabled: false, - } - renderPrototype(data) - - const budget = screen.getByRole("spinbutton", { name: "Shared Hub budget" }) - expect(budget).toHaveAttribute("min", "42") - expect(budget).toHaveAccessibleDescription("42 of 100 credits used") - fireEvent.change(budget, { target: { value: "30" } }) - - expect(budget).toBeInvalid() - fireEvent.blur(budget) - expect(screen.getByRole("alert")).toHaveTextContent("at least 42 credits") - expect(screen.queryByText("Hub evaluation budget saved.")).not.toBeInTheDocument() - - fireEvent.change(budget, { target: { value: "120" } }) - fireEvent.blur(budget) - - expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( - "Hub evaluation budget saved.", - ) - }) - - it("lets a repository administrator opt in without granting Hub budget access", () => { - const data: EvaluationSettingsPrototypeData = { - repositoryName: "github/prototype", - learningsPath: "/repositories/2001/learnings", - canManageHubBudget: false, - canManageRepositorySettings: true, - budgetLimitCredits: 100, - usedCredits: 42, - repositoryEnabled: false, - } - renderPrototype(data) - - const optIn = screen.getByRole("switch", { - name: "Evaluate github/prototype", - }) - expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument() - expect(optIn).toHaveAccessibleDescription( - "Turning this off stops future evaluations and keeps existing results.", - ) - - fireEvent.click(optIn) - - expect(optIn).toBeChecked() - expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( - "Automated evaluations enabled for github/prototype.", - ) - }) - - it("keeps an opted-in repository paused when the Hub budget is used", () => { - const data: EvaluationSettingsPrototypeData = { - repositoryName: "github/prototype", - learningsPath: "/repositories/2001/learnings", - canManageHubBudget: false, - canManageRepositorySettings: true, - budgetLimitCredits: 100, - usedCredits: 100, - repositoryEnabled: true, - } - renderPrototype(data) - - const optIn = screen.getByRole("switch", { - name: "Evaluate github/prototype", - }) - expect(optIn).toBeChecked() - expect(screen.getByRole("alert")).toHaveTextContent(/Evaluations are paused/) - - fireEvent.click(optIn) - - expect(optIn).not.toBeChecked() - expect(optIn).toBeDisabled() - }) - - it("prevents repository opt-in until a Hub administrator sets a budget", () => { - const data: EvaluationSettingsPrototypeData = { - repositoryName: "github/prototype", - learningsPath: "/repositories/2001/learnings", - canManageHubBudget: false, - canManageRepositorySettings: true, - budgetLimitCredits: 0, - usedCredits: 0, - repositoryEnabled: false, - } - renderPrototype(data) - - expect(screen.getByRole("status")).toHaveTextContent( - "A Hub admin must set a budget before evaluations can be enabled.", - ) - expect(screen.getByRole("switch", { name: "Evaluate github/prototype" })).toBeDisabled() - }) - - it("links back to the repository's Learning Library", () => { - const data: EvaluationSettingsPrototypeData = { - repositoryName: "github/empty", - learningsPath: "/repositories/2002/learnings", - canManageHubBudget: false, - canManageRepositorySettings: true, - budgetLimitCredits: 100, - usedCredits: 42, - repositoryEnabled: false, - } - renderPrototype(data) - - expect(screen.getByRole("link", { name: "Back to learnings" })).toHaveAttribute( - "href", - "/repositories/2002/learnings", - ) - }) -}) diff --git a/hub/client/pages/evaluation-settings-prototype/index.tsx b/hub/client/pages/evaluation-settings-prototype/index.tsx deleted file mode 100644 index f58396931..000000000 --- a/hub/client/pages/evaluation-settings-prototype/index.tsx +++ /dev/null @@ -1,195 +0,0 @@ -import { useState, type SyntheticEvent } from "react" -import { ArrowLeftIcon } from "@primer/octicons-react" -import { Heading, Text, TextInput, Tooltip } from "@primer/react-brand" - -import { HubAlert } from "@components/hub-alert" -import { HubIconButton } from "@components/hub-icon-button" -import { HubSwitch } from "@components/hub-switch" -import { HubToast } from "@components/hub-toast" -import { HubVisuallyHidden } from "@components/hub-visually-hidden" - -import type { EvaluationSettingsPrototypeData } from "./types" -import "./styles.css" - -const optInHint = "Turning this off stops future evaluations and keeps existing results." - -function credits(value: number) { - return `${value.toLocaleString()} ${value === 1 ? "credit" : "credits"}` -} - -export function EvaluationSettingsPrototype({ data }: { data: EvaluationSettingsPrototypeData }) { - const [budgetLimit, setBudgetLimit] = useState(data.budgetLimitCredits) - const [budgetDraft, setBudgetDraft] = useState(String(data.budgetLimitCredits)) - const [budgetError, setBudgetError] = useState("") - const [repositoryEnabled, setRepositoryEnabled] = useState(data.repositoryEnabled) - const [notice, setNotice] = useState("") - const remaining = Math.max(0, budgetLimit - data.usedCredits) - const budgetReached = budgetLimit > 0 && remaining === 0 - const budgetNotSet = budgetLimit === 0 - const canEnableRepository = !budgetReached && !budgetNotSet - - // A bar shows how much of the shared budget is gone at a glance; the label keeps - // the exact numbers for anyone who needs them. - const usage = budgetNotSet ? ( - - Not set - - ) : ( -
- - {data.usedCredits.toLocaleString()} of {credits(budgetLimit)} used - - -
- ) - - // Saving on blur or Enter keeps the row free of a Save button. Unchanged values are - // skipped so tabbing through the page does not show a confirmation. - function saveBudget() { - const nextBudget = Number(budgetDraft) - if (nextBudget === budgetLimit) return - if (budgetDraft === "" || !Number.isFinite(nextBudget) || nextBudget < data.usedCredits) { - setBudgetError(`Set a limit of at least ${credits(data.usedCredits)}, already used.`) - return - } - - setBudgetLimit(nextBudget) - setBudgetError("") - setNotice("Hub evaluation budget saved.") - } - - function setRepositoryOptIn(enabled: boolean) { - if (enabled && !canEnableRepository) return - setRepositoryEnabled(enabled) - setNotice( - enabled - ? `Automated evaluations enabled for ${data.repositoryName}.` - : `Automated evaluations paused for ${data.repositoryName}.`, - ) - } - - return ( -
-
- - - Automated evaluations - -
-
- - When enabled, Hub checks whether your learnings are helping and suggests updates when - needed. - - -
- {data.canManageHubBudget ? ( -
) => { - event.preventDefault() - saveBudget() - }} - > - - { - setBudgetDraft(event.target.value) - setBudgetError("") - }} - required - size="small" - step="any" - type="number" - value={budgetDraft} - /> - - credits - - {usage} - - ) : ( -
- - Shared Hub budget - - {usage} -
- )} - {budgetError ?

{budgetError}

: null} -
- -
- {budgetReached ? ( - - ) : budgetNotSet ? ( - - ) : null} - {data.canManageRepositorySettings ? ( -
- - Evaluate {data.repositoryName} - - - - - - - {optInHint} -
- ) : ( - - Only a repository administrator can change this setting. - - )} -
- {notice ? : null} -
-
- ) -} diff --git a/hub/client/pages/evaluation-settings-prototype/stories.tsx b/hub/client/pages/evaluation-settings-prototype/stories.tsx deleted file mode 100644 index cc502029c..000000000 --- a/hub/client/pages/evaluation-settings-prototype/stories.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite" - -import { RepositoryWorkspace } from "@features/repository-workspace" -import type { RepositoryWorkspaceData } from "@features/repository-workspace/types" -import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" -import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" - -import { EvaluationSettingsPrototype } from "." -import type { EvaluationSettingsPrototypeData } from "./types" - -const workspace: RepositoryWorkspaceData = { - ...authenticatedHeaderData, - analyticsLabel: "Analytics", - analyticsPath: "/repositories/2001/analytics", - collapseNavigationLabel: "Collapse sidebar", - expandNavigationLabel: "Expand sidebar", - learningsLabel: "Learnings", - learningsPath: "/repositories/2001/learnings", - navigationLabel: "Repository navigation", - newPrototypeLabel: "Create", - newPrototypePath: "/repositories/2001/new", - prototypesLabel: "Prototypes", - prototypesPath: "/repositories/2001", - repositories: [githubPrototype, githubEmpty], - repositoryMenuLabel: "Repositories", - repositorySelectorLabel: "Choose repository. github/prototype selected", - selectedRepositoryId: "2001", - selectedSection: "learnings", - welcomeLabel: "Welcome", - welcomePath: "/welcome", -} - -const settings: EvaluationSettingsPrototypeData = { - repositoryName: "github/prototype", - learningsPath: "/iframe.html?id=hub-pages-learnings-library--multiple&viewMode=story", - canManageHubBudget: true, - canManageRepositorySettings: true, - budgetLimitCredits: 100, - usedCredits: 42, - repositoryEnabled: false, -} - -const meta = { - title: "Hub/Pages/Learnings/Evaluation settings", - component: EvaluationSettingsPrototype, - parameters: { layout: "fullscreen" }, - args: { data: settings }, - render: ({ data }) => ( - - - - ), -} satisfies Meta - -export default meta -type Story = StoryObj - -export const HubAndRepositoryAdmin: Story = { - args: { - data: { - ...settings, - learningsPath: "/iframe.html?id=hub-pages-learnings-library--hub-admin&viewMode=story", - }, - }, -} -export const RepositoryAdmin: Story = { - args: { data: { ...settings, canManageHubBudget: false } }, -} -export const BudgetReached: Story = { - args: { - data: { - ...settings, - canManageHubBudget: false, - budgetLimitCredits: 100, - usedCredits: 100, - repositoryEnabled: true, - }, - }, -} -export const BudgetNotSet: Story = { - args: { - data: { - ...settings, - canManageHubBudget: false, - budgetLimitCredits: 0, - usedCredits: 0, - repositoryEnabled: false, - }, - }, -} diff --git a/hub/client/pages/evaluation-settings-prototype/types.ts b/hub/client/pages/evaluation-settings-prototype/types.ts deleted file mode 100644 index 8a19961ce..000000000 --- a/hub/client/pages/evaluation-settings-prototype/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface EvaluationSettingsPrototypeData { - repositoryName: string - learningsPath: string - canManageHubBudget: boolean - canManageRepositorySettings: boolean - budgetLimitCredits: number - usedCredits: number - repositoryEnabled: boolean -} diff --git a/hub/client/pages/learnings-page/index.tsx b/hub/client/pages/learnings-page/index.tsx index 1a34e6500..2830fa72a 100644 --- a/hub/client/pages/learnings-page/index.tsx +++ b/hub/client/pages/learnings-page/index.tsx @@ -82,6 +82,11 @@ function LearningsContent({ description={copy.description} trailing={
+ {data.evaluationsPath ? ( + + ) : null} {data.agentsPath ? ( - )} - -
- ) : null} - - - - ) -} diff --git a/hub/client/pages/screenshot-consent-prototype/stories.tsx b/hub/client/pages/screenshot-consent-prototype/stories.tsx deleted file mode 100644 index 367d70e63..000000000 --- a/hub/client/pages/screenshot-consent-prototype/stories.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite" - -import { RepositoryWorkspace } from "@features/repository-workspace" -import type { RepositoryWorkspaceData } from "@features/repository-workspace/types" -import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" -import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" -import { mona } from "@/storybook/fixtures/users" - -import { ScreenshotConsentPrototype } from "." -import type { ScreenshotConsentPrototypeData } from "./types" - -const workspace: RepositoryWorkspaceData = { - ...authenticatedHeaderData, - accountMenuLabel: "Account menu for @mona", - currentUser: mona, - analyticsLabel: "Analytics", - analyticsPath: "/repositories/2001/analytics", - collapseNavigationLabel: "Collapse sidebar", - expandNavigationLabel: "Expand sidebar", - learningsLabel: "Learnings", - learningsPath: "/repositories/2001/learnings", - navigationLabel: "Repository navigation", - newPrototypeLabel: "Create", - newPrototypePath: "/repositories/2001/new", - prototypesLabel: "Prototypes", - prototypesPath: "/repositories/2001", - repositories: [githubPrototype, githubEmpty], - repositoryMenuLabel: "Repositories", - repositorySelectorLabel: "Choose repository. github/prototype selected", - selectedRepositoryId: "2001", - selectedSection: null, - welcomeLabel: "Welcome", - welcomePath: "/welcome", -} - -const data: ScreenshotConsentPrototypeData = { - repositoryName: "github/prototype", - personName: "@mona", - consentRecordedAt: "November 24, 2026", - evaluatorName: "Prototype quality reviewer", - consentEvaluatorName: null, - evaluationAvailable: true, - consent: null, -} - -const meta = { - title: "Hub/Design/Screenshot consent", - component: ScreenshotConsentPrototype, - parameters: { layout: "fullscreen" }, - args: { data }, - render: (args) => ( - - - - ), -} satisfies Meta - -export default meta -type Story = StoryObj - -export const FirstUse: Story = {} - -export const Allowed: Story = { - args: { - data: { ...data, consentEvaluatorName: data.evaluatorName, consent: true }, - }, -} - -export const Declined: Story = { - args: { - data: { ...data, consent: false }, - }, -} - -export const Withdrawing: Story = { - args: { - data: { ...data, consentEvaluatorName: data.evaluatorName, consent: true }, - }, - play: async ({ canvas, userEvent }) => { - // Primer Brand covers the native checkbox with a styled box, so click its label. - await userEvent.click(canvas.getByText("Allow screenshot capture and automated review")) - }, -} - -export const Withdrawn: Story = { - args: { - data: { ...data, consentEvaluatorName: data.evaluatorName, consent: true }, - }, - play: async ({ canvas, userEvent }) => { - await userEvent.click(canvas.getByText("Allow screenshot capture and automated review")) - await userEvent.click(canvas.getByRole("button", { name: "Withdraw and request deletion" })) - }, -} - -export const ConsentRenewal: Story = { - args: { - data: { - ...data, - evaluatorName: "Updated quality reviewer", - consentEvaluatorName: "Prototype quality reviewer", - consent: true, - }, - }, -} - -export const EvaluationUnavailable: Story = { - args: { - data: { ...data, evaluationAvailable: false }, - }, -} - -export const EvaluationUnavailableAfterConsent: Story = { - args: { - data: { - ...data, - evaluationAvailable: false, - consentEvaluatorName: data.evaluatorName, - consent: true, - }, - }, -} diff --git a/hub/client/pages/screenshot-consent-prototype/styles.css b/hub/client/pages/screenshot-consent-prototype/styles.css deleted file mode 100644 index b329d2be7..000000000 --- a/hub/client/pages/screenshot-consent-prototype/styles.css +++ /dev/null @@ -1,158 +0,0 @@ -.screenshot-consent-page { - min-height: 100%; -} - -/* Matches the Learning Library header so the title sits centered above the border. */ -.screenshot-consent__page-header { - display: flex; - align-items: center; -} - -.screenshot-consent { - display: grid; - gap: 1.5rem; - max-width: 62rem; - margin-inline: auto; - padding: clamp(1rem, 3vw, 2rem); - color: var(--hub-fg-default); -} - -.screenshot-consent h2, -.screenshot-consent h3, -.screenshot-consent p { - margin: 0; -} - -.screenshot-consent__intro { - color: var(--hub-fg-muted); -} - -.screenshot-consent__choice { - display: grid; - gap: 0.75rem; -} - -.screenshot-consent__evidence { - display: grid; - gap: 1rem; - padding: 1.25rem; - border: 1px solid var(--hub-border-default); - border-radius: var(--hub-radius-medium); - background: var(--hub-canvas-default); -} - -.screenshot-consent__examples { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 1rem; -} - -.screenshot-consent__example { - display: grid; - align-content: start; - gap: 0.5rem; - margin: 0; -} - -.screenshot-consent__example figcaption { - color: var(--hub-fg-muted); - font-size: 0.8125rem; - font-weight: 600; -} - -/* The sample stands in for someone else's prototype, so it keeps its own colors in - both Hub themes. */ -.screenshot-consent__sample { - overflow: hidden; - border: 1px solid var(--hub-border-muted); - border-radius: var(--hub-radius-small); - background: #f5f2eb; - color: #23332f; - font-family: var(--brand-fontStack-sansSerif); -} - -.screenshot-consent__sample-bar { - display: flex; - justify-content: space-between; - padding: 0.375rem 0.625rem; - border-bottom: 1px solid #d5d1c8; - background: #fffefa; - color: #59645f; - font-size: 0.625rem; -} - -.screenshot-consent__sample-content { - display: grid; - gap: 0.5rem; - max-width: 25rem; - margin-inline: auto; - padding: clamp(0.75rem, 3vw, 1.25rem); - font-size: 0.75rem; -} - -.screenshot-consent__sample-content h3 { - margin: 0; - font-size: 1rem; -} - -.screenshot-consent__sample-content > p { - color: #59645f; -} - -.screenshot-consent__sample-brand { - font-weight: 700; -} - -.screenshot-consent__sample-field { - display: grid; - gap: 0.25rem; -} - -.screenshot-consent__sample-field > span { - font-size: 0.6875rem; - font-weight: 600; -} - -.screenshot-consent__sample-field > div { - min-height: 2rem; - padding: 0.5rem; - border: 1px solid #89958e; - border-radius: 0.25rem; - background: #fffefa; - color: #59645f; -} - -.screenshot-consent__sample-order { - display: flex; - justify-content: space-between; - padding-block: 0.25rem; - border-top: 1px solid #d5d1c8; - color: #59645f; -} - -.screenshot-consent__sample-button { - padding: 0.5rem; - border-radius: 0.25rem; - background: #23332f; - color: #fffefa; - text-align: center; - font-weight: 600; -} - -.screenshot-consent__record { - color: var(--hub-fg-muted); - font-size: 0.8125rem; -} - -.screenshot-consent__actions { - display: flex; - flex-wrap: wrap; - justify-content: flex-end; - gap: 0.5rem; -} - -@media (max-width: 40rem) { - .screenshot-consent__examples { - grid-template-columns: 1fr; - } -} diff --git a/hub/client/pages/screenshot-consent-prototype/types.ts b/hub/client/pages/screenshot-consent-prototype/types.ts deleted file mode 100644 index f833087cb..000000000 --- a/hub/client/pages/screenshot-consent-prototype/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface ScreenshotConsentPrototypeData { - repositoryName: string - personName: string - consentRecordedAt: string - evaluatorName: string - consentEvaluatorName: string | null - evaluationAvailable: boolean - consent: boolean | null -} diff --git a/hub/docs/architecture.md b/hub/docs/architecture.md index 2a65c1075..383dedfc9 100644 --- a/hub/docs/architecture.md +++ b/hub/docs/architecture.md @@ -28,7 +28,7 @@ The [Pino integration](logging.md) writes structured application and HTTP logs t The [prototype details editor](frontend.md#prototype-metadata-edits) lets signed-in members edit visible prototypes and register drafts. Hub holds session authority and prototype visibility locks through the write and detail read-back. -The [background-job foundation](background-jobs.md) uses BullMQ with PostgreSQL and separate on-demand and scheduled worker processes. Setup migrates BullMQ's own schema independently of Prisma. The on-demand worker registers user-requested learning runs, review redaction, local Build synchronization, and GitHub workflow run imports. The scheduled worker runs opt-in daily learning discovery and automatic runs, learning recovery, GitHub installation reconciliation every 15 minutes, and [GitHub Build recovery](github-actions-builds.md#recovery). +The [background-job foundation](background-jobs.md) uses BullMQ with PostgreSQL and separate on-demand and scheduled worker processes. Setup migrates BullMQ's own schema independently of Prisma. The on-demand worker registers user-requested learning runs, review redaction, withdrawn agent screenshot deletion, local Build synchronization, and GitHub workflow run imports. The scheduled worker runs opt-in daily learning discovery and automatic runs, learning recovery, GitHub installation reconciliation every 15 minutes, and [GitHub Build recovery](github-actions-builds.md#recovery). The [development local Build flow](development.md#build-local-prototype-repositories) scans immediate child Git repositories under one configured root. It records local repositories, branch prototypes, exact commit Builds, branch-head observations, and immutable package files through the normal Prisma and artifact-storage boundaries. It checks out committed revisions in isolated Git worktrees and runs the shared Replica build action without GitHub or GitHub Actions. This flow is not enabled in hosted or production modes. diff --git a/hub/docs/background-jobs.md b/hub/docs/background-jobs.md index b3f5c45e2..0f46ab39a 100644 --- a/hub/docs/background-jobs.md +++ b/hub/docs/background-jobs.md @@ -15,7 +15,7 @@ Each command starts one Node.js process consuming only its assigned queue. The A `ON_DEMAND_JOB_CONCURRENCY` and `SCHEDULED_JOB_CONCURRENCY` independently set the number of active jobs per worker process. Both default to one and accept integers from 1 through 100. CPU-heavy JavaScript still blocks that worker's event loop; move that work to a subprocess or an appropriate execution boundary when adding the domain. -`server/workers/configuration.ts` is the composition point for processors and schedules. Learnings registers explicit run and review-comment redaction work on `on-demand`, alongside [GitHub workflow run imports](github-actions-builds.md#import-worker). An opt-in daily learning discovery schedule runs at 02:00 UTC on `scheduled`, with three attempts and exponential backoff starting at 60 seconds. It creates no work while automatic runs are disabled or Copilot is unusable. Each sweep dispatches at most 100 automatic runs in fair repository order. Automatic learning jobs remain on `scheduled` at lower priority than recovery, discovery, reconciliation, and GitHub Build maintenance; before claiming work under the global learning lock, they also defer to queued user-requested runs. Expected global-lock contention and this user-work deferral move the job back to delayed for 30 seconds without consuming an attempt. A one-minute learning recovery sweep re-enqueues queued and interrupted running runs on their original queue and recovers deleted-comment redactions with stable job IDs. GitHub installation reconciliation runs every 15 minutes on the scheduled queue, with three attempts and exponential backoff starting at 60 seconds. GitHub Build [recovery](github-actions-builds.md#recovery) also runs there: webhook redelivery every minute, and workflow run discovery and retry of Builds awaiting import every 5 minutes. An unconfigured App is skipped; an incomplete configuration or a failed GitHub request fails the job. Reconciliation refreshes the installation's repository list, not each user's repository permissions. Worker startup logs readiness after connecting; unknown job names fail permanently rather than disappearing. +`server/workers/configuration.ts` is the composition point for processors and schedules. Learnings registers explicit run, review-comment redaction, and withdrawn agent screenshot deletion (`learning.delete-agent-screenshots`) work on `on-demand`, alongside [GitHub workflow run imports](github-actions-builds.md#import-worker). An opt-in daily learning discovery schedule runs at 02:00 UTC on `scheduled`, with three attempts and exponential backoff starting at 60 seconds. It creates no work while automatic runs are disabled or Copilot is unusable. Each sweep dispatches at most 100 automatic runs in fair repository order. Automatic learning jobs remain on `scheduled` at lower priority than recovery, discovery, reconciliation, and GitHub Build maintenance; before claiming work under the global learning lock, they also defer to queued user-requested runs. Expected global-lock contention and this user-work deferral move the job back to delayed for 30 seconds without consuming an attempt. A one-minute learning recovery sweep re-enqueues queued and interrupted running runs on their original queue and recovers deleted-comment redactions and withdrawn agent screenshot deletions with stable job IDs. GitHub installation reconciliation runs every 15 minutes on the scheduled queue, with three attempts and exponential backoff starting at 60 seconds. GitHub Build [recovery](github-actions-builds.md#recovery) also runs there: webhook redelivery every minute, and workflow run discovery and retry of Builds awaiting import every 5 minutes. An unconfigured App is skipped; an incomplete configuration or a failed GitHub request fails the job. Reconciliation refreshes the installation's repository list, not each user's repository permissions. Worker startup logs readiness after connecting; unknown job names fail permanently rather than disappearing. The decision-model control plane defines `decision.training` and `decision.recover-training`. Runtime composition registers them only when it also supplies the private taskset and Build screenshot sources. Training polling uses stable job IDs, five-minute retry spacing, a bounded 24-hour queue attempt window, and the repository's shorter wall-time deadline. See [Decision-model control plane](decision-model-control-plane.md#workers-and-recovery). diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 598b790a8..78b3779c0 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -120,7 +120,7 @@ The configuration holds no credential. The first time the agent calls Hub, it ge The agent gets the same tools and instructions as `replica-learning mcp` in the [learning package](../../packages/learning/README.md#connect-an-agent), because Hub loads them from the installed package. Hub supplies the backend: - `get_guidance`, `list_learnings`, and `get_learning` read only the repository's own accepted instruction learnings. A proposed learning links to its Learnings page, where a person decides. -- `report_usage` records which learnings the agent applied. It refuses screenshots for now. +- `report_usage` records which learnings the agent applied. It accepts base64 screenshots only when the repository allows them, as described in [Automated evaluations](#automated-evaluations). - `submit_session` is refused, because Hub does not collect agent sessions yet. Every request acts for the person who approved the connection. Hub rechecks their sign-in, membership, provider, and repository access before and after each command, so ending the person's sessions or removing their access stops the agent too. Agent commands take the same lock as other learning work, so they run one at a time and an agent that arrives while Hub is busy is asked to try again. A connection works for any repository the person can read, which is why the list is kept per person. People review and revoke their agents on the same page, and an agent can give up its own access through `/revoke`. Approving and revoking write security audits. @@ -136,6 +136,24 @@ The OAuth endpoints are `/.well-known/oauth-authorization-server`, `/.well-known The MCP endpoint accepts `POST` only and needs `HUB_APPLICATION_ORIGIN` and the learning package. Local repositories are not supported, because learnings belong to GitHub repositories, so their Learnings page offers no agent setup. +## Automated evaluations + +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. +- 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. + +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` +- `PATCH /api/repositories/:repositoryId/learnings/evaluations` with `{ "enabled": true }`, `{ "screenshots": true }`, or both +- `PATCH /api/learnings/evaluation-budget` with `{ "monthlyBudgetCredits": "100" }` + +Agent requests that carry screenshots may be up to 32 MB. + ## Configuration | Variable | Contract | diff --git a/hub/schema/agent-screenshot.prisma b/hub/schema/agent-screenshot.prisma new file mode 100644 index 000000000..d9dd799cf --- /dev/null +++ b/hub/schema/agent-screenshot.prisma @@ -0,0 +1,20 @@ +model AgentScreenshot { + // 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 + grantId String @map("grant_id") @db.VarChar(255) + sha256 String @db.Char(64) + storageKey String @unique @map("storage_key") @db.VarChar(128) + + // 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, grantId, sha256]) + @@map("agent_screenshots") +} diff --git a/hub/schema/evaluation-setting.prisma b/hub/schema/evaluation-setting.prisma new file mode 100644 index 000000000..4e7457214 --- /dev/null +++ b/hub/schema/evaluation-setting.prisma @@ -0,0 +1,15 @@ +model EvaluationSetting { + // ID columns + id String @id @default(uuid()) @db.Uuid + + // Attribute columns + key String @unique @db.VarChar(100) + monthlyBudgetCredits Decimal @default(0) @map("monthly_budget_credits") @db.Decimal(20, 9) + 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) + + @@map("evaluation_settings") +} diff --git a/hub/schema/membership.prisma b/hub/schema/membership.prisma index 58d611416..4259828d6 100644 --- a/hub/schema/membership.prisma +++ b/hub/schema/membership.prisma @@ -20,6 +20,7 @@ model Membership { withdrawnLearningShares LearningShare[] @relation("LearningShareWithdrawnBy") canvasGrants CanvasGrant[] agentConnections AgentConnection[] + screenshotConsentChanges RepositoryEvaluationSetting[] // Attribute columns lifecycle MembershipLifecycle @default(ACTIVE) diff --git a/hub/schema/migrations/20261224170000_evaluation_settings/migration.sql b/hub/schema/migrations/20261224170000_evaluation_settings/migration.sql new file mode 100644 index 000000000..203a20386 --- /dev/null +++ b/hub/schema/migrations/20261224170000_evaluation_settings/migration.sql @@ -0,0 +1,62 @@ +-- CreateTable +CREATE TABLE "agent_screenshots" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "grant_id" VARCHAR(255) NOT NULL, + "sha256" CHAR(64) NOT NULL, + "storage_key" VARCHAR(128) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "agent_screenshots_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "evaluation_settings" ( + "id" UUID NOT NULL, + "key" VARCHAR(100) NOT NULL, + "monthly_budget_credits" DECIMAL(20,9) NOT NULL DEFAULT 0, + "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 "evaluation_settings_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "repository_evaluation_settings" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "screenshots_changed_by_membership_id" UUID, + "enabled" BOOLEAN NOT NULL DEFAULT false, + "screenshot_grant_id" VARCHAR(255), + "screenshots_changed_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "repository_evaluation_settings_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_screenshots_storage_key_key" ON "agent_screenshots"("storage_key"); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_screenshots_repository_id_grant_id_sha256_key" ON "agent_screenshots"("repository_id", "grant_id", "sha256"); + +-- CreateIndex +CREATE UNIQUE INDEX "evaluation_settings_key_key" ON "evaluation_settings"("key"); + +-- CreateIndex +CREATE UNIQUE INDEX "repository_evaluation_settings_repository_id_key" ON "repository_evaluation_settings"("repository_id"); + +-- CreateIndex +CREATE INDEX "repository_evaluation_settings_screenshots_changed_by_membe_idx" ON "repository_evaluation_settings"("screenshots_changed_by_membership_id"); + +-- AddForeignKey +ALTER TABLE "agent_screenshots" ADD CONSTRAINT "agent_screenshots_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "repository_evaluation_settings" ADD CONSTRAINT "repository_evaluation_settings_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "repository_evaluation_settings" ADD CONSTRAINT "repository_evaluation_settings_screenshots_changed_by_memb_fkey" FOREIGN KEY ("screenshots_changed_by_membership_id") REFERENCES "memberships"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/hub/schema/repository-evaluation-setting.prisma b/hub/schema/repository-evaluation-setting.prisma new file mode 100644 index 000000000..616b94c44 --- /dev/null +++ b/hub/schema/repository-evaluation-setting.prisma @@ -0,0 +1,22 @@ +model RepositoryEvaluationSetting { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @unique @map("repository_id") @db.Uuid + screenshotsChangedByMembershipId String? @map("screenshots_changed_by_membership_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + screenshotsChangedByMembership Membership? @relation(fields: [screenshotsChangedByMembershipId], references: [id], onDelete: SetNull) + + // Attribute columns + enabled Boolean @default(false) + screenshotGrantId String? @map("screenshot_grant_id") @db.VarChar(255) + screenshotsChangedAt DateTime? @map("screenshots_changed_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([screenshotsChangedByMembershipId]) + @@map("repository_evaluation_settings") +} diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index bba3bcace..5598eeb75 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -8,6 +8,8 @@ model Repository { learningRuns LearningRun[] learningDecisionOperations LearningDecisionOperation[] learningShares LearningShare[] + evaluationSetting RepositoryEvaluationSetting? + agentScreenshots AgentScreenshot[] decisionModelConfiguration DecisionModelConfiguration? decisionReviewSnapshot DecisionReviewSnapshot? decisionTrainingJobs DecisionTrainingJob[] diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 905e1a189..6746ef7f4 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -63,7 +63,7 @@ export function createApp({ authenticationSecurity(), ) app.use( - /^(?!\/api\/(?:copilot-connection|notifications|private-preview)(?:\/|$))(?!\/api\/product\/sharing-settings(?:\/|$))(?!\/api\/repositories\/[^/]+\/(?:learnings|decision-model|analytics|prototype-management)(?:\/|$))(?!\/api\/(?:auth|canvas|administrators\/authorizations|session-revocation\/authorizations|github\/webhooks)(?:\/|$))(?!\/api\/repositories\/[^/]+\/prototypes\/[^/]+(?:\/review-comments(?:\/|$)|\/share-links(?:\/|$)|\/?$)).*/i, + /^(?!\/mcp(?:\/|$))(?!\/api\/(?:copilot-connection|learnings|notifications|private-preview)(?:\/|$))(?!\/api\/product\/sharing-settings(?:\/|$))(?!\/api\/repositories\/[^/]+\/(?:learnings|decision-model|analytics|prototype-management)(?:\/|$))(?!\/api\/(?:auth|canvas|administrators\/authorizations|session-revocation\/authorizations|github\/webhooks)(?:\/|$))(?!\/api\/repositories\/[^/]+\/prototypes\/[^/]+(?:\/review-comments(?:\/|$)|\/share-links(?:\/|$)|\/?$)).*/i, express.json(), ) 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 696d3058e..4eaedfd2c 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 @@ -151,6 +151,74 @@ it("gives no guidance for a repository without a learning store", async () => { const guidance = await backend.getGuidance({ task: "Build a form" }) - expect(guidance).toEqual({ guidanceId: null, text: "", learnings: [] }) + expect(guidance).toEqual({ guidanceId: null, text: "", learnings: [], screenshotsAllowed: false }) expect(runLearningCommand).not.toHaveBeenCalled() }) + +it("refuses screenshots for a repository that has not allowed them", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockClear() + 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 }, + screenshots: { grantId: () => Promise.resolve(null), save: vi.fn() }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const report = backend.reportUsage({ used: [{ after: { data: "aW1hZ2U=" } }] }) + + await expect(report).rejects.toThrow("unsupported") + expect(runLearningCommand).not.toHaveBeenCalled() +}) + +it("keeps screenshot bytes only while the repository still allows screenshots", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockClear() + runLearningCommand.mockResolvedValueOnce({ recorded: 1 }).mockResolvedValueOnce({ recorded: 1 }) + const grantId = vi + .fn() + .mockResolvedValueOnce("grant-1") + .mockResolvedValueOnce("grant-1") + .mockResolvedValueOnce("grant-1") + .mockResolvedValueOnce(null) + const save = 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 }, + screenshots: { grantId, save }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + await backend.reportUsage({ used: [{ after: { data: "aW1hZ2U=" } }] }) + await backend.reportUsage({ used: [{ after: { data: "aW1hZ2U=" } }] }) + + expect(runLearningCommand.mock.calls[0]![0]).toEqual( + expect.arrayContaining(["--grant", "grant-1"]), + ) + expect(save).toHaveBeenCalledOnce() + expect(save).toHaveBeenCalledWith({ grantId: "grant-1", bytes: Buffer.from("image") }) +}) 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 193ead614..ce40bdaa2 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 @@ -24,6 +24,11 @@ interface LearningSettings { staticDirectories: string[] } +interface Screenshot { + data?: unknown + file?: unknown +} + interface StoredLearning { record: { id: string; state: string } status: { recallEligible: boolean } @@ -54,6 +59,10 @@ export function createLearningMcpBackend(input: { learningsUrl: string repository: { id: string; githubRepositoryId: bigint } serialize(operation: (signal: AbortSignal) => Promise): Promise + screenshots?: { + grantId(): Promise + save(input: { grantId: string; bytes: Uint8Array }): Promise + } toAgentError: (code: string, message: string) => Error }) { const { learning, repository, toAgentError } = input @@ -139,8 +148,10 @@ export function createLearningMcpBackend(input: { limit?: number session?: { id: string; label?: string } }) { + // Agents check this before capturing, so they never take screenshots Hub refuses. + const screenshotsAllowed = Boolean(await input.screenshots?.grantId()) const directory = await storeDirectory() - if (!directory) return { guidanceId: null, text: "", learnings: [] } + if (!directory) return { guidanceId: null, text: "", learnings: [], screenshotsAllowed } const store = directory function recall(taskArguments: string[]) { return run(store, [ @@ -164,21 +175,44 @@ export function createLearningMcpBackend(input: { guidanceId: result.guidanceId, text: result.text, learnings: result.memories.map(({ id, deliveryId }) => ({ id, deliveryId })), + screenshotsAllowed, } }, - async reportUsage(report: { used: { before?: unknown; after?: unknown }[] }) { - if (report.used.some((item) => item.before !== undefined || item.after !== undefined)) + async reportUsage(report: { used: { before?: Screenshot; after?: Screenshot }[] }) { + const screenshots = report.used.flatMap((item) => + [item.before, item.after].filter((shot) => shot !== undefined), + ) + if (screenshots.some((shot) => shot.file !== undefined)) + throw toAgentError("invalid_input", "Hub accepts screenshots only as base64 data.") + if (screenshots.length > 0 && !input.screenshots) throw toAgentError( "unsupported", - "Hub does not accept screenshots yet. Report usage without them.", + "This Hub has no screenshot storage set up. Send the report without screenshots.", + ) + const grantId = screenshots.length > 0 ? ((await input.screenshots?.grantId()) ?? null) : null + if (screenshots.length > 0 && !grantId) + throw toAgentError( + "unsupported", + "Screenshots are not allowed for this repository. Send the report without them.", ) const directory = await storeDirectory() if (!directory) throw toAgentError("not_found", "This repository has no learnings to report on.") - return withPrivateFile(JSON.stringify(report), (file) => - run(directory, ["report-usage", file]), + const result = await withPrivateFile(JSON.stringify(report), (file) => + run(directory, ["report-usage", file, ...(grantId ? ["--grant", grantId] : [])]), ) + // The store checked the images and the grant first, so Hub keeps only accepted bytes. + // Consent withdrawn meanwhile leaves nothing to keep; recovery deletes any late copy. + if (grantId && (await input.screenshots!.grantId()) === grantId) { + for (const shot of screenshots) { + await input.screenshots!.save({ + grantId, + bytes: Buffer.from(String(shot.data), "base64"), + }) + } + } + return result }, submitSession() { diff --git a/hub/server/domains/agent-connections/save-agent-screenshot/index.ts b/hub/server/domains/agent-connections/save-agent-screenshot/index.ts new file mode 100644 index 000000000..12f26dabd --- /dev/null +++ b/hub/server/domains/agent-connections/save-agent-screenshot/index.ts @@ -0,0 +1,31 @@ +import { createHash, randomUUID } from "node:crypto" + +import type { ArtifactStorage } from "../../artifacts/create-artifact-storage/types.ts" + +/** + * Keeps one agent screenshot in Hub's artifact storage. The record is written before the + * bytes, so withdrawing consent always finds every image it has to delete. + */ +export async function saveAgentScreenshot( + dependencies: { + create(input: { + repositoryId: string + grantId: string + sha256: string + storageKey: string + }): Promise<{ storageKey: string }> + storage: Pick + }, + input: { repositoryId: string; grantId: string; bytes: Uint8Array }, +) { + const record = await dependencies.create({ + repositoryId: input.repositoryId, + grantId: input.grantId, + sha256: createHash("sha256").update(input.bytes).digest("hex"), + storageKey: randomUUID(), + }) + const { status } = await dependencies.storage.write(record.storageKey, input.bytes) + if (status !== "ok" && status !== "already-exists") { + throw new Error(`Hub could not store an agent screenshot (${status}).`) + } +} diff --git a/hub/server/domains/learning/change-screenshot-consent/index.ts b/hub/server/domains/learning/change-screenshot-consent/index.ts new file mode 100644 index 000000000..a0b35b2a2 --- /dev/null +++ b/hub/server/domains/learning/change-screenshot-consent/index.ts @@ -0,0 +1,78 @@ +import { z } from "zod" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" +import { prepareLearningStore } from "../prepare-learning-store/index.ts" + +const addedGrantSchema = z.object({ id: z.string().min(1).max(255) }).loose() + +/** + * 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. + */ +export async function changeScreenshotConsent(input: { + actor: string + allowed: boolean + cliPath: string + grantId: string | null + learningDatabaseUrl?: string + nodePath: string + repositoryId: string + repositoryScope: string + root: string + signal?: AbortSignal + staticDirectories: string[] +}): Promise { + const store = await prepareLearningStore({ + learningDatabaseUrl: input.learningDatabaseUrl, + repositoryKey: input.repositoryId, + repositoryScope: input.repositoryScope, + root: input.root, + staticDirectories: input.staticDirectories, + }) + const options = { + cliPath: input.cliPath, + nodePath: input.nodePath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), + ...(input.signal ? { signal: input.signal } : {}), + } + const common = learningStoreArguments(store) + if (input.allowed) { + const grant = addedGrantSchema.parse( + await runLearningCommand( + [ + "grants", + "add", + "--purpose", + "evaluation", + "--source", + "agent_screenshots", + "--basis", + "A repository administrator allowed agents to take screenshots and Hub to analyze them.", + "--by", + input.actor, + ...common, + ], + options, + ), + ) + return grant.id + } + if (input.grantId) { + await runLearningCommand( + [ + "grants", + "withdraw", + input.grantId, + "--purpose", + "evaluation", + "--by", + input.actor, + ...common, + ], + options, + ) + } + return null +} 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 e71feda6f..c5b4e04c5 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 @@ -13,6 +13,8 @@ import { createLearningJobProcessors } from "." const prisma = { learningRun: { findMany: vi.fn() }, + agentScreenshot: { findMany: vi.fn(), groupBy: vi.fn() }, + repositoryEvaluationSetting: { findMany: vi.fn() }, learningDecisionOperation: { findMany: vi.fn() }, repository: { findUnique: vi.fn() }, reviewComment: { findMany: vi.fn(), updateMany: vi.fn() }, @@ -111,6 +113,8 @@ describe("createLearningJobProcessors()", () => { JSON.stringify({ schemaVersion: "replica.learning-config/v1" }), ) prisma.learningRun.findMany.mockResolvedValue([]) + prisma.agentScreenshot.groupBy.mockResolvedValue([]) + prisma.repositoryEvaluationSetting.findMany.mockResolvedValue([]) prisma.learningDecisionOperation.findMany.mockResolvedValue([]) prisma.reviewComment.findMany.mockResolvedValue([ { 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 b6ffeb576..7e0642e19 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -6,7 +6,9 @@ import { getCopilotConnectionStatus } from "../../copilot-connection/get-copilot import { ReviewCommentError } from "../../review-comments/errors.ts" import { authorizeRepositoryAdministration } from "../authorize-repository-administration/index.ts" import { createReviewCommentLearningSource } from "../create-review-comment-learning-source/index.ts" +import { deleteWithdrawnAgentScreenshots } from "../delete-withdrawn-agent-screenshots/index.ts" import { getLearningRepositoryScope } from "../get-learning-repository-scope/index.ts" +import { deleteAgentScreenshotsJob } from "../jobs/delete-agent-screenshots.ts" import { learningRunJob } from "../jobs/learning-run.ts" import { automaticLearningRunPriority } from "../jobs/priorities.ts" import { recoverLearningRunsJob } from "../jobs/recover-learning-runs.ts" @@ -22,6 +24,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 { 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" import { enqueueRecoverableJob } from "../../../integrations/bullmq/enqueue-recoverable-job/index.ts" @@ -30,6 +33,10 @@ import { runLearningCommand } from "../../../integrations/learning/run-learning- import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { CopilotCredentialError } from "../../../integrations/github/create-installation-access-token/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 { 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 { 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" @@ -307,6 +314,15 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg ? { deletedAt: last.deletedAt, id: last.id } : undefined } while (redactionCursor) + for (const screenshots of await listAgentScreenshotGrants(prisma)) { + if (screenshots.active) continue + await enqueueRecoverableJob( + onDemandQueue, + deleteAgentScreenshotsJob, + { repositoryId: screenshots.repositoryId, grantId: screenshots.grantId }, + `learning-screenshots-${screenshots.repositoryId}-${screenshots.grantId}`, + ) + } for (const operation of await listLearningDecisionOperations(prisma)) { try { await reconcileLearningDecisionOperation(operation, { @@ -465,5 +481,29 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg }) }) - return { run, scheduledRun, recover, redact, schedule } + let storagePromise: ReturnType | undefined + // Storage opens only when there is an image to delete, and a failed open is retried. + function artifactStorage() { + storagePromise ??= createConfiguredArtifactStorage( + resolveLocalSignInEnvironment(environment), + ).catch((error: unknown) => { + storagePromise = undefined + throw error + }) + return storagePromise + } + const deleteScreenshots = createJobProcessor(deleteAgentScreenshotsJob, async (input) => { + const { prisma } = await databaseDependencies() + await deleteWithdrawnAgentScreenshots({ + activeGrantId: async () => + (await getRepositoryEvaluationSetting(prisma, input.repositoryId))?.screenshotGrantId ?? + null, + deleteRecord: (id) => deleteAgentScreenshot(prisma, id), + grantId: input.grantId, + list: () => listGrantAgentScreenshots(prisma, input), + storage: { delete: async (key) => (await artifactStorage()).delete(key) }, + }) + }) + + return { run, scheduledRun, recover, redact, schedule, deleteScreenshots } } diff --git a/hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.test.ts b/hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.test.ts new file mode 100644 index 000000000..a8e521b4f --- /dev/null +++ b/hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.test.ts @@ -0,0 +1,55 @@ +import { expect, it, vi } from "vitest" + +import { deleteWithdrawnAgentScreenshots } from "." + +it("deletes each withdrawn screenshot's bytes before its record", async () => { + const steps: string[] = [] + const list = vi + .fn() + .mockResolvedValueOnce([{ id: "shot-1", storageKey: "agent-screenshots/1.png" }]) + .mockResolvedValueOnce([]) + + await deleteWithdrawnAgentScreenshots({ + activeGrantId: () => Promise.resolve(null), + deleteRecord: (id) => Promise.resolve(steps.push(`record ${id}`)), + grantId: "grant-1", + list, + storage: { + delete: (key) => { + steps.push(`bytes ${key}`) + return Promise.resolve({ status: "ok" }) + }, + }, + }) + + expect(steps).toEqual(["bytes agent-screenshots/1.png", "record shot-1"]) +}) + +it("keeps screenshots taken under the grant the repository allows now", async () => { + const list = vi.fn() + + await deleteWithdrawnAgentScreenshots({ + activeGrantId: () => Promise.resolve("grant-1"), + deleteRecord: vi.fn(), + grantId: "grant-1", + list, + storage: { delete: vi.fn() }, + }) + + expect(list).not.toHaveBeenCalled() +}) + +it("keeps the record for a retry when storage cannot delete the bytes", async () => { + const deleteRecord = vi.fn() + + const deletion = deleteWithdrawnAgentScreenshots({ + activeGrantId: () => Promise.resolve(null), + deleteRecord, + grantId: "grant-1", + list: () => Promise.resolve([{ id: "shot-1", storageKey: "agent-screenshots/1.png" }]), + storage: { delete: () => Promise.resolve({ status: "unavailable" }) }, + }) + + await expect(deletion).rejects.toThrow("could not delete") + expect(deleteRecord).not.toHaveBeenCalled() +}) diff --git a/hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.ts b/hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.ts new file mode 100644 index 000000000..edf035cbc --- /dev/null +++ b/hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.ts @@ -0,0 +1,27 @@ +import type { ArtifactStorage } from "../../artifacts/create-artifact-storage/types.ts" + +/** + * Deletes the stored images taken under one withdrawn consent grant. A grant never becomes + * active again, since turning consent back on makes a new one, so this cannot remove images + * the repository allows now. The bytes go first so a failure leaves the record for a retry. + */ +export async function deleteWithdrawnAgentScreenshots(dependencies: { + activeGrantId(): Promise + deleteRecord(id: string): Promise + grantId: string + list(): Promise<{ id: string; storageKey: string }[]> + storage: Pick +}) { + if ((await dependencies.activeGrantId()) === dependencies.grantId) return + for (;;) { + const screenshots = await dependencies.list() + if (screenshots.length === 0) return + for (const screenshot of screenshots) { + const { status } = await dependencies.storage.delete(screenshot.storageKey) + if (status !== "ok" && status !== "not-found") { + throw new Error(`Hub could not delete a withdrawn agent screenshot (${status}).`) + } + await dependencies.deleteRecord(screenshot.id) + } + } +} diff --git a/hub/server/domains/learning/jobs/delete-agent-screenshots.ts b/hub/server/domains/learning/jobs/delete-agent-screenshots.ts new file mode 100644 index 000000000..fed08e489 --- /dev/null +++ b/hub/server/domains/learning/jobs/delete-agent-screenshots.ts @@ -0,0 +1,12 @@ +import { z } from "zod" + +export const deleteAgentScreenshotsJob = { + name: "learning.delete-agent-screenshots", + schema: z + .object({ + repositoryId: z.uuid(), + grantId: z.string().min(1).max(255), + }) + .strict(), + options: { attempts: 120, backoff: { type: "fixed", delay: 30_000 } }, +} diff --git a/hub/server/index.ts b/hub/server/index.ts index 7b18b1257..f822baa06 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -191,6 +191,7 @@ try { agentConnections = { applicationOrigin: agentApplicationOrigin, databaseUrl, + ...(storage ? { artifactStorage: storage } : {}), learning: learningConfiguration, } } diff --git a/hub/server/repositories/agent-screenshots/create-agent-screenshot/index.ts b/hub/server/repositories/agent-screenshots/create-agent-screenshot/index.ts new file mode 100644 index 000000000..7812cad26 --- /dev/null +++ b/hub/server/repositories/agent-screenshots/create-agent-screenshot/index.ts @@ -0,0 +1,17 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Records a screenshot Hub is about to store, or returns the record a retry already made, + * so the same image under the same grant is stored once. + */ +export function createAgentScreenshot( + database: PrismaClient, + input: { repositoryId: string; grantId: string; sha256: string; storageKey: string }, +) { + const { repositoryId, grantId, sha256 } = input + return database.agentScreenshot.upsert({ + where: { repositoryId_grantId_sha256: { repositoryId, grantId, sha256 } }, + create: input, + update: {}, + }) +} diff --git a/hub/server/repositories/agent-screenshots/delete-agent-screenshot/index.ts b/hub/server/repositories/agent-screenshots/delete-agent-screenshot/index.ts new file mode 100644 index 000000000..0fcbc8c1e --- /dev/null +++ b/hub/server/repositories/agent-screenshots/delete-agent-screenshot/index.ts @@ -0,0 +1,5 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function deleteAgentScreenshot(database: PrismaClient, id: string) { + return database.agentScreenshot.deleteMany({ where: { id } }) +} diff --git a/hub/server/repositories/agent-screenshots/list-agent-screenshot-grants/index.ts b/hub/server/repositories/agent-screenshots/list-agent-screenshot-grants/index.ts new file mode 100644 index 000000000..fd1614d8a --- /dev/null +++ b/hub/server/repositories/agent-screenshots/list-agent-screenshot-grants/index.ts @@ -0,0 +1,18 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** Lists each repository and consent grant that still has stored agent screenshots. */ +export async function listAgentScreenshotGrants(database: PrismaClient) { + const groups = await database.agentScreenshot.groupBy({ by: ["repositoryId", "grantId"] }) + const settings = await database.repositoryEvaluationSetting.findMany({ + where: { repositoryId: { in: [...new Set(groups.map((group) => group.repositoryId))] } }, + select: { repositoryId: true, screenshotGrantId: true }, + }) + const activeGrants = new Map( + settings.map((setting) => [setting.repositoryId, setting.screenshotGrantId]), + ) + return groups.map((group) => ({ + repositoryId: group.repositoryId, + grantId: group.grantId, + active: activeGrants.get(group.repositoryId) === group.grantId, + })) +} diff --git a/hub/server/repositories/agent-screenshots/list-grant-agent-screenshots/index.ts b/hub/server/repositories/agent-screenshots/list-grant-agent-screenshots/index.ts new file mode 100644 index 000000000..deee52949 --- /dev/null +++ b/hub/server/repositories/agent-screenshots/list-grant-agent-screenshots/index.ts @@ -0,0 +1,13 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function listGrantAgentScreenshots( + database: PrismaClient, + input: { repositoryId: string; grantId: string }, +) { + return database.agentScreenshot.findMany({ + where: input, + select: { id: true, storageKey: true }, + orderBy: { id: "asc" }, + take: 100, + }) +} diff --git a/hub/server/repositories/evaluation-settings/get-repository-evaluation-setting/index.ts b/hub/server/repositories/evaluation-settings/get-repository-evaluation-setting/index.ts new file mode 100644 index 000000000..47af88f5c --- /dev/null +++ b/hub/server/repositories/evaluation-settings/get-repository-evaluation-setting/index.ts @@ -0,0 +1,15 @@ +import type { PrismaClient, Prisma } from "../../../generated/prisma/client.ts" + +export function getRepositoryEvaluationSetting( + database: PrismaClient | Prisma.TransactionClient, + repositoryId: string, +) { + return database.repositoryEvaluationSetting.findUnique({ + where: { repositoryId }, + include: { + screenshotsChangedByMembership: { + select: { user: { select: { profile: { select: { login: true } } } } }, + }, + }, + }) +} diff --git a/hub/server/repositories/evaluation-settings/initialize-evaluation-setting/index.ts b/hub/server/repositories/evaluation-settings/initialize-evaluation-setting/index.ts new file mode 100644 index 000000000..6cc5d1d02 --- /dev/null +++ b/hub/server/repositories/evaluation-settings/initialize-evaluation-setting/index.ts @@ -0,0 +1,10 @@ +import type { PrismaClient, Prisma } from "../../../generated/prisma/client.ts" + +import { evaluationSettingKey } from "../../../utils/evaluation-setting-key/index.ts" + +export function initializeEvaluationSetting( + database: PrismaClient | Prisma.TransactionClient, + key = evaluationSettingKey, +) { + return database.evaluationSetting.upsert({ where: { key }, create: { key }, update: {} }) +} 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 new file mode 100644 index 000000000..44b4bb549 --- /dev/null +++ b/hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts @@ -0,0 +1,19 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function saveRepositoryEvaluationSetting( + database: Prisma.TransactionClient, + repositoryId: string, + data: + | { enabled: boolean } + | { + screenshotGrantId: string | null + screenshotsChangedAt: Date + screenshotsChangedByMembershipId: string + }, +) { + return database.repositoryEvaluationSetting.upsert({ + where: { repositoryId }, + create: { repositoryId, ...data }, + update: data, + }) +} diff --git a/hub/server/repositories/evaluation-settings/update-evaluation-budget/index.ts b/hub/server/repositories/evaluation-settings/update-evaluation-budget/index.ts new file mode 100644 index 000000000..3454dae75 --- /dev/null +++ b/hub/server/repositories/evaluation-settings/update-evaluation-budget/index.ts @@ -0,0 +1,15 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +import { evaluationSettingKey } from "../../../utils/evaluation-setting-key/index.ts" + +export function updateEvaluationBudget( + database: Prisma.TransactionClient, + monthlyBudgetCredits: string, + key = evaluationSettingKey, +) { + return database.evaluationSetting.upsert({ + where: { key }, + create: { key, monthlyBudgetCredits, revision: 1 }, + update: { monthlyBudgetCredits, revision: { increment: 1 } }, + }) +} diff --git a/hub/server/repositories/security-audits/create-security-audit/types.ts b/hub/server/repositories/security-audits/create-security-audit/types.ts index ef6e18af9..9ddd6ad07 100644 --- a/hub/server/repositories/security-audits/create-security-audit/types.ts +++ b/hub/server/repositories/security-audits/create-security-audit/types.ts @@ -256,7 +256,12 @@ export interface LearningRunAudit extends SecurityAuditEvent { export interface RepositoryAdministrationDeniedAudit extends SecurityAuditEvent { type: "repository_administration_denied" actorMembershipId: string - operation: "learning_overview" | "learning_run" | "learning_decision" | "learning_share" + operation: + | "learning_overview" + | "learning_run" + | "learning_decision" + | "learning_share" + | "learning_evaluation" reason: "authority_missing" repositoryId: string } diff --git a/hub/server/repositories/security-audits/parse-security-audit-event/index.ts b/hub/server/repositories/security-audits/parse-security-audit-event/index.ts index ba4aa5d21..f714ef8f4 100644 --- a/hub/server/repositories/security-audits/parse-security-audit-event/index.ts +++ b/hub/server/repositories/security-audits/parse-security-audit-event/index.ts @@ -329,6 +329,7 @@ const eventSchema = z.discriminatedUnion("type", [ "learning_run", "learning_decision", "learning_share", + "learning_evaluation", ]), reason: z.literal("authority_missing"), repositoryId: z.uuid(), diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 9b622abb8..6a3bd5bdb 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -5,6 +5,7 @@ import type { Logger } from "pino" import { createAgentConnections } from "../../domains/agent-connections/create-agent-connections/index.ts" import type { AgentConnections } from "../../domains/agent-connections/create-agent-connections/index.ts" import { createLearningMcpBackend } from "../../domains/agent-connections/create-learning-mcp-backend/index.ts" +import { saveAgentScreenshot } from "../../domains/agent-connections/save-agent-screenshot/index.ts" import { createCanvasAuthorization, type GetCanvasRepositoryPermission, @@ -20,6 +21,9 @@ import { handleMcpRequest } from "../../integrations/mcp/handle-mcp-request/inde import { requireAgentToken } from "../../integrations/mcp/require-agent-token/index.ts" import { withLearningExecutionLock } from "../../integrations/postgres/with-learning-execution-lock/index.ts" 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 type { PrismaClient } from "../../generated/prisma/client.ts" import type { AgentConnectionRouteDependencies } from "./types.ts" const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i @@ -38,14 +42,14 @@ export function agentConnectionRoutes( getRepositoryPermission?: GetCanvasRepositoryPermission, logger?: Logger, ) { - const { applicationOrigin, databaseUrl, learning } = dependencies + const { applicationOrigin, artifactStorage, databaseUrl, learning } = dependencies const router = express.Router() const browserMutation = requireOrigin(applicationOrigin) let services: Promise<{ connections: AgentConnections authority: ReturnType - prisma: Parameters[0] + prisma: PrismaClient }> | null = null function load() { services ??= import("../../integrations/prisma/index.ts").then(({ prisma }) => ({ @@ -176,6 +180,8 @@ export function agentConnectionRoutes( router.post( mcpPath, requireAgentToken(applicationOrigin, service), + // Usage reports can carry screenshots, so this route allows larger bodies than the rest. + express.json({ limit: "32mb" }), handler(async (request, response) => { const id = String(request.params.repositoryId) const { prisma, authority } = await load() @@ -219,6 +225,23 @@ export function agentConnectionRoutes( throw error } }, + ...(artifactStorage + ? { + screenshots: { + grantId: async () => + (await getRepositoryEvaluationSetting(prisma, repository.id)) + ?.screenshotGrantId ?? null, + save: ({ grantId, bytes }: { grantId: string; bytes: Uint8Array }) => + saveAgentScreenshot( + { + create: (record) => createAgentScreenshot(prisma, record), + storage: artifactStorage, + }, + { repositoryId: repository.id, grantId, bytes }, + ), + }, + } + : {}), toAgentError: (code, message) => new mcp.LearningError(code, message), }) const server = mcp.createLearningMcpServer(backend, { diff --git a/hub/server/routes/agent-connections/types.ts b/hub/server/routes/agent-connections/types.ts index 315765971..5004a1979 100644 --- a/hub/server/routes/agent-connections/types.ts +++ b/hub/server/routes/agent-connections/types.ts @@ -1,6 +1,10 @@ +import type { ArtifactStorage } from "../../domains/artifacts/create-artifact-storage/types.ts" + export interface AgentConnectionRouteDependencies { applicationOrigin: string databaseUrl: string + /** Where Hub keeps agent screenshots; without it Hub refuses them. */ + artifactStorage?: ArtifactStorage learning: { cliPath: string learningDatabaseUrl?: string 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 new file mode 100644 index 000000000..291e00aab --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts @@ -0,0 +1,164 @@ +import pino from "pino" +import { describe, expect, it, vi } from "vitest" + +import { changeScreenshotConsent } from "../../../../domains/learning/change-screenshot-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("../../../../integrations/bullmq/create-job-queue", () => ({ + createJobQueue: vi.fn(() => ({ close: vi.fn() })), +})) +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 () => { + const provider = await prisma.authenticationProvider.create({ + data: { key: "github", enabled: false }, + }) + const revision = await prisma.authenticationProviderRevision.create({ + data: { configurationDigest: "a".repeat(64), providerId: provider.id, revision: 1 }, + }) + await prisma.authenticationProvider.update({ + data: { enabled: true, selectedRevisionId: revision.id }, + where: { id: provider.id }, + }) + const user = await prisma.user.create({ data: {} }) + const membership = await prisma.membership.create({ data: { userId: user.id } }) + const identity = await prisma.externalIdentity.create({ + data: { issuer: "https://github.com", provider: "github", subject: "17", userId: user.id }, + }) + await prisma.membershipAssignment.create({ + data: { + externalIdentityId: identity.id, + membershipId: membership.id, + role: "ADMINISTRATOR", + source: "BOOTSTRAP", + }, + }) + const revocation = await prisma.sessionRevocationState.findUniqueOrThrow({ + where: { key: "global" }, + }) + const sessionDigest = "b".repeat(64) + await prisma.hubSession.create({ + data: { + digest: sessionDigest, + expiresAt: new Date(Date.now() + 60_000), + externalIdentityId: identity.id, + membershipId: membership.id, + providerRevisionId: revision.id, + revocationRevision: revocation.revision, + }, + }) + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 17n, nameWithOwner: "octo/source" }, + }) + await prisma.repositoryAccessGrant.create({ + data: { + accessLevel: "ADMIN", + membershipId: membership.id, + observedAt: new Date(), + repositoryId: repository.id, + }, + }) + vi.mocked(changeScreenshotConsent).mockResolvedValueOnce("grant_1") + vi.mocked(changeScreenshotConsent).mockResolvedValueOnce(null) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + const change = { + actor: "human:mona", + actorMembershipId: membership.id, + repositoryId: repository.id, + sessionDigest, + } + + await expect( + learnings.changeEvaluationSettings({ ...change, screenshots: true }), + ).rejects.toMatchObject({ code: "evaluations_disabled", status: 409 }) + await learnings.changeEvaluationSettings({ ...change, enabled: true, screenshots: true }) + expect(await learnings.getEvaluationSettings(repository.id)).toMatchObject({ + enabled: true, + screenshots: { allowed: true }, + }) + await learnings.changeEvaluationSettings({ ...change, enabled: false }) + + expect(await learnings.getEvaluationSettings(repository.id)).toMatchObject({ + enabled: false, + screenshots: { allowed: false }, + }) + expect(vi.mocked(changeScreenshotConsent).mock.lastCall?.[0]).toMatchObject({ + allowed: false, + grantId: "grant_1", + }) + expect(vi.mocked(enqueueJob).mock.lastCall?.[2]).toEqual({ + repositoryId: repository.id, + grantId: "grant_1", + }) + }) + + it("lets only a signed-in Hub administrator change the shared budget", async () => { + const provider = await prisma.authenticationProvider.create({ + data: { key: "github", enabled: false }, + }) + const revision = await prisma.authenticationProviderRevision.create({ + data: { configurationDigest: "a".repeat(64), providerId: provider.id, revision: 1 }, + }) + await prisma.authenticationProvider.update({ + data: { enabled: true, selectedRevisionId: revision.id }, + where: { id: provider.id }, + }) + const user = await prisma.user.create({ data: {} }) + const membership = await prisma.membership.create({ data: { userId: user.id } }) + const identity = await prisma.externalIdentity.create({ + data: { issuer: "https://github.com", provider: "github", subject: "17", userId: user.id }, + }) + const revocation = await prisma.sessionRevocationState.findUniqueOrThrow({ + where: { key: "global" }, + }) + const sessionDigest = "b".repeat(64) + await prisma.hubSession.create({ + data: { + digest: sessionDigest, + expiresAt: new Date(Date.now() + 60_000), + externalIdentityId: identity.id, + membershipId: membership.id, + providerRevisionId: revision.id, + revocationRevision: revocation.revision, + }, + }) + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 17n, nameWithOwner: "octo/source" }, + }) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + const budget = { actorMembershipId: membership.id, sessionDigest, monthlyBudgetCredits: "12.5" } + + await expect(learnings.changeEvaluationBudget(budget)).rejects.toMatchObject({ + code: "hub_administrator_required", + status: 403, + }) + await prisma.membershipAssignment.create({ + data: { + externalIdentityId: identity.id, + membershipId: membership.id, + role: "ADMINISTRATOR", + source: "BOOTSTRAP", + }, + }) + await learnings.changeEvaluationBudget(budget) + + expect(await learnings.getEvaluationSettings(repository.id)).toMatchObject({ + monthlyBudgetCredits: "12.5", + }) + }) +}) 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 f0553c63e..403ce6b7c 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 @@ -15,6 +15,12 @@ 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 { deleteAgentScreenshotsJob } from "../../../../domains/learning/jobs/delete-agent-screenshots.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 { saveRepositoryEvaluationSetting } from "../../../../repositories/evaluation-settings/save-repository-evaluation-setting/index.ts" +import { updateEvaluationBudget } from "../../../../repositories/evaluation-settings/update-evaluation-budget/index.ts" import { createJobQueue } from "../../../../integrations/bullmq/create-job-queue/index.ts" import { enqueueJob } from "../../../../integrations/bullmq/enqueue-job/index.ts" import { LearningCommandError } from "../../../../integrations/learning/run-learning-command/errors.ts" @@ -32,6 +38,7 @@ import { deleteLearningDecisionOperation } from "../../../../repositories/learni import { listLearningShares } from "../../../../repositories/learning-shares/list-learning-shares/index.ts" import { saveLearningShare } from "../../../../repositories/learning-shares/save-learning-share/index.ts" import { withdrawLearningShare } from "../../../../repositories/learning-shares/withdraw-learning-share/index.ts" +import { lockAdministratorHubSession } from "../../../../repositories/hub-sessions/lock-administrator-hub-session/index.ts" import { isEffectiveAdministrator } from "../../../../repositories/memberships/is-effective-administrator/index.ts" import { findActiveRepository } from "../../../../repositories/prototype-index/find-active-repository/index.ts" import { lockRepositoryAdministratorAuthority } from "../../../../repositories/repository-access/lock-repository-administrator-authority/index.ts" @@ -151,6 +158,34 @@ export async function createLearningsRouteDependencies( return shared } + /** + * Queues removal of the screenshots a withdrawn grant allowed. A failed enqueue is only + * logged because the worker's recovery pass finds every withdrawn grant again. + */ + async function queueScreenshotDeletion(input: { + databaseUrl: string + grantId: string + repositoryId: string + }) { + const { grantId, repositoryId } = input + const queue = createJobQueue({ name: "on-demand", databaseUrl: input.databaseUrl, logger }) + try { + await enqueueJob( + queue, + deleteAgentScreenshotsJob, + { repositoryId, grantId }, + { jobId: `learning-screenshots-${repositoryId}-${grantId}` }, + ) + } catch (error) { + logger.warn( + { errorType: error instanceof Error ? error.name : "UnknownError", repositoryId }, + "Screenshot consent was withdrawn but its screenshot removal could not be queued", + ) + } finally { + await queue.close() + } + } + async function getCopilot() { const connection = await getCopilotConnection(prisma) const state = await getCopilotConnectionState(prisma) @@ -502,6 +537,144 @@ export async function createLearningsRouteDependencies( await queue.close() } }, + getEvaluationSettings: async (repositoryId) => { + const budget = await initializeEvaluationSetting(prisma) + const setting = await getRepositoryEvaluationSetting(prisma, repositoryId) + return { + // toFixed keeps tiny budgets in plain digits instead of forms like 1e-9. + monthlyBudgetCredits: budget.monthlyBudgetCredits.toFixed(), + enabled: setting?.enabled ?? false, + screenshots: { + allowed: Boolean(setting?.screenshotGrantId), + changedBy: setting?.screenshotsChangedByMembership?.user.profile?.login ?? null, + changedAt: setting?.screenshotsChangedAt?.toISOString() ?? null, + }, + } + }, + changeEvaluationSettings: async ({ actorMembershipId, sessionDigest, ...input }) => { + async function deny(): Promise { + await createSecurityAudit(prisma, { + id: randomUUID(), + type: "repository_administration_denied", + actorMembershipId, + operation: "learning_evaluation", + reason: "authority_missing", + repositoryId: input.repositoryId, + }) + throw new LearningsError( + 403, + "repository_administrator_required", + "Repository administrator access is required.", + ) + } + // Each step re-locks the person's session, so losing access between steps stops + // the change rather than finishing it on authority they no longer hold. + function withAuthority( + operation: (transaction: Prisma.TransactionClient) => Promise, + ) { + return runRepositoryAuthorityTransaction(async (transaction) => + (await lockRepositoryAdministratorSession(transaction, { + membershipId: actorMembershipId, + repositoryId: input.repositoryId, + sessionDigest, + })) + ? { value: await operation(transaction) } + : null, + ) + } + try { + // Consent lives in the learning store, so one change at a time keeps Hub's + // record and the store's grant from drifting apart. + await withLearningExecutionLock({ + databaseUrl, + protectSessionAuthority: true, + run: async (signal) => { + const read = await withAuthority(async (transaction) => ({ + repositoryScope: await getLearningRepositoryScope(transaction, input.repositoryId), + setting: await getRepositoryEvaluationSetting(transaction, input.repositoryId), + })) + if (!read) return deny() + const { repositoryScope, setting } = read.value + const enabled = input.enabled ?? setting?.enabled ?? false + const grantId = setting?.screenshotGrantId ?? null + // Screenshots only serve evaluations, so turning evaluations off withdraws + // them too. + const allowed = enabled && (input.screenshots ?? Boolean(grantId)) + if (input.screenshots && !enabled) { + throw new LearningsError( + 409, + "evaluations_disabled", + "Turn on automated evaluations before allowing screenshots.", + ) + } + if (enabled !== (setting?.enabled ?? false)) { + if ( + !(await withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { enabled }), + )) + ) { + return deny() + } + } + if (allowed === Boolean(grantId)) return + const nextGrantId = await changeScreenshotConsent({ + ...configuration, + actor: input.actor, + allowed, + grantId, + repositoryId: input.repositoryId, + repositoryScope, + signal, + }) + const saved = await withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { + screenshotGrantId: nextGrantId, + screenshotsChangedAt: new Date(), + screenshotsChangedByMembershipId: actorMembershipId, + }), + ) + if (!saved) return deny() + if (grantId && !allowed) + await queueScreenshotDeletion({ + databaseUrl, + grantId, + repositoryId: input.repositoryId, + }) + }, + }) + } catch (error) { + if ( + error instanceof Error && + error.message === "Another learning operation is still running." + ) { + throw new LearningsError( + 409, + "learning_execution_busy", + "Another learning operation is still running.", + { cause: error }, + ) + } + throw error + } + return { notice: "Evaluation settings saved." } + }, + changeEvaluationBudget: async ({ actorMembershipId, sessionDigest, monthlyBudgetCredits }) => { + const saved = await runRepositoryAuthorityTransaction(async (transaction) => { + // Locking the session keeps a sign-out or demotion from landing mid-save. + const session = await lockAdministratorHubSession(transaction, sessionDigest) + if (session?.membershipId !== actorMembershipId) return false + await updateEvaluationBudget(transaction, monthlyBudgetCredits) + return true + }) + if (!saved) { + throw new LearningsError( + 403, + "hub_administrator_required", + "Hub administrator access is required.", + ) + } + return { notice: "Budget saved." } + }, serializeReviewCommentDeletion: (operation) => withLearningExecutionLock({ databaseUrl, diff --git a/hub/server/routes/api/learnings/evaluation-budget/patch/index.ts b/hub/server/routes/api/learnings/evaluation-budget/patch/index.ts new file mode 100644 index 000000000..c6d18e902 --- /dev/null +++ b/hub/server/routes/api/learnings/evaluation-budget/patch/index.ts @@ -0,0 +1,55 @@ +import type { RequestHandler } from "express" +import { z } from "zod" + +import { readLearningSession } from "../../read-learning-session/index.ts" +import { readLearningSessionDigest } from "../../read-learning-session-digest/index.ts" +import { respondLearningError } from "../../respond-learning-error/index.ts" +import type { LearningsRouteDependencies } from "../../types.ts" + +const budgetSchema = z + .object({ + monthlyBudgetCredits: z + .string() + .max(20) + .regex(/^(?:0|[1-9]\d*)(?:\.\d{1,9})?$/) + .refine((value) => Number(value) <= 1_000_000), + }) + .strict() +const denied = { + code: "hub_administrator_required", + error: "Hub administrator access is required.", +} + +/** + * Sets the monthly credit budget every repository's automated evaluations share. Credits + * are paid by the whole Hub, so only Hub administrators may change it. + */ +export function patch(dependencies: LearningsRouteDependencies): RequestHandler { + return async (request, response, next) => { + try { + const budget = budgetSchema.safeParse(request.body) + if (!budget.success) { + response.status(422).json({ + code: "invalid_evaluation_budget", + error: "Enter a budget from 0 to 1,000,000 credits.", + }) + return + } + const session = await readLearningSession(request, dependencies) + const sessionDigest = readLearningSessionDigest(request) + if (!session || session.role !== "ADMINISTRATOR" || !sessionDigest) { + response.status(403).json(denied) + return + } + response.json( + await dependencies.changeEvaluationBudget({ + actorMembershipId: session.membershipId, + sessionDigest, + monthlyBudgetCredits: budget.data.monthlyBudgetCredits, + }), + ) + } catch (error) { + if (!respondLearningError(response, error)) next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/evaluations/get/index.ts b/hub/server/routes/api/learnings/evaluations/get/index.ts new file mode 100644 index 000000000..f21288768 --- /dev/null +++ b/hub/server/routes/api/learnings/evaluations/get/index.ts @@ -0,0 +1,67 @@ +import type { RequestHandler } from "express" +import { z } from "zod" + +import { readLearningSession } from "../../read-learning-session/index.ts" +import { respondLearningError } from "../../respond-learning-error/index.ts" +import type { LearningsRouteDependencies } from "../../types.ts" + +/** + * Serves a repository's automated evaluation settings. Hub administrators set the shared + * budget and repository administrators choose what the repository allows, so either may + * read the page. Access is read again after loading so a lost role never sees more. + */ +export function get(dependencies: LearningsRouteDependencies): RequestHandler { + return async (request, response, next) => { + try { + const repositoryId = z.uuid().safeParse(request.params.repositoryId) + if (!repositoryId.success) { + response.status(400).json({ + code: "invalid_repository", + error: "Enter a valid repository address.", + }) + return + } + const initial = await readLearningSession(request, dependencies) + if (!initial) { + response.status(401).json({ code: "sign_in_required", error: "Sign in to continue." }) + return + } + const repository = await dependencies.findRepository(initial, repositoryId.data) + if (!repository) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + const settings = await dependencies.getEvaluationSettings(repository.id) + const current = await readLearningSession(request, dependencies) + if (!current || current.membershipId !== initial.membershipId) { + response.status(401).json({ code: "sign_in_required", error: "Sign in to continue." }) + return + } + if (!(await dependencies.findRepository(current, repository.id))) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + const changeBudget = current.role === "ADMINISTRATOR" + const changeRepository = await dependencies.authorizeRepositoryAdministration({ + membershipId: current.membershipId, + repositoryId: repository.id, + }) + if (!changeBudget && !changeRepository) { + response.status(403).json({ + code: "repository_administrator_required", + error: "Repository administrator access is required.", + }) + return + } + response.json({ + repository, + // Usage is counted once evaluations run against Builds. + usedCredits: "0", + ...settings, + permissions: { changeBudget, changeRepository }, + }) + } catch (error) { + if (!respondLearningError(response, error)) next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/evaluations/patch/index.ts b/hub/server/routes/api/learnings/evaluations/patch/index.ts new file mode 100644 index 000000000..5f828d4c5 --- /dev/null +++ b/hub/server/routes/api/learnings/evaluations/patch/index.ts @@ -0,0 +1,104 @@ +import type { RequestHandler } from "express" +import { z } from "zod" + +import { readLearningSession } from "../../read-learning-session/index.ts" +import { readLearningSessionDigest } from "../../read-learning-session-digest/index.ts" +import { respondLearningError } from "../../respond-learning-error/index.ts" +import type { ProductViewer } from "../../../product/types.ts" +import type { LearningsRouteDependencies } from "../../types.ts" + +const changeSchema = z + .object({ enabled: z.boolean().optional(), screenshots: z.boolean().optional() }) + .strict() +const denied = { + code: "repository_administrator_required", + error: "Repository administrator access is required.", +} + +/** Why a signed-in member may not change this repository's evaluations, if any. */ +async function checkAccess( + dependencies: LearningsRouteDependencies, + session: ProductViewer, + repositoryId: string, +) { + const { membershipId } = session + if (!(await dependencies.findRepository(session, repositoryId))) { + return { + status: 404, + body: { code: "repository_not_found", error: "Repository not found." }, + } + } + if (!(await dependencies.authorizeRepositoryAdministration({ membershipId, repositoryId }))) { + await dependencies.auditRepositoryAdministrationDenial({ + actorMembershipId: membershipId, + operation: "learning_evaluation", + repositoryId, + }) + return { status: 403, body: denied } + } + return null +} + +/** + * Turns a repository's automated evaluations or agent screenshots on or off. Only the + * repository's administrators speak for what it allows. Access is read twice so a change + * mid-request counts. + */ +export function patch(dependencies: LearningsRouteDependencies): RequestHandler { + return async (request, response, next) => { + try { + const repositoryId = z.uuid().safeParse(request.params.repositoryId) + if (!repositoryId.success) { + response.status(400).json({ + code: "invalid_repository", + error: "Enter a valid repository address.", + }) + return + } + const change = changeSchema.safeParse(request.body) + if (!change.success) { + response.status(422).json({ + code: "invalid_evaluation_settings", + error: "Choose which evaluation settings to change and try again.", + }) + return + } + const initial = await readLearningSession(request, dependencies) + if (!initial) { + response.status(403).json(denied) + return + } + const initialAccess = await checkAccess(dependencies, initial, repositoryId.data) + if (initialAccess) { + response.status(initialAccess.status).json(initialAccess.body) + return + } + const current = await readLearningSession(request, dependencies) + if (!current || current.membershipId !== initial.membershipId) { + response.status(403).json(denied) + return + } + const currentAccess = await checkAccess(dependencies, current, repositoryId.data) + if (currentAccess) { + response.status(currentAccess.status).json(currentAccess.body) + return + } + const sessionDigest = readLearningSessionDigest(request) + if (!sessionDigest) { + response.status(403).json(denied) + return + } + response.json( + await dependencies.changeEvaluationSettings({ + repositoryId: repositoryId.data, + actor: `human:${current.login}`, + actorMembershipId: current.membershipId, + sessionDigest, + ...change.data, + }), + ) + } catch (error) { + if (!respondLearningError(response, error)) next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index 907e66b60..1c9ae5e17 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -10,6 +10,8 @@ import { LearningCommandError } from "../../../integrations/learning/run-learnin import { LearningsError } from "./errors.ts" import { post as postDecision } from "./decision/post/index.ts" import { get as getLearnings } from "./get/index.ts" +import { get as getEvaluations } from "./evaluations/get/index.ts" +import { patch as patchEvaluations } from "./evaluations/patch/index.ts" import { get as getLearningHistory } from "./history/get/index.ts" import { post as postRun } from "./runs/post/index.ts" import { post as postShare } from "./share/post/index.ts" @@ -59,6 +61,13 @@ function dependencies( listActivity: vi.fn().mockResolvedValue([]), decide: vi.fn().mockResolvedValue({ notice: "Learning accepted." }), share: vi.fn().mockResolvedValue({ notice: "Shared across Hub." }), + getEvaluationSettings: vi.fn().mockResolvedValue({ + monthlyBudgetCredits: "0", + enabled: false, + screenshots: { allowed: false, changedBy: null, changedAt: null }, + }), + changeEvaluationSettings: vi.fn().mockResolvedValue({ notice: "Evaluation settings saved." }), + changeEvaluationBudget: vi.fn().mockResolvedValue({ notice: "Budget saved." }), redactComment: vi.fn().mockResolvedValue(undefined), serializeReviewCommentDeletion: (operation) => operation(), ...overrides, @@ -66,7 +75,7 @@ function dependencies( } async function withRoute( - method: "get" | "post", + method: "get" | "post" | "patch", path: string, handler: RequestHandler, operation: (baseUrl: string) => Promise, @@ -74,6 +83,7 @@ async function withRoute( const app = express() app.use(express.json()) if (method === "get") app.get(path, handler) + else if (method === "patch") app.patch(path, handler) else app.post(path, handler) const server = createServer(app) server.listen(0, "127.0.0.1") @@ -866,4 +876,86 @@ describe("learning routes", () => { ) }, ) + it("hides evaluation settings from a member who administers neither Hub nor the repository", async () => { + const deps = dependencies({ + authorizeRepositoryAdministration: vi.fn().mockResolvedValue(false), + }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/evaluations", + getEvaluations(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/evaluations`, + { headers }, + ) + + expect(response.status).toBe(403) + }, + ) + }) + it("refuses and records an evaluation change from a member who is not a repository administrator", async () => { + const changeEvaluationSettings = vi.fn() + const auditRepositoryAdministrationDenial = vi.fn().mockResolvedValue(undefined) + const deps = dependencies({ + authorizeRepositoryAdministration: vi.fn().mockResolvedValue(false), + auditRepositoryAdministrationDenial, + changeEvaluationSettings, + }) + + await withRoute( + "patch", + "/api/repositories/:repositoryId/learnings/evaluations", + patchEvaluations(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/evaluations`, + { + method: "PATCH", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ enabled: true }), + }, + ) + + expect(response.status).toBe(403) + expect(auditRepositoryAdministrationDenial).toHaveBeenCalledWith({ + actorMembershipId: session.membershipId, + operation: "learning_evaluation", + repositoryId, + }) + expect(changeEvaluationSettings).not.toHaveBeenCalled() + }, + ) + }) + it("saves a repository administrator's evaluation change under their current session", async () => { + const changeEvaluationSettings = vi.fn().mockResolvedValue({ notice: "Saved." }) + const deps = dependencies({ changeEvaluationSettings }) + + await withRoute( + "patch", + "/api/repositories/:repositoryId/learnings/evaluations", + patchEvaluations(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/evaluations`, + { + method: "PATCH", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ enabled: true, screenshots: true }), + }, + ) + + expect(response.status).toBe(200) + expect(changeEvaluationSettings).toHaveBeenCalledWith({ + repositoryId, + actor: "human:mona", + actorMembershipId: session.membershipId, + sessionDigest: hashAuthenticationValue("current-session"), + enabled: true, + screenshots: true, + }) + }, + ) + }) }) diff --git a/hub/server/routes/api/learnings/types.ts b/hub/server/routes/api/learnings/types.ts index c9793c8b8..58f5bfb64 100644 --- a/hub/server/routes/api/learnings/types.ts +++ b/hub/server/routes/api/learnings/types.ts @@ -49,6 +49,12 @@ export interface LearningActivityDay { suggestions: number } +export interface EvaluationSettings { + monthlyBudgetCredits: string + enabled: boolean + screenshots: { allowed: boolean; changedBy: string | null; changedAt: string | null } +} + export interface LearningsRouteDependencies { applicationOrigin: string automaticRunsEnabled: boolean @@ -67,7 +73,12 @@ export interface LearningsRouteDependencies { }): Promise auditRepositoryAdministrationDenial(input: { actorMembershipId: string - operation: "learning_overview" | "learning_run" | "learning_decision" | "learning_share" + operation: + | "learning_overview" + | "learning_run" + | "learning_decision" + | "learning_share" + | "learning_evaluation" repositoryId: string }): Promise getOverview(input: { repositoryId: string; viewer: string }): Promise<{ @@ -116,6 +127,20 @@ export interface LearningsRouteDependencies { shared: boolean sessionDigest: string }): Promise<{ notice: string }> + getEvaluationSettings(repositoryId: string): Promise + changeEvaluationSettings(input: { + repositoryId: string + actor: string + actorMembershipId: string + sessionDigest: string + enabled?: boolean + screenshots?: boolean + }): Promise<{ notice: string }> + changeEvaluationBudget(input: { + actorMembershipId: string + sessionDigest: string + monthlyBudgetCredits: string + }): Promise<{ notice: string }> redactComment(input: { repositoryId: string commentId: number diff --git a/hub/server/routes/api/security-audits/present-security-audit/index.ts b/hub/server/routes/api/security-audits/present-security-audit/index.ts index 7efb061bd..53c918902 100644 --- a/hub/server/routes/api/security-audits/present-security-audit/index.ts +++ b/hub/server/routes/api/security-audits/present-security-audit/index.ts @@ -29,6 +29,7 @@ const repositoryAdministrationOperationSchema = z.enum([ "learning_run", "learning_decision", "learning_share", + "learning_evaluation", ]) function actorFor(record: SecurityAuditListRecord) { @@ -106,6 +107,7 @@ function actorFor(record: SecurityAuditListRecord) { case "repository.administration.learning_run.denied": case "repository.administration.learning_decision.denied": case "repository.administration.learning_share.denied": + case "repository.administration.learning_evaluation.denied": case "decision.training.requested": case "decision.training.cancelled": case "decision.training.failed": @@ -442,7 +444,8 @@ function contextFor(record: SecurityAuditListRecord): Record { "deliver-analytics-event", "learning.run", "learning.redact-review-comment", + "learning.delete-agent-screenshots", "synchronize-local-builds", "import-github-workflow-run", ]) diff --git a/hub/server/workers/configuration.ts b/hub/server/workers/configuration.ts index aa3528277..8147085ec 100644 --- a/hub/server/workers/configuration.ts +++ b/hub/server/workers/configuration.ts @@ -75,6 +75,7 @@ const jobProcessors: Record = { ...(decisionConfigured ? [decision.run] : []), learning.run, learning.redact, + learning.deleteScreenshots, createJobProcessor(getLocalBuildJobDefinition(), async () => { const { runLocalBuilds } = await import("../scripts/run-local-builds/index.ts") return await runLocalBuilds() diff --git a/packages/learning/README.md b/packages/learning/README.md index c9e7d977b..70067ddfb 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -52,7 +52,7 @@ node /packages/learning/bin/replica-learning.mjs doctor | `memories`, `show ` | Lists learnings and shows one with its evidence and digests | | `accept`, `reject`, `retire`, `edit`, `reinstate`, `supersede` | Records a person's decision | | `recall --task ` | Prints the accepted learnings for the next run. `--task-file -` reads the task from standard input instead, which keeps a person's prompt out of the process list. `--session-id` and `--session-label` name the agent session asking. Each recall stores a guidance record and the exact text of each learning it gave, so a later report can name them. `--preview --by github:` shows a person the same text without recording a use. Only a person can preview, so an agent never reads learnings without an audit entry. A host such as Hub adds learnings other repositories shared to a preview with `--shared-file`, a JSON list of their accepted records read from their own stores. Recall refuses a damaged, unaccepted, or same-repository record. It leaves out a shared learning whose ID matches one of the repository's own, and keeps one copy of an ID that two sources share. A recall that stores deliveries refuses shared learnings, because a stored copy would outlive the source's deletion | -| `report-usage ` | Records which recalled learnings an agent says it used for a commit. The report names its own `reportId`, so sending it again stores nothing new. Each used learning names the `deliveryId` recall gave it, and may add a before and an after screenshot as a PNG file beside the report. Only each screenshot's digest is recorded; the bytes are kept under `evidence/` in the learning data directory. A report is the agent's claim, never a verified result | +| `report-usage ` | Records which recalled learnings an agent says it used for a commit. The report names its own `reportId`, so sending it again stores nothing new. Each used learning names the `deliveryId` recall gave it, and may add a before and an after screenshot as a PNG file beside the report. Only each screenshot's digest is recorded; in a local store the bytes are kept under `evidence/` in the learning data directory. A hosted store keeps no bytes and accepts screenshots only with `--grant `, an active grant for `evaluation` that lists the `agent_screenshots` source. A report is the agent's claim, never a verified result | | `delete --reason ` | Removes a learning for good: every version, the records of its deliveries and use, and their screenshots. A learning that is part of a replacement, or that a stored proposal would replace, cannot be deleted; retire it instead | | `expire-guidance [--days ]` | Removes guidance records older than `--days`, 365 by default, that no usage report names | | `delete-repository --confirm ` | Removes every record this repository's store holds, including its audit trail. Naming the repository again guards against deleting the wrong store. Copies outside the store, such as exports, are not touched | @@ -80,7 +80,7 @@ An agent session file for `import agent-session` looks like this. Only `sessionI } ``` -To report use, run recall once with `--json` and keep its output. `guidanceId` names the recall and each entry in `memories` carries its `deliveryId`. A second recall gives new IDs, so report against the recall the agent actually read. Then write `report.json` beside any screenshots and send it with `report-usage report.json --actor agent:`. Only `reportId`, `guidanceIds`, and `commitSha` are required. A screenshot names a PNG `file` in the report's directory, with the `route`, `viewport`, `theme`, and `capturedAt` it was taken with. +To report use, run recall once with `--json` and keep its output. `guidanceId` names the recall and each entry in `memories` carries its `deliveryId`. A second recall gives new IDs, so report against the recall the agent actually read. Then write `report.json` beside any screenshots and send it with `report-usage report.json --actor agent:`. Only `reportId`, `guidanceIds`, and `commitSha` are required. A screenshot names a PNG `file` in the report's directory, or carries its bytes as base64 `data`, with the `route`, `viewport`, `theme`, and `capturedAt` it was taken with. In a hosted store, the host saves the bytes itself and names the screenshot consent grant with `--grant`; without an active grant the report is refused, so the agent can send it again without screenshots. ```json { @@ -130,7 +130,7 @@ The agent gets these tools: | Tool | What it does | | --- | --- | | `get_guidance` | Returns the framed text `recall` gives for a task, with a `guidanceId` and each learning's `id` and `deliveryId` | -| `report_usage` | Records which delivered learnings a commit applied, like `report-usage`. A screenshot names a PNG file inside the directory the server runs in | +| `report_usage` | Records which delivered learnings a commit applied, like `report-usage`. A screenshot names a PNG file inside the directory the server runs in, or carries base64 `data` | | `submit_session` | Stores the session's user and agent messages and its outcome, like `import agent-session`, including its position rules. A person must start the server with `--grant ` for a grant that names `agent_session`; without one, the tool refuses | | `list_learnings`, `get_learning` | Read learnings for the instruction purpose, so the agent sees only the text recall could give it. Other learnings show only their state. For a proposed learning, `get_learning` gives the exact `accept` and `reject` commands for a person to run in the same store | diff --git a/packages/learning/index.d.mts b/packages/learning/index.d.mts index 55f9b600f..4303c39fe 100644 --- a/packages/learning/index.d.mts +++ b/packages/learning/index.d.mts @@ -1077,6 +1077,11 @@ export interface LearningStore { session?: AgentSessionRef prototypeId?: string used: Array<{ deliveryId: string; before?: UsageScreenshot; after?: UsageScreenshot }> + /** + * An active evaluation grant for agent screenshots. Required for screenshots when the + * screenshot store requiresGrant, as on a host. + */ + consentGrantId?: string }, ): Promise<{ id: string; reportId: string; stored: boolean }> /** Remove a learning for good, with its deliveries, use, and screenshots. Needs a person. */ @@ -1148,6 +1153,8 @@ export declare class ProviderConflictError extends LearningError {} /** Where a store keeps screenshot images; records hold only their sha256. */ export interface ScreenshotStore { + /** True when the host keeps the bytes, so screenshots need a consent grant. */ + requiresGrant?: boolean put(bytes: Uint8Array): Promise read(digest: Digest): Promise remove(digest: Digest): Promise diff --git a/packages/learning/mcp.d.mts b/packages/learning/mcp.d.mts index 574ea1f4a..814151863 100644 --- a/packages/learning/mcp.d.mts +++ b/packages/learning/mcp.d.mts @@ -42,9 +42,8 @@ export interface LearningMcpBackend { getLearning(input: { id: string }): Promise } -/** A screenshot an agent names by a PNG file's path. */ -export interface McpScreenshot { - file: string +/** A screenshot an agent names by a PNG file's path, or sends as base64 PNG data. */ +export type McpScreenshot = ({ file: string; data?: never } | { data: string; file?: never }) & { route: string viewport: { width: number; height: number } theme: string diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index 6ba474508..cfd8820fc 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -114,14 +114,16 @@ Use list of records; --preview shows a person what an agent would get, unaudited - report-usage --actor + report-usage --actor [--grant ] Record which recalled learnings an agent used for a - commit, with optional before and after screenshots + commit, with optional before and after screenshots; + --grant names the consent that allows them export --purpose

--by [--out ] [--learnings-only] [--preview] mcp [--actor ] [--grant ]... Serve the learning tools to a coding agent over standard input and output; --grant lets it submit - sessions, and screenshots must sit in this directory + sessions and, for a screenshot grant, screenshots, + which must sit in this directory Decision model decision models Base models suggested for checking screenshots @@ -1358,19 +1360,25 @@ function sessionOption(session) { } /** - * report-usage: the report file names each screenshot by a PNG file beside it, so the bytes - * are read here and only their digest reaches the records. + * report-usage: the report file names each screenshot by a PNG file beside it, or carries + * its base64 data, so the bytes are read here and only their digest reaches the records. */ async function reportUsage(session) { const file = argument(session, 1, "report file") const report = await readJsonFile(session, file) const directory = path.dirname(path.resolve(session.cwd, file)) const principal = actor(session, { required: true }) + if ((session.values.grant?.length ?? 0) > 1) + throw new UsageError("Name at most one --grant for a usage report.") if (!report || typeof report !== "object" || Array.isArray(report)) throw new LearningError("invalid_input", `${file} must be a JSON object.`) const used = await readReportScreenshots(directory, report.used) const { store } = await open(session) - const result = await store.reportUsage(context(session, principal), { ...report, used }) + const result = await store.reportUsage(context(session, principal), { + ...report, + used, + ...(session.values.grant ? { consentGrantId: session.values.grant[0] } : {}), + }) session.out( result, result.stored @@ -1380,9 +1388,9 @@ async function reportUsage(session) { } /** - * Swap each screenshot's file for its bytes. The store checks these limits too, but only - * after every file is in memory, so the count and total size are checked here first and - * files are read one at a time. + * Swap each screenshot's file or base64 data for its bytes. The store checks these limits + * too, but only after every file is in memory, so the count and total size are checked here + * first and files are read one at a time. */ async function readReportScreenshots(directory, items) { if (!Array.isArray(items)) return items @@ -1397,7 +1405,10 @@ async function readReportScreenshots(directory, items) { } const copy = { ...item } for (const role of ["before", "after"]) - if (copy[role]?.file !== undefined) { + if (copy[role]?.data !== undefined) { + copy[role] = screenshotData(copy[role], MAX_REPORT_SCREENSHOT_BYTES - total) + total += copy[role].bytes.length + } else if (copy[role]?.file !== undefined) { copy[role] = await screenshotFile( directory, copy[role], @@ -1410,6 +1421,25 @@ async function readReportScreenshots(directory, items) { return used } +function screenshotData({ data, file, ...rest }, remaining) { + if (file !== undefined) + throw new LearningError("invalid_input", "A screenshot names a file or carries data, not both.") + // Strict base64, so a typo is refused instead of silently decoding to other bytes. + if ( + typeof data !== "string" || + !data || + data.length % 4 !== 0 || + !/^[A-Za-z0-9+/]+={0,2}$/.test(data) + ) + throw new LearningError("invalid_input", "A screenshot's data must be base64 PNG bytes.") + if (Math.floor((data.length * 3) / 4) > MAX_SCREENSHOT_BYTES + 2) + throw new LearningError("invalid_input", "A screenshot can be at most 10 MB.") + const bytes = Buffer.from(data, "base64") + if (bytes.length > remaining) + throw new LearningError("invalid_input", "A report's screenshots can total at most 100 MB.") + return { ...rest, bytes } +} + async function screenshotFile(directory, { file, ...rest }, remaining) { if (typeof file !== "string" || !file) throw new LearningError("invalid_input", "A screenshot names its PNG file.") @@ -1483,6 +1513,15 @@ async function serveMcp(session) { await store.close() } } + // Of the grants this server started with, the one that allows screenshots now. + async function screenshotGrantId(store, ctx) { + return (await store.listGrants(ctx)).find( + ({ grant, activePurposes }) => + session.values.grant?.includes(grant.id) && + grant.sources.includes("agent_screenshots") && + activePurposes.includes("evaluation"), + )?.grant.id + } const server = mcp.createLearningMcpServer( { getGuidance: ({ task, limit, session: agentSession }) => @@ -1498,11 +1537,20 @@ async function serveMcp(session) { guidanceId: result.guidanceId, text: result.text, learnings: result.memories.map(({ id, deliveryId }) => ({ id, deliveryId })), + screenshotsAllowed: Boolean(await screenshotGrantId(store, ctx)), } }), reportUsage: async (report) => { const used = await readReportScreenshots(session.cwd, report.used) - return withStore((store, ctx) => store.reportUsage(ctx, { ...report, used })) + return withStore(async (store, ctx) => { + const hasShots = used?.some?.((item) => item?.before || item?.after) + const screenshotGrant = hasShots ? await screenshotGrantId(store, ctx) : undefined + return store.reportUsage(ctx, { + ...report, + used, + ...(screenshotGrant ? { consentGrantId: screenshotGrant } : {}), + }) + }) }, submitSession: (input) => { if (!session.values.grant?.length) diff --git a/packages/learning/src/config.mjs b/packages/learning/src/config.mjs index 5d0f0c17e..ad308bef5 100644 --- a/packages/learning/src/config.mjs +++ b/packages/learning/src/config.mjs @@ -29,7 +29,7 @@ import { createFileLock } from "./providers/lock.mjs" import { createPostgresMemoryProvider } from "./providers/postgres.mjs" import { backupSqliteMemoryStore, createSqliteMemoryProvider } from "./providers/sqlite.mjs" import { migrateRepositoryScope } from "./scope-migration.mjs" -import { createScreenshotStore } from "./screenshots.mjs" +import { createHostKeptScreenshotStore, createScreenshotStore } from "./screenshots.mjs" import { createLearningStore, scopeProblem } from "./store.mjs" /** @@ -576,13 +576,17 @@ export async function openLearningStore(environment, { clock = Date.now } = {}) clock, legacyScopes: migrations.map((migration) => migration.oldScope), digestMappings, - // The bytes stay on this machine, so a store other machines can read, through a - // hosted CLI or a shared database, keeps no screenshots. - ...(environment.hosted || !LOCAL_PROVIDERS.includes(source) - ? {} - : { - screenshots: createScreenshotStore(path.join(environment.dataDirectory, "evidence")), - }), + // A local store keeps the bytes on this machine. A hosted store leaves them to its + // host. A shared database reached without a host keeps none. + ...(environment.hosted + ? { screenshots: createHostKeptScreenshotStore() } + : !LOCAL_PROVIDERS.includes(source) + ? {} + : { + screenshots: createScreenshotStore( + path.join(environment.dataDirectory, "evidence"), + ), + }), }), providerSource: source, migrationRedactionFollowUps: migrations diff --git a/packages/learning/src/mcp.mjs b/packages/learning/src/mcp.mjs index 0e570ea97..0a39f991f 100644 --- a/packages/learning/src/mcp.mjs +++ b/packages/learning/src/mcp.mjs @@ -9,7 +9,7 @@ const INSTRUCTIONS = `This server holds the learnings a team accepted from past Before you start a task, call get_guidance with a short description of the task and follow the learnings it returns. Keep its guidanceId and each learning's deliveryId. -When a learning may change something visible, capture a screenshot before you edit and another once the change is in place, when screenshots are allowed. After you commit, call report_usage with the commit SHA and only the learnings you actually applied. +When a learning may change something visible, capture a screenshot before you edit and another once the change is in place, but only when get_guidance returned screenshotsAllowed: true. After you commit, call report_usage with the commit SHA and only the learnings you actually applied. When the session ends, call submit_session with the conversation so reviewers' feedback can become new learnings. @@ -24,7 +24,14 @@ const session = z const screenshot = z .object({ - file: z.string().describe("A PNG file's path, inside the directory the server runs in."), + file: z + .string() + .optional() + .describe("A PNG file's path, inside the directory the server runs in. Local only."), + data: z + .string() + .optional() + .describe("The PNG bytes in base64, instead of file. Hub accepts only this."), route: z.string().describe("The prototype route shown, such as /settings."), viewport: z.object({ width: z.number().int(), height: z.number().int() }), theme: z.string().describe("The color theme shown, such as light or dark."), @@ -79,7 +86,7 @@ export function createLearningMcpServer( { title: "Get guidance", description: - "Returns the accepted learnings that fit a task, as text to follow plus each learning's id and deliveryId. Records that this guidance was given. Call it before starting work.", + "Returns the accepted learnings that fit a task, as text to follow plus each learning's id and deliveryId, and whether report_usage accepts screenshots. Records that this guidance was given. Call it before starting work.", inputSchema: { task: z.string().optional().describe("A short description of the task."), limit: z.number().int().positive().optional().describe("The most learnings to return."), @@ -93,7 +100,7 @@ export function createLearningMcpServer( { title: "Report usage", description: - "Records which delivered learnings you applied in a commit. When screenshots are allowed, capture a before screenshot ahead of the edit and an after screenshot once the change is in place. Sending the same reportId again changes nothing.", + "Records which delivered learnings you applied in a commit. When get_guidance said screenshotsAllowed, capture a before screenshot ahead of the edit and an after screenshot once the change is in place. Sending the same reportId again changes nothing.", inputSchema: { reportId: z.string().describe("An ID you choose, so a retry is not counted twice."), guidanceIds: z diff --git a/packages/learning/src/screenshots.mjs b/packages/learning/src/screenshots.mjs index 98e214baa..8c72507ed 100644 --- a/packages/learning/src/screenshots.mjs +++ b/packages/learning/src/screenshots.mjs @@ -122,3 +122,22 @@ export function createScreenshotStore(directory) { }, } } + +/** + * For a hosted store, where the host keeps screenshot bytes in its own storage. The store + * still checks each image and records its digest, but keeps no bytes, so a report with + * screenshots needs an active screenshot consent grant the host recorded. + */ +export function createHostKeptScreenshotStore() { + return { + requiresGrant: true, + async put(bytes) { + assertScreenshot(bytes) + return screenshotDigest(bytes) + }, + async read() { + return null + }, + async remove() {}, + } +} diff --git a/packages/learning/src/store.mjs b/packages/learning/src/store.mjs index 1fd7850fb..ac265ecfc 100644 --- a/packages/learning/src/store.mjs +++ b/packages/learning/src/store.mjs @@ -75,6 +75,8 @@ const DIGEST = /^sha256:[0-9a-f]{64}$/ const SUBJECTS_PER_ENTRY = 10_000 const REPORT_ID = /^[A-Za-z0-9._:-]{1,128}$/ const COMMIT_SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/ +/** The grant source a person names to allow evaluating agent screenshots. */ +const SCREENSHOT_SOURCE = "agent_screenshots" const DAY_MS = 24 * 60 * 60 * 1000 // The streams that hold what agents received and said they used. const MEMORY_STATES = ["proposed", "accepted", "rejected", "retired"] @@ -3337,12 +3339,13 @@ class LearningStore { * stored one and writes nothing; sending other content under the same ID is a conflict. * * Each used learning may carry a before and an after screenshot: { role, route, viewport, - * theme, capturedAt, bytes }. The images stay on this machine; records hold only their - * SHA-256. A store opened without a screenshot store refuses screenshots. + * theme, capturedAt, bytes }. Records hold only each image's SHA-256. A store opened + * without a screenshot store refuses screenshots. A hosted store keeps no bytes, so its + * screenshots need consentGrantId: an active grant for evaluation of agent screenshots. */ async reportUsage( context, - { reportId, guidanceIds, commitSha, session, prototypeId, used = [] } = {}, + { reportId, guidanceIds, commitSha, session, prototypeId, used = [], consentGrantId } = {}, ) { assertContext(context) if (typeof reportId !== "string" || !REPORT_ID.test(reportId)) @@ -3393,6 +3396,12 @@ class LearningStore { "unsupported", "This store does not keep screenshots. Send the report without them.", ) + if ( + consentGrantId !== undefined && + (typeof consentGrantId !== "string" || !RECORD_ID.test(consentGrantId)) + ) + throw new LearningError("invalid_input", "A consent grant ID names a stored grant.") + const grantId = shots.length ? consentGrantId : undefined const contentDigest = digestOf({ reportId, guidanceIds, @@ -3405,6 +3414,9 @@ class LearningStore { after: after ? without(after, "bytes") : null, })), }) + // Checked before a retry returns too, so a host never keeps bytes after consent ends. + if (grantId !== undefined || (shots.length && this.#screenshots.requiresGrant)) + await this.#assertScreenshotGrant(context, grantId, shots) const id = derivedId("usage", { scope: context.scope, reportId }) const [stored] = await this.#read("usageReports", context, { ids: [id] }) if (stored) { @@ -3469,6 +3481,7 @@ class LearningStore { viewport: shot.viewport, theme: shot.theme, capturedAt: shot.capturedAt, + ...(grantId ? { consentGrantId: grantId } : {}), }) assertValid("screenshot", record) screenshots.set(record.id, record) @@ -3516,6 +3529,29 @@ class LearningStore { return { id, reportId, stored: result.usageReports.appended === 1 } } + /** + * Refuse screenshots unless the grant lets agent screenshots be evaluated now, and each was + * captured inside the period the grant covers. + */ + async #assertScreenshotGrant(context, grantId, shots = []) { + const { eligibility, grants } = await this.#eligibility(context) + const grant = grants.find((item) => item.id === grantId) + if ( + !grant || + !grant.sources.includes(SCREENSHOT_SOURCE) || + !eligibility.activePurposes(grant).includes("evaluation") || + shots.some( + ({ capturedAt }) => + (grant.evidenceFrom && capturedAt < grant.evidenceFrom) || + (grant.evidenceUntil && capturedAt >= grant.evidenceUntil), + ) + ) + throw new LearningError( + "unsupported", + "Screenshots are not allowed for this repository. Send the report without them.", + ) + } + /** * Remove one learning for good, at a person's request: every version, the deliveries that * gave it to agents, the claims that agents used it, and their screenshots. A usage report diff --git a/packages/learning/test/cli.test.mjs b/packages/learning/test/cli.test.mjs index 68885d2c7..7cd794078 100644 --- a/packages/learning/test/cli.test.mjs +++ b/packages/learning/test/cli.test.mjs @@ -754,6 +754,139 @@ describe("replica-learning CLI: a store a host names", () => { } }) + it("keeps agent screenshots only under an active grant that covers when they were taken", async () => { + const outside = mkdtempSync(path.join(tmpdir(), "replica-learning-hosted-")) + try { + writeFileSync(path.join(outside, "week-1.json"), JSON.stringify(hostedLog(weekOneLog()))) + writeFileSync(path.join(outside, "labels.json"), JSON.stringify(weekOneLabels())) + const store = ["--dir", "stores/42", ...HOSTED] + const reviews = ( + await ok(outside, [ + "grants", + "add", + "--purpose", + "review", + "--purpose", + "instruction", + "--basis", + "A Hub administrator turned on Learnings.", + "--by", + "github:ana-designer", + ...store, + "--json", + ]) + ).json() + await ok(outside, ["import", "hub-comments", "week-1.json", "--grant", reviews.id, ...store]) + await ok(outside, ["label", "labels.json", "--actor", "agent:copilot", ...store]) + const [proposal] = ( + await ok(outside, [ + "consolidate", + ...WINDOW, + "--actor", + "agent:copilot", + ...store, + "--json", + ]) + ).json().proposals + await ok(outside, [ + "accept", + proposal.id, + "--digest", + proposal.reviewDigest, + "--by", + "github:ana-designer", + ...store, + ]) + const recalled = (await ok(outside, ["recall", ...store, "--json"])).json() + const screenshots = ( + await ok(outside, [ + "grants", + "add", + "--purpose", + "evaluation", + "--source", + "agent_screenshots", + "--basis", + "A repository administrator allowed screenshot capture and automated review.", + "--by", + "github:ana-designer", + ...store, + "--json", + ]) + ).json() + function writeReport(reportId) { + writeFileSync( + path.join(outside, "report.json"), + JSON.stringify({ + reportId, + guidanceIds: [recalled.guidanceId], + commitSha: "a".repeat(40), + used: [ + { + deliveryId: recalled.memories[0].deliveryId, + after: { + data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).toString( + "base64", + ), + route: "/checkout", + viewport: { width: 1280, height: 800 }, + theme: "light", + capturedAt: "2026-10-09T12:00:00.000000Z", + }, + }, + ], + }), + ) + } + const report = ["report-usage", "report.json", "--actor", "agent:copilot", ...store] + + writeReport("report-1") + const refused = await cli(outside, report) + assert.match(refused.stderr, /Screenshots are not allowed for this repository/) + assert.equal( + (await ok(outside, [...report, "--grant", screenshots.id, "--json"])).json().stored, + true, + ) + assert.equal(existsSync(path.join(outside, "stores", "42", "evidence")), false) + const later = ( + await ok(outside, [ + "grants", + "add", + "--purpose", + "evaluation", + "--source", + "agent_screenshots", + "--evidence-from", + "2026-10-10T00:00:00Z", + "--basis", + "A repository administrator allowed screenshots taken from October 10.", + "--by", + "github:ana-designer", + ...store, + "--json", + ]) + ).json() + writeReport("report-2") + const early = await cli(outside, [...report, "--grant", later.id]) + assert.match(early.stderr, /Screenshots are not allowed for this repository/) + await ok(outside, [ + "grants", + "withdraw", + screenshots.id, + "--purpose", + "evaluation", + "--by", + "github:ana-designer", + ...store, + ]) + writeReport("report-1") + const retried = await cli(outside, [...report, "--grant", screenshots.id]) + assert.match(retried.stderr, /Screenshots are not allowed for this repository/) + } finally { + rmSync(outside, { recursive: true, force: true }) + } + }) + it("deletes one repository's records only after a person names it", async () => { const outside = mkdtempSync(path.join(tmpdir(), "replica-learning-hosted-")) try {