diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index 4bd142fd..f2d1708c 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, + AppliedLearningsResponse, EvaluationSettingsResponse, LearningActivityDayResponse, LearningDecisionInput, @@ -104,6 +105,26 @@ export const rejectedLearningResponseSchema = z }) .strict() satisfies z.ZodType +const appliedScreenshotSchema = z + .object({ sha256: z.string().regex(/^[0-9a-f]{64}$/), route: z.string() }) + .strict() + +export const appliedLearningsResponseSchema = z + .object({ + learnings: z.array( + z + .object({ + id: z.string().min(1), + title: z.string().nullable(), + version: identifier.nullable(), + before: appliedScreenshotSchema.optional(), + after: appliedScreenshotSchema.optional(), + }) + .strict(), + ), + }) + .strict() satisfies z.ZodType + export const learningHistoryResponseSchema = z .object({ decisions: z.array( diff --git a/hub/client/application/hub/learnings-contracts/types.ts b/hub/client/application/hub/learnings-contracts/types.ts index fdf20fc1..65bfd2bf 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -59,6 +59,18 @@ export interface RejectedLearningResponse { shared: boolean } +export interface AppliedLearningResponse { + id: string + title: string | null + version: number | null + before?: { sha256: string; route: string } + after?: { sha256: string; route: string } +} + +export interface AppliedLearningsResponse { + learnings: AppliedLearningResponse[] +} + export interface LearningHistoryResponse { decisions: Array<{ version: number diff --git a/hub/client/application/hub/requests/get-applied-learnings/index.ts b/hub/client/application/hub/requests/get-applied-learnings/index.ts new file mode 100644 index 00000000..412330f2 --- /dev/null +++ b/hub/client/application/hub/requests/get-applied-learnings/index.ts @@ -0,0 +1,16 @@ +import { appliedLearningsResponseSchema } from "@application/hub/learnings-contracts" + +import { requestJson } from "../request-json" + +/** Reads what agents said they applied in the commit a Build was made from. */ +export function getAppliedLearnings( + request: Request, + repositoryId: string, + prototypeId: string, + commitSha: string, +) { + const url = new URL(`/api/repositories/${repositoryId}/learnings/applied`, request.url) + url.searchParams.set("prototype", prototypeId) + url.searchParams.set("commit", commitSha) + return requestJson(url, appliedLearningsResponseSchema, { signal: request.signal }) +} diff --git a/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts b/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts index 8cd71bac..2e8c179d 100644 --- a/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts +++ b/hub/client/application/hub/routes/fixtures/preview-handlers/index.ts @@ -27,6 +27,9 @@ export function previewHandlers(data: ReturnType) { canBranch, }) }), + http.get(`/api/repositories/${repository.id}/learnings/applied`, () => + Response.json({ learnings: [] }), + ), http.get(`/api${path}/builds`, () => Response.json({ repository, diff --git a/hub/client/application/hub/routes/prototype/index.test.ts b/hub/client/application/hub/routes/prototype/index.test.ts index f0611b99..6c7e785f 100644 --- a/hub/client/application/hub/routes/prototype/index.test.ts +++ b/hub/client/application/hub/routes/prototype/index.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it, vi } from "vitest" import { http, stubHubFetch } from "@/test/stub-hub-fetch" + +import { previewRecords } from "../fixtures/preview-records" import { clientAction, clientLoader } from "." describe("prototype route", () => { @@ -17,6 +19,29 @@ describe("prototype route", () => { expect(send).not.toHaveBeenCalled() }) + it("loads the prototype without waiting for applied learnings", async () => { + const { historical, path, repository, prototype } = previewRecords() + const readApplied = vi.fn() + stubHubFetch( + http.get(`${window.location.origin}/api${path}`, () => + Response.json({ repository, prototype, selectedBuild: historical }), + ), + http.get( + `${window.location.origin}/api/repositories/${repository.id}/learnings/applied`, + readApplied, + ), + ) + const request = new Request(new URL(`${path}?build=1`, window.location.origin)) + + const result = await clientLoader({ + request, + params: { repositoryId: repository.id, prototypeId: prototype.id }, + }) + + expect(result.selectedBuild?.number).toBe(1) + expect(readApplied).not.toHaveBeenCalled() + }) + it("does not confirm a save when the API returns an invalid success response", async () => { const url = new URL("/api/repositories/2001/prototypes/1", window.location.origin) const respond = vi.fn(() => Response.json({ unexpected: "Not a prototype response." })) diff --git a/hub/client/application/hub/routes/prototype/index.tsx b/hub/client/application/hub/routes/prototype/index.tsx index ee33992d..b9ed7cc3 100644 --- a/hub/client/application/hub/routes/prototype/index.tsx +++ b/hub/client/application/hub/routes/prototype/index.tsx @@ -1,3 +1,4 @@ +import { useEffect, useState } from "react" import { data, useFetcher, useOutletContext } from "react-router" import { prototypeEditSchema } from "@application/hub/contracts" @@ -9,7 +10,9 @@ import type { import { readRecordIdentifier } from "@application/hub/read-record-identifier" import { ApiContractError } from "@application/hub/requests/api-contract-error" import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { getAppliedLearnings } from "@application/hub/requests/get-applied-learnings" import { getPrototype } from "@application/hub/requests/get-prototype" +import type { AppliedLearningResponse } from "@application/hub/learnings-contracts/types" import { updatePrototype } from "@application/hub/requests/update-prototype" import { PrototypeScreen } from "@application/hub/screens/prototype-screen" @@ -34,6 +37,34 @@ export async function clientLoader({ ) } +/** + * Reads what agents applied in the selected Build after the page shows. Learnings are + * optional, so a slow or failed read never holds up or breaks the prototype page. + */ +function useAppliedLearnings(prototype: PrototypeResponse) { + const repositoryId = prototype.repository.id + const prototypeId = prototype.prototype.id + const commitSha = prototype.selectedBuild?.commitSha?.toLowerCase() + const key = `${repositoryId}/${prototypeId}/${commitSha}` + const [loaded, setLoaded] = useState<{ key: string; learnings: AppliedLearningResponse[] }>() + useEffect(() => { + if (!commitSha) return + const controller = new AbortController() + getAppliedLearnings( + new Request(window.location.href, { signal: controller.signal }), + repositoryId, + prototypeId, + commitSha, + ).then( + (response) => setLoaded({ key, learnings: response.learnings }), + () => undefined, + ) + return () => controller.abort() + }, [commitSha, key, prototypeId, repositoryId]) + // Learnings from a previously selected Build must not show beside this one. + return loaded?.key === key ? loaded.learnings : [] +} + export async function clientAction({ request, params, @@ -94,11 +125,13 @@ export default function Prototype({ loaderData }: Pick { void fetcher.submit( { diff --git a/hub/client/application/hub/screens/prototype-screen/index.tsx b/hub/client/application/hub/screens/prototype-screen/index.tsx index 14df1165..7994171a 100644 --- a/hub/client/application/hub/screens/prototype-screen/index.tsx +++ b/hub/client/application/hub/screens/prototype-screen/index.tsx @@ -8,6 +8,7 @@ import { MentionProvider } from "@components/mention-provider" import { PrototypesShowPage } from "@pages/prototypes-show-page" import type { PrototypeDetailsInput } from "@pages/prototypes-show-page/types" import type { PrototypeResponse, WorkspaceResponse } from "@application/hub/contracts/types" +import type { AppliedLearningResponse } from "@application/hub/learnings-contracts/types" import { prototypeShowData } from "@application/hub/view-models/prototype-show-data" import { createReviewTransport } from "@application/hub/create-review-transport" import { readReviewQuery } from "@application/hub/read-review-query" @@ -23,6 +24,7 @@ import { readPreviewReturnPath } from "@utils/read-preview-return-path" export function PrototypeScreen({ workspace, data, + appliedLearnings, onSaveDetails, savingDetails, detailsError, @@ -30,6 +32,7 @@ export function PrototypeScreen({ }: { workspace: WorkspaceResponse data: PrototypeResponse + appliedLearnings?: AppliedLearningResponse[] onSaveDetails: (details: PrototypeDetailsInput) => void savingDetails: boolean detailsError: string | null @@ -43,7 +46,12 @@ export function PrototypeScreen({ const repositoryCapabilities = workspace.repositories.find( ({ id }) => id === data.repository.id, )?.capabilities - const pageData = prototypeShowData(workspace, data, new URLSearchParams(location.search)) + const pageData = prototypeShowData( + workspace, + data, + new URLSearchParams(location.search), + appliedLearnings, + ) pageData.reviewReadOnly = !repositoryCapabilities?.reviewPrototypes if (pageData.reviewReadOnly) { pageData.reviewComments = { diff --git a/hub/client/application/hub/view-models/prototype-show-data/index.test.ts b/hub/client/application/hub/view-models/prototype-show-data/index.test.ts index adfb3931..a49a565c 100644 --- a/hub/client/application/hub/view-models/prototype-show-data/index.test.ts +++ b/hub/client/application/hub/view-models/prototype-show-data/index.test.ts @@ -85,3 +85,61 @@ it("uses the per-prototype sharing decision rather than repository or edit acces prototypeShowData(workspace, data("2", false), new URLSearchParams()).shareLinksPath, ).toBeUndefined() }) + +it("lists the learnings agents applied in the selected Build", () => { + const repository = { id: "2001", nameWithOwner: "example/repository", defaultBranch: "main" } + const workspace: WorkspaceResponse = { + viewer: { id: "123", login: "octocat", name: null, provider: "github", avatarUrl: null }, + repositories: [repository], + } + const build = { + number: 3, + repositoryId: repository.id, + prototypeId: "1", + state: "successful", + commitSha: "a".repeat(40), + commitAuthorLogin: null, + createdAt: "2026-12-20T12:00:00Z", + startedAt: null, + finishedAt: null, + previewUrl: "https://preview.example.com/", + desktopScreenshotUrl: null, + narrowScreenshotUrl: null, + failureSummary: null, + } + const response = prototypeResponseSchema.parse({ + repository, + prototype: { + id: "1", + repositoryId: repository.id, + name: "Prototype", + branchName: "prototype/welcome", + authorLogin: null, + canEdit: false, + description: null, + builds: [build], + }, + selectedBuild: build, + }) + const sha256 = "b".repeat(64) + + const result = prototypeShowData(workspace, response, new URLSearchParams("build=3"), [ + { id: "mem_1", title: "Label every field", version: 2, after: { sha256, route: "/" } }, + ]) + + expect(result.agentReportedUseLabel).toBe("Applied learnings") + expect(result.agentReportedUse).toMatchObject({ + buildNumber: 3, + learnings: [ + { + id: "mem_1", + label: "Label every field · v2", + afterScreenshot: { + url: `/api/repositories/2001/learnings/screenshots/${sha256}`, + label: "View after screenshot for Label every field", + }, + }, + ], + }) + expect(result.agentReportedUse?.learnings[0]?.beforeScreenshot).toBeUndefined() +}) diff --git a/hub/client/application/hub/view-models/prototype-show-data/index.ts b/hub/client/application/hub/view-models/prototype-show-data/index.ts index 26ad44a1..3bbe341b 100644 --- a/hub/client/application/hub/view-models/prototype-show-data/index.ts +++ b/hub/client/application/hub/view-models/prototype-show-data/index.ts @@ -1,6 +1,7 @@ import type { PrototypesShowPageData } from "@pages/prototypes-show-page/types" import { reviewCommentsCopy } from "@utils/review-comment/en" import type { PrototypeResponse, WorkspaceResponse } from "@application/hub/contracts/types" +import type { AppliedLearningResponse } from "@application/hub/learnings-contracts/types" import { buildStateLabel } from "../build-state-label" import { productContinuation } from "../product-continuation" @@ -10,6 +11,7 @@ export function prototypeShowData( workspace: WorkspaceResponse, data: PrototypeResponse, search: URLSearchParams, + appliedLearnings: AppliedLearningResponse[] = [], ): PrototypesShowPageData { const selectedBuild = data.selectedBuild const previewBuild = @@ -106,6 +108,16 @@ export function prototypeShowData( selectedBuild && !previewBuild ? `Build ${selectedBuild.number} · ${buildStateLabel(selectedBuild.state)}` : "Choose build", + ...(previewBuild && appliedLearnings.length > 0 + ? { + agentReportedUseLabel: "Applied learnings", + agentReportedUse: agentReportedUse( + data.repository.id, + previewBuild.number, + appliedLearnings, + ), + } + : {}), selectedBuild: previewBuild?.previewUrl ? { number: previewBuild.number, @@ -115,3 +127,45 @@ export function prototypeShowData( : undefined, } } + +/** + * Shows what agents said they applied in a Build. Screenshots are served by Hub, which + * stops serving them once the repository withdraws screenshot consent. + */ +function agentReportedUse( + repositoryId: string, + buildNumber: number, + learnings: AppliedLearningResponse[], +): NonNullable { + function screenshot(name: string, kind: string, value?: { sha256: string }) { + return value + ? { + url: `/api/repositories/${repositoryId}/learnings/screenshots/${value.sha256}`, + label: `View ${kind} screenshot for ${name}`, + } + : undefined + } + return { + buildNumber, + copy: { + heading: `Applied learnings for Build ${buildNumber}`, + caption: "Reported by the agent; not independently verified.", + learningLabel: "Learning", + beforeLabel: "Before", + afterLabel: "After", + viewLabel: "View", + notAttachedLabel: "Not attached", + }, + learnings: learnings.map((learning) => { + const name = learning.title ?? "Untitled learning" + const beforeScreenshot = screenshot(name, "before", learning.before) + const afterScreenshot = screenshot(name, "after", learning.after) + return { + id: learning.id, + label: learning.version === null ? name : `${name} · v${learning.version}`, + ...(beforeScreenshot ? { beforeScreenshot } : {}), + ...(afterScreenshot ? { afterScreenshot } : {}), + } + }), + } +} diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 78b3779c..29425efd 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -136,6 +136,17 @@ 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. +## Applied learnings + +When an agent reports the learnings it applied, the prototype page shows them on the Build made from that commit. For example, an agent recalls "Label every form field", builds a checkout prototype, and reports it with commit `4f2c…`. Anyone who can read the library opens that Build with `?build=N` and chooses **Applied learnings** from **More actions**. The dialog lists each learning with the version the agent received and any before and after screenshots. It says the list is the agent's report and not verified. + +Hub matches a report to a Build only by the exact commit SHA, never by branch or time. A report that names a prototype shows only on that prototype. A report without one shows on every prototype built from that commit. Hub reads the package's `usage --commit` command after the page shows, so a slow read never holds up the Build. If Learnings is off or the read fails, the page stays without the menu item. + +Screenshots open from Hub, not the agent. Hub serves one only while the screenshot consent it was saved under is still active, so withdrawing consent hides it before the deletion job runs. The browser contracts are: + +- `GET /api/repositories/:repositoryId/learnings/applied?prototype=&commit=` +- `GET /api/repositories/:repositoryId/learnings/screenshots/:sha256`, which returns the PNG + ## 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**. diff --git a/hub/server/domains/learning/get-applied-learnings/index.test.ts b/hub/server/domains/learning/get-applied-learnings/index.test.ts new file mode 100644 index 00000000..537454af --- /dev/null +++ b/hub/server/domains/learning/get-applied-learnings/index.test.ts @@ -0,0 +1,66 @@ +import { access } from "node:fs/promises" +import { describe, expect, it, vi } from "vitest" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" +import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root" +import { getAppliedLearnings } from "." + +vi.mock("node:fs/promises", () => ({ access: vi.fn() })) +vi.mock("../../../integrations/learning/run-learning-command", () => ({ + runLearningCommand: vi.fn(), +})) +vi.mock("../../../utils/validate-private-storage-root", () => ({ + validatePrivateStorageRoot: vi.fn(), +})) + +describe("getAppliedLearnings()", () => { + it("lists learnings reported for this prototype's commit, skipping other prototypes", async () => { + vi.mocked(validatePrivateStorageRoot).mockResolvedValue("/private/learning/repositories/repo") + vi.mocked(access).mockResolvedValue(undefined) + const digest = "a".repeat(64) + vi.mocked(runLearningCommand).mockResolvedValue({ + reports: [ + { + used: [ + { + memoryId: "mem_1", + version: 2, + title: "Label every field", + after: { sha256: `sha256:${digest}`, route: "/checkout", consentGrantId: "grant-1" }, + }, + ], + }, + { + prototypeId: "another-prototype", + used: [{ memoryId: "mem_2", version: 1, title: "Use one column" }], + }, + ], + }) + + const result = await getAppliedLearnings({ + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + commitSha: "b".repeat(40), + nodePath: "/node", + prototypeId: "this-prototype", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }) + + expect(result).toEqual([ + { + id: "mem_1", + title: "Label every field", + version: 2, + after: { sha256: digest, route: "/checkout", consentGrantId: "grant-1" }, + }, + ]) + expect(vi.mocked(runLearningCommand).mock.calls[0]?.[0].slice(0, 3)).toEqual([ + "usage", + "--commit", + "b".repeat(40), + ]) + }) +}) diff --git a/hub/server/domains/learning/get-applied-learnings/index.ts b/hub/server/domains/learning/get-applied-learnings/index.ts new file mode 100644 index 00000000..c3e248a9 --- /dev/null +++ b/hub/server/domains/learning/get-applied-learnings/index.ts @@ -0,0 +1,119 @@ +import { access } from "node:fs/promises" +import { resolve } from "node:path" +import { z } from "zod" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" +import type { ReportedAppliedLearning } from "../types.ts" + +const screenshotSchema = z + .object({ + sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/), + route: z.string(), + consentGrantId: z.string().optional(), + }) + .loose() +const usageSchema = z + .object({ + reports: z.array( + z + .object({ + prototypeId: z.string().optional(), + used: z.array( + z + .object({ + memoryId: z.string().min(1), + version: z.number().int().positive().nullable(), + title: z.string().nullable(), + before: screenshotSchema.optional(), + after: screenshotSchema.optional(), + }) + .loose(), + ), + }) + .loose(), + ), + }) + .loose() + +/** + * Lists the learnings agents said they applied in one prototype's commit. Reports are + * matched by exact commit only, never by branch or time, so a Build shows only what was + * reported for the code it was built from. A report that names another prototype is left + * out. A report that names none counts for every prototype built from that commit. + */ +export async function getAppliedLearnings(input: { + applicationRoot?: string + cliPath: string + commitSha: string + learningDatabaseUrl?: string + nodePath: string + prototypeId: string + repositoryId: string + repositoryScope: string + root: string + staticDirectories: string[] +}): Promise { + const applicationRoot = input.applicationRoot ?? process.cwd() + const directory = await validatePrivateStorageRoot( + resolve(input.root, "repositories", input.repositoryId), + { + applicationRoot, + excludedDirectories: input.staticDirectories, + name: "REPLICA_LEARNING_ROOT", + publicRoot: resolve(applicationRoot, "public"), + }, + ) + if (!input.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return [] + } + } + const { reports } = usageSchema.parse( + await runLearningCommand( + [ + "usage", + "--commit", + input.commitSha, + ...learningStoreArguments({ + directory, + repositoryId: input.repositoryId, + repositoryScope: input.repositoryScope, + }), + ], + { + cliPath: input.cliPath, + nodePath: input.nodePath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), + }, + ), + ) + // A learning reported twice for the same commit is listed once, as last reported. + const applied = new Map() + for (const report of reports) { + if (report.prototypeId !== undefined && report.prototypeId !== input.prototypeId) continue + for (const used of report.used) { + applied.delete(used.memoryId) + applied.set(used.memoryId, { + id: used.memoryId, + title: used.title, + version: used.version, + ...(used.before ? { before: screenshot(used.before) } : {}), + ...(used.after ? { after: screenshot(used.after) } : {}), + }) + } + } + return [...applied.values()] +} + +function screenshot(value: z.infer) { + return { + sha256: value.sha256.slice("sha256:".length), + route: value.route, + ...(value.consentGrantId ? { consentGrantId: value.consentGrantId } : {}), + } +} diff --git a/hub/server/domains/learning/types.ts b/hub/server/domains/learning/types.ts index c7449971..3897ff34 100644 --- a/hub/server/domains/learning/types.ts +++ b/hub/server/domains/learning/types.ts @@ -79,3 +79,20 @@ export type LearningDecision = | { decision: "retire"; reason: string } | { decision: "edit"; digest: string; title?: string; content?: string; reason: string } | { decision: "reinstate"; digest: string; reason: string } + +/** A learning an agent said it applied in a Build, with screenshots it may show. */ +export type AppliedLearning = { + id: string + title: string | null + version: number | null + before?: { sha256: string; route: string } + after?: { sha256: string; route: string } +} + +/** An applied learning as reported, with the consent each screenshot was taken under. */ +export type ReportedAppliedLearning = Omit & { + before?: ReportedScreenshot + after?: ReportedScreenshot +} + +type ReportedScreenshot = { sha256: string; route: string; consentGrantId?: string } diff --git a/hub/server/index.ts b/hub/server/index.ts index f822baa0..60bd5cb5 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -183,7 +183,10 @@ try { authenticationEnvironment, authentication.currentSession, logger, - { scopeGitHubMembers: authenticationConfiguration.githubConfigured }, + { + scopeGitHubMembers: authenticationConfiguration.githubConfigured, + ...(storage ? { artifactStorage: storage } : {}), + }, ) learnings = learningDependencies const agentApplicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN diff --git a/hub/server/repositories/agent-screenshots/find-consented-agent-screenshots/index.ts b/hub/server/repositories/agent-screenshots/find-consented-agent-screenshots/index.ts new file mode 100644 index 00000000..4684c98b --- /dev/null +++ b/hub/server/repositories/agent-screenshots/find-consented-agent-screenshots/index.ts @@ -0,0 +1,28 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Finds stored agent screenshots only under the repository's active screenshot consent. + * Withdrawn screenshots are deleted later, so they must stop being shown first. The + * grant is returned so callers can check it is still active right before showing them. + */ +export async function findConsentedAgentScreenshots( + database: PrismaClient, + input: { repositoryId: string; sha256s: string[] }, +) { + const setting = await database.repositoryEvaluationSetting.findUnique({ + where: { repositoryId: input.repositoryId }, + select: { screenshotGrantId: true }, + }) + const grantId = setting?.screenshotGrantId + if (!grantId) return null + const screenshots = await database.agentScreenshot.findMany({ + where: { repositoryId: input.repositoryId, grantId, sha256: { in: input.sha256s } }, + select: { sha256: true, storageKey: true }, + }) + return { + grantId, + storageKeys: new Map( + screenshots.map((screenshot) => [screenshot.sha256, screenshot.storageKey]), + ), + } +} diff --git a/hub/server/routes/api/learnings/applied/get/index.ts b/hub/server/routes/api/learnings/applied/get/index.ts new file mode 100644 index 00000000..b7f0bbd6 --- /dev/null +++ b/hub/server/routes/api/learnings/applied/get/index.ts @@ -0,0 +1,63 @@ +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" + +const querySchema = z.object({ + prototype: z.uuid(), + commit: z.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/), +}) + +/** + * Lists the learnings agents said they applied in one prototype's commit, so a Build can + * show them. Access is read again after loading so a revoked session never sees the result. + */ +export function get(dependencies: LearningsRouteDependencies): RequestHandler { + return async (request, response, next) => { + try { + const repositoryId = z.uuid().safeParse(request.params.repositoryId) + const query = querySchema.safeParse(request.query) + if (!repositoryId.success || !query.success) { + response.status(400).json({ + code: "invalid_applied_learnings_address", + error: "Name a prototype and a full commit SHA.", + }) + return + } + const initial = await readLearningSession(request, dependencies) + if (!initial) { + response.status(401).json({ code: "sign_in_required", error: "Sign in to continue." }) + return + } + if (!(await dependencies.findRepository(initial, repositoryId.data))) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + const applied = await dependencies + .getAppliedLearnings({ + repositoryId: repositoryId.data, + prototypeId: query.data.prototype, + commitSha: query.data.commit, + }) + .then( + (value) => ({ ok: true as const, value }), + (error: unknown) => ({ ok: false as const, error }), + ) + 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, repositoryId.data))) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + if (!applied.ok) throw applied.error + response.json({ learnings: applied.value }) + } catch (error) { + if (!respondLearningError(response, error)) next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/applied-learnings.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/applied-learnings.db.test.ts new file mode 100644 index 00000000..df29ac26 --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/applied-learnings.db.test.ts @@ -0,0 +1,85 @@ +import pino from "pino" +import { describe, expect, it, vi } from "vitest" + +import { getAppliedLearnings } from "../../../../domains/learning/get-applied-learnings" +import { prisma } from "../../../../integrations/prisma" +import { getDatabaseUrl } from "../../../../../test/database/get-database-url" +import { createLearningsRouteDependencies } from "." + +vi.mock("../../../../integrations/bullmq/create-job-queue", () => ({ + createJobQueue: vi.fn(() => ({ close: vi.fn() })), +})) +vi.mock("../../../../domains/learning/get-applied-learnings", () => ({ + getAppliedLearnings: vi.fn(), +})) + +describe("applied learnings", () => { + it("stops showing a screenshot as soon as screenshot consent changes", async () => { + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 17n, nameWithOwner: "octo/source" }, + }) + await prisma.repositoryEvaluationSetting.create({ + data: { repositoryId: repository.id, enabled: true, screenshotGrantId: "grant_1" }, + }) + const sha256 = "c".repeat(64) + await prisma.agentScreenshot.create({ + data: { repositoryId: repository.id, grantId: "grant_1", sha256, storageKey: "shot-1" }, + }) + // The same image reported under an earlier, withdrawn grant must stay hidden. + vi.mocked(getAppliedLearnings).mockResolvedValue([ + { + id: "mem_1", + title: "Label every field", + version: 2, + after: { sha256, route: "/checkout", consentGrantId: "grant_1" }, + }, + { + id: "mem_2", + title: "Use one column", + version: 1, + after: { sha256, route: "/checkout", consentGrantId: "grant_0" }, + }, + ]) + const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]) + const read = vi.fn().mockResolvedValue({ status: "ok", bytes }) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + { artifactStorage: { read } }, + ) + const address = { + repositoryId: repository.id, + prototypeId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + commitSha: "a".repeat(40), + } + + expect(await learnings.getAppliedLearnings(address)).toEqual([ + { + id: "mem_1", + title: "Label every field", + version: 2, + after: { sha256, route: "/checkout" }, + }, + { id: "mem_2", title: "Use one column", version: 1 }, + ]) + expect(await learnings.readScreenshot({ repositoryId: repository.id, sha256 })).toEqual({ + bytes, + grantId: "grant_1", + }) + expect(read).toHaveBeenCalledWith("shot-1") + await prisma.repositoryEvaluationSetting.update({ + where: { repositoryId: repository.id }, + data: { screenshotGrantId: null }, + }) + + expect(await learnings.getAppliedLearnings(address)).toEqual([ + { id: "mem_1", title: "Label every field", version: 2 }, + { id: "mem_2", title: "Use one column", version: 1 }, + ]) + expect(await learnings.readScreenshot({ repositoryId: repository.id, sha256 })).toBeNull() + expect( + await learnings.isScreenshotGrantActive({ repositoryId: repository.id, grantId: "grant_1" }), + ).toBe(false) + }) +}) diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts index 291e00aa..55574797 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts @@ -66,7 +66,16 @@ describe("evaluation settings", () => { }, }) vi.mocked(changeScreenshotConsent).mockResolvedValueOnce("grant_1") - vi.mocked(changeScreenshotConsent).mockResolvedValueOnce(null) + // Records what Hub showed at the moment the store grant was withdrawn. + let grantAtWithdrawal: string | null | undefined + vi.mocked(changeScreenshotConsent).mockImplementationOnce(async () => { + grantAtWithdrawal = ( + await prisma.repositoryEvaluationSetting.findUnique({ + where: { repositoryId: repository.id }, + }) + )?.screenshotGrantId + return null + }) const learnings = await createLearningsRouteDependencies( { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, { restore: vi.fn() }, @@ -97,6 +106,7 @@ describe("evaluation settings", () => { allowed: false, grantId: "grant_1", }) + expect(grantAtWithdrawal).toBeNull() expect(vi.mocked(enqueueJob).mock.lastCall?.[2]).toEqual({ repositoryId: repository.id, grantId: "grant_1", diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts index 403ce6b7..be0eba9f 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 @@ -7,6 +7,9 @@ import { ReviewCommentError } from "../../../../domains/review-comments/errors.t import { executeLearningDecision } from "../../../../domains/learning/execute-learning-decision/index.ts" import { createReviewCommentLearningSource } from "../../../../domains/learning/create-review-comment-learning-source/index.ts" import { getLearningHistory } from "../../../../domains/learning/get-learning-history/index.ts" +import { getAppliedLearnings } from "../../../../domains/learning/get-applied-learnings/index.ts" +import type { ArtifactStorage } from "../../../../domains/artifacts/create-artifact-storage/types.ts" +import { findConsentedAgentScreenshots } from "../../../../repositories/agent-screenshots/find-consented-agent-screenshots/index.ts" import { recordFinishedLearningRun } from "../../../../domains/learning/record-finished-learning-run/index.ts" import { getLearningOverview } from "../../../../domains/learning/get-learning-overview/index.ts" import { getLearningRepositoryScope } from "../../../../domains/learning/get-learning-repository-scope/index.ts" @@ -59,7 +62,11 @@ export async function createLearningsRouteDependencies( environment: NodeJS.ProcessEnv, currentSession: CurrentSessionDependencies, logger: Logger, - options: { scopeGitHubMembers?: boolean; source?: ReviewCommentLearningSource } = {}, + options: { + artifactStorage?: Pick + scopeGitHubMembers?: boolean + source?: ReviewCommentLearningSource + } = {}, ): Promise { const configuration = await readLearningConfiguration(environment) const applicationOrigin = environment.HUB_APPLICATION_ORIGIN @@ -300,6 +307,61 @@ export async function createLearningsRouteDependencies( } return history }, + getAppliedLearnings: async ({ repositoryId, prototypeId, commitSha }) => { + const repositoryScope = await getLearningRepositoryScope(prisma, repositoryId) + const applied = await getAppliedLearnings({ + ...configuration, + commitSha, + prototypeId, + repositoryId, + repositoryScope, + }) + if (repositoryScope !== (await getLearningRepositoryScope(prisma, repositoryId))) { + throw new LearningCommandError( + "repository_scope_unavailable", + "The repository learning scope changed. Try again.", + ) + } + // Offer a screenshot only when it was taken under the consent that is on now, so + // the same image saved under a later grant can't revive one that was withdrawn. + const digests = applied.flatMap(({ before, after }) => + [before, after].flatMap((screenshot) => (screenshot ? [screenshot.sha256] : [])), + ) + const consented = + digests.length && options.artifactStorage + ? await findConsentedAgentScreenshots(prisma, { repositoryId, sha256s: digests }) + : null + function shown(screenshot?: { sha256: string; route: string; consentGrantId?: string }) { + if (!screenshot || !consented) return undefined + if (screenshot.consentGrantId !== consented.grantId) return undefined + if (!consented.storageKeys.has(screenshot.sha256)) return undefined + return { sha256: screenshot.sha256, route: screenshot.route } + } + return applied.map(({ before, after, ...learning }) => { + const shownBefore = shown(before) + const shownAfter = shown(after) + return { + ...learning, + ...(shownBefore ? { before: shownBefore } : {}), + ...(shownAfter ? { after: shownAfter } : {}), + } + }) + }, + readScreenshot: async ({ repositoryId, sha256 }) => { + if (!options.artifactStorage) return null + const consented = await findConsentedAgentScreenshots(prisma, { + repositoryId, + sha256s: [sha256], + }) + const storageKey = consented?.storageKeys.get(sha256) + if (!consented || !storageKey) return null + const result = await options.artifactStorage.read(storageKey) + if (result.status === "ok") return { bytes: result.bytes, grantId: consented.grantId } + if (result.status === "not-found") return null + throw new Error(`Hub could not read an agent screenshot (${result.status}).`) + }, + isScreenshotGrantActive: async ({ repositoryId, grantId }) => + (await getRepositoryEvaluationSetting(prisma, repositoryId))?.screenshotGrantId === grantId, getCopilot, listRuns: (repositoryId) => listLearningRuns(prisma, repositoryId, new Date()), listActivity: (repositoryId, from) => listLearningActivityDays(prisma, repositoryId, from), @@ -617,6 +679,19 @@ export async function createLearningsRouteDependencies( } } if (allowed === Boolean(grantId)) return + function saveGrant(screenshotGrantId: string | null) { + return withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { + screenshotGrantId, + screenshotsChangedAt: new Date(), + screenshotsChangedByMembershipId: actorMembershipId, + }), + ) + } + // Hub stops showing screenshots before the store grant is withdrawn, so a + // failed withdrawal can't leave Hub serving them. The cleanup sweep still + // deletes them, since their grant is no longer the active one. + if (grantId && !allowed && !(await saveGrant(null))) return deny() const nextGrantId = await changeScreenshotConsent({ ...configuration, actor: input.actor, @@ -626,15 +701,11 @@ export async function createLearningsRouteDependencies( 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) + if (allowed) { + if (!(await saveGrant(nextGrantId))) return deny() + return + } + if (grantId) await queueScreenshotDeletion({ databaseUrl, grantId, diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index 1c9ae5e1..2448538d 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -13,6 +13,8 @@ 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 { get as getAppliedLearnings } from "./applied/get/index.ts" +import { get as getScreenshot } from "./screenshots/get/index.ts" import { post as postRun } from "./runs/post/index.ts" import { post as postShare } from "./share/post/index.ts" import type { LearningsRouteDependencies } from "./types.ts" @@ -56,6 +58,9 @@ function dependencies( contradictions: [], otherContradictionsCount: 0, }), + getAppliedLearnings: vi.fn().mockResolvedValue([]), + readScreenshot: vi.fn().mockResolvedValue(null), + isScreenshotGrantActive: vi.fn().mockResolvedValue(true), getCopilot: vi.fn().mockResolvedValue({ state: "connected", connectedBy: "mona" }), listRuns: vi.fn().mockResolvedValue({ runs: [], usageCredits: "0", active: null }), listActivity: vi.fn().mockResolvedValue([]), @@ -694,6 +699,172 @@ describe("learning routes", () => { ) }) + it("lists the learnings reported for a prototype's commit", async () => { + const prototypeId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc" + const commitSha = "a".repeat(40) + const applied = [{ id: "mem_1", title: "Label every field", version: 2 }] + const getApplied = vi.fn().mockResolvedValue(applied) + const deps = dependencies({ getAppliedLearnings: getApplied }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/applied", + getAppliedLearnings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/applied?prototype=${prototypeId}&commit=${commitSha}`, + { headers }, + ) + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ learnings: applied }) + expect(getApplied).toHaveBeenCalledWith({ repositoryId, prototypeId, commitSha }) + }, + ) + }) + + it("serves an agent screenshot only as an image", async () => { + const sha256 = "b".repeat(64) + const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]) + const readScreenshot = vi.fn().mockResolvedValue({ bytes, grantId: "grant-1" }) + const deps = dependencies({ readScreenshot }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/screenshots/:sha256", + getScreenshot(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/screenshots/${sha256}`, + { headers }, + ) + + expect(response.status).toBe(200) + expect(response.headers.get("content-type")).toBe("image/png") + expect(response.headers.get("x-content-type-options")).toBe("nosniff") + expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes) + expect(readScreenshot).toHaveBeenCalledWith({ repositoryId, sha256 }) + }, + ) + }) + + it("refuses an applied-learnings address without a prototype and full commit", async () => { + const getApplied = vi.fn() + const deps = dependencies({ getAppliedLearnings: getApplied }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/applied", + getAppliedLearnings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/applied?prototype=cccccccc-cccc-4ccc-8ccc-cccccccccccc&commit=abc123`, + { headers }, + ) + + expect(response.status).toBe(400) + expect(getApplied).not.toHaveBeenCalled() + }, + ) + }) + + it("hides applied learnings after repository access is lost while they load", async () => { + const deps = dependencies({ + findRepository: vi.fn().mockResolvedValueOnce(repository).mockResolvedValueOnce(null), + getAppliedLearnings: vi + .fn() + .mockResolvedValue([{ id: "mem_1", title: "Label every field", version: 2 }]), + }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/applied", + getAppliedLearnings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/applied?prototype=cccccccc-cccc-4ccc-8ccc-cccccccccccc&commit=${"a".repeat(40)}`, + { headers }, + ) + + expect(response.status).toBe(404) + expect(await response.json()).toEqual({ + code: "repository_not_found", + error: "Repository not found.", + }) + }, + ) + }) + + it("treats a malformed screenshot address as not found", async () => { + const readScreenshot = vi.fn() + const deps = dependencies({ readScreenshot }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/screenshots/:sha256", + getScreenshot(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/screenshots/not-a-digest`, + { headers }, + ) + + expect(response.status).toBe(404) + expect(readScreenshot).not.toHaveBeenCalled() + }, + ) + }) + + it("withholds a screenshot from someone signed out while it loads", async () => { + const deps = dependencies({ + currentSession: { + restore: vi.fn().mockResolvedValueOnce(session).mockResolvedValueOnce(null), + }, + readScreenshot: vi + .fn() + .mockResolvedValue({ bytes: new Uint8Array([0x89]), grantId: "grant-1" }), + }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/screenshots/:sha256", + getScreenshot(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/screenshots/${"b".repeat(64)}`, + { headers }, + ) + + expect(response.status).toBe(401) + }, + ) + }) + + it("withholds a screenshot when consent is withdrawn while it loads", async () => { + const isScreenshotGrantActive = vi.fn().mockResolvedValue(false) + const deps = dependencies({ + readScreenshot: vi + .fn() + .mockResolvedValue({ bytes: new Uint8Array([0x89]), grantId: "grant-1" }), + isScreenshotGrantActive, + }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/screenshots/:sha256", + getScreenshot(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/screenshots/${"b".repeat(64)}`, + { headers }, + ) + + expect(response.status).toBe(404) + expect(isScreenshotGrantActive).toHaveBeenCalledWith({ repositoryId, grantId: "grant-1" }) + }, + ) + }) + it("hides whether a learning exists after repository access is lost", async () => { const deps = dependencies({ findRepository: vi.fn().mockResolvedValueOnce(repository).mockResolvedValueOnce(null), diff --git a/hub/server/routes/api/learnings/screenshots/get/index.ts b/hub/server/routes/api/learnings/screenshots/get/index.ts new file mode 100644 index 00000000..eae15a9c --- /dev/null +++ b/hub/server/routes/api/learnings/screenshots/get/index.ts @@ -0,0 +1,71 @@ +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" + +const notFound = { code: "screenshot_not_found", error: "Screenshot not found." } + +/** + * Serves one agent screenshot to anyone who can read the library, only while the + * repository still allows screenshots. Access and consent are read again before sending. + */ +export function get(dependencies: LearningsRouteDependencies): RequestHandler { + return async (request, response, next) => { + try { + const repositoryId = z.uuid().safeParse(request.params.repositoryId) + const sha256 = z + .string() + .regex(/^[0-9a-f]{64}$/) + .safeParse(request.params.sha256) + if (!repositoryId.success || !sha256.success) { + response.status(404).json(notFound) + return + } + const initial = await readLearningSession(request, dependencies) + if (!initial) { + response.status(401).json({ code: "sign_in_required", error: "Sign in to continue." }) + return + } + if (!(await dependencies.findRepository(initial, repositoryId.data))) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + const screenshot = await dependencies.readScreenshot({ + repositoryId: repositoryId.data, + sha256: sha256.data, + }) + 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, repositoryId.data))) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + // Consent may be withdrawn while the image and access are read, so check it last. + if ( + !screenshot || + !(await dependencies.isScreenshotGrantActive({ + repositoryId: repositoryId.data, + grantId: screenshot.grantId, + })) + ) { + response.status(404).json(notFound) + return + } + // Screenshots come from agents, so never let a browser run them as anything else. + response.set({ + "Cache-Control": "private, no-store", + "Content-Security-Policy": "default-src 'none'", + "Content-Type": "image/png", + "X-Content-Type-Options": "nosniff", + }) + response.send(Buffer.from(screenshot.bytes)) + } catch (error) { + if (!respondLearningError(response, error)) next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/types.ts b/hub/server/routes/api/learnings/types.ts index 58f5bfb6..f81ae74f 100644 --- a/hub/server/routes/api/learnings/types.ts +++ b/hub/server/routes/api/learnings/types.ts @@ -2,6 +2,7 @@ import type { CurrentSessionDependencies } from "../auth/types.ts" import type { ProductViewer } from "../product/types.ts" import type { AcceptedLearning, + AppliedLearning, LearningDecision, LearningDecisionRecord, LearningEvidence, @@ -12,6 +13,7 @@ import type { export type { AcceptedLearning, + AppliedLearning, LearningDecision, LearningDecisionRecord, LearningEvidence, @@ -95,6 +97,17 @@ export interface LearningsRouteDependencies { evidence: LearningEvidence[] otherEvidenceCount: number }> + getAppliedLearnings(input: { + repositoryId: string + prototypeId: string + commitSha: string + }): Promise + /** Reads a consented screenshot, with the grant that allowed it. */ + readScreenshot(input: { + repositoryId: string + sha256: string + }): Promise<{ bytes: Uint8Array; grantId: string } | null> + isScreenshotGrantActive(input: { repositoryId: string; grantId: string }): Promise getCopilot(): Promise< | { state: "connected"; connectedBy: string | null } | { state: "not-connected" } diff --git a/hub/server/routes/index.ts b/hub/server/routes/index.ts index b50e78ae..def08458 100644 --- a/hub/server/routes/index.ts +++ b/hub/server/routes/index.ts @@ -67,6 +67,8 @@ import { post as handleCopilotAuthorizationContinuePost } from "./api/copilot-co import { post as handleCopilotAuthorizationCancelPost } from "./api/copilot-connection/authorizations/cancel/post/index.ts" import { get as handleLearningsGet } from "./api/learnings/get/index.ts" import { get as handleLearningHistoryGet } from "./api/learnings/history/get/index.ts" +import { get as handleAppliedLearningsGet } from "./api/learnings/applied/get/index.ts" +import { get as handleLearningScreenshotGet } from "./api/learnings/screenshots/get/index.ts" import { post as handleLearningRunPost } from "./api/learnings/runs/post/index.ts" import { post as handleLearningDecisionPost } from "./api/learnings/decision/post/index.ts" import { post as handleLearningSharePost } from "./api/learnings/share/post/index.ts" @@ -371,6 +373,14 @@ export function routes(app: Express, dependencies: RouteDependencies = {}): void requireOrigin(learnings.applicationOrigin), handleLearningRunPost(learnings), ) + app.get( + "/api/repositories/:repositoryId/learnings/applied", + handleAppliedLearningsGet(learnings), + ) + app.get( + "/api/repositories/:repositoryId/learnings/screenshots/:sha256", + handleLearningScreenshotGet(learnings), + ) app.get( "/api/repositories/:repositoryId/learnings/:learningId/history", handleLearningHistoryGet(learnings), diff --git a/packages/learning/README.md b/packages/learning/README.md index 70067ddf..26dd5002 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -53,6 +53,7 @@ node /packages/learning/bin/replica-learning.mjs doctor | `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; 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 | +| `usage --commit ` | Lists the usage reports for one full commit SHA. Each used learning names its ID, the version the agent received, its title and text, and the digest, capture details, and consent grant of any before and after screenshot. Title and text are empty once the learning's evidence no longer allows review. A host uses it to show what was applied in the Build made from that commit | | `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 | diff --git a/packages/learning/index.d.mts b/packages/learning/index.d.mts index 4303c39f..a781aa1c 100644 --- a/packages/learning/index.d.mts +++ b/packages/learning/index.d.mts @@ -327,6 +327,12 @@ export interface UsedLearning { digest: Digest } +/** A screenshot as usageForCommit lists it, without the image. */ +export type UsedScreenshot = Pick< + ScreenshotRecord, + "sha256" | "route" | "viewport" | "theme" | "capturedAt" | "consentGrantId" +> + /** A screenshot's capture details. The image stays on the machine, named by sha256. */ export interface ScreenshotRecord { schemaVersion: "replica.screenshot/v1" @@ -1084,6 +1090,30 @@ export interface LearningStore { consentGrantId?: string }, ): Promise<{ id: string; reportId: string; stored: boolean }> + /** + * List what agents said they used for a commit. Title and text are null when the learning's + * evidence no longer allows review, so withdrawn consent hides the delivered wording. + */ + usageForCommit( + context: LearningContext, + options: { commitSha: string }, + ): Promise< + Array<{ + id: string + reportId: string + prototypeId?: string + reportedAt: Timestamp + used: Array<{ + id: string + memoryId: string + version: number | null + title: string | null + text: string | null + before?: UsedScreenshot + after?: UsedScreenshot + }> + }> + > /** Remove a learning for good, with its deliveries, use, and screenshots. Needs a person. */ deleteMemory( context: LearningContext, diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index cfd8820f..e1dde92e 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -118,6 +118,7 @@ Use Record which recalled learnings an agent used for a commit, with optional before and after screenshots; --grant names the consent that allows them + usage --commit List what agents reported using for one commit export --purpose

--by [--out ] [--learnings-only] [--preview] mcp [--actor ] [--grant ]... Serve the learning tools to a coding agent over @@ -196,6 +197,7 @@ const OPTIONS = { "created-at": { type: "string" }, "session-id": { type: "string" }, "session-label": { type: "string" }, + commit: { type: "string" }, days: { type: "string" }, confirm: { type: "string" }, } @@ -317,6 +319,7 @@ export async function main( "redact", "recall", "report-usage", + "usage", "delete", "expire-guidance", "delete-repository", @@ -427,6 +430,8 @@ async function run(session) { return recall(session) case "report-usage": return reportUsage(session) + case "usage": + return usage(session) case "delete": return deleteMemory(session) case "expire-guidance": @@ -1387,6 +1392,28 @@ async function reportUsage(session) { ) } +async function usage(session) { + const commitSha = session.values.commit + if (!commitSha) throw new UsageError("Name the commit with --commit .") + const { store } = await open(session) + const reports = await store.usageForCommit(context(session, actor(session)), { commitSha }) + session.out( + { reports }, + reports.length + ? reports + .map((report) => + [ + `${report.reportId} reported ${report.reportedAt}`, + ...report.used.map( + (item) => ` ${item.memoryId} v${item.version ?? "?"} ${item.title ?? ""}`, + ), + ].join("\n"), + ) + .join("\n") + : "No usage reports for this commit.", + ) +} + /** * 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 diff --git a/packages/learning/src/store.mjs b/packages/learning/src/store.mjs index ac265ecf..ed6e4414 100644 --- a/packages/learning/src/store.mjs +++ b/packages/learning/src/store.mjs @@ -3529,6 +3529,93 @@ class LearningStore { return { id, reportId, stored: result.usageReports.appended === 1 } } + /** + * What agents said they used for one commit, so a host can show it beside the Build made + * from that commit. Each used learning names the latest version whose content the agent + * received. A learning deleted since leaves nothing here. + */ + async usageForCommit(context, { commitSha } = {}) { + assertContext(context) + if (typeof commitSha !== "string" || !COMMIT_SHA.test(commitSha)) + throw new LearningError("invalid_input", "Name the full commit SHA.") + const reports = (await this.#read("usageReports", context)).filter( + (report) => report.commitSha === commitSha, + ) + if (!reports.length) return [] + const reportIds = new Set(reports.map((report) => report.id)) + const used = (await this.#read("usedLearnings", context)).filter((record) => + reportIds.has(record.usageReportId), + ) + const deliveries = new Map( + ( + await this.#read("deliveries", context, { ids: used.map((record) => record.deliveryId) }) + ).map((delivery) => [delivery.id, delivery]), + ) + const shots = new Map( + (await this.#read("screenshots", context)) + .filter((record) => reportIds.has(record.usageReportId)) + .map((record) => [record.id, record]), + ) + const delivered = await this.#deliveredVersions(context, "review") + function screenshot(id) { + const record = shots.get(id) + if (!record) return undefined + const { sha256, route, viewport, theme, capturedAt, consentGrantId } = record + return { + sha256, + route, + viewport, + theme, + capturedAt, + ...(consentGrantId ? { consentGrantId } : {}), + } + } + return reports.map((report) => ({ + id: report.id, + reportId: report.reportId, + ...(report.prototypeId ? { prototypeId: report.prototypeId } : {}), + reportedAt: report.reportedAt, + used: used + .filter((record) => record.usageReportId === report.id) + .map((record) => { + const delivery = deliveries.get(record.deliveryId) + const match = delivery && delivered(record.memoryId, delivery) + const shown = match?.allowed ? match.version : null + const before = screenshot(record.beforeScreenshotId) + const after = screenshot(record.afterScreenshotId) + return { + id: record.id, + memoryId: record.memoryId, + version: match?.version.version ?? null, + title: shown?.title ?? null, + text: shown ? delivery.text : null, + ...(before ? { before } : {}), + ...(after ? { after } : {}), + } + }), + })) + } + + /** + * Finds the learning version each delivery carried, and whether its evidence still permits + * purpose. Retiring or superseding keeps the content, so the version must also predate the + * delivery, or a later version would be named for text the agent got earlier. + */ + async #deliveredVersions(context, purpose) { + const view = await this.#statuses(context, purpose) + const items = new Map(view.items.map((item) => [item.id, item])) + return (memoryId, { contentDigest, deliveredAt }) => { + const item = items.get(memoryId) + const version = item?.versions.findLast( + (entry) => entry.contentDigest === contentDigest && entry.updatedAt <= deliveredAt, + ) + if (!version) return null + const allowed = + !item.problems.length && this.#evidenceEligible(dependencies(version), view.eligible) + return { version, allowed } + } + } + /** * Refuse screenshots unless the grant lets agent screenshots be evaluated now, and each was * captured inside the period the grant covers. diff --git a/packages/learning/test/cli.test.mjs b/packages/learning/test/cli.test.mjs index 7cd79407..c95748b3 100644 --- a/packages/learning/test/cli.test.mjs +++ b/packages/learning/test/cli.test.mjs @@ -1450,7 +1450,7 @@ describe("replica-learning CLI: guard rails", () => { it("records what an agent used, then deletes the learning with its screenshot", async () => { const repo = checkout("usage-and-deletion") - const { proposal } = await learnFromReviews(repo) + const { grant, proposal } = await learnFromReviews(repo) await ok(repo, [ "accept", proposal.id, @@ -1504,6 +1504,32 @@ describe("replica-learning CLI: guard rails", () => { assert.equal((await ok(repo, args)).json().stored, false) const evidence = path.join(repo, ".replica", "learning", "evidence") assert.equal(readdirSync(evidence).length, 1) + const usage = ["usage", "--commit", "a".repeat(40), "--json"] + const [report] = (await ok(repo, usage)).json().reports + assert.equal(report.reportId, "report-1") + assert.equal(report.used[0].memoryId, memory.id) + assert.equal(report.used[0].version, 2) + assert.equal(report.used[0].after.route, "/checkout") + writeFileSync(path.join(repo, "reason.txt"), "The team moved to a new form layout.") + await ok( + repo, + ["retire", memory.id, "--by", "github:ana-designer", "--reason-file", "reason.txt"], + { clock: CLOCK + 60_000 }, + ) + const [retired] = (await ok(repo, usage)).json().reports + assert.equal(retired.used[0].version, 2) + await ok(repo, [ + "grants", + "withdraw", + grant.id, + "--purpose", + "review", + "--by", + "github:ana-designer", + ]) + const [withdrawn] = (await ok(repo, usage)).json().reports + assert.equal(withdrawn.used[0].title, null) + assert.equal(withdrawn.used[0].text, null) const deleted = ( await ok(repo, [ @@ -1518,6 +1544,7 @@ describe("replica-learning CLI: guard rails", () => { ).json() assert.equal(deleted.records.screenshots, 1) assert.deepEqual(readdirSync(evidence), []) + assert.deepEqual((await ok(repo, usage)).json().reports, []) assert.equal((await ok(repo, ["verify", "--json"])).json().ok, true) })