From a9672967a5e3591076ebf141872eb7b578a42e21 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 10:26:13 -0800 Subject: [PATCH 01/32] feat(hub): add agent connection storage Add the persistence and initial user-facing connection page needed for authenticated learning agents. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../agent-connections-page/index.test.tsx | 117 +++++++++++ .../pages/agent-connections-page/index.tsx | 156 +++++++++++++++ .../pages/agent-connections-page/stories.tsx | 106 ++++++++++ .../pages/agent-connections-page/styles.css | 93 +++++++++ .../pages/agent-connections-page/types.ts | 24 +++ hub/package-lock.json | 187 ++++++++++++++++++ hub/package.json | 1 + hub/schema/agent-authorization.prisma | 24 +++ hub/schema/agent-client.prisma | 17 ++ hub/schema/agent-connection.prisma | 32 +++ .../authentication-provider-revision.prisma | 1 + hub/schema/external-identity.prisma | 1 + hub/schema/hub-session.prisma | 1 + hub/schema/membership.prisma | 1 + .../migration.sql | 92 +++++++++ 15 files changed, 853 insertions(+) create mode 100644 hub/client/pages/agent-connections-page/index.test.tsx create mode 100644 hub/client/pages/agent-connections-page/index.tsx create mode 100644 hub/client/pages/agent-connections-page/stories.tsx create mode 100644 hub/client/pages/agent-connections-page/styles.css create mode 100644 hub/client/pages/agent-connections-page/types.ts create mode 100644 hub/schema/agent-authorization.prisma create mode 100644 hub/schema/agent-client.prisma create mode 100644 hub/schema/agent-connection.prisma create mode 100644 hub/schema/migrations/20261223170000_agent_connections/migration.sql diff --git a/hub/client/pages/agent-connections-page/index.test.tsx b/hub/client/pages/agent-connections-page/index.test.tsx new file mode 100644 index 000000000..69c2c23d8 --- /dev/null +++ b/hub/client/pages/agent-connections-page/index.test.tsx @@ -0,0 +1,117 @@ +import { fireEvent, render, screen, within } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" + +import { HubThemeProvider } from "@hooks/use-hub-theme" + +import { AgentConnectionsPrototype } from "." +import type { AgentConnectionsPrototypeData } from "./types" + +function renderPrototype(data: AgentConnectionsPrototypeData) { + render(, { wrapper: HubThemeProvider }) +} + +describe("AgentConnectionsPrototype()", () => { + it("copies a repository MCP endpoint without putting a credential in the config", async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "connections", + connections: [], + } + renderPrototype(data) + + const config = screen.getByLabelText("Hub MCP configuration") + expect(config).toHaveTextContent("https://hub.example.com/mcp/repositories/2001") + expect(config).not.toHaveTextContent(/token|secret|password/i) + fireEvent.click(screen.getByRole("button", { name: "Copy: Hub MCP configuration" })) + + expect( + await screen.findByRole("button", { name: "Copied: Hub MCP configuration" }), + ).toBeVisible() + expect(writeText).toHaveBeenCalledWith(config.textContent) + }) + + it("requires confirmation and revokes only the selected agent connection", () => { + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "connections", + connections: [ + { + id: "agent-vscode", + name: "Visual Studio Code", + connectedAt: "2026-11-18", + lastUsedAt: "2026-11-24", + }, + { + id: "agent-local", + name: "Local MCP client", + connectedAt: "2026-11-12", + lastUsedAt: "2026-11-21", + }, + ], + } + renderPrototype(data) + + fireEvent.click(screen.getByRole("button", { name: "Revoke Visual Studio Code access" })) + const dialog = screen.getByRole("dialog", { name: "Revoke agent access?" }) + expect(dialog).toHaveTextContent("does not sign you out of Hub") + expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeVisible() + + fireEvent.click(within(dialog).getByRole("button", { name: "Revoke access" })) + + expect(screen.queryByText("Visual Studio Code")).not.toBeInTheDocument() + expect(screen.getByText("Local MCP client")).toBeVisible() + expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( + "Visual Studio Code can no longer access Hub.", + ) + expect(document.activeElement).toBe( + screen.getByRole("heading", { name: "Your connected agents" }), + ) + }) + + it("keeps agent access pending until approval and separates screenshot consent", () => { + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "approval", + requestingAgent: "Visual Studio Code", + connections: [], + } + renderPrototype(data) + + expect(screen.getByText(/does not allow session-message storage/)).toBeVisible() + expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() + fireEvent.click(screen.getByRole("button", { name: "Approve access" })) + + expect(screen.getByRole("heading", { name: "Agent connected" })).toBeVisible() + expect(screen.getByText(/revoke its Hub access at any time/)).toBeVisible() + }) + + it("does not connect the agent when the person cancels approval", () => { + const data: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "approval", + requestingAgent: "Visual Studio Code", + connections: [], + } + renderPrototype(data) + + fireEvent.click(screen.getByRole("button", { name: "Cancel" })) + + expect(screen.getByRole("heading", { name: "Connection cancelled" })).toBeVisible() + expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() + expect(screen.getByText(/No Hub access was granted/)).toBeVisible() + }) +}) diff --git a/hub/client/pages/agent-connections-page/index.tsx b/hub/client/pages/agent-connections-page/index.tsx new file mode 100644 index 000000000..8fbc4ea3f --- /dev/null +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -0,0 +1,156 @@ +import { useRef, useState } from "react" +import { Button, Heading, Text } from "@primer/react-brand" + +import { CanvasDialog } from "@components/prototype-canvas-dialog" +import { CopyableCodeBlock } from "@components/copyable-code-block" +import { HubToast } from "@components/hub-toast" + +import type { AgentConnectionsPrototypeData } from "./types" +import "./styles.css" + +export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsPrototypeData }) { + const [connections, setConnections] = useState(data.connections) + const [connectionToRevoke, setConnectionToRevoke] = useState(null) + const [notice, setNotice] = useState("") + const [approval, setApproval] = useState<"pending" | "approved" | "cancelled">("pending") + const connectionsHeadingRef = useRef(null) + const endpoint = `${data.hubUrl.replace(/\/$/, "")}/mcp/repositories/${data.repositoryId}` + const configuration = JSON.stringify({ mcpServers: { replica: { url: endpoint } } }, null, 2) + const selectedConnection = connections.find(({ id }) => id === connectionToRevoke) + + function revokeConnection() { + if (!selectedConnection) return + setConnections((current) => current.filter(({ id }) => id !== selectedConnection.id)) + setConnectionToRevoke(null) + setNotice(`${selectedConnection.name} can no longer access Hub.`) + } + + if (data.view === "approval") { + return ( +
+ {approval === "pending" ? ( +
+ + Connect {data.requestingAgent} to Hub? + + + You are signed in as {data.signedInAs}. This agent can read guidance + and report which learnings it applied for repositories you can access. Hub checks + access on every request; only people can accept or change learnings. + + + This does not allow session-message storage, screenshot storage, or automated + screenshot review. Those choices require separate consent. + +
+ + +
+
+ ) : ( +
+ + {approval === "approved" ? "Agent connected" : "Connection cancelled"} + + + {approval === "approved" + ? `Return to ${data.requestingAgent} to continue. You can revoke its Hub access at any time.` + : `You can close this page and return to ${data.requestingAgent}. No Hub access was granted.`} + +
+ )} +
+ ) + } + + return ( +
+
+ + Connect an agent + + + Set up an agent to use learning guidance from {data.repositoryName}. + +
+ +
+ + Add Hub to your agent + + + Copy this configuration into your agent. It contains the Hub address for this repository, + not a password or access token. Your agent will open a browser when it needs you to sign + in. + + +
+ +
+ + Your connected agents + + + Connected as {data.signedInAs}. These agents can use your Hub access for any repository + you can access. + + {connections.length ? ( +
    + {connections.map((connection) => ( +
  • +
    + {connection.name} + + Connected{" "} + + {" · "}Last used{" "} + + +
    + +
  • + ))} +
+ ) : ( + No agents are connected to your Hub account. + )} +
+ + {selectedConnection ? ( + setConnectionToRevoke(null)} + > +
+ + {selectedConnection.name} will no longer be able to use your Hub account. This does + not sign you out of Hub or change your repository access. + +
+ + +
+
+
+ ) : null} + {notice ? : null} +
+ ) +} diff --git a/hub/client/pages/agent-connections-page/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx new file mode 100644 index 000000000..56775d479 --- /dev/null +++ b/hub/client/pages/agent-connections-page/stories.tsx @@ -0,0 +1,106 @@ +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 { AgentConnectionsPrototype } from "." +import type { AgentConnectionsPrototypeData } 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 connections: AgentConnectionsPrototypeData = { + repositoryId: "2001", + repositoryName: "github/prototype", + hubUrl: "https://hub.example.com", + signedInAs: "@octocat", + view: "connections", + connections: [ + { + id: "agent-vscode", + name: "Visual Studio Code", + connectedAt: "2026-11-18", + lastUsedAt: "2026-11-24", + }, + { + id: "agent-local", + name: "Local MCP client", + connectedAt: "2026-11-12", + lastUsedAt: "2026-11-21", + }, + ], +} + +const approval: AgentConnectionsPrototypeData = { + ...connections, + view: "approval", + requestingAgent: "Visual Studio Code", +} + +const meta = { + title: "Hub/Pages/Learnings/Agent connections", + component: AgentConnectionsPrototype, + parameters: { layout: "fullscreen" }, + args: { data: connections }, + render: ({ data }) => + data.view === "connections" ? ( + + + + ) : ( + + ), +} satisfies Meta + +export default meta +type Story = StoryObj + +export const ConnectedAgents: Story = {} +export const NoConnectedAgents: Story = { + args: { data: { ...connections, connections: [] } }, +} +export const RevokeConfirmation: Story = { + args: { data: connections }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Revoke Visual Studio Code access" })) + await canvas.findByRole("dialog", { name: "Revoke agent access?" }) + }, +} +export const ApprovalRequest: Story = { + args: { data: approval }, +} +export const Approved: Story = { + args: { data: approval }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Approve access" })) + await canvas.findByRole("heading", { name: "Agent connected" }) + }, +} +export const Cancelled: Story = { + args: { data: approval }, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Cancel" })) + await canvas.findByRole("heading", { name: "Connection cancelled" }) + }, +} diff --git a/hub/client/pages/agent-connections-page/styles.css b/hub/client/pages/agent-connections-page/styles.css new file mode 100644 index 000000000..199e1f760 --- /dev/null +++ b/hub/client/pages/agent-connections-page/styles.css @@ -0,0 +1,93 @@ +.agent-connections { + display: grid; + gap: 1.5rem; + max-width: 64rem; + margin-inline: auto; + padding: clamp(1rem, 3vw, 2rem); +} + +.agent-connections h1, +.agent-connections h2, +.agent-connections p { + margin: 0; +} + +.agent-connections__header, +.agent-connections__section, +.agent-connections__approval, +.agent-connections__approval-result { + display: grid; + gap: 0.75rem; +} + +.agent-connections__header > p, +.agent-connections__section > p, +.agent-connections__approval > p, +.agent-connections__approval-result > p { + color: var(--hub-fg-muted); +} + +.agent-connections__section { + padding-block: 1.25rem; + border-top: 1px solid var(--hub-border-default); +} + +.agent-connections__list { + display: grid; + gap: 0.75rem; + margin: 0; + padding: 0; + list-style: none; +} + +.agent-connections__item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 1rem; + border: 1px solid var(--hub-border-default); + border-radius: var(--hub-radius-medium); +} + +.agent-connections__item > div { + display: grid; + gap: 0.25rem; +} + +.agent-connections__item span { + color: var(--hub-fg-muted); + font-size: 0.875rem; +} + +.agent-connections__approval { + max-width: 36rem; + margin: 10vh auto; + padding: 1.5rem; + border: 1px solid var(--hub-border-default); + border-radius: var(--hub-radius-medium); + background: var(--hub-canvas-default); +} + +.agent-connections__approval-result { + max-width: 36rem; + margin: 10vh auto; +} + +.agent-connections__actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.75rem; +} + +.agent-connections__revoke-dialog { + display: grid; + gap: 1.25rem; +} + +@media (max-width: 40rem) { + .agent-connections__item { + align-items: flex-start; + } +} diff --git a/hub/client/pages/agent-connections-page/types.ts b/hub/client/pages/agent-connections-page/types.ts new file mode 100644 index 000000000..146d4bced --- /dev/null +++ b/hub/client/pages/agent-connections-page/types.ts @@ -0,0 +1,24 @@ +export interface AgentConnection { + id: string + name: string + connectedAt: string + lastUsedAt: string +} + +interface AgentConnectionsPrototypeBase { + repositoryId: string + repositoryName: string + hubUrl: string + signedInAs: string +} + +export type AgentConnectionsPrototypeData = + | (AgentConnectionsPrototypeBase & { + view: "connections" + connections: AgentConnection[] + }) + | (AgentConnectionsPrototypeBase & { + view: "approval" + connections: AgentConnection[] + requestingAgent: string + }) diff --git a/hub/package-lock.json b/hub/package-lock.json index cc89cf007..055f93470 100644 --- a/hub/package-lock.json +++ b/hub/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "@azure/identity": "4.13.0", "@azure/storage-blob": "12.33.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opentelemetry/api": "1.10.0", "@opentelemetry/context-async-hooks": "3.0.0", "@opentelemetry/exporter-trace-otlp-proto": "0.300.0", @@ -1536,6 +1537,18 @@ "url": "https://github.com/sponsors/colinhacks" } }, + "node_modules/@hono/node-server": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.9.tgz", + "integrity": "sha512-Sk4NQd3GFY0WZWCzndwFMPwJhtD0y9qjsQ+pjID0/03nK9pxyBCUoUHCho8QYBLBVhi0ssL8UkNPHqbgSOFPIQ==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "dev": true, @@ -1990,6 +2003,55 @@ "react": ">=16" } }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.2", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", + "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": { "version": "3.0.4", "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz", @@ -5196,6 +5258,23 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha1-PV3HYryhdnnDwup+kK1rdTIwlXg=", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "dev": true, @@ -5634,6 +5713,23 @@ "node": ">=6.6.0" } }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/cron-parser": { "version": "5.10.2", "license": "MIT", @@ -6360,6 +6456,27 @@ "node": ">=0.8.x" } }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/exit-hook": { "version": "5.1.0", "dev": true, @@ -6420,6 +6537,25 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.7.5", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.5.tgz", + "integrity": "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/exsolve": { "version": "1.1.3", "license": "MIT" @@ -6826,6 +6962,15 @@ "hermes-estree": "0.25.1" } }, + "node_modules/hono": { + "version": "4.13.19", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz", + "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/hookified": { "version": "1.15.1", "dev": true, @@ -6935,6 +7080,15 @@ "node": ">=12" } }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "license": "MIT", @@ -7135,6 +7289,12 @@ "version": "1.0.0", "license": "MIT" }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "dev": true, @@ -7855,6 +8015,15 @@ "node": ">=18" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "license": "MIT", @@ -8278,6 +8447,15 @@ "version": "7.1.0", "license": "MIT" }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pkg-types": { "version": "2.3.3", "license": "MIT", @@ -9866,6 +10044,15 @@ "url": "https://github.com/sponsors/colinhacks" } }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + }, "node_modules/zod-validation-error": { "version": "4.0.2", "dev": true, diff --git a/hub/package.json b/hub/package.json index 22ea1da16..4203ad155 100644 --- a/hub/package.json +++ b/hub/package.json @@ -71,6 +71,7 @@ "dependencies": { "@azure/identity": "4.13.0", "@azure/storage-blob": "12.33.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opentelemetry/api": "1.10.0", "@opentelemetry/context-async-hooks": "3.0.0", "@opentelemetry/exporter-trace-otlp-proto": "0.300.0", diff --git a/hub/schema/agent-authorization.prisma b/hub/schema/agent-authorization.prisma new file mode 100644 index 000000000..26aa0f134 --- /dev/null +++ b/hub/schema/agent-authorization.prisma @@ -0,0 +1,24 @@ +model AgentAuthorization { + // ID columns + id String @id @default(uuid()) @db.Uuid + clientId String @map("client_id") @db.Uuid + sessionId String? @map("session_id") @db.Uuid + + // Relations + client AgentClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + session HubSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull) + + // Attribute columns + redirectUri String @map("redirect_uri") @db.VarChar(2048) + codeChallenge String @map("code_challenge") @db.VarChar(128) + state String? @db.VarChar(1024) + codeDigest String? @unique @map("code_digest") @db.VarChar(64) + expiresAt DateTime @map("expires_at") @db.Timestamptz(3) + approvedAt DateTime? @map("approved_at") @db.Timestamptz(3) + consumedAt DateTime? @map("consumed_at") @db.Timestamptz(3) + + @@index([clientId]) + @@index([sessionId]) + @@index([expiresAt]) + @@map("agent_authorizations") +} diff --git a/hub/schema/agent-client.prisma b/hub/schema/agent-client.prisma new file mode 100644 index 000000000..06b3164a4 --- /dev/null +++ b/hub/schema/agent-client.prisma @@ -0,0 +1,17 @@ +model AgentClient { + // ID columns + id String @id @default(uuid()) @db.Uuid + + // Relations + authorizations AgentAuthorization[] + connections AgentConnection[] + + // Attribute columns + name String @db.VarChar(200) + redirectUris String[] @map("redirect_uris") + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + + @@map("agent_clients") +} diff --git a/hub/schema/agent-connection.prisma b/hub/schema/agent-connection.prisma new file mode 100644 index 000000000..7a40fbde8 --- /dev/null +++ b/hub/schema/agent-connection.prisma @@ -0,0 +1,32 @@ +model AgentConnection { + // ID columns + id String @id @default(uuid()) @db.Uuid + clientId String @map("client_id") @db.Uuid + membershipId String @map("membership_id") @db.Uuid + externalIdentityId String @map("external_identity_id") @db.Uuid + providerRevisionId String @map("provider_revision_id") @db.Uuid + + // Relations + client AgentClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + membership Membership @relation(fields: [membershipId], references: [id], onDelete: Cascade) + externalIdentity ExternalIdentity @relation(fields: [externalIdentityId], references: [id], onDelete: Cascade) + providerRevision AuthenticationProviderRevision @relation(fields: [providerRevisionId], references: [id], onDelete: Cascade) + + // Attribute columns + revocationRevision Int @map("revocation_revision") + tokenDigest String @unique @map("token_digest") @db.VarChar(64) + refreshDigest String @unique @map("refresh_digest") @db.VarChar(64) + expiresAt DateTime @map("expires_at") @db.Timestamptz(3) + inactiveAt DateTime @map("inactive_at") @db.Timestamptz(3) + lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz(3) + revokedAt DateTime? @map("revoked_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + + @@index([clientId]) + @@index([externalIdentityId]) + @@index([providerRevisionId]) + @@index([membershipId, externalIdentityId, createdAt]) + @@map("agent_connections") +} diff --git a/hub/schema/authentication-provider-revision.prisma b/hub/schema/authentication-provider-revision.prisma index 74d96f416..1069a40f6 100644 --- a/hub/schema/authentication-provider-revision.prisma +++ b/hub/schema/authentication-provider-revision.prisma @@ -11,6 +11,7 @@ model AuthenticationProviderRevision { hubSessions HubSession[] membershipAssignments MembershipAssignment[] canvasGrants CanvasGrant[] + agentConnections AgentConnection[] // Attribute columns revision Int diff --git a/hub/schema/external-identity.prisma b/hub/schema/external-identity.prisma index 510cfe1e2..125afdb67 100644 --- a/hub/schema/external-identity.prisma +++ b/hub/schema/external-identity.prisma @@ -10,6 +10,7 @@ model ExternalIdentity { hubSessions HubSession[] sensitiveAuthorizations SensitiveAuthorization[] canvasGrants CanvasGrant[] + agentConnections AgentConnection[] shareLinks ShareLink[] // Attribute columns diff --git a/hub/schema/hub-session.prisma b/hub/schema/hub-session.prisma index 9037094c9..1e385f804 100644 --- a/hub/schema/hub-session.prisma +++ b/hub/schema/hub-session.prisma @@ -11,6 +11,7 @@ model HubSession { providerRevision AuthenticationProviderRevision? @relation(fields: [providerRevisionId], references: [id], onDelete: Restrict) sensitiveAuthorizations SensitiveAuthorization[] canvasPairings CanvasPairing[] + agentAuthorizations AgentAuthorization[] analyticsDestinationAuthorization AnalyticsDestinationAuthorization? // Attribute columns diff --git a/hub/schema/membership.prisma b/hub/schema/membership.prisma index ffc9d8b7c..fe80d947f 100644 --- a/hub/schema/membership.prisma +++ b/hub/schema/membership.prisma @@ -17,6 +17,7 @@ model Membership { decisionRuntimeDeletions DecisionRuntimeDeletion[] learningDecisionOperations LearningDecisionOperation[] canvasGrants CanvasGrant[] + agentConnections AgentConnection[] // Attribute columns lifecycle MembershipLifecycle @default(ACTIVE) diff --git a/hub/schema/migrations/20261223170000_agent_connections/migration.sql b/hub/schema/migrations/20261223170000_agent_connections/migration.sql new file mode 100644 index 000000000..e74b176cb --- /dev/null +++ b/hub/schema/migrations/20261223170000_agent_connections/migration.sql @@ -0,0 +1,92 @@ +-- CreateTable +CREATE TABLE "agent_authorizations" ( + "id" UUID NOT NULL, + "client_id" UUID NOT NULL, + "session_id" UUID, + "redirect_uri" VARCHAR(2048) NOT NULL, + "code_challenge" VARCHAR(128) NOT NULL, + "state" VARCHAR(1024), + "code_digest" VARCHAR(64), + "expires_at" TIMESTAMPTZ(3) NOT NULL, + "approved_at" TIMESTAMPTZ(3), + "consumed_at" TIMESTAMPTZ(3), + + CONSTRAINT "agent_authorizations_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "agent_clients" ( + "id" UUID NOT NULL, + "name" VARCHAR(200) NOT NULL, + "redirect_uris" TEXT[], + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "agent_clients_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "agent_connections" ( + "id" UUID NOT NULL, + "client_id" UUID NOT NULL, + "membership_id" UUID NOT NULL, + "external_identity_id" UUID NOT NULL, + "provider_revision_id" UUID NOT NULL, + "revocation_revision" INTEGER NOT NULL, + "token_digest" VARCHAR(64) NOT NULL, + "refresh_digest" VARCHAR(64) NOT NULL, + "expires_at" TIMESTAMPTZ(3) NOT NULL, + "inactive_at" TIMESTAMPTZ(3) NOT NULL, + "last_used_at" TIMESTAMPTZ(3), + "revoked_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "agent_connections_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_authorizations_code_digest_key" ON "agent_authorizations"("code_digest"); + +-- CreateIndex +CREATE INDEX "agent_authorizations_client_id_idx" ON "agent_authorizations"("client_id"); + +-- CreateIndex +CREATE INDEX "agent_authorizations_session_id_idx" ON "agent_authorizations"("session_id"); + +-- CreateIndex +CREATE INDEX "agent_authorizations_expires_at_idx" ON "agent_authorizations"("expires_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_connections_token_digest_key" ON "agent_connections"("token_digest"); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_connections_refresh_digest_key" ON "agent_connections"("refresh_digest"); + +-- CreateIndex +CREATE INDEX "agent_connections_client_id_idx" ON "agent_connections"("client_id"); + +-- CreateIndex +CREATE INDEX "agent_connections_external_identity_id_idx" ON "agent_connections"("external_identity_id"); + +-- CreateIndex +CREATE INDEX "agent_connections_provider_revision_id_idx" ON "agent_connections"("provider_revision_id"); + +-- CreateIndex +CREATE INDEX "agent_connections_membership_id_external_identity_id_create_idx" ON "agent_connections"("membership_id", "external_identity_id", "created_at"); + +-- AddForeignKey +ALTER TABLE "agent_authorizations" ADD CONSTRAINT "agent_authorizations_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "agent_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_authorizations" ADD CONSTRAINT "agent_authorizations_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "hub_sessions"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "agent_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_membership_id_fkey" FOREIGN KEY ("membership_id") REFERENCES "memberships"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_external_identity_id_fkey" FOREIGN KEY ("external_identity_id") REFERENCES "external_identities"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_provider_revision_id_fkey" FOREIGN KEY ("provider_revision_id") REFERENCES "authentication_provider_revisions"("id") ON DELETE CASCADE ON UPDATE CASCADE; From 66770437e0666536f9ebaf1671ba34785d0cbe87 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 11:42:53 -0800 Subject: [PATCH 02/32] feat(hub): complete the Learning agent experience Connect authenticated agents to repository learnings, add consent controls for review comments and Pick & Polish notes, and expose deployed setup through the Azure wizard. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../application/hub-application/index.tsx | 8 +- .../hub/agent-connections/contract.ts | 29 ++ .../hub/learnings-contracts/index.ts | 26 ++ .../hub/learnings-contracts/types.ts | 17 + hub/client/application/hub/routes.ts | 1 + .../hub/routes/agent-approval/index.tsx | 95 +++++ .../hub/routes/learning-agents/index.tsx | 103 ++++++ .../hub/routes/learning-settings/index.tsx | 129 +++++++ .../application/hub/routes/product-routes.ts | 2 + .../routes/real-workspace-navigation.test.tsx | 20 + .../view-models/settings-learnings/index.ts | 6 +- .../agent-connections-page/index.test.tsx | 141 +++---- .../pages/agent-connections-page/index.tsx | 126 ++++--- .../pages/agent-connections-page/stories.tsx | 82 ++-- .../pages/agent-connections-page/styles.css | 11 +- .../pages/agent-connections-page/types.ts | 35 +- .../pages/learning-settings-page/index.tsx | 118 ++++++ .../pages/learning-settings-page/stories.tsx | 59 +++ .../pages/learning-settings-page/styles.css | 51 +++ .../pages/learning-settings-page/types.ts | 16 + hub/client/pages/learnings-page/index.tsx | 8 +- hub/client/pages/learnings-page/stories.tsx | 6 +- hub/client/pages/learnings-page/styles.css | 6 + hub/client/pages/learnings-page/types.ts | 2 +- hub/client/storybook/fixtures/learnings.ts | 2 +- hub/docs/learning-foundation.md | 106 +----- hub/docs/storybook.md | 1 + hub/schema/copilot-connection.prisma | 1 + hub/schema/membership.prisma | 6 +- .../migration.sql | 51 +++ hub/schema/repository-learning-setting.prisma | 28 ++ hub/schema/repository.prisma | 1 + hub/server/create-app/index.ts | 4 + .../create-agent-connections/index.ts | 233 ++++++++++++ .../create-learning-mcp-backend/index.test.ts | 350 ++++++++++++++++++ .../create-learning-mcp-backend/index.ts | 272 ++++++++++++++ .../connect-copilot/index.test.ts | 3 +- .../connect-copilot/index.ts | 6 +- .../domains/copilot-connection/types.ts | 1 + .../change-pick-and-polish-consent/index.ts | 67 ++++ .../create-learning-job-processors/index.ts | 9 +- .../process-learning-run/index.test.ts | 144 +++++++ .../learning/process-learning-run/index.ts | 172 +++++---- .../read-learning-configuration/index.test.ts | 21 ++ .../read-learning-configuration/index.ts | 3 + .../read-review-comment-consent/index.test.ts | 8 + .../read-review-comment-consent/index.ts | 11 + hub/server/index.ts | 12 + .../express/canvas-sign-in-return/index.ts | 3 +- .../learning/load-learning-mcp/index.test.ts | 16 + .../learning/load-learning-mcp/index.ts | 33 ++ .../mcp/agent-oauth-provider/index.ts | 84 +++++ .../mcp/agent-oauth-provider/types.ts | 19 + .../mcp/create-agent-auth-router/index.ts | 23 ++ .../mcp/handle-mcp-request/index.test.ts | 41 ++ .../mcp/handle-mcp-request/index.ts | 24 ++ .../mcp/require-agent-token/index.ts | 23 ++ .../claim-agent-authorization/index.ts | 36 ++ .../create-agent-authorization/index.ts | 10 + .../decide-agent-authorization/index.ts | 18 + .../index.ts | 18 + .../find-pending-agent-authorization/index.ts | 18 + .../create-agent-client/index.ts | 8 + .../agent-clients/find-agent-client/index.ts | 8 + .../create-agent-connection/index.ts | 11 + .../find-agent-repository/index.ts | 20 + .../list-agent-connections/index.ts | 20 + .../record-agent-connection-audit/index.ts | 24 ++ .../revoke-agent-connection/index.ts | 17 + .../rotate-agent-connection/index.ts | 40 ++ .../touch-agent-connection/index.ts | 24 ++ .../replace-copilot-connection/index.ts | 1 + .../index.db.test.ts | 85 +++++ .../list-due-learning-repositories/index.ts | 26 +- .../get-repository-learning-setting/index.ts | 18 + .../get-review-comment-consent/index.ts | 34 ++ .../index.ts | 11 + .../save-repository-learning-setting/index.ts | 28 ++ .../create-security-audit/types.ts | 2 +- .../parse-security-audit-event/index.ts | 7 +- .../routes/agent-connections/index.db.test.ts | 253 +++++++++++++ hub/server/routes/agent-connections/index.ts | 246 ++++++++++++ hub/server/routes/agent-connections/types.ts | 11 + .../index.ts | 1 + .../index.ts | 127 ++++++- .../repository-authority.db.test.ts | 109 ++++++ hub/server/routes/api/learnings/index.test.ts | 8 + .../api/learnings/settings/get/index.ts | 71 ++++ .../api/learnings/settings/patch/index.ts | 98 +++++ hub/server/routes/api/learnings/types.ts | 17 +- .../present-security-audit/index.ts | 10 +- hub/server/routes/index.ts | 23 ++ hub/server/routes/types.ts | 2 + hub/server/run-api/index.ts | 4 + hub/server/start-server-processes/index.ts | 2 + infrastructure/README.md | 6 +- .../azure/post/configure/index.test.ts | 38 ++ infrastructure/azure/post/configure/index.ts | 23 +- infrastructure/azure/post/index.ts | 17 +- infrastructure/azure/post/progress/index.ts | 14 +- infrastructure/installer/entry/index.test.ts | 3 +- infrastructure/installer/entry/index.ts | 3 +- infrastructure/installer/types.ts | 2 +- 103 files changed, 4024 insertions(+), 423 deletions(-) create mode 100644 hub/client/application/hub/agent-connections/contract.ts create mode 100644 hub/client/application/hub/routes/agent-approval/index.tsx create mode 100644 hub/client/application/hub/routes/learning-agents/index.tsx create mode 100644 hub/client/application/hub/routes/learning-settings/index.tsx create mode 100644 hub/client/pages/learning-settings-page/index.tsx create mode 100644 hub/client/pages/learning-settings-page/stories.tsx create mode 100644 hub/client/pages/learning-settings-page/styles.css create mode 100644 hub/client/pages/learning-settings-page/types.ts create mode 100644 hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql create mode 100644 hub/schema/repository-learning-setting.prisma create mode 100644 hub/server/domains/agent-connections/create-agent-connections/index.ts create mode 100644 hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts create mode 100644 hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts create mode 100644 hub/server/domains/learning/change-pick-and-polish-consent/index.ts create mode 100644 hub/server/domains/learning/read-review-comment-consent/index.test.ts create mode 100644 hub/server/domains/learning/read-review-comment-consent/index.ts create mode 100644 hub/server/integrations/learning/load-learning-mcp/index.test.ts create mode 100644 hub/server/integrations/learning/load-learning-mcp/index.ts create mode 100644 hub/server/integrations/mcp/agent-oauth-provider/index.ts create mode 100644 hub/server/integrations/mcp/agent-oauth-provider/types.ts create mode 100644 hub/server/integrations/mcp/create-agent-auth-router/index.ts create mode 100644 hub/server/integrations/mcp/handle-mcp-request/index.test.ts create mode 100644 hub/server/integrations/mcp/handle-mcp-request/index.ts create mode 100644 hub/server/integrations/mcp/require-agent-token/index.ts create mode 100644 hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts create mode 100644 hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-clients/create-agent-client/index.ts create mode 100644 hub/server/repositories/agent-clients/find-agent-client/index.ts create mode 100644 hub/server/repositories/agent-connections/create-agent-connection/index.ts create mode 100644 hub/server/repositories/agent-connections/find-agent-repository/index.ts create mode 100644 hub/server/repositories/agent-connections/list-agent-connections/index.ts create mode 100644 hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts create mode 100644 hub/server/repositories/agent-connections/revoke-agent-connection/index.ts create mode 100644 hub/server/repositories/agent-connections/rotate-agent-connection/index.ts create mode 100644 hub/server/repositories/agent-connections/touch-agent-connection/index.ts create mode 100644 hub/server/repositories/learning-settings/get-repository-learning-setting/index.ts create mode 100644 hub/server/repositories/learning-settings/get-review-comment-consent/index.ts create mode 100644 hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts create mode 100644 hub/server/repositories/learning-settings/save-repository-learning-setting/index.ts create mode 100644 hub/server/routes/agent-connections/index.db.test.ts create mode 100644 hub/server/routes/agent-connections/index.ts create mode 100644 hub/server/routes/agent-connections/types.ts create mode 100644 hub/server/routes/api/learnings/settings/get/index.ts create mode 100644 hub/server/routes/api/learnings/settings/patch/index.ts diff --git a/hub/client/application/hub-application/index.tsx b/hub/client/application/hub-application/index.tsx index 5e67638e3..ff0cca245 100644 --- a/hub/client/application/hub-application/index.tsx +++ b/hub/client/application/hub-application/index.tsx @@ -197,9 +197,11 @@ export function HubApplication({ canvasReturnTo }: { canvasReturnTo?: string } = : null, badge: "Collaborative prototyping", badgeAlternate: "Built for feedback", - description: canvasReturnTo - ? "Sign in to continue to your Replica canvas connection." - : "Sign in with an active Replica Hub membership.", + description: canvasReturnTo?.startsWith("/agents/") + ? "Sign in to connect your coding agent to Replica Hub." + : canvasReturnTo + ? "Sign in to continue to your Replica canvas connection." + : "Sign in with an active Replica Hub membership.", footerNote: "\u00a9 2026 GitHub, Inc.", heading: "Build and review prototypes with your team.", notice: null, diff --git a/hub/client/application/hub/agent-connections/contract.ts b/hub/client/application/hub/agent-connections/contract.ts new file mode 100644 index 000000000..024922930 --- /dev/null +++ b/hub/client/application/hub/agent-connections/contract.ts @@ -0,0 +1,29 @@ +import { z } from "zod" + +export const agentAuthorizationSchema = z + .object({ + agent: z.string().min(1), + redirectUri: z.url(), + session: z.string().min(1).max(255), + signedInAs: z.string().min(1), + expiresAt: z.iso.datetime(), + }) + .strict() + +export const agentDecisionSchema = z.object({ redirectUrl: z.url() }).strict() + +export const agentConnectionsSchema = z + .object({ + connections: z.array( + z + .object({ + id: z.uuid(), + agent: z.string().min(1), + createdAt: z.iso.datetime(), + lastUsedAt: z.iso.datetime().nullable(), + inactiveAt: z.iso.datetime(), + }) + .strict(), + ), + }) + .strict() diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index 8946d837e..735f3bfe7 100644 --- a/hub/client/application/hub/learnings-contracts/index.ts +++ b/hub/client/application/hub/learnings-contracts/index.ts @@ -9,6 +9,8 @@ import type { LearningHistoryResponse, LearningMutationResponse, LearningRunResponse, + LearningSettingsInput, + LearningSettingsResponse, LearningSuggestionResponse, LearningsResponse, RejectedLearningResponse, @@ -247,3 +249,27 @@ export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ export const learningMutationResponseSchema = z .object({ notice: z.string().min(1) }) .strict() satisfies z.ZodType + +const learningSettingsRecordSchema = z + .object({ + allowed: z.boolean(), + changedBy: z.string().min(1).nullable(), + changedAt: timestamp.nullable(), + }) + .strict() + +export const learningSettingsResponseSchema = z + .object({ + repository: repositorySchema, + notes: learningSettingsRecordSchema, + reviewComments: learningSettingsRecordSchema, + }) + .strict() satisfies z.ZodType + +export const learningSettingsInputSchema = z + .object({ + notes: z.boolean().optional(), + reviewComments: z.boolean().optional(), + }) + .strict() + .refine((value) => Object.keys(value).length > 0) satisfies z.ZodType diff --git a/hub/client/application/hub/learnings-contracts/types.ts b/hub/client/application/hub/learnings-contracts/types.ts index ad1a8372a..864529f1c 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -129,3 +129,20 @@ export type LearningDecisionInput = export interface LearningMutationResponse { notice: string } + +export interface LearningSettingsRecord { + allowed: boolean + changedBy: string | null + changedAt: string | null +} + +export interface LearningSettingsResponse { + repository: RepositoryRecord + notes: LearningSettingsRecord + reviewComments: LearningSettingsRecord +} + +export interface LearningSettingsInput { + notes?: boolean + reviewComments?: boolean +} diff --git a/hub/client/application/hub/routes.ts b/hub/client/application/hub/routes.ts index 57fb007ab..4818cc8ae 100644 --- a/hub/client/application/hub/routes.ts +++ b/hub/client/application/hub/routes.ts @@ -8,6 +8,7 @@ export default [ route("signed-in/no-access", "routes/no-repository-access/index.tsx"), route("sign-in", "routes/sign-in/index.tsx"), route("canvas/pair/:userCode", "routes/canvas-pairing/index.tsx"), + route("agents/approve/:authorizationId", "routes/agent-approval/index.tsx"), route("shared/:shareId", "routes/product-public/index.tsx"), ...standaloneSetupRoutes, layout("routes/workspace/index.tsx", [ diff --git a/hub/client/application/hub/routes/agent-approval/index.tsx b/hub/client/application/hub/routes/agent-approval/index.tsx new file mode 100644 index 000000000..9609fd993 --- /dev/null +++ b/hub/client/application/hub/routes/agent-approval/index.tsx @@ -0,0 +1,95 @@ +import { redirect, useFetcher, useLocation } from "react-router" +import { z } from "zod" + +import { HubApplication } from "@application/hub-application" +import { + agentAuthorizationSchema, + agentDecisionSchema, +} from "@application/hub/agent-connections/contract" +import { canvasActionError } from "@application/hub/canvas-connections/contract" +import { FormBoundary } from "@application/hub/form-boundary" +import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { requestJson } from "@application/hub/requests/request-json" +import { AgentConnectionsPage } from "@pages/agent-connections-page" +import type { AgentConnectionsPageData } from "@pages/agent-connections-page/types" + +import type { Route } from "./+types/index" + +function authorizationPath(value: string | undefined) { + const id = z.uuid().safeParse(value) + if (!id.success) throw new Response("This agent request is invalid.", { status: 404 }) + return { id: id.data, browserPath: `/agents/approve/${id.data}` } +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const { id, browserPath } = authorizationPath(params.authorizationId) + try { + const authorization = await requestJson( + new URL(`/api/agent-connections/authorizations/${id}`, request.url), + agentAuthorizationSchema, + { signal: request.signal }, + ) + const destination = new URL(authorization.redirectUri) + const page: AgentConnectionsPageData = { + view: "approval", + requestingAgent: authorization.agent, + destination: destination.host, + localDestination: ["localhost", "127.0.0.1", "[::1]"].includes(destination.hostname), + session: authorization.session, + signedInAs: authorization.signedInAs, + expiresLabel: `This request expires at ${new Date(authorization.expiresAt).toLocaleTimeString()}.`, + decisionPath: browserPath, + } + return { page, browserPath } + } catch (error) { + if (error instanceof ApiRequestError && error.status === 401) return { page: null, browserPath } + if (error instanceof ApiRequestError && error.status === 410) + throw new Response(error.message, { status: 410 }) + throw error + } +} + +export async function clientAction({ request, params }: Route.ClientActionArgs) { + const { id, browserPath } = authorizationPath(params.authorizationId) + if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) + const form = await request.formData() + const decision = form.get("decision") + if (decision !== "approve" && decision !== "cancel") + throw new Response("Choose whether to approve this agent.", { status: 422 }) + try { + const { redirectUrl } = await requestJson( + new URL(`/api/agent-connections/authorizations/${id}/${decision}`, request.url), + agentDecisionSchema, + { + method: "POST", + body: JSON.stringify({ session: form.get("session") }), + signal: request.signal, + }, + ) + // The agent listens on its own address, so the browser leaves Hub to finish. + return redirect(redirectUrl) + } catch (error) { + if (error instanceof ApiRequestError && error.status === 401) return redirect(browserPath) + return canvasActionError(error) + } +} + +export function meta() { + return [{ title: "Connect an agent - Replica Hub" }] +} + +export default function AgentApproval({ loaderData }: Route.ComponentProps) { + const fetcher = useFetcher<{ error?: string }>() + const { pathname } = useLocation() + if (!loaderData.page) return + const busy = fetcher.state !== "idle" + return ( + void fetcher.submit(form, { method: "post", action: pathname })} + > + + + ) +} diff --git a/hub/client/application/hub/routes/learning-agents/index.tsx b/hub/client/application/hub/routes/learning-agents/index.tsx new file mode 100644 index 000000000..e19333e1d --- /dev/null +++ b/hub/client/application/hub/routes/learning-agents/index.tsx @@ -0,0 +1,103 @@ +import { useFetcher, useLocation, useOutletContext } from "react-router" +import { z } from "zod" + +import { agentConnectionsSchema } from "@application/hub/agent-connections/contract" +import { + canvasActionError, + canvasFormDestination, +} from "@application/hub/canvas-connections/contract" +import { recordIdentifierSchema } from "@application/hub/contracts" +import type { WorkspaceResponse } from "@application/hub/contracts/types" +import { FormBoundary } from "@application/hub/form-boundary" +import { requestJson } from "@application/hub/requests/request-json" +import { AgentConnectionsPage } from "@pages/agent-connections-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 +} + +function dateLabel(value: string) { + return new Date(value).toLocaleDateString() +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const id = repositoryId(params.repositoryId) + const { connections } = await requestJson( + new URL("/api/agent-connections", request.url), + agentConnectionsSchema, + { signal: request.signal }, + ) + return { + mcpUrl: new URL(`/mcp/repositories/${id}`, request.url).href, + connections: connections.map((connection) => ({ + id: connection.id, + name: connection.agent, + connectedLabel: `Connected ${dateLabel(connection.createdAt)}`, + lastUsedLabel: connection.lastUsedAt + ? `Last used ${dateLabel(connection.lastUsedAt)}` + : "Not used yet", + revokePath: `/repositories/${id}/learnings/agents/${connection.id}`, + })), + } +} + +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 destination = canvasFormDestination(form, request.url) + const connectionId = destination?.pathname.startsWith(`/repositories/${id}/learnings/agents/`) + ? z.uuid().safeParse(destination.pathname.split("/").at(-1)) + : null + if (!connectionId?.success || form.get("_method") !== "delete") { + throw new Response("This agent connection could not be revoked.", { status: 422 }) + } + try { + await requestJson( + new URL(`/api/agent-connections/${connectionId.data}`, request.url), + z.undefined(), + { method: "DELETE", signal: request.signal }, + ) + } catch (error) { + return canvasActionError(error) + } + return { notice: "Agent access revoked." } +} + +export function meta() { + return [{ title: "Connect an agent - Replica Hub" }] +} + +export default function LearningAgents({ loaderData, params }: Route.ComponentProps) { + const workspace = useOutletContext() + const fetcher = useFetcher<{ error?: string; notice?: string }>() + const { pathname } = useLocation() + const busy = fetcher.state !== "idle" + const repository = workspace?.repositories.find(({ id }) => id === params.repositoryId) + return ( + void fetcher.submit(form, { method: "post", action: pathname })} + > + + + ) +} diff --git a/hub/client/application/hub/routes/learning-settings/index.tsx b/hub/client/application/hub/routes/learning-settings/index.tsx new file mode 100644 index 000000000..f8e4d379a --- /dev/null +++ b/hub/client/application/hub/routes/learning-settings/index.tsx @@ -0,0 +1,129 @@ +import { data, useFetcher, useOutletContext } from "react-router" +import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router" + +import { recordIdentifierSchema, workspaceResponseSchema } from "@application/hub/contracts" +import { + learningSettingsInputSchema, + learningSettingsResponseSchema, +} from "@application/hub/learnings-contracts" +import type { LearningSettingsInput } from "@application/hub/learnings-contracts/types" +import { RepositoryWorkspace } from "@features/repository-workspace" +import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { repositoryWorkspace } from "@application/hub/view-models/repository-workspace" +import { LearningSettingsPage } from "@pages/learning-settings-page" +import type { LearningSettingsChange } from "@pages/learning-settings-page/types" + +import { productActionError } from "../product-action-error" +import { requestProductJson } from "../request-product-json" +import type { WorkspaceRouteHandle } from "../workspace/types" + +export const handle = { workspaceSection: "learnings" } satisfies WorkspaceRouteHandle + +function repositoryId(params: LoaderFunctionArgs["params"]) { + const parsed = recordIdentifierSchema.safeParse(params.repositoryId) + if (!parsed.success) throw new Response("Invalid repository identifier.", { status: 400 }) + return parsed.data +} + +export async function clientLoader({ request, params }: LoaderFunctionArgs) { + const id = repositoryId(params) + const response = await requestProductJson( + request, + `/api/repositories/${id}/learnings/settings`, + learningSettingsResponseSchema, + ) + if (response.repository.id !== id) { + throw new Response("This repository is not available.", { status: 404 }) + } + return response +} + +export async function clientAction({ request, params }: ActionFunctionArgs) { + if (request.method.toUpperCase() !== "POST") { + return data({ saved: false, error: "Method not allowed." }, { status: 405 }) + } + const id = repositoryId(params) + const form = await request.formData() + const setting = form.get("setting") + const allowed = form.get("allowed") + const input: LearningSettingsInput = + setting === "notes" && (allowed === "true" || allowed === "false") + ? { notes: allowed === "true" } + : setting === "reviewComments" && (allowed === "true" || allowed === "false") + ? { reviewComments: allowed === "true" } + : {} + const parsed = learningSettingsInputSchema.safeParse(input) + if (!parsed.success) { + return data( + { saved: false, error: "Choose a Learning setting and try again." }, + { status: 422 }, + ) + } + try { + await requestProductJson( + request, + `/api/repositories/${id}/learnings/settings`, + learningSettingsResponseSchema, + { method: "PATCH", body: parsed.data }, + ) + return data({ saved: true, notice: "Learning settings saved." }) + } catch (error) { + if (error instanceof Response) { + return data({ saved: false, error: await error.text() }, { status: error.status }) + } + if (error instanceof ApiRequestError && [403, 404, 409, 502, 503].includes(error.status)) { + return data({ saved: false, error: error.message }, { status: error.status }) + } + return productActionError(error) + } +} + +export function meta({ loaderData }: { loaderData?: { repository: { nameWithOwner: string } } }) { + return [ + { + title: loaderData + ? `Learning settings - ${loaderData.repository.nameWithOwner} - Replica Hub` + : "Replica Hub", + }, + ] +} + +export default function LearningSettings({ + loaderData, +}: { + loaderData: Awaited> +}) { + const workspace = workspaceResponseSchema.parse(useOutletContext()) + const fetcher = useFetcher<{ saved: boolean; error?: string; notice?: string }>() + const busy = fetcher.state !== "idle" + const pageWorkspace = { + ...repositoryWorkspace(workspace, loaderData.repository), + learningsPath: `/repositories/${loaderData.repository.id}/learnings`, + selectedSection: "learnings" as const, + } + const data = { + ...pageWorkspace, + repositoryName: loaderData.repository.nameWithOwner, + learningsPath: `/repositories/${loaderData.repository.id}/learnings`, + notes: loaderData.notes, + reviewComments: loaderData.reviewComments, + } + + return ( + + { + const submission = + "notes" in change + ? { setting: "notes", allowed: String(change.notes) } + : { setting: "reviewComments", allowed: String(change.reviewComments) } + void fetcher.submit(submission, { method: "post" }) + }} + /> + + ) +} diff --git a/hub/client/application/hub/routes/product-routes.ts b/hub/client/application/hub/routes/product-routes.ts index 0d0b79f60..48bd8d7a0 100644 --- a/hub/client/application/hub/routes/product-routes.ts +++ b/hub/client/application/hub/routes/product-routes.ts @@ -11,6 +11,8 @@ export const repositoryProductRoutes: RouteConfigEntry[] = [ route("prototypes/:prototypeId/share-links", "routes/product-share-links/index.tsx"), route("analytics", "routes/settings-analytics/index.tsx"), route("learnings", "routes/settings-learnings/index.tsx"), + route("learnings/agents", "routes/learning-agents/index.tsx"), + route("learnings/settings", "routes/learning-settings/index.tsx"), ] export const workspaceProductRoutes: RouteConfigEntry[] = [ diff --git a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx index 761f0a9cd..83feabcf7 100644 --- a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx +++ b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx @@ -1336,6 +1336,26 @@ describe("real workspace navigation", () => { expect(screen.queryByRole("link", { name: "Prototypes" })).not.toBeInTheDocument() }) + it("returns to an agent's approval request after sign-in", async () => { + const path = "/agents/approve/7c9e6679-7425-40de-944b-e07fc1f90ae7" + await renderApplication(path, [ + json("/api/auth/providers", { providers: ["github"] }), + ...[ + "/api/auth/session", + "/api/agent-connections/authorizations/7c9e6679-7425-40de-944b-e07fc1f90ae7", + ].map((endpoint) => + http.get(`${window.location.origin}${endpoint}`, () => + Response.json({ error: "Sign in to continue." }, { status: 401 }), + ), + ), + ]) + + const signIn = await screen.findByRole("button", { + name: "Sign in with GitHub", + }) + expect(new FormData(signIn.form ?? undefined).get("return_to")).toBe(path) + }) + it("shows a disabled picker and Prototypes without Create on a repository-free landing", async () => { await renderApplication("/repositories", workspaceApi([])) 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 42d51b12a..b428e96b5 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -69,9 +69,9 @@ export function settingsLearnings( agentsPath: workspace.repositories.find(({ id }) => id === repositoryId)?.capabilities?.local ? null : `/repositories/${repositoryId}/learnings/agents`, - evaluationsPath: - !state.solo && (state.capabilities.administerHub || state.capabilities.administerRepository) - ? `/repositories/${repositoryId}/learnings/evaluations` + settingsPath: + !state.solo && state.capabilities.administerRepository + ? `/repositories/${repositoryId}/learnings/settings` : null, // Daily runs keep the page to the library. A Hub without them still needs a way // to look for learnings. diff --git a/hub/client/pages/agent-connections-page/index.test.tsx b/hub/client/pages/agent-connections-page/index.test.tsx index 69c2c23d8..9471050e9 100644 --- a/hub/client/pages/agent-connections-page/index.test.tsx +++ b/hub/client/pages/agent-connections-page/index.test.tsx @@ -3,26 +3,25 @@ import { describe, expect, it, vi } from "vitest" import { HubThemeProvider } from "@hooks/use-hub-theme" -import { AgentConnectionsPrototype } from "." -import type { AgentConnectionsPrototypeData } from "./types" +import { AgentConnectionsPage } from "." -function renderPrototype(data: AgentConnectionsPrototypeData) { - render(, { wrapper: HubThemeProvider }) -} - -describe("AgentConnectionsPrototype()", () => { - it("copies a repository MCP endpoint without putting a credential in the config", async () => { +describe("AgentConnectionsPage()", () => { + it("copies a repository MCP address without putting a credential in the config", async () => { const writeText = vi.fn().mockResolvedValue(undefined) vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "connections", - connections: [], - } - renderPrototype(data) + render( + , + { wrapper: HubThemeProvider }, + ) const config = screen.getByLabelText("Hub MCP configuration") expect(config).toHaveTextContent("https://hub.example.com/mcp/repositories/2001") @@ -35,83 +34,41 @@ describe("AgentConnectionsPrototype()", () => { expect(writeText).toHaveBeenCalledWith(config.textContent) }) - it("requires confirmation and revokes only the selected agent connection", () => { - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "connections", - connections: [ - { - id: "agent-vscode", - name: "Visual Studio Code", - connectedAt: "2026-11-18", - lastUsedAt: "2026-11-24", - }, - { - id: "agent-local", - name: "Local MCP client", - connectedAt: "2026-11-12", - lastUsedAt: "2026-11-21", - }, - ], - } - renderPrototype(data) - - fireEvent.click(screen.getByRole("button", { name: "Revoke Visual Studio Code access" })) - const dialog = screen.getByRole("dialog", { name: "Revoke agent access?" }) - expect(dialog).toHaveTextContent("does not sign you out of Hub") - expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeVisible() - - fireEvent.click(within(dialog).getByRole("button", { name: "Revoke access" })) - - expect(screen.queryByText("Visual Studio Code")).not.toBeInTheDocument() - expect(screen.getByText("Local MCP client")).toBeVisible() - expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( - "Visual Studio Code can no longer access Hub.", - ) - expect(document.activeElement).toBe( - screen.getByRole("heading", { name: "Your connected agents" }), + it("asks for confirmation before revoking only the chosen agent", () => { + render( + , + { wrapper: HubThemeProvider }, ) - }) - - it("keeps agent access pending until approval and separates screenshot consent", () => { - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "approval", - requestingAgent: "Visual Studio Code", - connections: [], - } - renderPrototype(data) - expect(screen.getByText(/does not allow session-message storage/)).toBeVisible() - expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() - fireEvent.click(screen.getByRole("button", { name: "Approve access" })) - - expect(screen.getByRole("heading", { name: "Agent connected" })).toBeVisible() - expect(screen.getByText(/revoke its Hub access at any time/)).toBeVisible() - }) + fireEvent.click(screen.getByRole("button", { name: "Revoke Local MCP client access" })) - it("does not connect the agent when the person cancels approval", () => { - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "approval", - requestingAgent: "Visual Studio Code", - connections: [], - } - renderPrototype(data) - - fireEvent.click(screen.getByRole("button", { name: "Cancel" })) - - expect(screen.getByRole("heading", { name: "Connection cancelled" })).toBeVisible() - expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() - expect(screen.getByText(/No Hub access was granted/)).toBeVisible() + const dialog = screen.getByRole("dialog", { name: "Revoke agent access?" }) + const form = within(dialog).getByRole("button", { name: "Revoke access" }).closest("form") + expect(form).toHaveAttribute("action", "/repositories/2001/learnings/agents/agent-local") + expect(new FormData(form!).get("_method")).toBe("delete") }) }) diff --git a/hub/client/pages/agent-connections-page/index.tsx b/hub/client/pages/agent-connections-page/index.tsx index 8fbc4ea3f..d557590cf 100644 --- a/hub/client/pages/agent-connections-page/index.tsx +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -3,70 +3,70 @@ import { Button, Heading, Text } from "@primer/react-brand" import { CanvasDialog } from "@components/prototype-canvas-dialog" import { CopyableCodeBlock } from "@components/copyable-code-block" +import { HubAlert } from "@components/hub-alert" import { HubToast } from "@components/hub-toast" -import type { AgentConnectionsPrototypeData } from "./types" +import type { AgentConnectionsPageData } from "./types" import "./styles.css" -export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsPrototypeData }) { - const [connections, setConnections] = useState(data.connections) +/** + * Lets people approve a coding agent's request to use their Hub access, and review or + * revoke the agents they already connected. + */ +export function AgentConnectionsPage({ + data, + busy = false, +}: { + data: AgentConnectionsPageData + busy?: boolean +}) { const [connectionToRevoke, setConnectionToRevoke] = useState(null) - const [notice, setNotice] = useState("") - const [approval, setApproval] = useState<"pending" | "approved" | "cancelled">("pending") const connectionsHeadingRef = useRef(null) - const endpoint = `${data.hubUrl.replace(/\/$/, "")}/mcp/repositories/${data.repositoryId}` - const configuration = JSON.stringify({ mcpServers: { replica: { url: endpoint } } }, null, 2) - const selectedConnection = connections.find(({ id }) => id === connectionToRevoke) - - function revokeConnection() { - if (!selectedConnection) return - setConnections((current) => current.filter(({ id }) => id !== selectedConnection.id)) - setConnectionToRevoke(null) - setNotice(`${selectedConnection.name} can no longer access Hub.`) - } if (data.view === "approval") { return (
- {approval === "pending" ? ( -
- - Connect {data.requestingAgent} to Hub? - - - You are signed in as {data.signedInAs}. This agent can read guidance - and report which learnings it applied for repositories you can access. Hub checks - access on every request; only people can accept or change learnings. - - - This does not allow session-message storage, screenshot storage, or automated - screenshot review. Those choices require separate consent. - -
- - -
-
- ) : ( -
- - {approval === "approved" ? "Agent connected" : "Connection cancelled"} - - - {approval === "approved" - ? `Return to ${data.requestingAgent} to continue. You can revoke its Hub access at any time.` - : `You can close this page and return to ${data.requestingAgent}. No Hub access was granted.`} - -
- )} +
+ + Connect {data.requestingAgent} to Hub? + + + Hub cannot confirm this agent's name. Approving sends access to{" "} + {data.destination}. + + {data.localDestination ? null : ( + + )} + + You are signed in as @{data.signedInAs}. This agent can read guidance + and report which learnings it applied for repositories you can access. Hub checks access + on every request; only people can accept or change learnings. + + + This does not allow session-message storage, screenshot storage, or automated screenshot + review. Those choices require separate consent. + + {data.expiresLabel} +
+ + + +
+
) } + const configuration = JSON.stringify({ mcpServers: { replica: { url: data.mcpUrl } } }, null, 2) + const selectedConnection = data.connections.find(({ id }) => id === connectionToRevoke) + return (
@@ -95,24 +95,22 @@ export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsProt Your connected agents - Connected as {data.signedInAs}. These agents can use your Hub access for any repository + Connected as @{data.signedInAs}. These agents can use your Hub access for any repository you can access. - {connections.length ? ( + {data.connections.length ? (
    - {connections.map((connection) => ( + {data.connections.map((connection) => (
  • {connection.name} - Connected{" "} - - {" · "}Last used{" "} - + {connection.connectedLabel} · {connection.lastUsedLabel}
    -
- + ) : null} - {notice ? : null} + {data.notice ? : null} ) } diff --git a/hub/client/pages/agent-connections-page/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx index 56775d479..3b587f217 100644 --- a/hub/client/pages/agent-connections-page/stories.tsx +++ b/hub/client/pages/agent-connections-page/stories.tsx @@ -5,8 +5,8 @@ import type { RepositoryWorkspaceData } from "@features/repository-workspace/typ import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" -import { AgentConnectionsPrototype } from "." -import type { AgentConnectionsPrototypeData } from "./types" +import { AgentConnectionsPage } from "." +import type { AgentConnectionsPageData } from "./types" const workspace: RepositoryWorkspaceData = { ...authenticatedHeaderData, @@ -30,48 +30,59 @@ const workspace: RepositoryWorkspaceData = { welcomePath: "/welcome", } -const connections: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", +const connections: AgentConnectionsPageData = { view: "connections", + repositoryName: "github/prototype", + mcpUrl: "https://hub.example.com/mcp/repositories/2001", + signedInAs: "octocat", + notice: null, connections: [ { id: "agent-vscode", name: "Visual Studio Code", - connectedAt: "2026-11-18", - lastUsedAt: "2026-11-24", + connectedLabel: "Connected 11/18/2026", + lastUsedLabel: "Last used 11/24/2026", + revokePath: "/repositories/2001/learnings/agents/agent-vscode", }, { id: "agent-local", name: "Local MCP client", - connectedAt: "2026-11-12", - lastUsedAt: "2026-11-21", + connectedLabel: "Connected 11/12/2026", + lastUsedLabel: "Not used yet", + revokePath: "/repositories/2001/learnings/agents/agent-local", }, ], } -const approval: AgentConnectionsPrototypeData = { - ...connections, +const approval: AgentConnectionsPageData = { view: "approval", requestingAgent: "Visual Studio Code", + destination: "127.0.0.1:33418", + localDestination: true, + session: "session-octocat", + signedInAs: "octocat", + expiresLabel: "This request expires at 3:15:00 PM.", + decisionPath: "/agents/approve/7c9e6679-7425-40de-944b-e07fc1f90ae7", } const meta = { title: "Hub/Pages/Learnings/Agent connections", - component: AgentConnectionsPrototype, + component: AgentConnectionsPage, parameters: { layout: "fullscreen" }, args: { data: connections }, - render: ({ data }) => - data.view === "connections" ? ( - - - - ) : ( - - ), -} satisfies Meta + // The page's forms post to Hub, so stories keep them from leaving Storybook. + render: ({ data }) => ( +
event.preventDefault()}> + {data.view === "connections" ? ( + + + + ) : ( + + )} +
+ ), +} satisfies Meta export default meta type Story = StoryObj @@ -81,26 +92,23 @@ export const NoConnectedAgents: Story = { args: { data: { ...connections, connections: [] } }, } export const RevokeConfirmation: Story = { - args: { data: connections }, play: async ({ canvas, userEvent }) => { await userEvent.click(canvas.getByRole("button", { name: "Revoke Visual Studio Code access" })) await canvas.findByRole("dialog", { name: "Revoke agent access?" }) }, } -export const ApprovalRequest: Story = { - args: { data: approval }, -} -export const Approved: Story = { - args: { data: approval }, - play: async ({ canvas, userEvent }) => { - await userEvent.click(canvas.getByRole("button", { name: "Approve access" })) - await canvas.findByRole("heading", { name: "Agent connected" }) +export const Revoked: Story = { + args: { + data: { + ...connections, + connections: connections.connections.slice(1), + notice: "Agent access revoked.", + }, }, } -export const Cancelled: Story = { +export const ApprovalRequest: Story = { args: { data: approval }, - play: async ({ canvas, userEvent }) => { - await userEvent.click(canvas.getByRole("button", { name: "Cancel" })) - await canvas.findByRole("heading", { name: "Connection cancelled" }) - }, +} +export const RemoteApprovalRequest: Story = { + args: { data: { ...approval, destination: "agent.example.net", localDestination: false } }, } diff --git a/hub/client/pages/agent-connections-page/styles.css b/hub/client/pages/agent-connections-page/styles.css index 199e1f760..e368b5699 100644 --- a/hub/client/pages/agent-connections-page/styles.css +++ b/hub/client/pages/agent-connections-page/styles.css @@ -14,16 +14,14 @@ .agent-connections__header, .agent-connections__section, -.agent-connections__approval, -.agent-connections__approval-result { +.agent-connections__approval { display: grid; gap: 0.75rem; } .agent-connections__header > p, .agent-connections__section > p, -.agent-connections__approval > p, -.agent-connections__approval-result > p { +.agent-connections__approval > p { color: var(--hub-fg-muted); } @@ -69,11 +67,6 @@ background: var(--hub-canvas-default); } -.agent-connections__approval-result { - max-width: 36rem; - margin: 10vh auto; -} - .agent-connections__actions { display: flex; flex-wrap: wrap; diff --git a/hub/client/pages/agent-connections-page/types.ts b/hub/client/pages/agent-connections-page/types.ts index 146d4bced..21d17301b 100644 --- a/hub/client/pages/agent-connections-page/types.ts +++ b/hub/client/pages/agent-connections-page/types.ts @@ -1,24 +1,29 @@ export interface AgentConnection { id: string name: string - connectedAt: string - lastUsedAt: string + connectedLabel: string + lastUsedLabel: string + revokePath: string } -interface AgentConnectionsPrototypeBase { - repositoryId: string - repositoryName: string - hubUrl: string - signedInAs: string -} - -export type AgentConnectionsPrototypeData = - | (AgentConnectionsPrototypeBase & { +export type AgentConnectionsPageData = + | { view: "connections" + repositoryName: string + mcpUrl: string + signedInAs: string connections: AgentConnection[] - }) - | (AgentConnectionsPrototypeBase & { + notice: string | null + } + | { view: "approval" - connections: AgentConnection[] requestingAgent: string - }) + /** Where the agent asked Hub to send its access, such as "127.0.0.1:33418". */ + destination: string + /** Whether that address is on the person's own computer. */ + localDestination: boolean + session: string + signedInAs: string + expiresLabel: string + decisionPath: string + } diff --git a/hub/client/pages/learning-settings-page/index.tsx b/hub/client/pages/learning-settings-page/index.tsx new file mode 100644 index 000000000..1840fba3f --- /dev/null +++ b/hub/client/pages/learning-settings-page/index.tsx @@ -0,0 +1,118 @@ +import { ArrowLeftIcon } from "@primer/octicons-react" +import { Heading, Text } 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 { LearningSettingsChange, LearningSettingsPageData } from "./types" +import "./styles.css" + +function changedLabel(setting: { changedBy: string | null; changedAt: string | null }) { + if (!setting.changedAt) return null + const date = new Date(setting.changedAt).toLocaleDateString() + return `Last changed ${setting.changedBy ? `by @${setting.changedBy} ` : ""}on ${date}.` +} + +function EvidenceSetting({ + busy, + heading, + hint, + id, + label, + onChange, + setting, +}: { + busy: boolean + heading: string + hint: string + id: string + label: string + onChange: (allowed: boolean) => void + setting: LearningSettingsPageData["notes"] +}) { + return ( +
+ + {heading} + +
+ + {label} + + + + {hint} + +
+ {changedLabel(setting) ? ( + + {changedLabel(setting)} + + ) : null} +
+ ) +} + +export function LearningSettingsPage({ + busy, + data, + error, + notice, + onChange, +}: { + busy: boolean + data: LearningSettingsPageData + error: string | null + notice: string | null + onChange: (change: LearningSettingsChange) => void +}) { + return ( +
+
+ +
+ + Learning settings + + + Choose what Hub can learn from {data.repositoryName}. + +
+
+ {error ? : null} + {notice ? : null} + onChange({ reviewComments: allowed })} + setting={data.reviewComments} + /> + onChange({ notes: allowed })} + setting={data.notes} + /> +
+ ) +} diff --git a/hub/client/pages/learning-settings-page/stories.tsx b/hub/client/pages/learning-settings-page/stories.tsx new file mode 100644 index 000000000..73595f644 --- /dev/null +++ b/hub/client/pages/learning-settings-page/stories.tsx @@ -0,0 +1,59 @@ +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 { githubPrototype } from "@/storybook/fixtures/repositories" + +import { LearningSettingsPage } from "." +import type { LearningSettingsPageData } 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], + repositoryMenuLabel: "Repositories", + repositorySelectorLabel: "Choose repository. github/prototype selected", + selectedRepositoryId: "2001", + selectedSection: "learnings", + welcomeLabel: "Welcome", + welcomePath: "/welcome", +} + +const data: LearningSettingsPageData = { + ...workspace, + repositoryName: "github/prototype", + learningsPath: "/repositories/2001/learnings", + notes: { allowed: false, changedBy: null, changedAt: null }, + reviewComments: { allowed: true, changedBy: null, changedAt: null }, +} + +const meta = { + title: "Hub/Pages/Learnings/Settings", + component: LearningSettingsPage, + parameters: { layout: "fullscreen" }, + args: { busy: false, data, error: null, notice: null, onChange: () => undefined }, + render: (args) => ( + + + + ), +} satisfies Meta + +export default meta +type Story = StoryObj + +export const Defaults: Story = {} +export const Saving: Story = { args: { busy: true } } +export const Saved: Story = { args: { notice: "Learning settings saved." } } +export const Failed: Story = { args: { error: "Hub could not save this setting." } } diff --git a/hub/client/pages/learning-settings-page/styles.css b/hub/client/pages/learning-settings-page/styles.css new file mode 100644 index 000000000..eb93cb4de --- /dev/null +++ b/hub/client/pages/learning-settings-page/styles.css @@ -0,0 +1,51 @@ +.learning-settings { + display: grid; + gap: 1.5rem; + max-width: 64rem; + margin-inline: auto; + padding: clamp(1rem, 3vw, 2rem); +} + +.learning-settings h1, +.learning-settings h2, +.learning-settings p { + margin: 0; +} + +.learning-settings__header { + display: flex; + align-items: flex-start; + gap: 0.75rem; +} + +.learning-settings__header > div { + display: grid; + gap: 0.5rem; +} + +.learning-settings__header p { + color: var(--hub-fg-muted); +} + +.learning-settings__section { + display: grid; + gap: 0.75rem; + padding-block: 1.25rem; + border-top: 1px solid var(--hub-border-default); +} + +.learning-settings__row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 0.5rem 1rem; +} + +.learning-settings__row > p:last-child { + grid-column: 1 / -1; + color: var(--hub-fg-muted); +} + +.learning-settings__label { + font-weight: 600; +} diff --git a/hub/client/pages/learning-settings-page/types.ts b/hub/client/pages/learning-settings-page/types.ts new file mode 100644 index 000000000..6101dad71 --- /dev/null +++ b/hub/client/pages/learning-settings-page/types.ts @@ -0,0 +1,16 @@ +import type { RepositoryWorkspaceData } from "@features/repository-workspace/types" + +interface LearningSettingRecord { + allowed: boolean + changedBy: string | null + changedAt: string | null +} + +export interface LearningSettingsPageData extends RepositoryWorkspaceData { + repositoryName: string + learningsPath: string + notes: LearningSettingRecord + reviewComments: LearningSettingRecord +} + +export type LearningSettingsChange = { notes: boolean } | { reviewComments: boolean } diff --git a/hub/client/pages/learnings-page/index.tsx b/hub/client/pages/learnings-page/index.tsx index aadf105cb..4622d8127 100644 --- a/hub/client/pages/learnings-page/index.tsx +++ b/hub/client/pages/learnings-page/index.tsx @@ -44,7 +44,7 @@ function LearningsContent({ data }: { data: Extract {data.run ? (
@@ -54,9 +54,9 @@ function LearningsContent({ data }: { data: Extract ) : null} - {data.evaluationsPath ? ( - ) : null} diff --git a/hub/client/pages/learnings-page/stories.tsx b/hub/client/pages/learnings-page/stories.tsx index 662008db5..5833b03ec 100644 --- a/hub/client/pages/learnings-page/stories.tsx +++ b/hub/client/pages/learnings-page/stories.tsx @@ -130,7 +130,7 @@ export const IdentityRevalidation: Story = { } export const ReadableMember: Story = { - args: { data: { ...data, evaluationsPath: null } }, + args: { data: { ...data, settingsPath: null } }, } export const CopilotRefused: Story = { @@ -152,7 +152,7 @@ export const LocalLearning: Story = { data: { ...data, agentsPath: null, - evaluationsPath: null, + settingsPath: null, soloNotice: "These learnings come from Solo in this checkout. Solo looks for new ones after each agent session, and agents here get the ones you accept.", activity: [ @@ -189,7 +189,7 @@ export const LocalLearningSetup: Story = { data: { ...data, agentsPath: null, - evaluationsPath: null, + settingsPath: null, soloNotice: null, localLearningSetupCommand: "node /packages/learning/bin/replica-learning.mjs setup", diff --git a/hub/client/pages/learnings-page/styles.css b/hub/client/pages/learnings-page/styles.css index 8db36df1a..29cb1e1a7 100644 --- a/hub/client/pages/learnings-page/styles.css +++ b/hub/client/pages/learnings-page/styles.css @@ -41,3 +41,9 @@ color: var(--hub-fg-link); font-weight: 600; } + +.learnings-page__header-actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} diff --git a/hub/client/pages/learnings-page/types.ts b/hub/client/pages/learnings-page/types.ts index 2121a56af..1a91dd7dc 100644 --- a/hub/client/pages/learnings-page/types.ts +++ b/hub/client/pages/learnings-page/types.ts @@ -25,7 +25,7 @@ export type LearningsPageData = run: { path: string } | null agentsPath: string | null /** Null for people who can change neither the budget nor this repository. */ - evaluationsPath: string | null + settingsPath: string | null loadError: string | null identityNotice: string | null library: LearningsLibraryData diff --git a/hub/client/storybook/fixtures/learnings.ts b/hub/client/storybook/fixtures/learnings.ts index 90f7a6b77..37889a968 100644 --- a/hub/client/storybook/fixtures/learnings.ts +++ b/hub/client/storybook/fixtures/learnings.ts @@ -187,7 +187,7 @@ export const learningsPageData: Extract&commit=` -- `GET /api/repositories/:repositoryId/learnings/screenshots/:sha256`, which returns the PNG - -## Automated evaluations - -The evaluation backend can score reported usage and draft update suggestions, but the current v2 Learnings page does not display observed outcomes or offer suggested-update review. - -Hub can check whether a repository's learnings help and suggest updates. Someone who administers Hub or the repository opens it from **Evaluation settings** on the Learnings page. For example, a Hub administrator sets a shared budget of 100 credits per month, and an administrator of `github/checkout` turns on **Evaluate github/checkout**. - -- The budget is one monthly credit limit shared by every repository. Only Hub administrators change it, from 0 to 1,000,000 credits. Usage counts every score attempt and every update check that finished since the start of the month in UTC, including attempts that fail. A budget of 0 means nothing is scored or checked. The limit is checked before each attempt, and an attempt's cost is only known once it finishes, so the last attempt in a month can go over the limit by up to one attempt's cost. -- Each repository is off until one of its administrators turns it on. Hub and repository administration stay separate, so a Hub administrator alone cannot turn on a repository. -- **Allow screenshots** lets agents send screenshots with `report_usage` and lets Hub analyze them. It needs evaluations on, and turning evaluations off turns it off too. The page shows who changed it last. - -Allowing screenshots adds a consent grant in the repository's learning store with who allowed it. Hub records the grant and passes it to every `report_usage` call, and the store refuses screenshots once the grant is withdrawn. Hub keeps a copy of each accepted image in artifact storage only while the grant is still the active one. Turning screenshots off withdraws the grant and queues a job that deletes the copies taken under it. The worker's recovery pass finds every withdrawn grant again, so a failed enqueue or a copy saved during the change is still deleted. Allowing screenshots again makes a new grant. - -Turning evaluations on also adds a consent grant that lets the store use the repository's review comments as evaluation evidence. Turning them off stops scoring, turns screenshots off, and withdraws it. Hub keeps the grant's ID until the withdrawal succeeds, so saving again retries a failed one. A repository without this grant isn't scored until an administrator saves its settings again. - -### Scoring applied learnings - -When an agent's `report_usage` call names a commit, Hub remembers it. A later report for the same commit is kept for another pass, even if scoring is already running. Once a successful Build exists for that commit, the worker's recovery pass queues a scoring job. For example, an agent applies the learning "Use the shared empty state" in commit `abc123`, a Build for `abc123` succeeds, and Hub asks the store to score that learning against the commit's diff and any screenshots the agent sent. - -- Each reported use of a learning gets one automated score, plus at most one reviewer-confirmed score (see below). Hub records the attempt and its cost before asking for the next one, so a crash retries the same operation instead of paying twice. -- A failed score is recorded with what it spent and is not retried. A score interrupted by a worker stopping stays running and is retried with the same operation. -- Before each score, Hub checks again that evaluations are still on, the repository is still connected, and budget remains, and it asks for a fresh Copilot credential. -- When the budget runs out or Copilot is unavailable, the request waits. If Copilot refuses the credential, Hub marks the connection refused, as a learning run does. The recovery pass tries it again each minute and starts scoring once the budget is raised or the next month begins. Requests that never find a successful Build are dropped after 30 days. A storage outage while reading a screenshot also leaves the score to be retried, so it is never scored without that evidence. -- Scoring holds the learning execution lock for each command, so agent calls may briefly get a busy reply while a score runs. Scoring is automatic work, so it waits behind learning runs a person asked for. - -When the person who left review feedback resolves their own thread, Hub treats that as verification. It finds the prototype's newest successful Build after the one they commented on, judged by when each Build's workflow started, and asks for that commit to be scored again. Each learning an agent applied in that commit gets one more score that tells the scorer a reviewer confirmed the work. The first score is kept. For example, a reviewer comments on Checkout Build 3, an agent's fix lands in Build 5, and the reviewer resolves the thread. Hub scores Build 5's applied learnings again with that confirmation. - -- Hub keeps the verification for that prototype and commit, so usage reported after the thread is resolved still gets the extra score. A report that names a different prototype doesn't. -- Someone else resolving the thread doesn't count. A thread on the newest Build has no later change to verify, so nothing is scored. -- The scorer gets only the time of the verification, never the thread's text. -- The re-score follows the same budget, retry, and lock rules as the first score. - -### Suggesting learning updates - -Each new score flags its learning for a check. Once a day at 03:00 UTC, a job queues one check per flagged learning, oldest first, at the same low priority as automatic learning runs. Each check runs on its own, so other scheduled work runs in between and one repository's failure doesn't hold up the rest. The learning package decides whether the same issue keeps coming up in enough Builds and, only then, asks Copilot to draft new wording. Hub records each check's result and cost. For example, two Builds score "Use the shared empty state" low because it never says where the empty state goes, so the check keeps a suggestion that names the position. - -- A suggestion only waits for review. Agents keep getting the current wording until someone applies a change. -- Each check runs under the learning execution lock. It confirms evaluations are still on, the repository is still connected, and the budget remains before it starts. -- When the budget runs out or Copilot is unavailable, the check keeps its flag for the next day. A learning scored again during its check stays flagged too. -- Flags for repositories with evaluations off or no longer connected are dropped. -- A check can't be resumed. One interrupted by a worker stopping is recorded as interrupted by the next check, and it may have spent credits Hub didn't see. - -### Reviewing suggested updates - -An open suggestion appears on the active learning's detail view under **Suggested update**. It shows the issue, the new wording, Copilot's reasoning, and links to the scored Builds that showed the issue. For example, "Use one primary button per form" gets a suggestion that says which button wins when two actions are equal, with links to Signup Builds 4 and 6. - -- People who can decide on learnings can apply or dismiss it, and both need a reason. **Apply update** opens the suggested title and wording in a form, so the person can change them first. The wording can be up to 2,000 characters, and a suggested title can't be left empty. Agents get the applied wording as the learning's next version. -- **Dismiss** closes the suggestion. Copilot suggests the same issue again only after new Builds show it. -- Hub sends the suggestion's ID and checks that it belongs to the learning. Both decisions pass the decision's operation ID, so recovery after a crash finds whether it landed. A dismissal counts as Hub's own only when it carries that ID, so another administrator's dismissal fails the retry instead. -- When the last check found too few Builds with the same issue, **Observed outcomes** says so. -- Hub hides a suggestion when any score behind it no longer has a Build or its screenshot was withheld, and checks again before applying it. A suggestion goes away when the learning's wording changes. - -### Observed outcomes - -An active learning's detail view lists how later Builds did with its current wording, newest first. Each entry reads a score as one result. A score where the agent didn't clearly follow the guidance is "Inconclusive". Otherwise a score of 3 or 4 "Supports the guidance" and 1 or 2 is a "Possible concern". The entry shows the scorer's issue, or its reasoning when there is no issue, and links to the Build it judged. For example, "Possible concern · Automated assessment · Checkout, Build 12" with "The rule did not say where the label goes." A score made after a reviewer verified the work reads "Reviewer-confirmed" instead, and replaces the earlier score for the same use. - -- Scores of earlier wording are left out, since they say nothing about the guidance agents get now. Retiring and reinstating a learning keeps its wording, so its scores stay. -- **Earlier guidance** lists each wording agents had before, newest first, with its own scores. This lets people compare an applied update with what came before it. -- A score with no successful Build people can open is left out. -- Before and after screenshot links appear only under the screenshot consent that is on now, the same rule as applied learnings. -- When a screenshot the scorer saw is no longer shown, its written summary is hidden too, because the words may describe that screenshot. -- An active learning with no scores reads "Not evaluated yet." - -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 | @@ -234,9 +159,10 @@ Agent requests that carry screenshots may be up to 32 MB. | `REPLICA_LEARNING_CLI` | Optional package CLI path. Source development defaults to `../packages/learning/bin/replica-learning.mjs` from `hub/`; the image sets `/opt/replica/learning/bin/replica-learning.mjs`. | | `REPLICA_LEARNING_NODE` | Optional Node.js executable. Defaults to the running Node.js executable. | | `REPLICA_LEARNING_AUTOMATIC_RUNS` | Optional `true` / `false` switch. Defaults to `false`. When enabled, due repositories are discovered daily at 02:00 UTC, but no runs are created unless the saved Copilot connection is usable. | +| `REPLICA_LEARNING_REVIEW_COMMENT_CONSENT` | Optional `true` / `false` switch. Defaults to `false`. When `true`, a Hub administrator's next Copilot connection records deployment-wide consent for review-comment learning. Otherwise, each repository without an active repository-specific grant needs a repository administrator's first run request. | The environment-token mode may obtain its secret through a platform secret reference, but the learning child receives only the allowlisted values above. The GitHub App provider supplies a fresh credential for each command without changing that process boundary, so short-lived credentials are never durable connection identity. Organization Copilot model policy, budget controls, and installation revocation continue to apply to every request. ## Current limits -GitHub is the only repository-authority provider in this version; Entra, local sessions, and Hub administrator assignments do not synthesize repository administration. Automatic discovery is deployment-wide rather than configurable per repository and runs only after a repository administrator has established consent through an explicit run. The package remains authoritative for consent, evidence eligibility, lifecycle, recall, and redaction. +GitHub is the only repository-authority provider in this version; Entra, local sessions, and Hub administrator assignments do not synthesize repository administration. Automatic discovery is deployment-wide rather than configurable per repository. Scheduled runs need an active repository-specific grant or a Hub administrator's active deployment-wide consent; otherwise a repository administrator must request the first run for that repository. The package remains authoritative for consent, evidence eligibility, lifecycle, recall, and redaction. diff --git a/hub/docs/storybook.md b/hub/docs/storybook.md index ab4f6cb50..1d6d617c1 100644 --- a/hub/docs/storybook.md +++ b/hub/docs/storybook.md @@ -38,6 +38,7 @@ Start Storybook before opening these links. Each row points to an example of a d | `/repositories/:repositoryId/analytics` | [Analytics](http://localhost:6006/?path=/story/hub-pages-repositories-analytics--configured) | | `/repositories/:repositoryId/learnings` | [Learnings](http://localhost:6006/?path=/story/hub-pages-learnings-index--default) | | `/repositories/:repositoryId/learnings?learning=:learningId` | [Learning detail](http://localhost:6006/?path=/story/hub-pages-learnings-detail--suggestion) | +| `/repositories/:repositoryId/learnings/settings` | [Learning settings](http://localhost:6006/?path=/story/hub-pages-learnings-settings--defaults) | | `/notifications` | [Inbox](http://localhost:6006/?path=/story/hub-pages-inbox--cached-refresh) | | `/canvas/connections` | [Canvas connections](http://localhost:6006/?path=/story/hub-pages-canvas-connection--connected) | | `/canvas/pair/:userCode` | [Approve a connection](http://localhost:6006/?path=/story/hub-pages-canvas-connection--approval) | diff --git a/hub/schema/copilot-connection.prisma b/hub/schema/copilot-connection.prisma index 1dd395c7b..8b76b8abd 100644 --- a/hub/schema/copilot-connection.prisma +++ b/hub/schema/copilot-connection.prisma @@ -11,6 +11,7 @@ model CopilotConnection { credentialProvider String @map("credential_provider") @db.VarChar(100) credentialDigest String @map("credential_digest") @db.VarChar(64) verifiedAt DateTime @map("verified_at") @db.Timestamptz(3) + reviewCommentConsentAt DateTime? @map("review_comment_consent_at") @db.Timestamptz(3) // Timestamp columns createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) diff --git a/hub/schema/membership.prisma b/hub/schema/membership.prisma index fe80d947f..1369074fb 100644 --- a/hub/schema/membership.prisma +++ b/hub/schema/membership.prisma @@ -16,8 +16,10 @@ model Membership { rejectedDecisionCandidates DecisionCandidate[] decisionRuntimeDeletions DecisionRuntimeDeletion[] learningDecisionOperations LearningDecisionOperation[] - canvasGrants CanvasGrant[] - agentConnections AgentConnection[] + canvasGrants CanvasGrant[] + agentConnections AgentConnection[] + noteConsentChanges RepositoryLearningSetting[] @relation("NoteConsentChangedBy") + reviewCommentSettingChanges RepositoryLearningSetting[] @relation("ReviewCommentConsentChangedBy") // Attribute columns lifecycle MembershipLifecycle @default(ACTIVE) diff --git a/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql b/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql new file mode 100644 index 000000000..23abce38b --- /dev/null +++ b/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql @@ -0,0 +1,51 @@ +-- AlterTable +ALTER TABLE "copilot_connections" +ADD COLUMN "review_comment_consent_at" TIMESTAMPTZ(3); + +-- CreateTable +CREATE TABLE "repository_learning_settings" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "notes_changed_by_membership_id" UUID, + "review_comments_changed_by_membership_id" UUID, + "note_grant_id" VARCHAR(255), + "review_comment_grant_id" VARCHAR(255), + "notes_changed_at" TIMESTAMPTZ(3), + "notes_received_at" TIMESTAMPTZ(3), + "review_comments_turned_off" BOOLEAN NOT NULL DEFAULT false, + "review_comments_changed_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "repository_learning_settings_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "repository_learning_settings_repository_id_key" +ON "repository_learning_settings"("repository_id"); + +-- CreateIndex +CREATE INDEX "repository_learning_settings_notes_changed_by_membership_id_idx" +ON "repository_learning_settings"("notes_changed_by_membership_id"); + +-- CreateIndex +CREATE INDEX "repository_learning_settings_review_comments_changed_by_membership_id_idx" +ON "repository_learning_settings"("review_comments_changed_by_membership_id"); + +-- AddForeignKey +ALTER TABLE "repository_learning_settings" +ADD CONSTRAINT "repository_learning_settings_repository_id_fkey" +FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") +ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "repository_learning_settings" +ADD CONSTRAINT "repository_learning_settings_notes_changed_by_membership_id_fkey" +FOREIGN KEY ("notes_changed_by_membership_id") REFERENCES "memberships"("id") +ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "repository_learning_settings" +ADD CONSTRAINT "repository_learning_settings_review_comments_changed_by_membership_id_fkey" +FOREIGN KEY ("review_comments_changed_by_membership_id") REFERENCES "memberships"("id") +ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/hub/schema/repository-learning-setting.prisma b/hub/schema/repository-learning-setting.prisma new file mode 100644 index 000000000..a82886a4e --- /dev/null +++ b/hub/schema/repository-learning-setting.prisma @@ -0,0 +1,28 @@ +model RepositoryLearningSetting { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @unique @map("repository_id") @db.Uuid + notesChangedByMembershipId String? @map("notes_changed_by_membership_id") @db.Uuid + reviewCommentsChangedByMembershipId String? @map("review_comments_changed_by_membership_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + notesChangedByMembership Membership? @relation("NoteConsentChangedBy", fields: [notesChangedByMembershipId], references: [id], onDelete: SetNull) + reviewCommentsChangedByMembership Membership? @relation("ReviewCommentConsentChangedBy", fields: [reviewCommentsChangedByMembershipId], references: [id], onDelete: SetNull) + + // Attribute columns + noteGrantId String? @map("note_grant_id") @db.VarChar(255) + reviewCommentGrantId String? @map("review_comment_grant_id") @db.VarChar(255) + notesChangedAt DateTime? @map("notes_changed_at") @db.Timestamptz(3) + notesReceivedAt DateTime? @map("notes_received_at") @db.Timestamptz(3) + reviewCommentsTurnedOff Boolean @default(false) @map("review_comments_turned_off") + reviewCommentsChangedAt DateTime? @map("review_comments_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([notesChangedByMembershipId]) + @@index([reviewCommentsChangedByMembershipId]) + @@map("repository_learning_settings") +} diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index 0fdb4796e..007640cad 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -26,6 +26,7 @@ model Repository { analyticsDestinations AnalyticsDestination[] analyticsState AnalyticsRepositoryState? analyticsDestinationAuthorizations AnalyticsDestinationAuthorization[] + learningSetting RepositoryLearningSetting? // Attribute columns githubRepositoryId BigInt? @unique @map("github_repository_id") diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 56914eb24..71a4189e2 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -16,6 +16,7 @@ import type { CreateAppOptions } from "./types.ts" /** Give every endpoint the same request logging and safe error responses. */ export function createApp({ + agentConnections, agentVisualCritic, authentication, broadcast, @@ -51,8 +52,10 @@ export function createApp({ app.use( [ "/api/canvas", + "/api/agent-connections", "/api/auth", "/canvas/pair", + "/agents/approve", "/api/administrators", "/api/copilot-connection", "/api/session-revocation", @@ -73,6 +76,7 @@ export function createApp({ ) routes(app, { + agentConnections, agentVisualCritic, authentication, broadcast, diff --git a/hub/server/domains/agent-connections/create-agent-connections/index.ts b/hub/server/domains/agent-connections/create-agent-connections/index.ts new file mode 100644 index 000000000..458255bb2 --- /dev/null +++ b/hub/server/domains/agent-connections/create-agent-connections/index.ts @@ -0,0 +1,233 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" +import { claimAgentAuthorization } from "../../../repositories/agent-authorizations/claim-agent-authorization/index.ts" +import { createAgentAuthorization } from "../../../repositories/agent-authorizations/create-agent-authorization/index.ts" +import { decideAgentAuthorization } from "../../../repositories/agent-authorizations/decide-agent-authorization/index.ts" +import { findAgentAuthorizationChallenge } from "../../../repositories/agent-authorizations/find-agent-authorization-challenge/index.ts" +import { findPendingAgentAuthorization } from "../../../repositories/agent-authorizations/find-pending-agent-authorization/index.ts" +import { createAgentClient } from "../../../repositories/agent-clients/create-agent-client/index.ts" +import { findAgentClient } from "../../../repositories/agent-clients/find-agent-client/index.ts" +import { createAgentConnection } from "../../../repositories/agent-connections/create-agent-connection/index.ts" +import { listAgentConnections } from "../../../repositories/agent-connections/list-agent-connections/index.ts" +import { recordAgentConnectionAudit } from "../../../repositories/agent-connections/record-agent-connection-audit/index.ts" +import { revokeAgentConnection } from "../../../repositories/agent-connections/revoke-agent-connection/index.ts" +import { rotateAgentConnection } from "../../../repositories/agent-connections/rotate-agent-connection/index.ts" +import { touchAgentConnection } from "../../../repositories/agent-connections/touch-agent-connection/index.ts" +import { + canvasAuthorityReference, + readCanvasAuthority, +} from "../../../repositories/canvas/authority/index.ts" +import type { CanvasBrowser } from "../../canvas/authorization/index.ts" +import { + accessLifetime, + canvasDigest, + canvasSecret, + inactiveLifetime, + pairingLifetime, +} from "../../canvas/credentials/index.ts" + +const accessPattern = /^ra_[A-Za-z0-9_-]{43}$/ +const refreshPattern = /^rar_[A-Za-z0-9_-]{43}$/ +const codePattern = /^rac_[A-Za-z0-9_-]{43}$/ + +function issueTokens() { + const accessToken = canvasSecret("ra_") + const refreshToken = canvasSecret("rar_") + const now = Date.now() + return { + accessToken, + refreshToken, + tokenDigest: canvasDigest(accessToken), + refreshDigest: canvasDigest(refreshToken), + expiresAt: new Date(now + accessLifetime), + inactiveAt: new Date(now + inactiveLifetime), + } +} + +function tokenResponse(tokens: ReturnType) { + return { + access_token: tokens.accessToken, + token_type: "Bearer", + expires_in: Math.floor(accessLifetime / 1000), + refresh_token: tokens.refreshToken, + } +} + +/** + * Lets a person connect a coding agent to Hub with OAuth. A connection acts for the person + * who approved it, so every use rechecks that their Hub sign-in still holds. Only digests + * of codes and tokens are stored. + */ +export function createAgentConnections(database: PrismaClient) { + return { + async registerClient(client: { id: string; name: string; redirectUris: string[] }) { + return createAgentClient(database, client) + }, + + getClient(id: string) { + return findAgentClient(database, id) + }, + + async startAuthorization(input: { + clientId: string + redirectUri: string + codeChallenge: string + state?: string + }) { + const { id } = await createAgentAuthorization(database, { + ...input, + expiresAt: new Date(Date.now() + pairingLifetime), + }) + return id + }, + + async readAuthorization(id: string) { + const pending = await findPendingAgentAuthorization(database, id) + return ( + pending && { + clientName: pending.client.name, + expiresAt: pending.expiresAt, + redirectUri: pending.redirectUri, + } + ) + }, + + async decideAuthorization(id: string, browser: CanvasBrowser, approve: boolean) { + const pending = await findPendingAgentAuthorization(database, id) + if (!pending) return null + const redirect = new URL(pending.redirectUri) + const code = canvasSecret("rac_") + const decided = await database.$transaction(async (transaction) => { + const settled = await decideAgentAuthorization( + transaction, + id, + approve ? { sessionId: browser.sessionId, codeDigest: canvasDigest(code) } : null, + ) + if (settled && approve) { + await recordAgentConnectionAudit(transaction, { + action: "agent_connection.approve", + actorMembershipId: browser.viewer.membershipId, + clientId: pending.clientId, + }) + } + return settled + }) + if (!decided) return null + if (approve) redirect.searchParams.set("code", code) + else redirect.searchParams.set("error", "access_denied") + if (pending.state !== null) redirect.searchParams.set("state", pending.state) + return redirect.toString() + }, + + async challenge(clientId: string, code: string) { + if (!codePattern.test(code)) return null + const found = await findAgentAuthorizationChallenge(database, clientId, canvasDigest(code)) + return found?.codeChallenge ?? null + }, + + async exchangeCode(clientId: string, code: string, redirectUri?: string) { + if (!codePattern.test(code)) return null + return database.$transaction(async (transaction) => { + const claimed = await claimAgentAuthorization(transaction, clientId, canvasDigest(code)) + const session = claimed?.session + if (!claimed || !session || (redirectUri && redirectUri !== claimed.redirectUri)) + return null + if (session.endedAt || session.expiresAt <= new Date()) return null + const reference = canvasAuthorityReference(session) + const viewer = reference && (await readCanvasAuthority(transaction, reference)) + if (!viewer) return null + const tokens = issueTokens() + await createAgentConnection(transaction, { + clientId, + membershipId: viewer.membershipId, + externalIdentityId: viewer.externalIdentityId, + providerRevisionId: viewer.providerRevisionId, + revocationRevision: viewer.revocationRevision, + tokenDigest: tokens.tokenDigest, + refreshDigest: tokens.refreshDigest, + expiresAt: tokens.expiresAt, + inactiveAt: tokens.inactiveAt, + }) + return tokenResponse(tokens) + }) + }, + + async refresh(clientId: string, refreshToken: string) { + if (!refreshPattern.test(refreshToken)) return null + const tokens = issueTokens() + return database.$transaction(async (transaction) => { + const connection = await rotateAgentConnection(transaction, { + clientId, + refreshDigest: canvasDigest(refreshToken), + tokenDigest: tokens.tokenDigest, + nextRefreshDigest: tokens.refreshDigest, + expiresAt: tokens.expiresAt, + inactiveAt: tokens.inactiveAt, + }) + const reference = connection && canvasAuthorityReference(connection) + const viewer = reference && (await readCanvasAuthority(transaction, reference)) + if (!viewer) return null + return tokenResponse(tokens) + }) + }, + + /** Returns who the token acts for, or null when it or their Hub access has ended. */ + async verify(accessToken: string) { + if (!accessPattern.test(accessToken)) return null + const connection = await touchAgentConnection( + database, + canvasDigest(accessToken), + new Date(Date.now() + inactiveLifetime), + ) + const reference = connection && canvasAuthorityReference(connection) + const viewer = reference && (await readCanvasAuthority(database, reference)) + return connection && viewer ? { connection, viewer } : null + }, + + async revokeToken(clientId: string, token: string) { + const digest = canvasDigest(token) + const where = accessPattern.test(token) + ? { clientId, tokenDigest: digest } + : refreshPattern.test(token) + ? { clientId, refreshDigest: digest } + : null + if (!where) return + await database.$transaction(async (transaction) => { + const revoked = await revokeAgentConnection(transaction, where) + if (!revoked) return + await recordAgentConnectionAudit(transaction, { + action: "agent_connection.revoke", + actorMembershipId: revoked.membershipId, + connectionId: revoked.id, + }) + }) + }, + + // Only connections that would still pass verify() are listed, so ones ended by a + // sign-out everywhere or a provider change do not look connected. + list(browser: CanvasBrowser) { + const reference = canvasAuthorityReference(browser.viewer) + return reference ? listAgentConnections(database, reference) : Promise.resolve([]) + }, + + revokeBrowser(id: string, browser: CanvasBrowser) { + const { membershipId, externalIdentityId } = browser.viewer + return database.$transaction(async (transaction) => { + const revoked = await revokeAgentConnection(transaction, { + id, + membershipId, + externalIdentityId, + }) + if (!revoked) return false + await recordAgentConnectionAudit(transaction, { + action: "agent_connection.revoke", + actorMembershipId: membershipId, + connectionId: revoked.id, + }) + return true + }) + }, + } +} + +export type AgentConnections = ReturnType +export type AgentViewer = NonNullable>>["viewer"] 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 new file mode 100644 index 000000000..f8e511c6f --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts @@ -0,0 +1,350 @@ +import { mkdtemp, readFile, realpath, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { expect, it, onTestFinished, vi } from "vitest" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { createLearningMcpBackend } from "." + +const runLearningCommand = vi.hoisted(() => vi.fn()) +vi.mock("../../../integrations/learning/run-learning-command/index.ts", () => ({ + runLearningCommand, +})) + +it("keeps server details out of what agents see when the store fails", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockRejectedValueOnce( + new LearningCommandError("storage_corrupt", `The store at ${root} is damaged.`), + ) + 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 }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const failure = backend.listLearnings({}) + + await expect(failure).rejects.toBeInstanceOf(LearningCommandError) +}) + +it("passes the task through a private file and session values as data", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + let task = "" + runLearningCommand.mockImplementationOnce(async (arguments_: string[]) => { + task = await readFile(arguments_[arguments_.indexOf("--task-file") + 1]!, "utf8") + return { guidanceId: "guidance", text: "Use tokens.", memories: [] } + }) + 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 }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + await backend.getGuidance({ task: "-private task", session: { id: "-s", label: "-l" } }) + + const arguments_ = runLearningCommand.mock.calls.at(-1)![0] as string[] + expect(task).toBe("-private task") + expect(arguments_).not.toContain("-private task") + expect(arguments_).toEqual(expect.arrayContaining(["--session-id=-s", "--session-label=-l"])) +}) + +it("withholds guidance when the connection loses access while the command runs", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockResolvedValueOnce({ guidanceId: "g", text: "Secret.", memories: [] }) + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(false), + 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 }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const guidance = backend.getGuidance({}) + + await expect(guidance).rejects.toThrow("access_denied") +}) + +it("withholds the text of a learning no one has accepted", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockResolvedValueOnce({ + record: { id: "memory-1", state: "proposed", text: "Unreviewed idea." }, + status: { recallEligible: false }, + withheld: false, + }) + 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 }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const learning = await backend.getLearning({ id: "memory-1" }) + + expect(JSON.stringify(learning)).not.toContain("Unreviewed idea.") + expect(learning).toMatchObject({ id: "memory-1", state: "proposed", withheld: true }) +}) + +it("gives no guidance for a repository without a learning store", 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", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const guidance = await backend.getGuidance({ task: "Build a form" }) + + expect(guidance).toEqual({ guidanceId: null, text: "", learnings: [] }) + expect(runLearningCommand).not.toHaveBeenCalled() +}) + +type SessionSubmission = Parameters["submitSession"]>[0] + +function submitSession(backend: ReturnType, submission: object) { + return backend.submitSession(submission as SessionSubmission) +} + +function createSessionBackend( + root: string, + notes: { grantId(): Promise; received(): Promise }, + events: string[] = [], +) { + const input = { + confirmAccess: () => { + events.push("access") + return Promise.resolve(true) + }, + connectionId: "connection", + notes, + 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 }, + serialize: async (operation: (signal: AbortSignal) => Promise) => { + events.push("serialize:start") + try { + return await operation(new AbortController().signal) + } finally { + events.push("serialize:end") + } + }, + toAgentError: (code: string, message: string) => new Error(`${code}: ${message}`), + user: "ana-designer", + } + input.notes = { + grantId: async () => { + events.push("grant") + return notes.grantId() + }, + received: async () => { + events.push("received") + await notes.received() + }, + } + return createLearningMcpBackend(input) +} + +async function createSessionTestRoot() { + const root = await realpath(await mkdtemp(join(process.cwd(), ".agent-session-test-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + return root +} + +it("imports only supplied Pick & Polish notes as the connected GitHub user", async () => { + const root = await createSessionTestRoot() + let imported: Record | undefined + let importArguments: string[] | undefined + const events: string[] = [] + const received = vi.fn(async () => {}) + runLearningCommand.mockImplementationOnce(async (arguments_: string[]) => { + events.push("import") + importArguments = arguments_ + const file = arguments_[arguments_.indexOf("agent-session") + 1]! + const parsed: unknown = JSON.parse(await readFile(file, "utf8")) + imported = parsed as Record + return { addedEpisodes: 1, addedEvents: 0 } + }) + runLearningCommand.mockImplementationOnce(() => { + events.push("import") + return Promise.resolve({ addedEpisodes: 0, addedEvents: 1 }) + }) + const backend = createSessionBackend( + root, + { + grantId: () => Promise.resolve("pick-polish-grant"), + received, + }, + events, + ) + const note = { + localId: "note-1", + body: "Make the button easier to tap.", + thread: { messages: [{ id: "reply-1", role: "copilot" as const, body: "I enlarged it." }] }, + } + + await submitSession(backend, { + sessionId: "session-1", + task: "Do not store this private task.", + user: "github:untrusted-agent-input", + messages: [{ role: "user", text: "Do not store this private chat." }], + pickAndPolishNotes: [note], + }) + await submitSession(backend, { + sessionId: "session-2", + pickAndPolishNotes: [note], + }) + + expect(imported).toMatchObject({ + sessionId: "session-1", + user: "github:ana-designer", + messages: [], + pickAndPolishNotes: [note], + }) + expect(imported).not.toHaveProperty("task") + expect(JSON.stringify(imported)).not.toContain("private") + expect(importArguments).toEqual( + expect.arrayContaining([ + "--grant", + "pick-polish-grant", + "--repository", + "github.com/repositories/1", + ]), + ) + expect(received).toHaveBeenCalledTimes(2) + expect(events).toEqual([ + "serialize:start", + "grant", + "access", + "import", + "access", + "received", + "serialize:end", + "serialize:start", + "grant", + "access", + "import", + "access", + "received", + "serialize:end", + ]) +}) + +it("does not mark notes received when the import adds no episodes or events", async () => { + const root = await createSessionTestRoot() + const received = vi.fn(async () => {}) + runLearningCommand.mockImplementationOnce(() => + Promise.resolve({ addedEpisodes: 0, addedEvents: 0 }), + ) + const backend = createSessionBackend(root, { + grantId: () => Promise.resolve("pick-polish-grant"), + received, + }) + const note = { + localId: "note-1", + body: "Make the button easier to tap.", + thread: { messages: [] }, + } + + await submitSession(backend, { + sessionId: "session-1", + task: "Build a checkout form.", + user: "github:untrusted-agent-input", + messages: [], + pickAndPolishNotes: [note], + }) + + expect(received).not.toHaveBeenCalled() +}) + +it("stores no notes and reports an inactive grant without note consent", async () => { + const root = await createSessionTestRoot() + const backend = createSessionBackend(root, { + grantId: () => Promise.resolve(null), + received: vi.fn(async () => {}), + }) + const submission = { + sessionId: "session-1", + task: "Build a checkout form.", + user: "github:untrusted-agent-input", + messages: [], + pickAndPolishNotes: [ + { + localId: "note-1", + body: "Make the button easier to tap.", + thread: { messages: [] }, + }, + ], + } + + await expect(submitSession(backend, submission)).rejects.toThrow( + /grant_inactive.*repository.*Pick & Polish notes/i, + ) + expect( + runLearningCommand.mock.calls.some(([arguments_]) => + (arguments_ as string[]).includes("agent-session"), + ), + ).toBe(false) +}) 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 new file mode 100644 index 000000000..3292b0183 --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts @@ -0,0 +1,272 @@ +import { access, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join, resolve } from "node:path" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" +import { learningStoreArguments } from "../../learning/learning-store-arguments/index.ts" + +const agentErrorCodes = new Set([ + "conflict", + "invalid_input", + "invalid_transition", + "grant_inactive", + "not_found", + "unsupported", +]) + +interface LearningSettings { + applicationRoot?: string + cliPath: string + learningDatabaseUrl?: string + nodePath: string + root: string + staticDirectories: string[] +} + +interface StoredLearning { + record: { id: string; state: string } + status: { recallEligible: boolean } + withheld: boolean +} + +/** Writes private text to a file only this process can read, and removes it afterwards. */ +async function withPrivateFile(content: string, operation: (file: string) => Promise) { + const folder = await mkdtemp(join(tmpdir(), "replica-agent-")) + try { + const file = join(folder, "input") + await writeFile(file, content, { mode: 0o600 }) + return await operation(file) + } finally { + await rm(folder, { recursive: true, force: true }) + } +} + +/** + * Answers one agent's learning tools for one repository by running the replica-learning + * command, the same way the Learnings page does. Each call names the connection as the + * agent, so records show which connection received or used guidance. + */ +export function createLearningMcpBackend(input: { + confirmAccess(): Promise + connectionId: string + learning: LearningSettings + learningsUrl: string + notes?: { + grantId(): Promise + received(): Promise + } + repository: { id: string; githubRepositoryId: bigint } + serialize(operation: (signal: AbortSignal) => Promise): Promise + toAgentError: (code: string, message: string) => Error + user?: string +}) { + const { learning, repository, toAgentError } = input + const actor = `agent:hub-connection-${input.connectionId}` + + async function storeDirectory() { + const applicationRoot = learning.applicationRoot ?? process.cwd() + const directory = await validatePrivateStorageRoot( + resolve(learning.root, "repositories", repository.id), + { + applicationRoot, + excludedDirectories: learning.staticDirectories, + name: "REPLICA_LEARNING_ROOT", + publicRoot: resolve(applicationRoot, "public"), + }, + ) + if (learning.learningDatabaseUrl) return directory + try { + await access(resolve(directory, "config.json")) + return directory + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return null + } + } + + /** + * Runs one command while no other learning work can change the store, then checks the + * connection still has access, so a revoked agent never receives what it asked for. + */ + async function runCommand(directory: string, arguments_: string[], signal: AbortSignal) { + try { + if (!(await input.confirmAccess())) + throw toAgentError("access_denied", "This agent connection no longer has access.") + const result = await runLearningCommand( + [ + ...arguments_, + "--actor", + actor, + ...learningStoreArguments({ + directory, + repositoryId: repository.id, + repositoryScope: `github.com/repositories/${repository.githubRepositoryId}`, + }), + ], + { + cliPath: learning.cliPath, + nodePath: learning.nodePath, + signal, + ...(learning.learningDatabaseUrl + ? { learningDatabaseUrl: learning.learningDatabaseUrl } + : {}), + }, + ) + if (!(await input.confirmAccess())) + throw toAgentError("access_denied", "This agent connection no longer has access.") + return result + } catch (error) { + // These codes describe the agent's own request. Other failures can name server + // paths or storage, so they reach the agent only as a plain message. + if (error instanceof LearningCommandError && agentErrorCodes.has(error.code)) + throw toAgentError(error.code, error.message) + throw error + } + } + + async function run(directory: string, arguments_: string[]) { + try { + return await input.serialize((signal) => runCommand(directory, arguments_, signal)) + } catch (error) { + if (error instanceof LearningCommandError && agentErrorCodes.has(error.code)) + throw toAgentError(error.code, error.message) + throw error + } + } + + function sessionArguments(session?: { id: string; label?: string }) { + if (!session) return [] + // Joined to the flag so a value starting with "-" is read as data. + return [ + `--session-id=${session.id}`, + ...(session.label === undefined ? [] : [`--session-label=${session.label}`]), + ] + } + + return { + async getGuidance({ + task, + limit, + session, + }: { + task?: string + limit?: number + session?: { id: string; label?: string } + }) { + const directory = await storeDirectory() + if (!directory) return { guidanceId: null, text: "", learnings: [] } + const store = directory + function recall(taskArguments: string[]) { + return run(store, [ + "recall", + ...taskArguments, + "--limit", + String(limit ?? 20), + ...sessionArguments(session), + ]) + } + // The task goes through a private file so it never shows in the process list. + const result = (await (task === undefined + ? recall([]) + : withPrivateFile(task, (file) => recall(["--task-file", file])))) as { + guidanceId: string + text: string + memories: { id: string; deliveryId: string }[] + } + // Only the framed text was recorded as delivered, so the raw learnings stay out. + return { + guidanceId: result.guidanceId, + text: result.text, + learnings: result.memories.map(({ id, deliveryId }) => ({ id, deliveryId })), + } + }, + + async reportUsage(report: { used: { before?: unknown; after?: unknown }[] }) { + if (report.used.some((item) => item.before !== undefined || item.after !== undefined)) + throw toAgentError( + "unsupported", + "Hub does not accept screenshots yet. Report usage 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]), + ) + }, + + async submitSession(session: { sessionId: string; pickAndPolishNotes?: unknown[] }) { + const notes = session.pickAndPolishNotes ?? [] + if (notes.length === 0) + return { + sessionId: session.sessionId, + addedEpisodes: 0, + addedEvents: 0, + note: "Hub keeps only Pick & Polish notes, and this session had none.", + } + + const notesConsent = input.notes + return input.serialize(async (signal) => { + const grantId = (await notesConsent?.grantId()) ?? null + if (!grantId) + throw toAgentError( + "grant_inactive", + `This repository doesn't let Hub learn from Pick & Polish notes, so nothing was stored. A repository administrator can turn on "Learn from Pick & Polish notes" in Learnings settings at ${input.learningsUrl}.`, + ) + + const directory = await storeDirectory() + if (!directory) + throw toAgentError("not_found", "This repository has no learning store yet.") + const kept = { + sessionId: session.sessionId, + ...(input.user ? { user: `github:${input.user}` } : {}), + messages: [], + pickAndPolishNotes: notes, + } + const result = await withPrivateFile(JSON.stringify(kept), (file) => + runCommand(directory, ["import", "agent-session", file, "--grant", grantId], signal), + ) + const imported = result as { addedEpisodes?: number; addedEvents?: number } + if ((imported.addedEpisodes ?? 0) + (imported.addedEvents ?? 0) > 0) + await notesConsent?.received() + return result + }) + }, + + async listLearnings({ state }: { state?: string[] }) { + const directory = await storeDirectory() + if (!directory) return [] + return run(directory, [ + "memories", + "--purpose", + "instruction", + ...(state ?? []).flatMap((value) => ["--state", value]), + ]) + }, + + async getLearning({ id }: { id: string }) { + const directory = await storeDirectory() + if (!directory) throw toAgentError("not_found", `Learning ${id} was not found.`) + const item = (await run(directory, [ + "show", + id, + "--purpose", + "instruction", + ])) as StoredLearning + const { record } = item + if (record.state === "accepted" && !item.withheld && item.status.recallEligible) return item + // A learning no one accepted is not guidance, so its text stays with people. + const summary = { id: record.id, state: record.state, withheld: true } + if (record.state !== "proposed") return summary + return { + ...summary, + decide: { + note: "Only a person can decide. Ask a repository administrator to accept or reject it on the Hub Learnings page.", + url: input.learningsUrl, + }, + } + }, + } +} diff --git a/hub/server/domains/copilot-connection/connect-copilot/index.test.ts b/hub/server/domains/copilot-connection/connect-copilot/index.test.ts index 0cd993861..bccf73b6d 100644 --- a/hub/server/domains/copilot-connection/connect-copilot/index.test.ts +++ b/hub/server/domains/copilot-connection/connect-copilot/index.test.ts @@ -110,7 +110,7 @@ describe("connectCopilot()", () => { await expect( connectCopilot( - { credentialProvider, sessionDigest: "session-digest" }, + { credentialProvider, reviewCommentConsent: true, sessionDigest: "session-digest" }, { check: vi.fn().mockResolvedValue({ signedIn: true, login: "octocat", models: ["gpt"] }), createId, @@ -132,6 +132,7 @@ describe("connectCopilot()", () => { credentialDigest: credentialProvider.configurationDigest, credentialProvider: credentialProvider.key, id: connectionId, + reviewCommentConsentAt: verifiedAt, verifiedAt, }) const savedConnection = vi.mocked(records.replaceConnection).mock.calls[0]?.[0] diff --git a/hub/server/domains/copilot-connection/connect-copilot/index.ts b/hub/server/domains/copilot-connection/connect-copilot/index.ts index 811ba911c..3a1b47c64 100644 --- a/hub/server/domains/copilot-connection/connect-copilot/index.ts +++ b/hub/server/domains/copilot-connection/connect-copilot/index.ts @@ -25,6 +25,7 @@ export async function connectCopilot( authorizationId, credentialProvider, hubSessionId, + reviewCommentConsent = false, sessionDigest, }: { authorizationId?: string @@ -34,6 +35,7 @@ export async function connectCopilot( key: CopilotCredentialProviderKey } hubSessionId?: string + reviewCommentConsent?: boolean sessionDigest: string }, { @@ -218,12 +220,14 @@ export async function connectCopilot( }) } const connectionId = createId() + const verifiedAt = now() await repositories.replaceConnection({ connectedByMembershipId: session.membershipId, credentialDigest, credentialProvider: credentialProvider.key, id: connectionId, - verifiedAt: now(), + reviewCommentConsentAt: reviewCommentConsent ? verifiedAt : null, + verifiedAt, }) await repositories.clearRefusal() await repositories.advanceState() diff --git a/hub/server/domains/copilot-connection/types.ts b/hub/server/domains/copilot-connection/types.ts index 6f197294d..939f4fa57 100644 --- a/hub/server/domains/copilot-connection/types.ts +++ b/hub/server/domains/copilot-connection/types.ts @@ -25,6 +25,7 @@ export interface CopilotConnectionTransactionRepositories { credentialDigest: string credentialProvider: string id: string + reviewCommentConsentAt: Date | null verifiedAt: Date }) => Promise recordRefusal: (input: { diff --git a/hub/server/domains/learning/change-pick-and-polish-consent/index.ts b/hub/server/domains/learning/change-pick-and-polish-consent/index.ts new file mode 100644 index 000000000..51495fb2c --- /dev/null +++ b/hub/server/domains/learning/change-pick-and-polish-consent/index.ts @@ -0,0 +1,67 @@ +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 grantSchema = z.object({ id: z.string().min(1).max(255) }).loose() +const purposes = ["review", "instruction"] as const +const basis = + "A repository administrator allowed Hub to learn from Pick & Polish notes agents send." + +export async function changePickAndPolishConsent(input: { + actor: string + allowed: boolean + cliPath: string + grantId: string | null + learningDatabaseUrl?: string + nodePath: string + repositoryId: string + repositoryScope: string + root: string + signal?: AbortSignal + staticDirectories: string[] +}) { + 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) + const purposeArguments = purposes.flatMap((purpose) => ["--purpose", purpose]) + if (input.allowed) { + const grant = grantSchema.parse( + await runLearningCommand( + [ + "grants", + "add", + ...purposeArguments, + "--source", + "agent_session", + "--basis", + basis, + "--by", + input.actor, + ...common, + ], + options, + ), + ) + return grant.id + } + if (input.grantId) { + await runLearningCommand( + ["grants", "withdraw", input.grantId, ...purposeArguments, "--by", input.actor, ...common], + options, + ) + } + return null +} 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 656ef7c08..76f10bec0 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -35,6 +35,8 @@ import { advanceCopilotConnectionState } from "../../../repositories/copilot-con import { lockCopilotConnectionState } from "../../../repositories/copilot-connection-states/lock-copilot-connection-state/index.ts" import { recordCopilotCredentialRefusal } from "../../../repositories/copilot-connection-states/record-copilot-credential-refusal/index.ts" import { getCopilotConnection } from "../../../repositories/copilot-connections/get-copilot-connection/index.ts" +import { getReviewCommentConsent } from "../../../repositories/learning-settings/get-review-comment-consent/index.ts" +import { saveRepositoryLearningSetting } from "../../../repositories/learning-settings/save-repository-learning-setting/index.ts" import { claimLearningRun } from "../../../repositories/learning-runs/claim-learning-run/index.ts" import { createLearningRun } from "../../../repositories/learning-runs/create-learning-run/index.ts" import { deleteExpiredLearningRuns } from "../../../repositories/learning-runs/delete-expired-learning-runs/index.ts" @@ -144,6 +146,10 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg finish: (id, input) => finishLearningRun(prisma, id, input), getRun: (id) => getLearningRun(prisma, id), hasPendingUserRun: () => hasPendingUserLearningRun(prisma), + reviewCommentConsent: (repositoryId) => + getReviewCommentConsent(prisma, repositoryId, configuration.reviewCommentConsent), + recordRepositoryReviewCommentGrant: (repositoryId, grantId) => + saveRepositoryLearningSetting(prisma, repositoryId, { reviewCommentGrantId: grantId }), isRepositoryAvailable: (repositoryId) => prisma.$transaction(async (transaction) => { await lockGitHubRepositoryAccessState(transaction) @@ -376,7 +382,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg now: () => new Date(), }) } - const { databaseUrl, prisma, source } = await dependencies() + const { configuration, databaseUrl, prisma, source } = await dependencies() const queue = createJobQueue({ name: "scheduled", databaseUrl, logger }) try { return await scheduleLearningRuns({ @@ -388,6 +394,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg await lockGitHubRepositoryAccessState(transaction) return listDueLearningRepositories(transaction, { requireGitHubId: true, + hubReviewCommentConsentEnabled: configuration.reviewCommentConsent, }) }), capture: async (repositoryId) => { diff --git a/hub/server/domains/learning/process-learning-run/index.test.ts b/hub/server/domains/learning/process-learning-run/index.test.ts index 909e82caf..68b69db0a 100644 --- a/hub/server/domains/learning/process-learning-run/index.test.ts +++ b/hub/server/domains/learning/process-learning-run/index.test.ts @@ -55,6 +55,12 @@ function dependencies(overrides: Partial = {}) { getRun: vi.fn().mockImplementation(() => Promise.resolve(run)), hasPendingUserRun: vi.fn().mockResolvedValue(false), isRepositoryAvailable: vi.fn().mockResolvedValue(true), + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: null, + repositoryGrantId: null, + }), + recordRepositoryReviewCommentGrant: vi.fn().mockResolvedValue(undefined), now: vi.fn(() => new Date("2026-11-13T10:00:00Z")), authorizeRepositoryAdministration: vi.fn().mockResolvedValue(true), prepare: vi.fn().mockResolvedValue({ @@ -130,6 +136,10 @@ describe("processLearningRun()", () => { expect( deps.commands.find((arguments_) => arguments_[0] === "grants" && arguments_[1] === "add"), ).toEqual(expect.arrayContaining(["--by", "human:mona"])) + expect(deps.recordRepositoryReviewCommentGrant).toHaveBeenCalledWith( + deps.run.repositoryId, + "grant-1", + ) expect(deps.progress.at(-1)).toEqual({ id: "11111111-2222-4333-8444-555555555555", input: { @@ -316,6 +326,11 @@ describe("processLearningRun()", () => { overBudget: 1, }) }), + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: "human:mona", + repositoryGrantId: null, + }), }) deps.run.scheduled = true deps.run.requestedBy = null @@ -396,6 +411,11 @@ describe("processLearningRun()", () => { const deps = dependencies({ expectedScheduled: true, isRepositoryAvailable: vi.fn().mockResolvedValue(false), + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: "human:admin", + repositoryGrantId: null, + }), runCommand: vi.fn((arguments_: string[]) => { if (arguments_[0] === "grants" && arguments_[1] === "list") { return Promise.resolve([ @@ -607,4 +627,128 @@ describe("processLearningRun()", () => { }, }) }) + + it("uses Hub administrator consent for a scheduled run's first review-comment grant", async () => { + const deps = dependencies({ + expectedScheduled: true, + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: "human:mona", + repositoryGrantId: null, + }), + }) + deps.run.scheduled = true + deps.run.requestedBy = null + deps.run.requestedByMembershipId = null + + await processLearningRun("11111111-2222-4333-8444-555555555555", deps) + + expect( + deps.commands.find((arguments_) => arguments_[0] === "grants" && arguments_[1] === "add"), + ).toContain("human:mona") + expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) + }) + + it("does not import review comments after a repository administrator turns them off", async () => { + const deps = dependencies({ + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: true, + hubAdministrator: "human:mona", + repositoryGrantId: null, + }), + }) + + await processLearningRun("11111111-2222-4333-8444-555555555555", deps) + + expect(deps.commands.some((arguments_) => arguments_[0] === "grants")).toBe(false) + expect(deps.commands.some((arguments_) => arguments_[0] === "import")).toBe(false) + expect(deps.commands.some((arguments_) => arguments_[0] === "consolidate")).toBe(true) + expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) + }) + + it("does not reuse a deployment-wide grant after deployment consent is disabled", async () => { + const deps = dependencies({ + expectedScheduled: true, + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: null, + repositoryGrantId: null, + }), + runCommand: vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants" && arguments_[1] === "list") { + return Promise.resolve([ + { + grant: { + id: "global-grant", + sources: ["hub_review_comments"], + grantedBy: { kind: "human", id: "github:admin" }, + }, + activePurposes: ["review", "instruction"], + expired: false, + }, + ]) + } + return Promise.reject(new Error("An old deployment-wide grant must not be used.")) + }), + }) + deps.run.scheduled = true + deps.run.requestedBy = null + deps.run.requestedByMembershipId = null + + await processLearningRun("11111111-2222-4333-8444-555555555555", deps) + + expect(deps.commands.some((arguments_) => arguments_[0] === "import")).toBe(false) + expect(deps.finished[0]).toMatchObject({ + input: { state: "FAILED", failureCode: "grant_required" }, + }) + }) + + it("reuses the repository grant established by an administrator's requested run", async () => { + const deps = dependencies({ + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: null, + repositoryGrantId: "repository-grant", + }), + runCommand: vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants" && arguments_[1] === "list") { + return Promise.resolve([ + { + grant: { + id: "repository-grant", + sources: ["hub_review_comments"], + grantedBy: { kind: "human", id: "github:mona" }, + }, + activePurposes: ["review", "instruction"], + expired: false, + }, + ]) + } + if (arguments_[0] === "import") return Promise.resolve({ complete: true, problems: [] }) + if (arguments_[0] === "label") { + return Promise.resolve({ + considered: 4, + labeled: 3, + remaining: 1, + usage: { requests: 2, nanoAiu: 2_500_000 }, + }) + } + return Promise.resolve({ + status: "complete", + proposals: [{ id: "proposal-1", updatedAt: "2026-11-13T10:00:00Z" }], + overBudget: 1, + }) + }), + }) + + await processLearningRun("11111111-2222-4333-8444-555555555555", deps) + + expect( + deps.commands.find((arguments_) => arguments_[0] === "grants" && arguments_[1] === "add"), + ).toBeUndefined() + expect( + vi.mocked(deps.runCommand).mock.calls.some(([arguments_]) => arguments_[0] === "import"), + ).toBe(true) + expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) + }) }) diff --git a/hub/server/domains/learning/process-learning-run/index.ts b/hub/server/domains/learning/process-learning-run/index.ts index 79b9329b6..1636fdc97 100644 --- a/hub/server/domains/learning/process-learning-run/index.ts +++ b/hub/server/domains/learning/process-learning-run/index.ts @@ -15,6 +15,7 @@ const grantListSchema = z.array( .object({ id: z.string().min(1), sources: z.array(z.string()), + purposes: z.array(z.string()).default([]), grantedBy: z.object({ kind: z.string(), id: z.string().min(1) }).loose(), }) .loose(), @@ -98,6 +99,12 @@ export async function processLearningRun( now(): Date hasPendingUserRun(): Promise isRepositoryAvailable(repositoryId: string): Promise + reviewCommentConsent(repositoryId: string): Promise<{ + turnedOff: boolean + hubAdministrator: string | null + repositoryGrantId: string | null + }> + recordRepositoryReviewCommentGrant(repositoryId: string, grantId: string): Promise prepare(repositoryId: string): Promise<{ directory: string repositoryScope: string @@ -191,86 +198,105 @@ export async function processLearningRun( ) } const common = learningStoreArguments(store) - const grants = grantListSchema.parse( - await dependencies.runCommand(["grants", "list", ...common], { signal }), - ) - const sourceGrants = grants.filter((entry) => - entry.grant.sources.includes("hub_review_comments"), - ) - const humanSourceGrants = sourceGrants.filter( - (entry) => entry.grant.grantedBy.kind === "human", - ) - let grantIds = humanSourceGrants - .filter( - (entry) => - !entry.expired && - entry.activePurposes.includes("review") && - entry.activePurposes.includes("instruction"), + const consent = await dependencies.reviewCommentConsent(current.repositoryId) + if (!consent.turnedOff) { + const grants = grantListSchema.parse( + await dependencies.runCommand(["grants", "list", ...common], { signal }), ) - .map((entry) => entry.grant.id) - if (grantIds.length === 0) { - if (humanSourceGrants.length > 0) { - throw new LearningCommandError( - "grant_inactive", - "Consent to use this repository's review comments ended.", + const sourceGrants = grants.filter((entry) => + entry.grant.sources.includes("hub_review_comments"), + ) + const humanSourceGrants = sourceGrants.filter( + (entry) => entry.grant.grantedBy.kind === "human", + ) + const consentedGrants = consent.hubAdministrator + ? humanSourceGrants + : humanSourceGrants.filter((entry) => entry.grant.id === consent.repositoryGrantId) + let grantIds = consentedGrants + .filter( + (entry) => + !entry.expired && + entry.activePurposes.includes("review") && + entry.activePurposes.includes("instruction"), ) - } - if (current.scheduled) { - throw new LearningCommandError( - "grant_required", - "A repository administrator must request the first learning run.", + .map((entry) => entry.grant.id) + if (grantIds.length === 0) { + if ( + !consent.hubAdministrator && + consentedGrants.some((entry) => + entry.grant.purposes.some( + (purpose) => purpose === "review" || purpose === "instruction", + ), + ) + ) { + throw new LearningCommandError( + "grant_inactive", + "Consent to use this repository's review comments ended.", + ) + } + const consenter = current.scheduled ? consent.hubAdministrator : actor + if (!consenter) { + throw new LearningCommandError( + "grant_required", + "A Hub administrator must reconnect Copilot, or a repository administrator must request the first learning run.", + ) + } + const grant = addedGrantSchema.parse( + await dependencies.runCommand( + [ + "grants", + "add", + "--purpose", + "review", + "--purpose", + "instruction", + "--source", + "hub_review_comments", + "--basis", + current.scheduled + ? "A Hub administrator agreed to learn from every repository's review comments when connecting Copilot." + : "A repository administrator explicitly requested this learning run.", + "--by", + consenter, + ...common, + ], + { signal }, + ), ) + grantIds = [grant.id] + if (!current.scheduled) { + await dependencies.recordRepositoryReviewCommentGrant(current.repositoryId, grant.id) + } } - const grant = addedGrantSchema.parse( - await dependencies.runCommand( - [ - "grants", - "add", - "--purpose", - "review", - "--purpose", - "instruction", - "--source", - "hub_review_comments", - "--basis", - "A repository administrator explicitly requested this learning run.", - "--by", - actor!, - ...common, - ], - { signal }, - ), - ) - grantIds = [grant.id] - } - const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-run-")) - try { - const collectionPath = resolve(temporary, "review-collection.json") - await writeFile(collectionPath, JSON.stringify(snapshot.collection), { mode: 0o600 }) - const imported = importSchema.parse( - await dependencies.runCommand( - [ - "import", - "hub-comments", - collectionPath, - ...grantIds.flatMap((grantId) => ["--grant", grantId]), - "--actor", - "system:replica-hub", - "--redact-deleted", - ...common, - ], - { signal }, - ), - ) - if (!imported.complete) { - throw new LearningCommandError( - "incomplete_collection", - `The repository review snapshot is incomplete: ${imported.problems.join(" ")}`, + const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-run-")) + try { + const collectionPath = resolve(temporary, "review-collection.json") + await writeFile(collectionPath, JSON.stringify(snapshot.collection), { mode: 0o600 }) + const imported = importSchema.parse( + await dependencies.runCommand( + [ + "import", + "hub-comments", + collectionPath, + ...grantIds.flatMap((grantId) => ["--grant", grantId]), + "--actor", + "system:replica-hub", + "--redact-deleted", + ...common, + ], + { signal }, + ), ) + if (!imported.complete) { + throw new LearningCommandError( + "incomplete_collection", + `The repository review snapshot is incomplete: ${imported.problems.join(" ")}`, + ) + } + } finally { + await rm(temporary, { recursive: true }) } - } finally { - await rm(temporary, { recursive: true }) } const credential = await dependencies.credential() diff --git a/hub/server/domains/learning/read-learning-configuration/index.test.ts b/hub/server/domains/learning/read-learning-configuration/index.test.ts index e646e69c3..8f81c12f5 100644 --- a/hub/server/domains/learning/read-learning-configuration/index.test.ts +++ b/hub/server/domains/learning/read-learning-configuration/index.test.ts @@ -32,6 +32,27 @@ describe("readLearningConfiguration()", () => { ).rejects.toThrow("REPLICA_LEARNING_AUTOMATIC_RUNS must be true or false.") }) + it("defaults deployment-wide review-comment consent to false", async () => { + const applicationRoot = resolve(`server/domains/learning/.root-test-${randomUUID()}`) + onTestFinished(() => rm(applicationRoot, { force: true, recursive: true })) + + await expect(readLearningConfiguration({}, applicationRoot)).resolves.toMatchObject({ + reviewCommentConsent: false, + }) + }) + + it("rejects an invalid deployment-wide review-comment consent value", async () => { + const applicationRoot = resolve(`server/domains/learning/.root-test-${randomUUID()}`) + onTestFinished(() => rm(applicationRoot, { force: true, recursive: true })) + + await expect( + readLearningConfiguration( + { REPLICA_LEARNING_REVIEW_COMMENT_CONSENT: "sometimes" }, + applicationRoot, + ), + ).rejects.toThrow("REPLICA_LEARNING_REVIEW_COMMENT_CONSENT must be true or false.") + }) + it("rejects an environment token without explicit local authentication mode", async () => { const applicationRoot = resolve(`server/domains/learning/.root-test-${randomUUID()}`) onTestFinished(() => rm(applicationRoot, { force: true, recursive: true })) diff --git a/hub/server/domains/learning/read-learning-configuration/index.ts b/hub/server/domains/learning/read-learning-configuration/index.ts index 2604d670e..3305cf4dc 100644 --- a/hub/server/domains/learning/read-learning-configuration/index.ts +++ b/hub/server/domains/learning/read-learning-configuration/index.ts @@ -4,12 +4,14 @@ import { validatePrivateStorageRoot } from "../../../utils/validate-private-stor import { createCopilotCredentialProvider } from "../../copilot-credentials/create-copilot-credential-provider/index.ts" import { LearningConfigurationError } from "../errors.ts" import { readAutomaticLearningRunsEnabled } from "../read-automatic-learning-runs-enabled/index.ts" +import { readReviewCommentConsent } from "../read-review-comment-consent/index.ts" export async function readLearningConfiguration( environment: NodeJS.ProcessEnv, applicationRoot = process.cwd(), ) { const automaticRuns = readAutomaticLearningRunsEnabled(environment) + const reviewCommentConsent = readReviewCommentConsent(environment) const clientDirectory = environment.CLIENT_DIRECTORY?.trim() let root: string try { @@ -49,6 +51,7 @@ export async function readLearningConfiguration( copilotCredentialProvider, learningDatabaseUrl, nodePath, + reviewCommentConsent, root, staticDirectories: [ resolve(applicationRoot, "public"), diff --git a/hub/server/domains/learning/read-review-comment-consent/index.test.ts b/hub/server/domains/learning/read-review-comment-consent/index.test.ts new file mode 100644 index 000000000..13ba7c65f --- /dev/null +++ b/hub/server/domains/learning/read-review-comment-consent/index.test.ts @@ -0,0 +1,8 @@ +import { expect, it } from "vitest" + +import { readReviewCommentConsent } from "." + +it("keeps deployment-wide review-comment consent off until explicitly enabled", () => { + expect(readReviewCommentConsent({})).toBe(false) + expect(readReviewCommentConsent({ REPLICA_LEARNING_REVIEW_COMMENT_CONSENT: "true" })).toBe(true) +}) diff --git a/hub/server/domains/learning/read-review-comment-consent/index.ts b/hub/server/domains/learning/read-review-comment-consent/index.ts new file mode 100644 index 000000000..4671cdf2b --- /dev/null +++ b/hub/server/domains/learning/read-review-comment-consent/index.ts @@ -0,0 +1,11 @@ +import { LearningConfigurationError } from "../errors.ts" + +export function readReviewCommentConsent(environment: NodeJS.ProcessEnv) { + const value = environment.REPLICA_LEARNING_REVIEW_COMMENT_CONSENT?.trim().toLowerCase() + if (value !== undefined && value !== "true" && value !== "false") { + throw new LearningConfigurationError( + "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT must be true or false.", + ) + } + return value === "true" +} diff --git a/hub/server/index.ts b/hub/server/index.ts index ed4ac6dc5..a982d4c46 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -34,6 +34,7 @@ import { startServerProcesses } from "./start-server-processes/index.ts" import { parseRuntimeConfig } from "./utils/parse-runtime-config/index.ts" import { getJobProcessors } from "./workers/configuration.ts" import { runJobWorker } from "./workers/run-job-worker/index.ts" +import type { AgentConnectionRouteDependencies } from "./routes/agent-connections/types.ts" import type { AuthenticationRouteDependencies } from "./routes/api/auth/types.ts" import type { AgentVisualCriticRouteDependencies } from "./routes/api/canvas/decision-model/types.ts" import type { CopilotConnectionRouteDependencies } from "./routes/api/copilot-connection/types.ts" @@ -79,6 +80,7 @@ try { } const trustedProxyHops = runsApi ? configuredTrustedProxyHops : 0 let authentication: AuthenticationRouteDependencies | undefined + let agentConnections: AgentConnectionRouteDependencies | undefined let agentVisualCritic: AgentVisualCriticRouteDependencies | undefined let copilotConnection: CopilotConnectionRouteDependencies | undefined let decisionModels: DecisionModelRouteDependencies | undefined @@ -207,6 +209,14 @@ try { { scopeGitHubMembers: authenticationConfiguration.githubConfigured }, ) learnings = learningDependencies + const agentApplicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN + if (learningConfiguration && agentApplicationOrigin) { + agentConnections = { + applicationOrigin: agentApplicationOrigin, + databaseUrl, + learning: learningConfiguration, + } + } if (decisionRuntimeConfiguration) { const applicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN if (!storage || !learningConfiguration || !applicationOrigin) { @@ -397,6 +407,7 @@ try { await runApi({ ...configuration, logger, + agentConnections, agentVisualCritic, isReady: isStorageReady, authentication, @@ -419,6 +430,7 @@ try { ...configuration, databaseUrl, logger, + agentConnections, agentVisualCritic, isStorageReady, authentication, diff --git a/hub/server/integrations/express/canvas-sign-in-return/index.ts b/hub/server/integrations/express/canvas-sign-in-return/index.ts index 3f8cfe996..862f7ed8e 100644 --- a/hub/server/integrations/express/canvas-sign-in-return/index.ts +++ b/hub/server/integrations/express/canvas-sign-in-return/index.ts @@ -4,7 +4,8 @@ import type { Request } from "express" import { readCookie } from "../read-cookie/index.ts" export const canvasSignInReturnCookie = "replica_canvas_sign_in_return" -export const canvasSignInReturnPattern = /^\/canvas\/(?:pair\/[A-F0-9]{10}|connections)(?![\s\S])/ +export const canvasSignInReturnPattern = + /^\/(?:canvas\/(?:pair\/[A-F0-9]{10}|connections)|agents\/approve\/[0-9a-f-]{36})(?![\s\S])/ function bindingDigest(browserBinding: string) { return createHash("sha256").update(browserBinding).digest("hex") diff --git a/hub/server/integrations/learning/load-learning-mcp/index.test.ts b/hub/server/integrations/learning/load-learning-mcp/index.test.ts new file mode 100644 index 000000000..a137cdac3 --- /dev/null +++ b/hub/server/integrations/learning/load-learning-mcp/index.test.ts @@ -0,0 +1,16 @@ +import { fileURLToPath } from "node:url" +import { expect, it } from "vitest" + +import { loadLearningMcp } from "." + +it("loads the learning tools that sit beside the configured command", async () => { + const cliPath = fileURLToPath( + new URL("../../../../../packages/learning/bin/replica-learning.mjs", import.meta.url), + ) + + const mcp = await loadLearningMcp(cliPath) + + expect(new mcp.LearningError("not_found", "Missing.")).toMatchObject({ code: "not_found" }) + const server = mcp.createLearningMcpServer({}) + await server.close() +}) diff --git a/hub/server/integrations/learning/load-learning-mcp/index.ts b/hub/server/integrations/learning/load-learning-mcp/index.ts new file mode 100644 index 000000000..138336c15 --- /dev/null +++ b/hub/server/integrations/learning/load-learning-mcp/index.ts @@ -0,0 +1,33 @@ +import { dirname, resolve } from "node:path" +import { pathToFileURL } from "node:url" + +export interface LearningMcpServer { + connect(transport: unknown): Promise + close(): Promise +} + +export interface LearningMcp { + createLearningMcpServer( + backend: Record Promise>, + options?: { name?: string; version?: string; onError?: (error: unknown) => void }, + ): LearningMcpServer + LearningError: new (code: string, message: string) => Error +} + +const loaded = new Map>() + +/** + * Loads the learning tools from the installed replica-learning package, so Hub offers + * agents the same tools and instructions as the local server. The package's MCP SDK is + * optional, which is why it loads only when an agent first connects. + */ +export function loadLearningMcp(cliPath: string) { + const url = pathToFileURL(resolve(dirname(cliPath), "../src/mcp.mjs")).href + let module = loaded.get(url) + if (!module) { + module = import(url) as Promise + module.catch(() => loaded.delete(url)) + loaded.set(url, module) + } + return module +} diff --git a/hub/server/integrations/mcp/agent-oauth-provider/index.ts b/hub/server/integrations/mcp/agent-oauth-provider/index.ts new file mode 100644 index 000000000..7af308bea --- /dev/null +++ b/hub/server/integrations/mcp/agent-oauth-provider/index.ts @@ -0,0 +1,84 @@ +import { + InvalidGrantError, + InvalidTokenError, +} from "@modelcontextprotocol/sdk/server/auth/errors.js" +import type { OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js" + +import type { AgentOAuthService } from "./types.ts" + +function clientInformation(client: { id: string; name: string; redirectUris: string[] }) { + return { + client_id: client.id, + client_name: client.name, + redirect_uris: client.redirectUris, + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: "none", + } +} + +/** Adapts Hub's agent connections to the SDK's OAuth provider contract. */ +export function agentOAuthProvider(service: AgentOAuthService): OAuthServerProvider { + return { + clientsStore: { + getClient: async (id) => { + if (!/^[0-9a-f-]{36}$/i.test(id)) return undefined + const client = await service.getClient(id) + return client ? clientInformation(client) : undefined + }, + // Agents run on people's machines and cannot keep a secret, so every client is + // public and relies on PKCE. + registerClient: async (metadata) => { + const client = { + id: (metadata as { client_id?: string }).client_id ?? crypto.randomUUID(), + name: (metadata.client_name ?? "Coding agent").slice(0, 200), + redirectUris: metadata.redirect_uris.map(String), + } + await service.registerClient(client) + return { + ...clientInformation(client), + client_id_issued_at: Math.floor(Date.now() / 1000), + } + }, + }, + async authorize(client, params, response) { + const id = await service.startAuthorization({ + clientId: client.client_id, + redirectUri: params.redirectUri, + codeChallenge: params.codeChallenge, + ...(params.state === undefined ? {} : { state: params.state }), + }) + response.redirect(302, `/agents/approve/${id}`) + }, + async challengeForAuthorizationCode(client, code) { + const challenge = await service.challenge(client.client_id, code) + if (!challenge) throw new InvalidGrantError("The authorization code is invalid or expired.") + return challenge + }, + async exchangeAuthorizationCode(client, code, _verifier, redirectUri) { + const tokens = await service.exchangeCode(client.client_id, code, redirectUri) + if (!tokens) throw new InvalidGrantError("The authorization code is invalid or expired.") + return tokens + }, + async exchangeRefreshToken(client, refreshToken) { + const tokens = await service.refresh(client.client_id, refreshToken) + if (!tokens) throw new InvalidGrantError("The refresh token is invalid or expired.") + return tokens + }, + async verifyAccessToken(token) { + const result = await service.verify(token) + if (!result) throw new InvalidTokenError("The access token is invalid or expired.") + const { connection } = result + return { + token, + clientId: connection.clientId, + scopes: [], + expiresAt: Math.floor(connection.expiresAt.getTime() / 1000), + extra: { result }, + } + }, + async revokeToken(client, request) { + await service.revokeToken(client.client_id, request.token) + }, + } +} diff --git a/hub/server/integrations/mcp/agent-oauth-provider/types.ts b/hub/server/integrations/mcp/agent-oauth-provider/types.ts new file mode 100644 index 000000000..37bd0a6ce --- /dev/null +++ b/hub/server/integrations/mcp/agent-oauth-provider/types.ts @@ -0,0 +1,19 @@ +import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" + +export interface AgentOAuthService { + registerClient(client: { id: string; name: string; redirectUris: string[] }): Promise + getClient(id: string): Promise<{ id: string; name: string; redirectUris: string[] } | null> + startAuthorization(input: { + clientId: string + redirectUri: string + codeChallenge: string + state?: string + }): Promise + challenge(clientId: string, code: string): Promise + exchangeCode(clientId: string, code: string, redirectUri?: string): Promise + refresh(clientId: string, refreshToken: string): Promise + verify(accessToken: string): Promise<{ + connection: { id: string; clientId: string; expiresAt: Date } + } | null> + revokeToken(clientId: string, token: string): Promise +} diff --git a/hub/server/integrations/mcp/create-agent-auth-router/index.ts b/hub/server/integrations/mcp/create-agent-auth-router/index.ts new file mode 100644 index 000000000..d13205634 --- /dev/null +++ b/hub/server/integrations/mcp/create-agent-auth-router/index.ts @@ -0,0 +1,23 @@ +import type { RequestHandler } from "express" +import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js" + +import { agentOAuthProvider } from "../agent-oauth-provider/index.ts" +import type { AgentOAuthService } from "../agent-oauth-provider/types.ts" + +export const agentMcpPath = "/mcp" + +/** + * Serves OAuth discovery, client registration, sign-in and token endpoints, so agents + * that support MCP authorization can connect with only Hub's MCP URL. + */ +export function createAgentAuthRouter( + applicationOrigin: string, + service: AgentOAuthService, +): RequestHandler { + return mcpAuthRouter({ + provider: agentOAuthProvider(service), + issuerUrl: new URL(applicationOrigin), + resourceServerUrl: new URL(agentMcpPath, applicationOrigin), + resourceName: "Replica Hub learnings", + }) +} diff --git a/hub/server/integrations/mcp/handle-mcp-request/index.test.ts b/hub/server/integrations/mcp/handle-mcp-request/index.test.ts new file mode 100644 index 000000000..bcf3b4e2b --- /dev/null +++ b/hub/server/integrations/mcp/handle-mcp-request/index.test.ts @@ -0,0 +1,41 @@ +import { once } from "node:events" +import type { AddressInfo } from "node:net" +import express from "express" +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" +import { expect, it, onTestFinished } from "vitest" + +import { handleMcpRequest } from "." + +it("answers an MCP call whose body Express already parsed", async () => { + const app = express() + app.use(express.json()) + app.post("/mcp", async (request, response) => { + const server = new McpServer({ name: "test", version: "1.0.0" }) + server.registerTool("ping", { description: "Replies." }, () => ({ + content: [{ type: "text", text: "pong" }], + })) + await handleMcpRequest(server, request, response) + }) + const listener = app.listen(0, "127.0.0.1") + onTestFinished(() => void listener.close()) + await once(listener, "listening") + + const response = await fetch(`http://127.0.0.1:${(listener.address() as AddressInfo).port}/mcp`, { + method: "POST", + headers: { + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "ping", arguments: {} }, + }), + }) + + expect(await response.json()).toMatchObject({ + id: 1, + result: { content: [{ type: "text", text: "pong" }] }, + }) +}) diff --git a/hub/server/integrations/mcp/handle-mcp-request/index.ts b/hub/server/integrations/mcp/handle-mcp-request/index.ts new file mode 100644 index 000000000..7330ec466 --- /dev/null +++ b/hub/server/integrations/mcp/handle-mcp-request/index.ts @@ -0,0 +1,24 @@ +import type { Request, Response } from "express" +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js" + +interface McpServer { + connect(transport: StreamableHTTPServerTransport): Promise + close(): Promise +} + +/** + * Answers one MCP request with a fresh server. Nothing is kept between requests, so a + * revoked connection or lost access takes effect on the next call. + */ +export async function handleMcpRequest(server: McpServer, request: Request, response: Response) { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }) + response.on("close", () => { + void transport.close() + void server.close() + }) + await server.connect(transport) + await transport.handleRequest(request, response, request.body) +} diff --git a/hub/server/integrations/mcp/require-agent-token/index.ts b/hub/server/integrations/mcp/require-agent-token/index.ts new file mode 100644 index 000000000..6480403ae --- /dev/null +++ b/hub/server/integrations/mcp/require-agent-token/index.ts @@ -0,0 +1,23 @@ +import type { RequestHandler } from "express" +import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js" +import { getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/sdk/server/auth/router.js" + +import { agentOAuthProvider } from "../agent-oauth-provider/index.ts" +import type { AgentOAuthService } from "../agent-oauth-provider/types.ts" +import { agentMcpPath } from "../create-agent-auth-router/index.ts" + +/** + * Rejects requests without a live agent token. The response points agents at Hub's OAuth + * metadata, which is how they learn to start sign-in. + */ +export function requireAgentToken( + applicationOrigin: string, + service: AgentOAuthService, +): RequestHandler { + return requireBearerAuth({ + verifier: agentOAuthProvider(service), + resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl( + new URL(agentMcpPath, applicationOrigin), + ), + }) +} diff --git a/hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts new file mode 100644 index 000000000..592257256 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts @@ -0,0 +1,36 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Uses an approved code exactly once, even when two exchanges race. */ +export async function claimAgentAuthorization( + database: Pick, + clientId: string, + codeDigest: string, +) { + const now = new Date() + const [claimed] = await database.agentAuthorization.updateManyAndReturn({ + where: { + clientId, + codeDigest, + approvedAt: { not: null }, + consumedAt: null, + expiresAt: { gt: now }, + }, + data: { consumedAt: now }, + select: { + id: true, + redirectUri: true, + session: { + select: { + id: true, + membershipId: true, + externalIdentityId: true, + providerRevisionId: true, + revocationRevision: true, + endedAt: true, + expiresAt: true, + }, + }, + }, + }) + return claimed ?? null +} diff --git a/hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts new file mode 100644 index 000000000..1d871f186 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts @@ -0,0 +1,10 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Drops expired requests first, so abandoned sign-ins do not pile up. */ +export async function createAgentAuthorization( + database: Pick, + data: Prisma.AgentAuthorizationUncheckedCreateInput, +) { + await database.agentAuthorization.deleteMany({ where: { expiresAt: { lte: new Date() } } }) + return database.agentAuthorization.create({ data, select: { id: true } }) +} diff --git a/hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts new file mode 100644 index 000000000..87b71db33 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Settles a pending request once. Approval binds the person's session and stores only + * the code's digest; cancelling uses the request up so it cannot be approved later. + */ +export async function decideAgentAuthorization( + database: Pick, + id: string, + decision: { sessionId: string; codeDigest: string } | null, +) { + const now = new Date() + const result = await database.agentAuthorization.updateMany({ + where: { id, expiresAt: { gt: now }, approvedAt: null, consumedAt: null }, + data: decision ? { ...decision, approvedAt: now } : { consumedAt: now }, + }) + return result.count === 1 +} diff --git a/hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts b/hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts new file mode 100644 index 000000000..1707b01c5 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function findAgentAuthorizationChallenge( + database: Pick, + clientId: string, + codeDigest: string, +) { + return database.agentAuthorization.findFirst({ + where: { + clientId, + codeDigest, + approvedAt: { not: null }, + consumedAt: null, + expiresAt: { gt: new Date() }, + }, + select: { codeChallenge: true }, + }) +} diff --git a/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts new file mode 100644 index 000000000..01e0f9a4a --- /dev/null +++ b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function findPendingAgentAuthorization( + database: Pick, + id: string, +) { + return database.agentAuthorization.findFirst({ + where: { id, expiresAt: { gt: new Date() }, approvedAt: null, consumedAt: null }, + select: { + id: true, + clientId: true, + redirectUri: true, + state: true, + expiresAt: true, + client: { select: { name: true } }, + }, + }) +} diff --git a/hub/server/repositories/agent-clients/create-agent-client/index.ts b/hub/server/repositories/agent-clients/create-agent-client/index.ts new file mode 100644 index 000000000..316ae8658 --- /dev/null +++ b/hub/server/repositories/agent-clients/create-agent-client/index.ts @@ -0,0 +1,8 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function createAgentClient( + database: Pick, + data: { id: string; name: string; redirectUris: string[] }, +) { + return database.agentClient.create({ data }) +} diff --git a/hub/server/repositories/agent-clients/find-agent-client/index.ts b/hub/server/repositories/agent-clients/find-agent-client/index.ts new file mode 100644 index 000000000..2c79388ed --- /dev/null +++ b/hub/server/repositories/agent-clients/find-agent-client/index.ts @@ -0,0 +1,8 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function findAgentClient( + database: Pick, + id: string, +) { + return database.agentClient.findUnique({ where: { id } }) +} diff --git a/hub/server/repositories/agent-connections/create-agent-connection/index.ts b/hub/server/repositories/agent-connections/create-agent-connection/index.ts new file mode 100644 index 000000000..2dcb145f8 --- /dev/null +++ b/hub/server/repositories/agent-connections/create-agent-connection/index.ts @@ -0,0 +1,11 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function createAgentConnection( + database: Pick, + data: Prisma.AgentConnectionUncheckedCreateInput, +) { + return database.agentConnection.create({ + data, + select: { id: true, expiresAt: true }, + }) +} diff --git a/hub/server/repositories/agent-connections/find-agent-repository/index.ts b/hub/server/repositories/agent-connections/find-agent-repository/index.ts new file mode 100644 index 000000000..65e8945c7 --- /dev/null +++ b/hub/server/repositories/agent-connections/find-agent-repository/index.ts @@ -0,0 +1,20 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Learnings belong to GitHub repositories, so agents can reach only those. */ +export function findAgentRepository( + database: Pick, + id: string, +) { + return database.repository.findFirst({ + where: { id, removedAt: null, localPath: null, githubRepositoryId: { not: null } }, + select: { + id: true, + canvasId: true, + githubRepositoryId: true, + nameWithOwner: true, + defaultBranch: true, + localPath: true, + removedAt: true, + }, + }) +} diff --git a/hub/server/repositories/agent-connections/list-agent-connections/index.ts b/hub/server/repositories/agent-connections/list-agent-connections/index.ts new file mode 100644 index 000000000..8c55133bb --- /dev/null +++ b/hub/server/repositories/agent-connections/list-agent-connections/index.ts @@ -0,0 +1,20 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" +import type { CanvasAuthorityReference } from "../../canvas/authority/index.ts" + +export function listAgentConnections( + database: Pick, + owner: CanvasAuthorityReference, +) { + const now = new Date() + return database.agentConnection.findMany({ + where: { ...owner, revokedAt: null, inactiveAt: { gt: now } }, + orderBy: [{ createdAt: "desc" }, { id: "desc" }], + select: { + id: true, + createdAt: true, + lastUsedAt: true, + inactiveAt: true, + client: { select: { name: true } }, + }, + }) +} diff --git a/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts new file mode 100644 index 000000000..848f9d9e5 --- /dev/null +++ b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts @@ -0,0 +1,24 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function recordAgentConnectionAudit( + database: Pick, + input: { + action: "agent_connection.approve" | "agent_connection.revoke" + actorMembershipId: string + } & ({ connectionId: string } | { clientId: string }), +) { + // An approval happens before its connection exists, so it names the lasting agent + // client instead of the short-lived authorization request. + const target = + "connectionId" in input + ? { targetType: "agent_connection", targetId: input.connectionId } + : { targetType: "agent_client", targetId: input.clientId } + return database.securityAudit.create({ + data: { + action: input.action, + outcome: "SUCCESS", + ...target, + context: { actorMembershipId: input.actorMembershipId }, + }, + }) +} diff --git a/hub/server/repositories/agent-connections/revoke-agent-connection/index.ts b/hub/server/repositories/agent-connections/revoke-agent-connection/index.ts new file mode 100644 index 000000000..3c35abbe9 --- /dev/null +++ b/hub/server/repositories/agent-connections/revoke-agent-connection/index.ts @@ -0,0 +1,17 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Ends one connection, found by either of its tokens or by its owner. */ +export async function revokeAgentConnection( + database: Pick, + where: + | { clientId: string; tokenDigest: string } + | { clientId: string; refreshDigest: string } + | { id: string; membershipId: string; externalIdentityId: string }, +) { + const [revoked] = await database.agentConnection.updateManyAndReturn({ + where: { ...where, revokedAt: null }, + data: { revokedAt: new Date() }, + select: { id: true, membershipId: true }, + }) + return revoked ?? null +} diff --git a/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts b/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts new file mode 100644 index 000000000..e16b8a6e2 --- /dev/null +++ b/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts @@ -0,0 +1,40 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Replaces both tokens, so a stolen refresh token stops working after one use. */ +export async function rotateAgentConnection( + database: Pick, + input: { + clientId: string + refreshDigest: string + tokenDigest: string + nextRefreshDigest: string + expiresAt: Date + inactiveAt: Date + }, +) { + const now = new Date() + const [connection] = await database.agentConnection.updateManyAndReturn({ + where: { + clientId: input.clientId, + refreshDigest: input.refreshDigest, + revokedAt: null, + inactiveAt: { gt: now }, + }, + data: { + tokenDigest: input.tokenDigest, + refreshDigest: input.nextRefreshDigest, + expiresAt: input.expiresAt, + inactiveAt: input.inactiveAt, + lastUsedAt: now, + }, + select: { + id: true, + membershipId: true, + externalIdentityId: true, + providerRevisionId: true, + revocationRevision: true, + expiresAt: true, + }, + }) + return connection ?? null +} diff --git a/hub/server/repositories/agent-connections/touch-agent-connection/index.ts b/hub/server/repositories/agent-connections/touch-agent-connection/index.ts new file mode 100644 index 000000000..e66e59a54 --- /dev/null +++ b/hub/server/repositories/agent-connections/touch-agent-connection/index.ts @@ -0,0 +1,24 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Finds the connection for an access token and pushes back its inactivity limit. */ +export async function touchAgentConnection( + database: Pick, + tokenDigest: string, + inactiveAt: Date, +) { + const now = new Date() + const [connection] = await database.agentConnection.updateManyAndReturn({ + where: { tokenDigest, revokedAt: null, expiresAt: { gt: now }, inactiveAt: { gt: now } }, + data: { lastUsedAt: now, inactiveAt }, + select: { + id: true, + clientId: true, + membershipId: true, + externalIdentityId: true, + providerRevisionId: true, + revocationRevision: true, + expiresAt: true, + }, + }) + return connection ?? null +} diff --git a/hub/server/repositories/copilot-connections/replace-copilot-connection/index.ts b/hub/server/repositories/copilot-connections/replace-copilot-connection/index.ts index c94a49ed4..eaa9a8a60 100644 --- a/hub/server/repositories/copilot-connections/replace-copilot-connection/index.ts +++ b/hub/server/repositories/copilot-connections/replace-copilot-connection/index.ts @@ -7,6 +7,7 @@ export async function replaceCopilotConnection( credentialDigest: string credentialProvider: string id: string + reviewCommentConsentAt: Date | null verifiedAt: Date }, ) { diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts index 2d3324ab4..e52e0b425 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts @@ -320,6 +320,91 @@ describe("listDueLearningRepositories()", () => { expect(new Set(due.map(({ id }) => id))).toEqual(new Set([supersededId, otherFailureId])) }) + it("requires enabled deployment consent recorded after the latest automatic consent failure", async () => { + const consentedId = randomUUID() + const staleConsentId = randomUUID() + const sameTimeConsentId = randomUUID() + const membershipUser = await prisma.user.create({ data: {} }) + const membership = await prisma.membership.create({ + data: { userId: membershipUser.id }, + }) + const consentAt = new Date("2026-11-18T10:00:00Z") + await prisma.copilotConnection.create({ + data: { + connectedByMembershipId: membership.id, + credentialProvider: "environment_token", + credentialDigest: "a".repeat(64), + verifiedAt: consentAt, + reviewCommentConsentAt: consentAt, + }, + }) + await prisma.repository.createMany({ + data: [ + { id: consentedId, nameWithOwner: "team/consented", defaultBranch: "main" }, + { id: staleConsentId, nameWithOwner: "team/stale-consent", defaultBranch: "main" }, + { id: sameTimeConsentId, nameWithOwner: "team/same-time-consent", defaultBranch: "main" }, + ], + }) + await Promise.all( + [consentedId, staleConsentId, sameTimeConsentId].map((repositoryId) => + createReviewEvidence({ + repositoryId, + updatedAt: new Date("2026-11-18T09:00:00Z"), + }), + ), + ) + await prisma.learningRun.createMany({ + data: [ + { + repositoryId: consentedId, + scheduled: true, + state: "FAILED", + snapshotDigest: `sha256:${"a".repeat(64)}`, + failureCode: "grant_required", + failureSummary: "Review comment consent is required.", + createdAt: new Date("2026-11-18T09:00:00Z"), + finishedAt: new Date("2026-11-18T09:30:00Z"), + }, + { + repositoryId: staleConsentId, + scheduled: true, + state: "FAILED", + snapshotDigest: `sha256:${"b".repeat(64)}`, + failureCode: "grant_required", + failureSummary: "Review comment consent is required.", + createdAt: new Date("2026-11-18T11:00:00Z"), + finishedAt: new Date("2026-11-18T11:30:00Z"), + }, + { + repositoryId: sameTimeConsentId, + scheduled: true, + state: "FAILED", + snapshotDigest: `sha256:${"c".repeat(64)}`, + failureCode: "grant_required", + failureSummary: "Review comment consent is required.", + createdAt: consentAt, + finishedAt: new Date("2026-11-18T10:30:00Z"), + }, + ], + }) + + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual( + [], + ) + await expect( + listDueLearningRepositories(prisma, { + requireGitHubId: false, + hubReviewCommentConsentEnabled: false, + }), + ).resolves.toEqual([]) + await expect( + listDueLearningRepositories(prisma, { + requireGitHubId: false, + hubReviewCommentConsentEnabled: true, + }), + ).resolves.toEqual([{ id: consentedId }]) + }) + it("finds review evidence committed after snapshot capture with an earlier timestamp", async () => { const repositoryId = randomUUID() await prisma.repository.create({ diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts index cef8e8719..fd9ec5478 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts @@ -2,7 +2,11 @@ import { Prisma } from "../../../generated/prisma/client.ts" export function listDueLearningRepositories( database: Pick, - input: { requireGitHubId: boolean; limit?: number }, + input: { + requireGitHubId: boolean + hubReviewCommentConsentEnabled?: boolean + limit?: number + }, ) { const limit = input.limit ?? 2_000 return database.$queryRaw>(Prisma.sql` @@ -18,6 +22,7 @@ export function listDueLearningRepositories( latest_successes AS ( SELECT DISTINCT ON (repository_id) repository_id, + created_at, review_activity_snapshot, comments_remaining, suggestions_remaining @@ -56,6 +61,10 @@ export function listDueLearningRepositories( ON latest_automatic_runs.repository_id = repositories.id LEFT JOIN latest_explicit_runs ON latest_explicit_runs.repository_id = repositories.id + LEFT JOIN repository_learning_settings settings + ON settings.repository_id = repositories.id + LEFT JOIN copilot_connections copilot + ON copilot.key = 'global' LEFT JOIN LATERAL ( SELECT jsonb_object_agg(id::text, activity_version) AS snapshot FROM review_threads @@ -78,6 +87,12 @@ export function listDueLearningRepositories( OR (latest_explicit_runs.created_at, latest_explicit_runs.number) < (latest_automatic_runs.created_at, latest_automatic_runs.number) ) + AND ( + ${input.hubReviewCommentConsentEnabled ?? false} = false + OR copilot.review_comment_consent_at IS NULL + OR copilot.review_comment_consent_at <= latest_automatic_runs.created_at + ) + AND COALESCE(settings.review_comments_turned_off, false) = false ) AND ( COALESCE(latest_runs.comments_remaining, 0) > 0 @@ -85,9 +100,18 @@ export function listDueLearningRepositories( OR COALESCE(latest_successes.comments_remaining, 0) > 0 OR COALESCE(latest_successes.suggestions_remaining, 0) > 0 OR ( + COALESCE(settings.review_comments_turned_off, false) = false + AND review_activity.snapshot IS NOT NULL AND review_activity.snapshot IS DISTINCT FROM latest_successes.review_activity_snapshot ) + OR ( + settings.notes_received_at IS NOT NULL + AND ( + latest_successes.repository_id IS NULL + OR settings.notes_received_at > latest_successes.created_at + ) + ) ) ORDER BY latest_runs.created_at ASC NULLS FIRST, repositories.id ASC LIMIT ${limit} diff --git a/hub/server/repositories/learning-settings/get-repository-learning-setting/index.ts b/hub/server/repositories/learning-settings/get-repository-learning-setting/index.ts new file mode 100644 index 000000000..436082da9 --- /dev/null +++ b/hub/server/repositories/learning-settings/get-repository-learning-setting/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function getRepositoryLearningSetting( + database: Pick, + repositoryId: string, +) { + return database.repositoryLearningSetting.findUnique({ + where: { repositoryId }, + include: { + notesChangedByMembership: { + select: { user: { select: { profile: { select: { login: true } } } } }, + }, + reviewCommentsChangedByMembership: { + select: { user: { select: { profile: { select: { login: true } } } } }, + }, + }, + }) +} diff --git a/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts b/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts new file mode 100644 index 000000000..a1cb0393a --- /dev/null +++ b/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts @@ -0,0 +1,34 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export async function getReviewCommentConsent( + database: Pick, + repositoryId: string, + deploymentConsentEnabled: boolean, +) { + const [setting, connection] = await Promise.all([ + database.repositoryLearningSetting.findUnique({ + where: { repositoryId }, + select: { reviewCommentsTurnedOff: true, reviewCommentGrantId: true }, + }), + database.copilotConnection.findUnique({ + where: { key: "global" }, + select: { + reviewCommentConsentAt: true, + connectedByMembership: { + select: { lifecycle: true, user: { select: { profile: { select: { login: true } } } } }, + }, + }, + }), + ]) + const administrator = + deploymentConsentEnabled && connection?.reviewCommentConsentAt + ? connection.connectedByMembership + : null + const login = + administrator?.lifecycle === "ACTIVE" ? administrator.user.profile?.login : undefined + return { + turnedOff: setting?.reviewCommentsTurnedOff ?? false, + hubAdministrator: login ? `human:${login}` : null, + repositoryGrantId: setting?.reviewCommentGrantId ?? null, + } +} diff --git a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts new file mode 100644 index 000000000..90dbdc30f --- /dev/null +++ b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts @@ -0,0 +1,11 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export async function recordPickAndPolishNotesReceived( + database: PrismaClient, + repositoryId: string, +) { + await database.repositoryLearningSetting.updateMany({ + where: { repositoryId }, + data: { notesReceivedAt: new Date() }, + }) +} diff --git a/hub/server/repositories/learning-settings/save-repository-learning-setting/index.ts b/hub/server/repositories/learning-settings/save-repository-learning-setting/index.ts new file mode 100644 index 000000000..404d0496a --- /dev/null +++ b/hub/server/repositories/learning-settings/save-repository-learning-setting/index.ts @@ -0,0 +1,28 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +type LearningSettingChange = + | { + noteGrantId: string | null + notesChangedAt: Date + notesChangedByMembershipId: string + } + | { + reviewCommentsTurnedOff: boolean + reviewCommentsChangedAt: Date + reviewCommentsChangedByMembershipId: string + } + | { + reviewCommentGrantId: string + } + +export function saveRepositoryLearningSetting( + database: Pick, + repositoryId: string, + change: LearningSettingChange, +) { + return database.repositoryLearningSetting.upsert({ + where: { repositoryId }, + create: { repositoryId, ...change }, + update: change, + }) +} 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 a4a5aa64d..2926aab4b 100644 --- a/hub/server/repositories/security-audits/create-security-audit/types.ts +++ b/hub/server/repositories/security-audits/create-security-audit/types.ts @@ -248,7 +248,7 @@ export interface LearningRunAudit extends SecurityAuditEvent { export interface RepositoryAdministrationDeniedAudit extends SecurityAuditEvent { type: "repository_administration_denied" actorMembershipId: string - operation: "learning_overview" | "learning_run" | "learning_decision" + operation: "learning_overview" | "learning_run" | "learning_decision" | "learning_settings" 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 550c5c15e..3e778cf91 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 @@ -314,7 +314,12 @@ const eventSchema = z.discriminatedUnion("type", [ .object({ actorMembershipId: z.uuid(), id: z.uuid(), - operation: z.enum(["learning_overview", "learning_run", "learning_decision"]), + operation: z.enum([ + "learning_overview", + "learning_run", + "learning_decision", + "learning_settings", + ]), reason: z.literal("authority_missing"), repositoryId: z.uuid(), type: z.literal("repository_administration_denied"), diff --git a/hub/server/routes/agent-connections/index.db.test.ts b/hub/server/routes/agent-connections/index.db.test.ts new file mode 100644 index 000000000..fe097500f --- /dev/null +++ b/hub/server/routes/agent-connections/index.db.test.ts @@ -0,0 +1,253 @@ +import { createHash, randomBytes } from "node:crypto" +import { once } from "node:events" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" +import { expect, it, vi } from "vitest" + +import { createApp } from "../../create-app" +import { createLogger } from "../../integrations/pino/create-logger" +import { prisma } from "../../integrations/prisma" +import { createAuthenticationRouteDependencies } from "../api/auth/create-authentication-route-dependencies" +import { createProductRouteDependencies } from "../api/product/create-product-route-dependencies" + +it("connects an agent with the person's approval and stops it after they revoke it", async () => { + const server = createServer() + try { + server.listen(0, "127.0.0.1") + await once(server, "listening") + const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + const authentication = await createAuthenticationRouteDependencies( + { + NODE_ENV: "development", + DATABASE_URL: process.env.DATABASE_URL, + HUB_LOCAL_SIGN_IN: "true", + HUB_APPLICATION_ORIGIN: origin, + HUB_AUTHENTICATION_ENCRYPTION_KEY: randomBytes(32).toString("base64"), + HUB_BOOTSTRAP_SECRET: "synthetic-bootstrap-secret-for-agent-test", + }, + () => { + throw new Error("The agent connection test must not reach an outside provider.") + }, + ) + const product = Object.assign(createProductRouteDependencies(), { + getRepositoryPermission: vi.fn(() => Promise.resolve("admin" as const)), + }) + const githubRepositoryId = BigInt(Math.floor(Math.random() * 1_000_000_000) + 1) + const repository = await prisma.repository.create({ + data: { + nameWithOwner: `octo/agent-${githubRepositoryId}`, + defaultBranch: "main", + githubRepositoryId, + }, + }) + server.on( + "request", + createApp({ + authentication, + product, + agentConnections: { + applicationOrigin: origin, + databaseUrl: process.env.DATABASE_URL!, + learning: { + cliPath: "/missing/cli.mjs", + nodePath: "node", + root: "/", + staticDirectories: [], + }, + }, + logger: createLogger({ level: "silent" }), + }), + ) + const mcpUrl = `${origin}/mcp/repositories/${repository.id}` + function callMcp(token?: string) { + return fetch(mcpUrl, { + method: "POST", + headers: { + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }) + } + + const unauthenticated = await callMcp() + expect(unauthenticated.status).toBe(401) + expect(unauthenticated.headers.get("www-authenticate")).toContain( + `${origin}/.well-known/oauth-protected-resource/mcp`, + ) + + expect( + await (await fetch(`${origin}/.well-known/oauth-protected-resource/mcp`)).json(), + ).toMatchObject({ resource: `${origin}/mcp`, authorization_servers: [`${origin}/`] }) + + const redirectUri = "http://127.0.0.1:9/callback" + const registered = (await ( + await fetch(`${origin}/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "Test agent", redirect_uris: [redirectUri] }), + }) + ).json()) as { client_id: string; client_secret?: string } + expect(registered.client_secret).toBeUndefined() + + const verifier = randomBytes(32).toString("base64url") + const authorize = await fetch( + `${origin}/authorize?${new URLSearchParams({ + response_type: "code", + client_id: registered.client_id, + redirect_uri: redirectUri, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + state: "agent-state", + })}`, + { redirect: "manual" }, + ) + const approvalPath = authorize.headers.get("location")! + expect(approvalPath).toMatch(/^\/agents\/approve\/[0-9a-f-]{36}$/) + const authorizationId = approvalPath.split("/").at(-1)! + const authorizationPath = `/api/agent-connections/authorizations/${authorizationId}` + expect((await fetch(origin + authorizationPath)).status).toBe(401) + + const start = await fetch(`${origin}/api/auth/local/start`, { + method: "POST", + redirect: "manual", + headers: { Origin: origin }, + body: new URLSearchParams({ return_to: approvalPath }), + }) + const callback = await fetch(new URL(start.headers.get("location")!, origin), { + redirect: "manual", + headers: { + Cookie: start.headers + .getSetCookie() + .map((cookie) => cookie.split(";", 1)[0]) + .join("; "), + }, + }) + expect(callback.headers.get("location")).toBe(approvalPath) + const session = callback.headers + .getSetCookie() + .find((cookie) => cookie.startsWith("hub_session="))! + .split(";", 1)[0]! + function browser(path: string, method = "GET", body?: unknown) { + return fetch(origin + path, { + method, + headers: { + Cookie: session, + Origin: origin, + ...(body ? { "Content-Type": "application/json" } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }) + } + const pending = (await (await browser(authorizationPath)).json()) as { + agent: string + redirectUri: string + session: string + } + expect(pending).toMatchObject({ agent: "Test agent", redirectUri }) + // A page loaded under a different account must not approve for this one. + expect( + (await browser(`${authorizationPath}/approve`, "POST", { session: "other" })).status, + ).toBe(409) + const { redirectUrl } = (await ( + await browser(`${authorizationPath}/approve`, "POST", { session: pending.session }) + ).json()) as { redirectUrl: string } + const returned = new URL(redirectUrl) + expect(returned.searchParams.get("state")).toBe("agent-state") + expect( + (await browser(`${authorizationPath}/approve`, "POST", { session: pending.session })).status, + ).toBe(410) + + function requestTokens(fields: Record) { + return fetch(`${origin}/token`, { method: "POST", body: new URLSearchParams(fields) }) + } + const codeExchange = { + grant_type: "authorization_code", + client_id: registered.client_id, + code: returned.searchParams.get("code")!, + redirect_uri: redirectUri, + } + expect((await requestTokens({ ...codeExchange, code_verifier: "wrong" })).status).toBe(400) + const firstTokens = (await ( + await requestTokens({ ...codeExchange, code_verifier: verifier }) + ).json()) as { access_token: string; refresh_token: string } + expect((await requestTokens({ ...codeExchange, code_verifier: verifier })).status).toBe(400) + + const otherClient = (await ( + await fetch(`${origin}/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "Other agent", redirect_uris: [redirectUri] }), + }) + ).json()) as { client_id: string } + function refreshWith(clientId: string, refreshToken: string) { + return requestTokens({ + grant_type: "refresh_token", + client_id: clientId, + refresh_token: refreshToken, + }) + } + expect((await refreshWith(otherClient.client_id, firstTokens.refresh_token)).status).toBe(400) + const tokens = (await ( + await refreshWith(registered.client_id, firstTokens.refresh_token) + ).json()) as { access_token: string; refresh_token: string } + expect((await callMcp(firstTokens.access_token)).status).toBe(401) + expect((await refreshWith(registered.client_id, firstTokens.refresh_token)).status).toBe(400) + + // Local sign-in cannot read GitHub repositories, so the token works but access stops + // at the repository check. + expect((await callMcp(tokens.access_token)).status).toBe(403) + + const listed = (await (await browser("/api/agent-connections")).json()) as { + connections: { id: string; agent: string }[] + } + expect(listed.connections).toEqual([expect.objectContaining({ agent: "Test agent" })]) + const connectionId = listed.connections[0]!.id + expect((await browser(`/api/agent-connections/${connectionId}`, "DELETE")).status).toBe(204) + expect((await callMcp(tokens.access_token)).status).toBe(401) + + // An agent can also give up its own access through the standard revocation endpoint. + const again = await fetch( + `${origin}/authorize?${new URLSearchParams({ + response_type: "code", + client_id: registered.client_id, + redirect_uri: redirectUri, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + })}`, + { redirect: "manual" }, + ) + const againPath = `/api/agent-connections/authorizations/${again.headers.get("location")!.split("/").at(-1)}` + const againApproved = (await ( + await browser(`${againPath}/approve`, "POST", { session: pending.session }) + ).json()) as { redirectUrl: string } + const agentTokens = (await ( + await requestTokens({ + ...codeExchange, + code: new URL(againApproved.redirectUrl).searchParams.get("code")!, + code_verifier: verifier, + }) + ).json()) as { access_token: string } + const revoked = await fetch(`${origin}/revoke`, { + method: "POST", + body: new URLSearchParams({ + client_id: registered.client_id, + token: agentTokens.access_token, + }), + }) + expect(revoked.status).toBe(200) + expect((await callMcp(agentTokens.access_token)).status).toBe(401) + expect( + await prisma.securityAudit.count({ + where: { action: { in: ["agent_connection.approve", "agent_connection.revoke"] } }, + }), + ).toBe(4) + } finally { + if (server.listening) { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + } +}, 20_000) diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts new file mode 100644 index 000000000..758bf92b6 --- /dev/null +++ b/hub/server/routes/agent-connections/index.ts @@ -0,0 +1,246 @@ +import express from "express" +import type { Request, RequestHandler, Response } from "express" +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 { + createCanvasAuthorization, + type GetCanvasRepositoryPermission, +} from "../../domains/canvas/authorization/index.ts" +import { canvasDigest } from "../../domains/canvas/credentials/index.ts" +import { hubSessionCookieName } from "../../integrations/express/hub-session-cookie-name/index.ts" +import { readCookie } from "../../integrations/express/read-cookie/index.ts" +import { requireOrigin } from "../../integrations/express/require-origin/index.ts" +import { GitHubProviderRequestError } from "../../integrations/github/errors.ts" +import { loadLearningMcp } from "../../integrations/learning/load-learning-mcp/index.ts" +import { createAgentAuthRouter } from "../../integrations/mcp/create-agent-auth-router/index.ts" +import { handleMcpRequest } from "../../integrations/mcp/handle-mcp-request/index.ts" +import { requireAgentToken } from "../../integrations/mcp/require-agent-token/index.ts" +import { withLearningExecutionLock } from "../../integrations/postgres/with-learning-execution-lock/index.ts" +import type { PrismaClient } from "../../generated/prisma/client.ts" +import { findAgentRepository } from "../../repositories/agent-connections/find-agent-repository/index.ts" +import { getRepositoryLearningSetting } from "../../repositories/learning-settings/get-repository-learning-setting/index.ts" +import { recordPickAndPolishNotesReceived } from "../../repositories/learning-settings/record-pick-and-polish-notes-received/index.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 + +function status(response: Response, code: number, error: string) { + response.status(code).json({ error }) +} + +/** + * Lets people connect coding agents to Hub and lets those agents read a repository's + * learnings over MCP. People approve and manage connections with their Hub sign-in; + * agents use OAuth tokens that act for the person who approved them. + */ +export function agentConnectionRoutes( + dependencies: AgentConnectionRouteDependencies, + getRepositoryPermission?: GetCanvasRepositoryPermission, + logger?: Logger, +) { + const { applicationOrigin, databaseUrl, learning } = dependencies + const router = express.Router() + const browserMutation = requireOrigin(applicationOrigin) + + let services: Promise<{ + connections: AgentConnections + authority: ReturnType + prisma: PrismaClient + }> | null = null + function load() { + services ??= import("../../integrations/prisma/index.ts").then(({ prisma }) => ({ + prisma, + connections: createAgentConnections(prisma), + authority: createCanvasAuthorization(prisma, getRepositoryPermission), + })) + return services + } + + // The SDK's router needs the service before any request, so each call loads it lazily. + const service: Parameters[1] = { + registerClient: async (client) => (await load()).connections.registerClient(client), + getClient: async (id) => (await load()).connections.getClient(id), + startAuthorization: async (input) => (await load()).connections.startAuthorization(input), + challenge: async (clientId, code) => (await load()).connections.challenge(clientId, code), + exchangeCode: async (clientId, code, redirectUri) => + (await load()).connections.exchangeCode(clientId, code, redirectUri), + refresh: async (clientId, token) => (await load()).connections.refresh(clientId, token), + verify: async (token) => (await load()).connections.verify(token), + revokeToken: async (clientId, token) => (await load()).connections.revokeToken(clientId, token), + } + + function handler( + handle: (request: Request, response: Response) => Promise, + ): RequestHandler { + return async (request, response, next) => { + try { + await handle(request, response) + } catch (error) { + if (error instanceof GitHubProviderRequestError) { + status(response, 503, "Repository access could not be verified. Try again.") + return + } + next(error) + } + } + } + + async function browser(request: Request) { + const cookie = readCookie(request, hubSessionCookieName) + return cookie ? (await load()).authority.browser(canvasDigest(cookie)) : null + } + + function decision(approve: boolean) { + return handler(async (request, response) => { + const id = String(request.params.authorizationId) + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + // The page names the account it loaded with. If another tab switched accounts since, + // the person has not seen who they would be granting access as. + const shown = (request.body as { session?: unknown } | undefined)?.session + if (shown !== session.sessionId) + return status(response, 409, "You switched accounts. Review this request again.") + const redirectUrl = uuidPattern.test(id) + ? await (await load()).connections.decideAuthorization(id, session, approve) + : null + if (!redirectUrl) + return status(response, 410, "This request expired. Connect again from your agent.") + response.json({ redirectUrl }) + }) + } + + router.use(createAgentAuthRouter(applicationOrigin, service)) + + router.get( + "/api/agent-connections/authorizations/:authorizationId", + handler(async (request, response) => { + const id = String(request.params.authorizationId) + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const pending = uuidPattern.test(id) + ? await (await load()).connections.readAuthorization(id) + : null + if (!pending) + return status(response, 410, "This request expired. Connect again from your agent.") + response.json({ + agent: pending.clientName, + redirectUri: pending.redirectUri, + session: session.sessionId, + signedInAs: session.viewer.login, + expiresAt: pending.expiresAt.toISOString(), + }) + }), + ) + router.post( + "/api/agent-connections/authorizations/:authorizationId/approve", + browserMutation, + decision(true), + ) + router.post( + "/api/agent-connections/authorizations/:authorizationId/cancel", + browserMutation, + decision(false), + ) + router.get( + "/api/agent-connections", + handler(async (request, response) => { + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const connections = await (await load()).connections.list(session) + response.json({ + connections: connections.map((connection) => ({ + id: connection.id, + agent: connection.client.name, + createdAt: connection.createdAt.toISOString(), + lastUsedAt: connection.lastUsedAt?.toISOString() ?? null, + inactiveAt: connection.inactiveAt.toISOString(), + })), + }) + }), + ) + router.delete( + "/api/agent-connections/:connectionId", + browserMutation, + handler(async (request, response) => { + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const id = String(request.params.connectionId) + const revoked = + uuidPattern.test(id) && (await (await load()).connections.revokeBrowser(id, session)) + if (!revoked) return status(response, 404, "Agent connection was not found.") + response.status(204).end() + }), + ) + + const mcpPath = "/mcp/repositories/:repositoryId" + router.post( + mcpPath, + requireAgentToken(applicationOrigin, service), + handler(async (request, response) => { + const id = String(request.params.repositoryId) + const { prisma, authority } = await load() + const repository = uuidPattern.test(id) ? await findAgentRepository(prisma, id) : null + if (!repository?.githubRepositoryId) return status(response, 404, "Repository not found.") + const { result } = request.auth!.extra as { + result: NonNullable>> + } + if ((await authority.permission(result.viewer, repository)) === "none") + return status(response, 403, "Repository access was denied.") + const mcp = await loadLearningMcp(learning.cliPath) + const token = request.auth!.token + const backend = createLearningMcpBackend({ + async confirmAccess() { + const current = await (await load()).connections.verify(token) + const stillListed = current && (await findAgentRepository(prisma, repository.id)) + return Boolean( + stillListed && (await authority.permission(current.viewer, stillListed)) !== "none", + ) + }, + connectionId: result.connection.id, + learning, + learningsUrl: new URL(`/repositories/${repository.id}/learnings`, applicationOrigin).href, + notes: { + grantId: async () => + (await getRepositoryLearningSetting(prisma, repository.id))?.noteGrantId ?? null, + received: () => recordPickAndPolishNotesReceived(prisma, repository.id), + }, + repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, + async serialize(operation) { + try { + return await withLearningExecutionLock({ + databaseUrl, + protectSessionAuthority: true, + run: operation, + }) + } catch (error) { + if ( + error instanceof Error && + error.message === "Another learning operation is still running." + ) + throw new mcp.LearningError( + "busy", + "Hub is busy with other learning work. Try again in a minute.", + ) + throw error + } + }, + toAgentError: (code, message) => new mcp.LearningError(code, message), + user: result.viewer.login, + }) + const server = mcp.createLearningMcpServer(backend, { + name: "replica-hub-learning", + onError: (error) => logger?.error({ err: error }, "Agent learning tool failed"), + }) + await handleMcpRequest(server, request, response) + }), + ) + router.all(mcpPath, (_request, response) => { + response.set("Allow", "POST") + status(response, 405, "Send MCP messages with POST.") + }) + + return router +} diff --git a/hub/server/routes/agent-connections/types.ts b/hub/server/routes/agent-connections/types.ts new file mode 100644 index 000000000..315765971 --- /dev/null +++ b/hub/server/routes/agent-connections/types.ts @@ -0,0 +1,11 @@ +export interface AgentConnectionRouteDependencies { + applicationOrigin: string + databaseUrl: string + learning: { + cliPath: string + learningDatabaseUrl?: string + nodePath: string + root: string + staticDirectories: string[] + } +} diff --git a/hub/server/routes/api/copilot-connection/create-copilot-connection-route-dependencies/index.ts b/hub/server/routes/api/copilot-connection/create-copilot-connection-route-dependencies/index.ts index a4e5d78eb..883e2d694 100644 --- a/hub/server/routes/api/copilot-connection/create-copilot-connection-route-dependencies/index.ts +++ b/hub/server/routes/api/copilot-connection/create-copilot-connection-route-dependencies/index.ts @@ -89,6 +89,7 @@ export async function createCopilotConnectionRouteDependencies( authorizationId, credentialProvider: configuration.copilotCredentialProvider, hubSessionId: input.hubSessionId, + reviewCommentConsent: configuration.reviewCommentConsent, sessionDigest: input.sessionDigest, }, { 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 6a17ba25a..cae86f2c5 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,7 @@ import type { Prisma } from "../../../../generated/prisma/client.ts" import { getCopilotConnectionStatus } from "../../../../domains/copilot-connection/get-copilot-connection-status/index.ts" import { ReviewCommentError } from "../../../../domains/review-comments/errors.ts" import { executeLearningDecision } from "../../../../domains/learning/execute-learning-decision/index.ts" +import { changePickAndPolishConsent } from "../../../../domains/learning/change-pick-and-polish-consent/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 { getLearningOverview } from "../../../../domains/learning/get-learning-overview/index.ts" @@ -25,6 +26,8 @@ import { prisma } from "../../../../integrations/prisma/index.ts" import { classifyPrismaTransactionError } from "../../../../integrations/prisma/classify-transaction-error/index.ts" import { getCopilotConnectionState } from "../../../../repositories/copilot-connection-states/get-copilot-connection-state/index.ts" import { getCopilotConnection } from "../../../../repositories/copilot-connections/get-copilot-connection/index.ts" +import { getRepositoryLearningSetting } from "../../../../repositories/learning-settings/get-repository-learning-setting/index.ts" +import { saveRepositoryLearningSetting } from "../../../../repositories/learning-settings/save-repository-learning-setting/index.ts" import { createLearningRun } from "../../../../repositories/learning-runs/create-learning-run/index.ts" import { finishLearningRun } from "../../../../repositories/learning-runs/finish-learning-run/index.ts" import { listLearningRuns } from "../../../../repositories/learning-runs/list-learning-runs/index.ts" @@ -51,10 +54,13 @@ export async function createLearningsRouteDependencies( ): Promise { const configuration = await readLearningConfiguration(environment) const applicationOrigin = environment.HUB_APPLICATION_ORIGIN - const databaseUrl = environment.DATABASE_URL - if (!applicationOrigin || !databaseUrl) { - throw new Error("HUB_APPLICATION_ORIGIN and DATABASE_URL are required for the Learnings API.") - } + const requiredDatabaseUrl = ((): string => { + const databaseUrl = environment.DATABASE_URL + if (!applicationOrigin || !databaseUrl) { + throw new Error("HUB_APPLICATION_ORIGIN and DATABASE_URL are required for the Learnings API.") + } + return databaseUrl + })() const source = options.source ?? createReviewCommentLearningSource(prisma, applicationOrigin) async function runRepositoryAuthorityTransaction( @@ -186,6 +192,109 @@ export async function createLearningsRouteDependencies( return result } + async function getLearningSettings(repositoryId: string) { + const setting = await getRepositoryLearningSetting(prisma, repositoryId) + return { + notes: { + allowed: Boolean(setting?.noteGrantId), + changedBy: setting?.notesChangedByMembership?.user.profile?.login ?? null, + changedAt: setting?.notesChangedAt?.toISOString() ?? null, + }, + reviewComments: { + allowed: !(setting?.reviewCommentsTurnedOff ?? false), + changedBy: setting?.reviewCommentsChangedByMembership?.user.profile?.login ?? null, + changedAt: setting?.reviewCommentsChangedAt?.toISOString() ?? null, + }, + } + } + + async function changeLearningSettings(input: { + repositoryId: string + actor: string + actorMembershipId: string + sessionDigest: string + notes?: boolean + reviewComments?: boolean + }) { + async function deny(): Promise { + await createSecurityAudit(prisma, { + id: randomUUID(), + type: "repository_administration_denied", + actorMembershipId: input.actorMembershipId, + operation: "learning_settings", + reason: "authority_missing", + repositoryId: input.repositoryId, + }) + throw new LearningsError( + 403, + "repository_administrator_required", + "Repository administrator access is required.", + ) + } + function withAuthority( + operation: (transaction: Prisma.TransactionClient) => Promise, + ) { + return runRepositoryAuthorityTransaction(async (transaction) => + (await lockRepositoryAdministratorSession(transaction, { + membershipId: input.actorMembershipId, + repositoryId: input.repositoryId, + sessionDigest: input.sessionDigest, + })) + ? { value: await operation(transaction) } + : null, + ) + } + + await withLearningExecutionLock({ + databaseUrl: requiredDatabaseUrl, + protectSessionAuthority: true, + run: async (signal) => { + const access = await withAuthority(async (transaction) => ({ + repositoryScope: await getLearningRepositoryScope(transaction, input.repositoryId), + setting: await getRepositoryLearningSetting(transaction, input.repositoryId), + })) + if (!access) return deny() + const { repositoryScope, setting } = access.value + + if ( + input.reviewComments !== undefined && + input.reviewComments !== !(setting?.reviewCommentsTurnedOff ?? false) + ) { + const saved = await withAuthority((transaction) => + saveRepositoryLearningSetting(transaction, input.repositoryId, { + reviewCommentsTurnedOff: !input.reviewComments, + reviewCommentsChangedAt: new Date(), + reviewCommentsChangedByMembershipId: input.actorMembershipId, + }), + ) + if (!saved) return deny() + } + + const grantId = setting?.noteGrantId ?? null + if (input.notes !== undefined && input.notes !== Boolean(grantId)) { + const nextGrantId = await changePickAndPolishConsent({ + ...configuration, + actor: input.actor, + allowed: input.notes, + grantId, + repositoryId: input.repositoryId, + repositoryScope, + signal, + }) + const saved = await withAuthority((transaction) => + saveRepositoryLearningSetting(transaction, input.repositoryId, { + noteGrantId: nextGrantId, + notesChangedAt: new Date(), + notesChangedByMembershipId: input.actorMembershipId, + }), + ) + if (!saved) return deny() + } + }, + }) + return getLearningSettings(input.repositoryId) + } + return { applicationOrigin, automaticRunsEnabled: configuration.automaticRuns, @@ -261,6 +370,8 @@ export async function createLearningsRouteDependencies( }), ) }, + getLearningSettings, + changeLearningSettings, getCopilot, listRuns: (repositoryId) => listLearningRuns(prisma, repositoryId, new Date()), listActivity: (repositoryId, from) => @@ -383,7 +494,7 @@ export async function createLearningsRouteDependencies( ) } const { run, created, promoted } = requested - const queue = createJobQueue({ name: "on-demand", databaseUrl, logger }) + const queue = createJobQueue({ name: "on-demand", databaseUrl: requiredDatabaseUrl, logger }) try { await enqueueJob( queue, @@ -424,7 +535,7 @@ export async function createLearningsRouteDependencies( } }, redactComment: async ({ repositoryId, commentId, actorLogin }) => { - const queue = createJobQueue({ name: "on-demand", databaseUrl, logger }) + const queue = createJobQueue({ name: "on-demand", databaseUrl: requiredDatabaseUrl, logger }) try { await enqueueJob( queue, @@ -451,7 +562,7 @@ export async function createLearningsRouteDependencies( }, serializeReviewCommentDeletion: (operation) => withLearningExecutionLock({ - databaseUrl, + databaseUrl: requiredDatabaseUrl, run: () => operation(), }), decide: async ({ actorMembershipId, sessionDigest, ...input }) => { @@ -464,7 +575,7 @@ export async function createLearningsRouteDependencies( let operationCreated = false try { const result = await withLearningExecutionLock({ - databaseUrl, + databaseUrl: requiredDatabaseUrl, protectSessionAuthority: true, run: async (signal) => { if (!(await findRepository(viewer, input.repositoryId))) { diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts index 585c337d0..e5744f02c 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts @@ -427,3 +427,112 @@ describe("learning decision repository authority", () => { expect(JSON.stringify(audits[0])).not.toContain(privateReason) }) }) + +describe("learning settings repository authority", () => { + it("does not change review-comment consent after a Hub admin loses repository admin access", async () => { + const provider = await prisma.authenticationProvider.create({ + data: { key: "github", enabled: false }, + }) + const revision = await prisma.authenticationProviderRevision.create({ + data: { + configurationDigest: "d".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: "19", + userId: user.id, + }, + }) + await prisma.membershipAssignment.create({ + data: { + externalIdentityId: identity.id, + membershipId: membership.id, + role: "ADMINISTRATOR", + source: "HUB_ADMINISTRATOR", + }, + }) + const revocation = await prisma.sessionRevocationState.findUniqueOrThrow({ + where: { key: "global" }, + }) + const sessionDigest = "c".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: 19n, + nameWithOwner: "octo/consent", + }, + }) + const accessGrant = await prisma.repositoryAccessGrant.create({ + data: { + accessLevel: "ADMIN", + membershipId: membership.id, + observedAt: new Date(), + repositoryId: repository.id, + }, + }) + await prisma.repositoryLearningSetting.create({ + data: { repositoryId: repository.id, reviewCommentsTurnedOff: false }, + }) + const learnings = await createLearningsRouteDependencies( + { + HUB_APPLICATION_ORIGIN: "https://hub.example.test", + DATABASE_URL: getDatabaseUrl(), + }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + await prisma.repositoryAccessGrant.update({ + data: { accessLevel: "READ" }, + where: { id: accessGrant.id }, + }) + + await expect( + learnings.changeLearningSettings({ + actor: "human:mona", + actorMembershipId: membership.id, + repositoryId: repository.id, + reviewComments: false, + sessionDigest, + }), + ).rejects.toMatchObject({ + code: "repository_administrator_required", + status: 403, + }) + + await expect( + prisma.repositoryLearningSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + select: { + reviewCommentsTurnedOff: true, + reviewCommentsChangedAt: true, + reviewCommentsChangedByMembershipId: true, + }, + }), + ).resolves.toEqual({ + reviewCommentsTurnedOff: false, + reviewCommentsChangedAt: null, + reviewCommentsChangedByMembershipId: null, + }) + }) +}) diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index e756c06e2..22f7a7d8a 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -49,6 +49,14 @@ function dependencies( recall: { text: "", count: 0 }, }), getHistory: vi.fn().mockResolvedValue({ decisions: [], evidence: [], otherEvidenceCount: 0 }), + getLearningSettings: vi.fn().mockResolvedValue({ + notes: { allowed: false, changedBy: null, changedAt: null }, + reviewComments: { allowed: true, changedBy: null, changedAt: null }, + }), + changeLearningSettings: vi.fn().mockResolvedValue({ + notes: { allowed: false, changedBy: null, changedAt: null }, + reviewComments: { allowed: true, changedBy: null, changedAt: null }, + }), getCopilot: vi.fn().mockResolvedValue({ state: "connected", connectedBy: "mona" }), listRuns: vi.fn().mockResolvedValue({ runs: [], usageCredits: "0", active: null }), listActivity: vi.fn().mockResolvedValue([]), diff --git a/hub/server/routes/api/learnings/settings/get/index.ts b/hub/server/routes/api/learnings/settings/get/index.ts new file mode 100644 index 000000000..14ba5510d --- /dev/null +++ b/hub/server/routes/api/learnings/settings/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 type { LearningsRouteDependencies } from "../../types.ts" + +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 + } + if ( + !(await dependencies.authorizeRepositoryAdministration({ + membershipId: initial.membershipId, + repositoryId: repository.id, + })) + ) { + response.status(403).json({ + code: "repository_administrator_required", + error: "Repository administrator access is required.", + }) + return + } + const settings = await dependencies.getLearningSettings(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 + } + if ( + !(await dependencies.authorizeRepositoryAdministration({ + membershipId: current.membershipId, + repositoryId: repository.id, + })) + ) { + await dependencies.auditRepositoryAdministrationDenial({ + actorMembershipId: current.membershipId, + operation: "learning_settings", + repositoryId: repository.id, + }) + response.status(403).json({ + code: "repository_administrator_required", + error: "Repository administrator access is required.", + }) + return + } + response.json({ repository, ...settings }) + } catch (error) { + next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/settings/patch/index.ts b/hub/server/routes/api/learnings/settings/patch/index.ts new file mode 100644 index 000000000..c740f0c7f --- /dev/null +++ b/hub/server/routes/api/learnings/settings/patch/index.ts @@ -0,0 +1,98 @@ +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 changeSchema = z + .object({ + notes: z.boolean().optional(), + reviewComments: z.boolean().optional(), + }) + .strict() + .refine((value) => Object.keys(value).length > 0) + +const denied = { + code: "repository_administrator_required", + error: "Repository administrator access is required.", +} + +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_learning_settings", + error: "Choose at least one Learning setting to change.", + }) + return + } + const initial = await readLearningSession(request, dependencies) + if (!initial) { + response.status(403).json(denied) + return + } + const repository = await dependencies.findRepository(initial, repositoryId.data) + if (!repository) { + response.status(404).json({ code: "repository_not_found", error: "Repository not found." }) + return + } + if ( + !(await dependencies.authorizeRepositoryAdministration({ + membershipId: initial.membershipId, + repositoryId: repository.id, + })) + ) { + await dependencies.auditRepositoryAdministrationDenial({ + actorMembershipId: initial.membershipId, + operation: "learning_settings", + repositoryId: repository.id, + }) + response.status(403).json(denied) + return + } + const sessionDigest = readLearningSessionDigest(request) + if (!sessionDigest) { + response.status(403).json(denied) + return + } + const current = await readLearningSession(request, dependencies) + if (!current || current.membershipId !== initial.membershipId) { + response.status(403).json(denied) + return + } + const updated = await dependencies.changeLearningSettings({ + repositoryId: repository.id, + actor: `human:${current.login}`, + actorMembershipId: current.membershipId, + sessionDigest, + ...change.data, + }) + const latest = await readLearningSession(request, dependencies) + if ( + !latest || + latest.membershipId !== current.membershipId || + !(await dependencies.authorizeRepositoryAdministration({ + membershipId: latest.membershipId, + repositoryId: repository.id, + })) + ) { + response.status(403).json(denied) + return + } + response.json(updated) + } 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 dc4a8dfa0..67bc4a6a1 100644 --- a/hub/server/routes/api/learnings/types.ts +++ b/hub/server/routes/api/learnings/types.ts @@ -65,7 +65,7 @@ export interface LearningsRouteDependencies { }): Promise auditRepositoryAdministrationDenial(input: { actorMembershipId: string - operation: "learning_overview" | "learning_run" | "learning_decision" + operation: "learning_overview" | "learning_run" | "learning_decision" | "learning_settings" repositoryId: string }): Promise getOverview(input: { repositoryId: string; viewer: string }): Promise<{ @@ -83,6 +83,21 @@ export interface LearningsRouteDependencies { evidence: LearningEvidence[] otherEvidenceCount: number }> + getLearningSettings(repositoryId: string): Promise<{ + notes: { allowed: boolean; changedBy: string | null; changedAt: string | null } + reviewComments: { allowed: boolean; changedBy: string | null; changedAt: string | null } + }> + changeLearningSettings(input: { + repositoryId: string + actor: string + actorMembershipId: string + sessionDigest: string + notes?: boolean + reviewComments?: boolean + }): Promise<{ + notes: { allowed: boolean; changedBy: string | null; changedAt: string | null } + reviewComments: { allowed: boolean; changedBy: string | null; changedAt: string | null } + }> getCopilot(): Promise< | { state: "connected"; connectedBy: string | null } | { state: "not-connected" } 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 f500a19b5..f41bbd3e9 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 @@ -28,6 +28,7 @@ const repositoryAdministrationOperationSchema = z.enum([ "learning_overview", "learning_run", "learning_decision", + "learning_settings", ]) function actorFor(record: SecurityAuditListRecord) { @@ -76,6 +77,8 @@ function actorFor(record: SecurityAuditListRecord) { case "canvas_connection.renew": case "canvas_connection.revoke": case "canvas_connection.activity": + case "agent_connection.approve": + case "agent_connection.revoke": case "analytics_destination.create": case "analytics_destination.update": case "analytics_destination.pause": @@ -425,7 +428,8 @@ function contextFor(record: SecurityAuditListRecord): Record Promise + agentConnections?: AgentConnectionRouteDependencies agentVisualCritic?: AgentVisualCriticRouteDependencies authentication?: AuthenticationRouteDependencies copilotConnection?: CopilotConnectionRouteDependencies diff --git a/infrastructure/README.md b/infrastructure/README.md index bc2b075cc..b3a50c22f 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -61,7 +61,7 @@ It then uses separate protected Terraform state files for the foundation, applic The wizard builds and pushes a Linux AMD64 image and deploys its immutable digest. On first installation, Hub remains absent while a separate private-network job initializes the database roles. This job has its own temporary managed identity and secret-scoped administrator/password access; neither Hub nor normal setup receives administrator access. After success, the wizard records completion in Key Vault and destroys the temporary job, identity, and grants before invoking the existing serialized release procedure. -New installations use the separate PostgreSQL learning login, which the wizard provisions and configures before Hub starts. After release, a Hub administrator must still connect the configured Copilot provider at `/settings/copilot` to enable learning runs; see [Enable learnings in a deployed Hub](../hub/docs/learning-foundation.md#enable-learnings-in-a-deployed-hub). Existing installations are not switched from SQLite automatically. Before configuring `learning_database_secret`, stop old writers, hold the release lock, migrate and verify each learning store, run setup with the migration URL, and grant the learning login access as described in [Private storage](../hub/docs/learning-foundation.md#private-storage). The release refuses to proceed without durable learning storage. Do not retry against an unavailable old revision or discard its disk as proof that no learning history exists. +New installations use the separate PostgreSQL learning login, which the wizard provisions and configures before Hub starts. After release, a Hub administrator must connect the configured Copilot provider at `/settings/copilot` before learning runs can start. The post-setup menu also configures whether that connection may consent to review-comment learning across repositories; see [Enable learnings in a deployed Hub](../hub/docs/learning-foundation.md#enable-learnings-in-a-deployed-hub). Existing installations are not switched from SQLite automatically. Before configuring `learning_database_secret`, stop old writers, hold the release lock, migrate and verify each learning store, run setup with the migration URL, and grant the learning login access as described in [Private storage](../hub/docs/learning-foundation.md#private-storage). The release refuses to proceed without durable learning storage. Do not retry against an unavailable old revision or discard its disk as proof that no learning history exists. The final release stops old revisions, runs migrations and schedule setup, starts Hub, and checks HTTPS readiness. Readiness is not authorization. After installation, use the separate [post-setup menu](#post-setup-configuration) to enable setup access and GitHub sign-in without another build or database setup. A Hub administrator must also connect Copilot in `/settings/copilot` before learning runs can start. Artifact import, hosted previews, and reviews are not available yet. @@ -599,12 +599,14 @@ Verify the custom hostname, HTTPS certificate, redirects/cookies/callback origin ## Post-setup configuration -From the repository root, run `npm run setup:post`. It uses the same terminal interface as installation, but offers only **Configure sign-in and setup access**, **Configure GitHub App**, **Restart Hub**, and **Exit**. Choose an existing saved installation or enter its config-file path with `--config FILE` (relative to `infrastructure/` through the root shortcut). An unfinished setup draft must be resolved first. Exit performs no local writes or Azure calls. +From the repository root, run `npm run setup:post`. It uses the same terminal interface as installation, but offers **Configure sign-in and setup access**, **Configure GitHub App**, **Configure Learning consent**, **Restart Hub**, and **Exit**. Choose an existing saved installation or enter its config-file path with `--config FILE` (relative to `infrastructure/` through the root shortcut). An unfinished setup draft must be resolved first. Exit performs no local writes or Azure calls. Post-setup reuses the active deployment's exact immutable image. It never builds/publishes an image, bootstraps infrastructure, provisions database roles, runs setup/migrations, or starts the full maintenance release. It verifies the saved target, resource-group ownership and selected jobs, and coordinates with the existing local writer/workspace and installation/release leases. It does not scan other installations or the subscription. Confirm all other deployment processes have stopped; unknown or foreign retained leases block it rather than being broken. **Configure sign-in and setup access** defaults to Azure's authoritative app origin, or retains an existing configured origin. A custom origin must already be bound to the app and use the standard HTTPS port. Changing the origin while Entra settings exist is blocked: coordinate the Entra callback and provider revision separately. An origin change with GitHub configured also requires the stored GitHub revision described below and explicit permission to enable GitHub sign-in, even if the provider is currently disabled. Declining preserves desired inputs and secret versions. Enter the actual protected proxy hop count; the tool does not guess. A secret-backed hop count must be reviewed separately rather than overwritten with a plain value. Existing shared keys are preserved and validated. An unversioned shared key or secret-backed origin is pinned to the exact version read and validated. When absent, it reuses valid secrets with the documented names in the installation's protected Key Vault, or privately generates and stores them. A newly generated bootstrap secret is saved in a named private workspace file for the operator to escrow; its value is not printed. Keep that file until the secret is recoverably stored in your secret manager. An ordinary rerun never rotates existing shared keys. +**Configure Learning consent** asks whether the next Hub administrator who connects Copilot may consent to review-comment learning across repositories. The default is off. This setting does not enable automatic runs or grant access to Pick & Polish notes; repository administrators control those separately in Learning settings. After changing it, a Hub administrator must connect or reconnect Copilot at `/settings/copilot` to apply the choice. When deployment-wide consent is off, each repository's administrator can establish consent by requesting its first learning run. + If saved authentication settings lack an origin, configure sign-in to repair them. The updated inputs must pass normal validation before Terraform runs. GitHub App configuration and restart remain blocked until the origin is repaired. **Configure GitHub App** requires the shared setup context first. Open the reported `/settings/github/setup` guide to create or explicitly reuse an App in GitHub and install it on approved repositories. The tool shows the exact callback, setup and webhook URLs, collects the public identifiers/provider revision, and accepts credentials through private file paths only. Client secret/webhook files and the RSA PEM must be current-user-owned 0600 files inside a private 0700 directory. Do not paste credentials into path prompts. The webhook value must match GitHub. Blank paths retain existing credentials, pinning unversioned references to the exact version read and validated; supplying a file creates a new version under the existing secret name. Rotations in another vault or of an unsupported reference require separate review. Public IDs remain plain inputs, and secret values never enter Terraform inputs or telemetry. A reused App has one webhook destination; changing it can affect another Hub. diff --git a/infrastructure/azure/post/configure/index.test.ts b/infrastructure/azure/post/configure/index.test.ts index 2584258a5..7ef3d86da 100644 --- a/infrastructure/azure/post/configure/index.test.ts +++ b/infrastructure/azure/post/configure/index.test.ts @@ -292,6 +292,44 @@ function expectNoCredentials(visible: string, values: readonly string[]) { for (const line of value.split(/\r?\n/).filter(Boolean)) expect(visible).not.toContain(line) } +it("saves deployment-wide review-comment consent for the next Copilot connection", async () => { + const test = await scenario() + vi.mocked(test.ui.select).mockImplementation(async (_message, options) => + choose(options, /Enable deployment-wide review-comment consent/), + ) + + const desired = await configurePostSetup(test.context, "learning", test.inputs, test.deployment) + + expect(desired.runtime_environment_variables?.REPLICA_LEARNING_REVIEW_COMMENT_CONSENT).toBe( + "true", + ) + expect(test.ui.select).toHaveBeenCalledWith( + expect.stringMatching(/Hub administrator who connects Copilot/i), + expect.any(Array), + ) + expect(test.inputs.runtime_environment_variables).not.toHaveProperty( + "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT", + ) + await test.finish() +}) + +it("saves an explicit repository-admin-first choice as deployment consent off", async () => { + const test = await scenario() + vi.mocked(test.ui.select).mockImplementation(async (_message, options) => + choose(options, /Require each repository's administrator/), + ) + + const desired = await configurePostSetup(test.context, "learning", test.inputs, test.deployment) + + expect(desired.runtime_environment_variables?.REPLICA_LEARNING_REVIEW_COMMENT_CONSENT).toBe( + "false", + ) + expect(test.inputs.runtime_environment_variables).not.toHaveProperty( + "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT", + ) + await test.finish() +}) + it("validates the authoritative origin and explicit proxy hops while preserving shared keys and unrelated settings across repeats", async () => { const test = await scenario() const original = structuredClone(test.inputs) diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index 0a79a430e..947c55e91 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -24,7 +24,7 @@ export async function configurePostSetup( onPrepared?(finish: () => Promise): void onMutation?(): void }, - action: "sign-in" | "github", + action: "sign-in" | "github" | "learning", inputs: PostInputs, deployment: PostDeployment, ): Promise { @@ -92,6 +92,27 @@ export async function configurePostSetup( } Object.assign(references, progress.references) context.onPrepared?.(() => progress.finish()) + if (action === "learning") { + const key = "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT" + const existing = + inputs.runtime_environment_variables?.[key] ?? deployment.environment[key] ?? "false" + if (!["true", "false"].includes(existing)) + throw new Error(`${key} must be true or false before Learning setup can continue.`) + const savedAnswer = resume ? progress.answers.learningConsent : undefined + const consent = + savedAnswer ?? + (await recoveryUI.select( + "Allow a Hub administrator who connects Copilot to consent to learning from review comments in every repository? Repository administrators can turn this off. Pick & Polish notes still need repository-specific consent in Learning settings.", + [ + { label: "Enable deployment-wide review-comment consent", value: "true" }, + { label: "Require each repository's administrator to start the first run", value: "false" }, + { label: "Save and exit", value: "exit" }, + ], + )) + await progress.saveAnswer("learningConsent", consent) + next.runtime_environment_variables[key] = consent + return next + } async function field( key: string, label: string, diff --git a/infrastructure/azure/post/index.ts b/infrastructure/azure/post/index.ts index 55cc588b5..66eb20224 100644 --- a/infrastructure/azure/post/index.ts +++ b/infrastructure/azure/post/index.ts @@ -43,7 +43,7 @@ export async function postSetupAzure( }, ): Promise { signal?.throwIfAborted() - if (!["sign-in", "github", "restart"].includes(action)) + if (!["sign-in", "github", "learning", "restart"].includes(action)) throw new Error("Choose a supported post-setup action.") const target = { path: resolve(input.path), config: parseConfig(input.config) } const config = target.config @@ -182,7 +182,7 @@ export async function postSetupAzure( (!journal || journal.target !== JSON.stringify(config) || !["pending", "complete"].includes(String(journal.phase)) || - !["sign-in", "github"].includes(String(journal.action)) || + !["sign-in", "github", "learning"].includes(String(journal.action)) || typeof journal.hash !== "string" || !/^[a-f0-9]{64}$/.test(journal.hash)) ) @@ -270,6 +270,8 @@ export async function postSetupAzure( "GITHUB_APP_INSTALLATION_ID", "GITHUB_PROVIDER_REVISION", ] + : action === "learning" + ? ["REPLICA_LEARNING_REVIEW_COMMENT_CONSENT"] : [] const deploymentSettings = [ "NODE_ENV", @@ -625,7 +627,16 @@ export async function postSetupAzure( for (const lock of [...locks].reverse()) await lock.release() success = true ui.complete?.() - return `${config.name}: ${action === "restart" ? "active Hub revision restarted" : "post-setup configuration applied"} using the unchanged deployed image.\n${publicOrigin}${action !== "restart" ? "/settings/github/setup" : ""}\n${action === "github" ? "GitHub sign-in is enabled. Verify the App connection, administrator enrollment, OAuth callback and signed webhooks separately." : action === "sign-in" ? "Setup access is available. GitHub sign-in remains dependent on the configured App credentials." : "Settings and pinned secret versions were retained."}${bootstrapFile ? `\nBootstrap secret saved privately: ${bootstrapFile}. Escrow it before removing this local copy.` : ""}` + const result = + action === "restart" + ? "Settings and pinned secret versions were retained." + : action === "github" + ? "GitHub sign-in is enabled. Verify the App connection, administrator enrollment, OAuth callback and signed webhooks separately." + : action === "sign-in" + ? "Setup access is available. GitHub sign-in remains dependent on the configured App credentials." + : "Learning consent was saved. Connect or reconnect Copilot in /settings/copilot to apply it." + const setupUrl = action === "sign-in" || action === "github" ? `${publicOrigin}/settings/github/setup` : "" + return `${config.name}: ${action === "restart" ? "active Hub revision restarted" : "post-setup configuration applied"} using the unchanged deployed image.\n${setupUrl}\n${result}${bootstrapFile ? `\nBootstrap secret saved privately: ${bootstrapFile}. Escrow it before removing this local copy.` : ""}` } catch (error) { if (changesStarted) { const summary = `Post-setup stopped; secrets or runtime changes may be partial, and Hub may remain stopped. ${desiredSaved ? "Desired inputs and their private backup were saved; rerun the same post-setup action to replan." : "Previous inputs were retained; rerun after reviewing the failed step. Named shared secrets already created will be reused."} No rollback, database setup, image rebuild, or lock breaking was attempted. If Azure created a grant not recorded in state, reconcile that exact resource before retrying.${bootstrapFile ? ` Bootstrap secret retained privately at ${bootstrapFile}.` : ""}` diff --git a/infrastructure/azure/post/progress/index.ts b/infrastructure/azure/post/progress/index.ts index da4a0ffdf..d187b81b7 100644 --- a/infrastructure/azure/post/progress/index.ts +++ b/infrastructure/azure/post/progress/index.ts @@ -15,6 +15,7 @@ const publicAnswers = [ "github_client_id", "github_app_installation_id", "github_provider_revision", + "learningConsent", ] as const const credentialKeys = [ "GITHUB_CLIENT_SECRET", @@ -27,7 +28,7 @@ type Reference = NonNullable[string] interface Progress { version: 1 target: string - action: "sign-in" | "github" + action: "sign-in" | "github" | "learning" answers: Record references: Record pending?: string @@ -42,7 +43,7 @@ interface Progress { export async function postSetupProgress( context: Pick, - action: "sign-in" | "github", + action: "sign-in" | "github" | "learning", inputs?: PostInputs, verifiedImage?: string, ) { @@ -98,13 +99,17 @@ export async function postSetupProgress( if (!value || typeof value !== "object" || Array.isArray(value)) invalid() return value as Record } - const keys: readonly string[] = action === "github" ? credentialKeys : sharedKeys + const keys: readonly string[] = + action === "github" ? credentialKeys : action === "sign-in" ? sharedKeys : [] const pinned = (secretId: string) => /\/secrets\/[a-z0-9-]{1,127}\/[a-f0-9]{32}$/i.test(secretId) function answer(key: string, value: unknown): string { if (typeof value !== "string" || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value)) invalid() if (publicAnswers.includes(key as (typeof publicAnswers)[number])) { + if (key === "learningConsent") { + if (action !== "learning" || !["true", "false"].includes(value)) invalid() + } else { if (action === "sign-in" && !["origin", "proxyHops"].includes(key)) invalid() if (action === "github" && ["origin", "proxyHops"].includes(key)) invalid() if (key === "origin") { @@ -114,6 +119,7 @@ export async function postSetupProgress( } else if (key === "github_client_id") { if (!/^\S{1,200}$/.test(value)) invalid() } else if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) invalid() + } } else if ( !credentialKeys.some((name) => key === `${name}_FILE`) || action !== "github" || @@ -232,6 +238,8 @@ export async function postSetupProgress( github_client_id: inputs?.github_client_id, github_app_installation_id: inputs?.github_app_installation_id, github_provider_revision: inputs?.github_provider_revision, + learningConsent: + inputs?.runtime_environment_variables?.REPLICA_LEARNING_REVIEW_COMMENT_CONSENT, } const retainedReferences = { ...data.secretOrigin?.references, ...data.references } const currentReferences = inputs?.runtime_secret_references ?? {} diff --git a/infrastructure/installer/entry/index.test.ts b/infrastructure/installer/entry/index.test.ts index 61fc0e797..ae1803cd9 100644 --- a/infrastructure/installer/entry/index.test.ts +++ b/infrastructure/installer/entry/index.test.ts @@ -100,6 +100,7 @@ it("exits post-setup without creating a local directory or requesting installati expect(vi.mocked(ui.select).mock.calls[0]![1].map(({ value }) => value)).toEqual([ "sign-in", "github", + "learning", "restart", "exit", ]) @@ -109,7 +110,7 @@ it("exits post-setup without creating a local directory or requesting installati expect(ui.confirm).not.toHaveBeenCalled() }) -it.each(["sign-in", "github", "restart"] as const)( +it.each(["sign-in", "github", "learning", "restart"] as const)( "selects a complete saved installation for post-setup %s without changing its files", async (postAction) => { const root = await directory() diff --git a/infrastructure/installer/entry/index.ts b/infrastructure/installer/entry/index.ts index c64503572..1924a95f5 100644 --- a/infrastructure/installer/entry/index.ts +++ b/infrastructure/installer/entry/index.ts @@ -154,6 +154,7 @@ export async function selectInstallerEntry( ? [ { label: "Configure sign-in and setup access", value: "sign-in" }, { label: "Configure GitHub App", value: "github" }, + { label: "Configure Learning consent", value: "learning" }, { label: "Restart Hub (keep current settings)", value: "restart" }, { label: "Exit and do nothing", value: "exit" }, ] @@ -167,7 +168,7 @@ export async function selectInstallerEntry( if (action === "exit") return undefined let postAction: PostSetupAction | undefined if (postSetup) { - if (action !== "sign-in" && action !== "github" && action !== "restart") + if (action !== "sign-in" && action !== "github" && action !== "learning" && action !== "restart") throw new Error("Choose a supported post-setup action.") postAction = action action = "update" diff --git a/infrastructure/installer/types.ts b/infrastructure/installer/types.ts index 2388cfdec..1c21bb20a 100644 --- a/infrastructure/installer/types.ts +++ b/infrastructure/installer/types.ts @@ -21,7 +21,7 @@ export interface DeploymentConfig { } } -export type PostSetupAction = "sign-in" | "github" | "restart" +export type PostSetupAction = "sign-in" | "github" | "learning" | "restart" export interface CommandOptions { cwd?: string From 8363f54d8ef7c87fe48469c5d5fc6214848e34da Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 11:57:23 -0800 Subject: [PATCH 03/32] fix(hub): suppress MCP payload logging Mark MCP routes private before parsing request bodies. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/server/create-app/index.test.ts | 81 +++++++++++++++++++++++++++++ hub/server/create-app/index.ts | 1 + 2 files changed, 82 insertions(+) diff --git a/hub/server/create-app/index.test.ts b/hub/server/create-app/index.test.ts index bfff7c98e..f4e80cc25 100644 --- a/hub/server/create-app/index.test.ts +++ b/hub/server/create-app/index.test.ts @@ -614,6 +614,87 @@ describe("createApp()", () => { } }) + it("omits MCP request bodies from logs before parsing", async () => { + const records: Record[] = [] + const logger = createLogger({ + destination: { write: (line) => records.push(parseRecord(line)) }, + }) + const server = createServer( + createApp({ + authentication: { + currentSession: { restore: vi.fn().mockResolvedValue(null) }, + signOut: { + applicationOrigin: "http://127.0.0.1", + secureCookie: false, + end: vi.fn(), + }, + }, + product: { + getRepositoryPermission: vi.fn().mockResolvedValue("admin" as const), + isRepositoryVisible: vi.fn().mockResolvedValue(false), + listRepositories: vi.fn().mockResolvedValue([]), + findRepositoryIndex: vi.fn(), + findPrototypeDetail: vi.fn(), + readPrototypeWithIntroduction: vi.fn(), + findRepositoryAuthors: vi.fn(), + editPrototypeMetadata: vi.fn(), + findBuildPreviewTarget: vi.fn(), + } satisfies ProductRouteDependencies, + agentConnections: { + applicationOrigin: "http://127.0.0.1", + databaseUrl: "postgresql://test:test@127.0.0.1:5432/test", + learning: { + cliPath: "/missing/cli.mjs", + nodePath: "node", + root: "/", + staticDirectories: [], + }, + }, + logger, + }), + ) + + try { + server.listen(0, "127.0.0.1") + await once(server, "listening") + const { port } = server.address() as AddressInfo + const url = `http://127.0.0.1:${port}/mcp/repositories/${randomUUID()}` + const privateNote = "private-pick-and-polish-note" + const valid = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ method: "tools/call", params: { note: privateNote } }), + }) + expect(valid.status).toBe(401) + await valid.arrayBuffer() + await vi.waitFor(() => expect(records).toHaveLength(1)) + expect(records[0]).not.toHaveProperty("body") + expect(JSON.stringify(records)).not.toContain(privateNote) + + const malformed = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: '{"note":"malformed-private-note"', + }) + expect(malformed.status).toBe(400) + expect(malformed.headers.get("cache-control")).toBe("no-store") + await malformed.arrayBuffer() + + await vi.waitFor(() => expect(records).toHaveLength(2)) + expect(records[0]).toMatchObject({ method: "POST", statusCode: 401, outcome: "completed" }) + expect(records[1]).toMatchObject({ method: "POST", statusCode: 400, outcome: "completed" }) + expect(records[0]).not.toHaveProperty("body") + expect(records[1]).not.toHaveProperty("body") + expect(JSON.stringify(records)).not.toMatch( + /private-pick-and-polish-note|malformed-private-note/, + ) + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + }) + it.each([ { name: "malformed", body: '{"password":"malformed-body-secret"', statusCode: 400 }, { name: "oversized", body: JSON.stringify({ text: "x".repeat(1024 * 1024) }), statusCode: 413 }, diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 71a4189e2..356ee89c1 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -53,6 +53,7 @@ export function createApp({ [ "/api/canvas", "/api/agent-connections", + "/mcp", "/api/auth", "/canvas/pair", "/agents/approve", From 2f9f656cc1c273959fb0708a9012cda0159cd756 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 12:05:27 -0800 Subject: [PATCH 04/32] docs(hub): map agent learning routes in Storybook List the new agent management and approval screens beside their stories. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/docs/storybook.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hub/docs/storybook.md b/hub/docs/storybook.md index 1d6d617c1..068a6d38f 100644 --- a/hub/docs/storybook.md +++ b/hub/docs/storybook.md @@ -38,7 +38,9 @@ Start Storybook before opening these links. Each row points to an example of a d | `/repositories/:repositoryId/analytics` | [Analytics](http://localhost:6006/?path=/story/hub-pages-repositories-analytics--configured) | | `/repositories/:repositoryId/learnings` | [Learnings](http://localhost:6006/?path=/story/hub-pages-learnings-index--default) | | `/repositories/:repositoryId/learnings?learning=:learningId` | [Learning detail](http://localhost:6006/?path=/story/hub-pages-learnings-detail--suggestion) | +| `/repositories/:repositoryId/learnings/agents` | [Agent connections](http://localhost:6006/?path=/story/hub-pages-learnings-agent-connections--connected-agents) | | `/repositories/:repositoryId/learnings/settings` | [Learning settings](http://localhost:6006/?path=/story/hub-pages-learnings-settings--defaults) | +| `/agents/approve/:authorizationId` | [Agent approval](http://localhost:6006/?path=/story/hub-pages-learnings-agent-connections--approval-request) | | `/notifications` | [Inbox](http://localhost:6006/?path=/story/hub-pages-inbox--cached-refresh) | | `/canvas/connections` | [Canvas connections](http://localhost:6006/?path=/story/hub-pages-canvas-connection--connected) | | `/canvas/pair/:userCode` | [Approve a connection](http://localhost:6006/?path=/story/hub-pages-canvas-connection--approval) | From 1661ec7638524c7765ad316acc194713f78af824 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 12:21:39 -0800 Subject: [PATCH 05/32] fix(infrastructure): clarify learning consent state Explain how disabling and re-enabling deployment-wide learning consent affects the saved administrator grant. Make the lifecycle visible in the Azure setup prompt and operator guidance. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/docs/learning-foundation.md | 2 +- infrastructure/README.md | 2 +- infrastructure/azure/post/configure/index.test.ts | 4 ++++ infrastructure/azure/post/configure/index.ts | 2 +- infrastructure/azure/post/index.ts | 2 +- 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 156279f95..50595d03c 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -8,7 +8,7 @@ The package remains the authority for consent, purpose, evidence, approval, reda Learning is available after the deployment has durable learning storage and a verified Copilot connection. New Azure installations configure a separate PostgreSQL learning login in the installation wizard. Existing installations must keep their current store until any SQLite history has been imported and verified; follow the migration steps in [Private storage](#private-storage) before adding `learning_database_secret`. Other deployments need a persistent `REPLICA_LEARNING_ROOT` or a separately provisioned PostgreSQL learning database and runtime role. -An operator configures a Copilot credential provider and restarts Hub and its workers. On Azure, run `npm run setup:post` and choose **Configure Learning consent** to decide whether a Hub administrator's next Copilot connection may consent to review-comment learning across repositories. The default is off. After changing this choice, a Hub administrator must connect or reconnect Copilot at `/settings/copilot` to apply it. While deployment-wide consent is off, Hub ignores grants created only under that consent; repository-specific consent remains in effect. See [Copilot connection](copilot.md) for provider setup and authorization. Without a verified connection, Learnings stays visible but cannot run. +An operator configures a Copilot credential provider and restarts Hub and its workers. On Azure, run `npm run setup:post` and choose **Configure Learning consent** to decide whether a Hub administrator's next Copilot connection may consent to review-comment learning across repositories. The default is off. Connect or reconnect Copilot at `/settings/copilot` to record the administrator's consent. Turning the switch off immediately stops Hub from using deployment-wide consent, but does not erase the saved consent. Reconnect Copilot while the switch is off to clear it; if the switch is re-enabled before then, the saved consent becomes active again. Repository-specific consent remains in effect while deployment-wide consent is off. See [Copilot connection](copilot.md) for provider setup and authorization. Without a verified connection, Learnings stays visible but cannot run. Repository administrators can request the first run for a repository. That request records consent to use its review comments unless a Hub administrator already consented deployment-wide. Daily runs remain off unless `REPLICA_LEARNING_AUTOMATIC_RUNS=true` is configured. Repository administrators can turn review-comment learning off in **Learning settings**. They can separately allow Hub to learn from Pick & Polish notes; Hub stores only those notes, never the surrounding chat messages. Turning either repository setting off does not remove accepted Learnings. diff --git a/infrastructure/README.md b/infrastructure/README.md index b3a50c22f..b1828edad 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -605,7 +605,7 @@ Post-setup reuses the active deployment's exact immutable image. It never builds **Configure sign-in and setup access** defaults to Azure's authoritative app origin, or retains an existing configured origin. A custom origin must already be bound to the app and use the standard HTTPS port. Changing the origin while Entra settings exist is blocked: coordinate the Entra callback and provider revision separately. An origin change with GitHub configured also requires the stored GitHub revision described below and explicit permission to enable GitHub sign-in, even if the provider is currently disabled. Declining preserves desired inputs and secret versions. Enter the actual protected proxy hop count; the tool does not guess. A secret-backed hop count must be reviewed separately rather than overwritten with a plain value. Existing shared keys are preserved and validated. An unversioned shared key or secret-backed origin is pinned to the exact version read and validated. When absent, it reuses valid secrets with the documented names in the installation's protected Key Vault, or privately generates and stores them. A newly generated bootstrap secret is saved in a named private workspace file for the operator to escrow; its value is not printed. Keep that file until the secret is recoverably stored in your secret manager. An ordinary rerun never rotates existing shared keys. -**Configure Learning consent** asks whether the next Hub administrator who connects Copilot may consent to review-comment learning across repositories. The default is off. This setting does not enable automatic runs or grant access to Pick & Polish notes; repository administrators control those separately in Learning settings. After changing it, a Hub administrator must connect or reconnect Copilot at `/settings/copilot` to apply the choice. When deployment-wide consent is off, each repository's administrator can establish consent by requesting its first learning run. +**Configure Learning consent** asks whether the next Hub administrator who connects Copilot may consent to review-comment learning across repositories. The default is off. This setting does not enable automatic runs or grant access to Pick & Polish notes; repository administrators control those separately in Learning settings. Turning this switch off immediately stops deployment-wide consent from applying, but does not erase saved consent. Reconnect Copilot while it is off to clear the saved consent; otherwise, re-enabling the switch makes it active again. See [Enable learnings in a deployed Hub](../hub/docs/learning-foundation.md#enable-learnings-in-a-deployed-hub) for the full lifecycle. When deployment-wide consent is off, each repository's administrator can establish consent by requesting its first learning run. If saved authentication settings lack an origin, configure sign-in to repair them. The updated inputs must pass normal validation before Terraform runs. GitHub App configuration and restart remain blocked until the origin is repaired. diff --git a/infrastructure/azure/post/configure/index.test.ts b/infrastructure/azure/post/configure/index.test.ts index 7ef3d86da..e63dce2f8 100644 --- a/infrastructure/azure/post/configure/index.test.ts +++ b/infrastructure/azure/post/configure/index.test.ts @@ -307,6 +307,10 @@ it("saves deployment-wide review-comment consent for the next Copilot connection expect.stringMatching(/Hub administrator who connects Copilot/i), expect.any(Array), ) + expect(test.ui.select).toHaveBeenCalledWith( + expect.stringMatching(/reconnect Copilot while disabled to clear it/i), + expect.any(Array), + ) expect(test.inputs.runtime_environment_variables).not.toHaveProperty( "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT", ) diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index 947c55e91..f626e7b64 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -102,7 +102,7 @@ export async function configurePostSetup( const consent = savedAnswer ?? (await recoveryUI.select( - "Allow a Hub administrator who connects Copilot to consent to learning from review comments in every repository? Repository administrators can turn this off. Pick & Polish notes still need repository-specific consent in Learning settings.", + "Allow a Hub administrator who connects Copilot to consent to learning from review comments in every repository? Repository administrators can turn it off for their repository. Pick & Polish notes still need repository-specific consent in Learning settings. Disabling this switch stops deployment-wide consent immediately but keeps the saved consent; reconnect Copilot while disabled to clear it, or re-enabling later will reactivate it.", [ { label: "Enable deployment-wide review-comment consent", value: "true" }, { label: "Require each repository's administrator to start the first run", value: "false" }, diff --git a/infrastructure/azure/post/index.ts b/infrastructure/azure/post/index.ts index 66eb20224..6fcf986ca 100644 --- a/infrastructure/azure/post/index.ts +++ b/infrastructure/azure/post/index.ts @@ -634,7 +634,7 @@ export async function postSetupAzure( ? "GitHub sign-in is enabled. Verify the App connection, administrator enrollment, OAuth callback and signed webhooks separately." : action === "sign-in" ? "Setup access is available. GitHub sign-in remains dependent on the configured App credentials." - : "Learning consent was saved. Connect or reconnect Copilot in /settings/copilot to apply it." + : "Learning consent was saved. Connect or reconnect Copilot in /settings/copilot to record the administrator's consent; reconnect while the setting is off to clear it." const setupUrl = action === "sign-in" || action === "github" ? `${publicOrigin}/settings/github/setup` : "" return `${config.name}: ${action === "restart" ? "active Hub revision restarted" : "post-setup configuration applied"} using the unchanged deployed image.\n${setupUrl}\n${result}${bootstrapFile ? `\nBootstrap secret saved privately: ${bootstrapFile}. Escrow it before removing this local copy.` : ""}` } catch (error) { From 3826fecacc66c5786c36d288cf92d7fe6662acbd Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 13:21:01 -0800 Subject: [PATCH 06/32] fix(hub): add timestamps to agent tables Keep the new agent tables consistent with Hub schema conventions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/schema/agent-authorization.prisma | 4 ++++ hub/schema/agent-client.prisma | 1 + hub/schema/agent-connection.prisma | 1 + .../migrations/20261223170000_agent_connections/migration.sql | 4 ++++ 4 files changed, 10 insertions(+) diff --git a/hub/schema/agent-authorization.prisma b/hub/schema/agent-authorization.prisma index 26aa0f134..d6fa138fe 100644 --- a/hub/schema/agent-authorization.prisma +++ b/hub/schema/agent-authorization.prisma @@ -17,6 +17,10 @@ model AgentAuthorization { approvedAt DateTime? @map("approved_at") @db.Timestamptz(3) consumedAt DateTime? @map("consumed_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([clientId]) @@index([sessionId]) @@index([expiresAt]) diff --git a/hub/schema/agent-client.prisma b/hub/schema/agent-client.prisma index 06b3164a4..4ac73127a 100644 --- a/hub/schema/agent-client.prisma +++ b/hub/schema/agent-client.prisma @@ -12,6 +12,7 @@ model AgentClient { // Timestamp columns createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) @@map("agent_clients") } diff --git a/hub/schema/agent-connection.prisma b/hub/schema/agent-connection.prisma index 7a40fbde8..adf899abc 100644 --- a/hub/schema/agent-connection.prisma +++ b/hub/schema/agent-connection.prisma @@ -23,6 +23,7 @@ model AgentConnection { // Timestamp columns createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) @@index([clientId]) @@index([externalIdentityId]) diff --git a/hub/schema/migrations/20261223170000_agent_connections/migration.sql b/hub/schema/migrations/20261223170000_agent_connections/migration.sql index e74b176cb..c65a0648b 100644 --- a/hub/schema/migrations/20261223170000_agent_connections/migration.sql +++ b/hub/schema/migrations/20261223170000_agent_connections/migration.sql @@ -10,6 +10,8 @@ CREATE TABLE "agent_authorizations" ( "expires_at" TIMESTAMPTZ(3) NOT NULL, "approved_at" TIMESTAMPTZ(3), "consumed_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT "agent_authorizations_pkey" PRIMARY KEY ("id") ); @@ -20,6 +22,7 @@ CREATE TABLE "agent_clients" ( "name" VARCHAR(200) NOT NULL, "redirect_uris" TEXT[], "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT "agent_clients_pkey" PRIMARY KEY ("id") ); @@ -39,6 +42,7 @@ CREATE TABLE "agent_connections" ( "last_used_at" TIMESTAMPTZ(3), "revoked_at" TIMESTAMPTZ(3), "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT "agent_connections_pkey" PRIMARY KEY ("id") ); From 687b81bb1c91dec5f5ec4eb6c470f15fcd4e57af Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 13:47:42 -0800 Subject: [PATCH 07/32] fix(hub): harden Learning MCP inputs and errors Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../create-learning-mcp-backend/index.test.ts | 129 ++++++++++++++---- .../create-learning-mcp-backend/index.ts | 22 +-- 2 files changed, 114 insertions(+), 37 deletions(-) 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 f8e511c6f..96d5c660d 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 @@ -11,13 +11,14 @@ vi.mock("../../../integrations/learning/run-learning-command/index.ts", () => ({ runLearningCommand, })) -it("keeps server details out of what agents see when the store fails", async () => { - const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) - onTestFinished(() => rm(root, { recursive: true, force: true })) - runLearningCommand.mockRejectedValueOnce( - new LearningCommandError("storage_corrupt", `The store at ${root} is damaged.`), - ) - const backend = createLearningMcpBackend({ +function createBackend( + root: string, + toAgentError: (code: string, message: string) => Error = (code, message) => + new Error(`${code}: ${message}`), + serialize: (operation: (signal: AbortSignal) => Promise) => Promise = (operation) => + operation(new AbortController().signal), +) { + return createLearningMcpBackend({ confirmAccess: () => Promise.resolve(true), connectionId: "connection", learning: { @@ -30,13 +31,81 @@ it("keeps server details out of what agents see when the store fails", async () }, learningsUrl: "https://hub.example/learnings", repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, - serialize: (operation) => operation(new AbortController().signal), - toAgentError: (code, message) => new Error(`${code}: ${message}`), + serialize, + toAgentError, }) +} + +async function expectSafeLearningErrorMapping(code: string) { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const toAgentError = vi.fn( + (mappedCode: string, message: string) => new Error(`${mappedCode}: ${message}`), + ) + runLearningCommand.mockRejectedValueOnce(new LearningCommandError(code, "Safe details.")) + const backend = createBackend(root, toAgentError) + + await expect(backend.listLearnings({})).rejects.toThrow(`${code}: Safe details.`) + expect(toAgentError).toHaveBeenCalledWith(code, "Safe details.") +} + +it("keeps server details out of what agents see when the store fails", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockRejectedValueOnce( + new LearningCommandError("storage_corrupt", `The store at ${root} is damaged.`), + ) + const toAgentError = vi.fn((code: string, message: string) => new Error(`${code}: ${message}`)) + const backend = createBackend(root, toAgentError) const failure = backend.listLearnings({}) - await expect(failure).rejects.toBeInstanceOf(LearningCommandError) + await expect(failure).rejects.toThrow("internal_error: Learning command failed.") + expect(toAgentError).toHaveBeenCalledWith("internal_error", "Learning command failed.") +}) + +it("maps unknown learning errors rejected before serialization runs the command", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const toAgentError = vi.fn((code: string, message: string) => new Error(`${code}: ${message}`)) + function serialize(operation: (signal: AbortSignal) => Promise): Promise { + void operation + return Promise.reject( + new LearningCommandError("storage_corrupt", `The store at ${root} is damaged.`), + ) + } + runLearningCommand.mockClear() + const backend = createBackend(root, toAgentError, serialize) + + await expect(backend.listLearnings({})).rejects.toThrow( + "internal_error: Learning command failed.", + ) + expect(toAgentError).toHaveBeenCalledWith("internal_error", "Learning command failed.") + expect(runLearningCommand).not.toHaveBeenCalled() +}) + +it("preserves the conflict learning error mapping", async () => { + await expectSafeLearningErrorMapping("conflict") +}) + +it("preserves the invalid-input learning error mapping", async () => { + await expectSafeLearningErrorMapping("invalid_input") +}) + +it("preserves the invalid-transition learning error mapping", async () => { + await expectSafeLearningErrorMapping("invalid_transition") +}) + +it("preserves the inactive-grant learning error mapping", async () => { + await expectSafeLearningErrorMapping("grant_inactive") +}) + +it("preserves the not-found learning error mapping", async () => { + await expectSafeLearningErrorMapping("not_found") +}) + +it("preserves the unsupported learning error mapping", async () => { + await expectSafeLearningErrorMapping("unsupported") }) it("passes the task through a private file and session values as data", async () => { @@ -101,32 +170,34 @@ it("withholds guidance when the connection loses access while the command runs", it("withholds the text of a learning no one has accepted", async () => { const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) onTestFinished(() => rm(root, { recursive: true, force: true })) + const id = "mem_0123456789abcdef01234567" runLearningCommand.mockResolvedValueOnce({ - record: { id: "memory-1", state: "proposed", text: "Unreviewed idea." }, + record: { id, state: "proposed", text: "Unreviewed idea." }, status: { recallEligible: false }, withheld: false, }) - 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 }, - serialize: (operation) => operation(new AbortController().signal), - toAgentError: (code, message) => new Error(`${code}: ${message}`), - }) + const backend = createBackend(root) - const learning = await backend.getLearning({ id: "memory-1" }) + const learning = await backend.getLearning({ id }) expect(JSON.stringify(learning)).not.toContain("Unreviewed idea.") - expect(learning).toMatchObject({ id: "memory-1", state: "proposed", withheld: true }) + expect(learning).toMatchObject({ id, state: "proposed", withheld: true }) + expect(runLearningCommand.mock.calls.at(-1)![0]).toEqual( + expect.arrayContaining(["show", id, "--purpose", "instruction"]), + ) +}) + +it("rejects an option-like learning ID before invoking the CLI", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockClear() + const backend = createBackend(root) + + await expect(backend.getLearning({ id: "--help" })).rejects.toThrow( + "invalid_input: The learning ID is invalid.", + ) + + expect(runLearningCommand).not.toHaveBeenCalled() }) it("gives no guidance for a repository without a learning store", async () => { 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 3292b0183..eb19deddb 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 @@ -15,6 +15,7 @@ const agentErrorCodes = new Set([ "not_found", "unsupported", ]) +const LEARNING_ID = /^mem_[0-9a-f]{24}$/ interface LearningSettings { applicationRoot?: string @@ -65,6 +66,16 @@ export function createLearningMcpBackend(input: { const { learning, repository, toAgentError } = input const actor = `agent:hub-connection-${input.connectionId}` + // Preserve public codes but hide internal LearningCommandError details. + function safeLearningCommandError(error: unknown) { + if (!(error instanceof LearningCommandError)) return error + const safeCode = agentErrorCodes.has(error.code) + return toAgentError( + safeCode ? error.code : "internal_error", + safeCode ? error.message : "Learning command failed.", + ) + } + async function storeDirectory() { const applicationRoot = learning.applicationRoot ?? process.cwd() const directory = await validatePrivateStorageRoot( @@ -118,11 +129,7 @@ export function createLearningMcpBackend(input: { throw toAgentError("access_denied", "This agent connection no longer has access.") return result } catch (error) { - // These codes describe the agent's own request. Other failures can name server - // paths or storage, so they reach the agent only as a plain message. - if (error instanceof LearningCommandError && agentErrorCodes.has(error.code)) - throw toAgentError(error.code, error.message) - throw error + throw safeLearningCommandError(error) } } @@ -130,9 +137,7 @@ export function createLearningMcpBackend(input: { try { return await input.serialize((signal) => runCommand(directory, arguments_, signal)) } catch (error) { - if (error instanceof LearningCommandError && agentErrorCodes.has(error.code)) - throw toAgentError(error.code, error.message) - throw error + throw safeLearningCommandError(error) } } @@ -247,6 +252,7 @@ export function createLearningMcpBackend(input: { }, async getLearning({ id }: { id: string }) { + if (!LEARNING_ID.test(id)) throw toAgentError("invalid_input", "The learning ID is invalid.") const directory = await storeDirectory() if (!directory) throw toAgentError("not_found", `Learning ${id} was not found.`) const item = (await run(directory, [ From 682ce622f92082b9b907d173ec42da28d9be5c1f Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 14:55:02 -0800 Subject: [PATCH 08/32] fix(hub): bind agent access and isolate note processing Tie agent tokens to the approving session and bound OAuth registrations. Accept only Pick & Polish notes through Hub MCP and keep their scheduled work separate from review-comment consent. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/schema/agent-connection.prisma | 3 + hub/schema/hub-session.prisma | 17 +- hub/schema/learning-run.prisma | 43 ++-- .../migration.sql | 7 + .../migration.sql | 14 ++ .../migration.sql | 4 + .../pick-and-polish-note-receipt.prisma | 13 + hub/schema/repository.prisma | 49 ++-- .../create-agent-connections/index.ts | 1 + .../create-learning-mcp-backend/index.test.ts | 57 ++++- .../create-learning-mcp-backend/index.ts | 84 ++++--- .../process-learning-run/index.test.ts | 88 +++++++ .../learning/process-learning-run/index.ts | 238 ++++++++++-------- .../schedule-learning-runs/index.test.ts | 34 ++- .../learning/schedule-learning-runs/index.ts | 32 +-- .../learning/load-learning-mcp/index.ts | 10 +- .../mcp/agent-oauth-provider/index.ts | 12 +- .../mcp/agent-oauth-provider/types.ts | 6 +- .../with-learning-execution-lock/errors.ts | 6 + .../with-learning-execution-lock/index.ts | 3 +- .../create-agent-client/index.ts | 26 +- .../create-agent-connection/index.ts | 2 +- .../list-agent-connections/index.ts | 7 +- .../rotate-agent-connection/index.ts | 1 + .../touch-agent-connection/index.ts | 8 +- .../create-learning-run/index.db.test.ts | 25 ++ .../create-learning-run/index.ts | 9 +- .../index.db.test.ts | 69 ++++- .../list-due-learning-repositories/index.ts | 162 ++++++++---- .../index.db.test.ts | 53 ++++ .../index.ts | 21 +- .../client-registration.db.test.ts | 86 +++++++ .../routes/agent-connections/index.db.test.ts | 151 +++++++++-- hub/server/routes/agent-connections/index.ts | 37 +-- hub/vite.config.ts | 11 +- packages/learning/mcp.d.mts | 13 +- packages/learning/src/mcp.mjs | 114 +++++---- packages/learning/test/mcp.test.mjs | 113 ++++++++- 38 files changed, 1239 insertions(+), 390 deletions(-) create mode 100644 hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql create mode 100644 hub/schema/migrations/20261223172000_learning_run_sources/migration.sql create mode 100644 hub/schema/pick-and-polish-note-receipt.prisma create mode 100644 hub/server/integrations/postgres/with-learning-execution-lock/errors.ts create mode 100644 hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts create mode 100644 hub/server/routes/agent-connections/client-registration.db.test.ts diff --git a/hub/schema/agent-connection.prisma b/hub/schema/agent-connection.prisma index adf899abc..4deb8662e 100644 --- a/hub/schema/agent-connection.prisma +++ b/hub/schema/agent-connection.prisma @@ -2,12 +2,14 @@ model AgentConnection { // ID columns id String @id @default(uuid()) @db.Uuid clientId String @map("client_id") @db.Uuid + sessionId String @map("session_id") @db.Uuid membershipId String @map("membership_id") @db.Uuid externalIdentityId String @map("external_identity_id") @db.Uuid providerRevisionId String @map("provider_revision_id") @db.Uuid // Relations client AgentClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + session HubSession @relation(fields: [sessionId], references: [id], onDelete: Cascade) membership Membership @relation(fields: [membershipId], references: [id], onDelete: Cascade) externalIdentity ExternalIdentity @relation(fields: [externalIdentityId], references: [id], onDelete: Cascade) providerRevision AuthenticationProviderRevision @relation(fields: [providerRevisionId], references: [id], onDelete: Cascade) @@ -26,6 +28,7 @@ model AgentConnection { updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) @@index([clientId]) + @@index([sessionId]) @@index([externalIdentityId]) @@index([providerRevisionId]) @@index([membershipId, externalIdentityId, createdAt]) diff --git a/hub/schema/hub-session.prisma b/hub/schema/hub-session.prisma index 1e385f804..088846e6d 100644 --- a/hub/schema/hub-session.prisma +++ b/hub/schema/hub-session.prisma @@ -1,17 +1,18 @@ model HubSession { // ID columns - id String @id @default(uuid()) @db.Uuid - membershipId String @map("membership_id") @db.Uuid + id String @id @default(uuid()) @db.Uuid + membershipId String @map("membership_id") @db.Uuid externalIdentityId String? @map("external_identity_id") @db.Uuid providerRevisionId String? @map("provider_revision_id") @db.Uuid // Relations - membership Membership @relation(fields: [membershipId], references: [id], onDelete: Restrict) - externalIdentity ExternalIdentity? @relation(fields: [externalIdentityId], references: [id], onDelete: Restrict) - providerRevision AuthenticationProviderRevision? @relation(fields: [providerRevisionId], references: [id], onDelete: Restrict) - sensitiveAuthorizations SensitiveAuthorization[] - canvasPairings CanvasPairing[] - agentAuthorizations AgentAuthorization[] + membership Membership @relation(fields: [membershipId], references: [id], onDelete: Restrict) + externalIdentity ExternalIdentity? @relation(fields: [externalIdentityId], references: [id], onDelete: Restrict) + providerRevision AuthenticationProviderRevision? @relation(fields: [providerRevisionId], references: [id], onDelete: Restrict) + sensitiveAuthorizations SensitiveAuthorization[] + canvasPairings CanvasPairing[] + agentAuthorizations AgentAuthorization[] + agentConnections AgentConnection[] analyticsDestinationAuthorization AnalyticsDestinationAuthorization? // Attribute columns diff --git a/hub/schema/learning-run.prisma b/hub/schema/learning-run.prisma index 8e9c7d63f..9410c70c5 100644 --- a/hub/schema/learning-run.prisma +++ b/hub/schema/learning-run.prisma @@ -1,32 +1,33 @@ model LearningRun { // ID columns - id String @id @default(uuid()) @db.Uuid - repositoryId String @map("repository_id") @db.Uuid - requestedById String? @map("requested_by_id") @db.Uuid + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + requestedById String? @map("requested_by_id") @db.Uuid requestedByMembershipId String? @map("requested_by_membership_id") @db.Uuid - number Int @unique @default(autoincrement()) + number Int @unique @default(autoincrement()) // Relations - repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) - requestedBy User? @relation(fields: [requestedById], references: [id], onDelete: SetNull) + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + requestedBy User? @relation(fields: [requestedById], references: [id], onDelete: SetNull) requestedByMembership Membership? @relation(fields: [requestedByMembershipId], references: [id], onDelete: SetNull) // Attribute columns - scheduled Boolean @default(false) - state LearningRunState @default(QUEUED) - commentsConsidered Int @default(0) @map("comments_considered") - commentsLabeled Int @default(0) @map("comments_labeled") - commentsRemaining Int @default(0) @map("comments_remaining") - suggestions Int @default(0) - suggestionsRemaining Int @default(0) @map("suggestions_remaining") - copilotRequests Int @default(0) @map("copilot_requests") - aiCredits Decimal @default(0) @map("ai_credits") @db.Decimal(20, 9) - snapshotDigest String @map("snapshot_digest") @db.VarChar(71) - reviewActivitySnapshot Json? @map("review_activity_snapshot") - failureCode String? @map("failure_code") @db.VarChar(60) - failureSummary String? @map("failure_summary") @db.VarChar(1000) - startedAt DateTime? @map("started_at") @db.Timestamptz(3) - finishedAt DateTime? @map("finished_at") @db.Timestamptz(3) + scheduled Boolean @default(false) + reviewCommentsDue Boolean @default(true) @map("review_comments_due") + state LearningRunState @default(QUEUED) + commentsConsidered Int @default(0) @map("comments_considered") + commentsLabeled Int @default(0) @map("comments_labeled") + commentsRemaining Int @default(0) @map("comments_remaining") + suggestions Int @default(0) + suggestionsRemaining Int @default(0) @map("suggestions_remaining") + copilotRequests Int @default(0) @map("copilot_requests") + aiCredits Decimal @default(0) @map("ai_credits") @db.Decimal(20, 9) + snapshotDigest String? @map("snapshot_digest") @db.VarChar(71) + reviewActivitySnapshot Json? @map("review_activity_snapshot") + failureCode String? @map("failure_code") @db.VarChar(60) + failureSummary String? @map("failure_summary") @db.VarChar(1000) + startedAt DateTime? @map("started_at") @db.Timestamptz(3) + finishedAt DateTime? @map("finished_at") @db.Timestamptz(3) // Timestamp columns createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) diff --git a/hub/schema/migrations/20261223170000_agent_connections/migration.sql b/hub/schema/migrations/20261223170000_agent_connections/migration.sql index c65a0648b..e64465848 100644 --- a/hub/schema/migrations/20261223170000_agent_connections/migration.sql +++ b/hub/schema/migrations/20261223170000_agent_connections/migration.sql @@ -31,6 +31,7 @@ CREATE TABLE "agent_clients" ( CREATE TABLE "agent_connections" ( "id" UUID NOT NULL, "client_id" UUID NOT NULL, + "session_id" UUID NOT NULL, "membership_id" UUID NOT NULL, "external_identity_id" UUID NOT NULL, "provider_revision_id" UUID NOT NULL, @@ -68,6 +69,9 @@ CREATE UNIQUE INDEX "agent_connections_refresh_digest_key" ON "agent_connections -- CreateIndex CREATE INDEX "agent_connections_client_id_idx" ON "agent_connections"("client_id"); +-- CreateIndex +CREATE INDEX "agent_connections_session_id_idx" ON "agent_connections"("session_id"); + -- CreateIndex CREATE INDEX "agent_connections_external_identity_id_idx" ON "agent_connections"("external_identity_id"); @@ -86,6 +90,9 @@ ALTER TABLE "agent_authorizations" ADD CONSTRAINT "agent_authorizations_session_ -- AddForeignKey ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "agent_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE; +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "hub_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + -- AddForeignKey ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_membership_id_fkey" FOREIGN KEY ("membership_id") REFERENCES "memberships"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql b/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql new file mode 100644 index 000000000..e9a5b0f94 --- /dev/null +++ b/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql @@ -0,0 +1,14 @@ +-- CreateTable +CREATE TABLE "pick_and_polish_note_receipts" ( + "repository_id" UUID NOT NULL, + "receipt_id" VARCHAR(64) NOT NULL, + "received_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "pick_and_polish_note_receipts_pkey" PRIMARY KEY ("repository_id", "receipt_id") +); + +-- CreateIndex +CREATE INDEX "pick_and_polish_note_receipts_repository_id_received_at_idx" ON "pick_and_polish_note_receipts"("repository_id", "received_at"); + +-- AddForeignKey +ALTER TABLE "pick_and_polish_note_receipts" ADD CONSTRAINT "pick_and_polish_note_receipts_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/migrations/20261223172000_learning_run_sources/migration.sql b/hub/schema/migrations/20261223172000_learning_run_sources/migration.sql new file mode 100644 index 000000000..35871c746 --- /dev/null +++ b/hub/schema/migrations/20261223172000_learning_run_sources/migration.sql @@ -0,0 +1,4 @@ +-- AlterTable +ALTER TABLE "learning_runs" +ADD COLUMN "review_comments_due" BOOLEAN NOT NULL DEFAULT true, +ALTER COLUMN "snapshot_digest" DROP NOT NULL; diff --git a/hub/schema/pick-and-polish-note-receipt.prisma b/hub/schema/pick-and-polish-note-receipt.prisma new file mode 100644 index 000000000..3588b9469 --- /dev/null +++ b/hub/schema/pick-and-polish-note-receipt.prisma @@ -0,0 +1,13 @@ +model PickAndPolishNoteReceipt { + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + repositoryId String @map("repository_id") @db.Uuid + receiptId String @map("receipt_id") @db.VarChar(64) + receivedAt DateTime @default(now()) @map("received_at") @db.Timestamptz(3) + + @@id([repositoryId, receiptId]) + @@index([repositoryId, receivedAt]) + @@map("pick_and_polish_note_receipts") +} diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index 007640cad..d9dd55e42 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -1,32 +1,33 @@ model Repository { // ID columns - id String @id @default(uuid()) @db.Uuid - canvasId Int @unique @default(autoincrement()) @map("canvas_id") + id String @id @default(uuid()) @db.Uuid + canvasId Int @unique @default(autoincrement()) @map("canvas_id") // Relations - learningRuns LearningRun[] - learningDecisionOperations LearningDecisionOperation[] - decisionModelConfiguration DecisionModelConfiguration? - decisionReviewSnapshot DecisionReviewSnapshot? - decisionTrainingJobs DecisionTrainingJob[] - decisionCandidates DecisionCandidate[] - decisionModelPromotions DecisionModelPromotion[] - decisionBuildEvaluations DecisionBuildEvaluation[] - decisionAgentEvaluations DecisionAgentEvaluation[] - decisionRuntimeCopies DecisionRuntimeCopy[] - decisionRuntimeDeletions DecisionRuntimeDeletion[] - prototypes Prototype[] - branchHeadObservations BranchHeadObservation[] - reviewThreads ReviewThread[] - accessGrants RepositoryAccessGrant[] - securityAudits SecurityAudit[] - canvasPairings CanvasPairing[] - canvasGrants CanvasGrant[] - analyticsEvents AnalyticsEvent[] - analyticsDestinations AnalyticsDestination[] - analyticsState AnalyticsRepositoryState? + learningRuns LearningRun[] + learningDecisionOperations LearningDecisionOperation[] + decisionModelConfiguration DecisionModelConfiguration? + decisionReviewSnapshot DecisionReviewSnapshot? + decisionTrainingJobs DecisionTrainingJob[] + decisionCandidates DecisionCandidate[] + decisionModelPromotions DecisionModelPromotion[] + decisionBuildEvaluations DecisionBuildEvaluation[] + decisionAgentEvaluations DecisionAgentEvaluation[] + decisionRuntimeCopies DecisionRuntimeCopy[] + decisionRuntimeDeletions DecisionRuntimeDeletion[] + prototypes Prototype[] + branchHeadObservations BranchHeadObservation[] + reviewThreads ReviewThread[] + accessGrants RepositoryAccessGrant[] + securityAudits SecurityAudit[] + canvasPairings CanvasPairing[] + canvasGrants CanvasGrant[] + analyticsEvents AnalyticsEvent[] + analyticsDestinations AnalyticsDestination[] + analyticsState AnalyticsRepositoryState? analyticsDestinationAuthorizations AnalyticsDestinationAuthorization[] - learningSetting RepositoryLearningSetting? + learningSetting RepositoryLearningSetting? + pickAndPolishNoteReceipts PickAndPolishNoteReceipt[] // Attribute columns githubRepositoryId BigInt? @unique @map("github_repository_id") diff --git a/hub/server/domains/agent-connections/create-agent-connections/index.ts b/hub/server/domains/agent-connections/create-agent-connections/index.ts index 458255bb2..56d8c53c4 100644 --- a/hub/server/domains/agent-connections/create-agent-connections/index.ts +++ b/hub/server/domains/agent-connections/create-agent-connections/index.ts @@ -138,6 +138,7 @@ export function createAgentConnections(database: PrismaClient) { const tokens = issueTokens() await createAgentConnection(transaction, { clientId, + sessionId: session.id, membershipId: viewer.membershipId, externalIdentityId: viewer.externalIdentityId, providerRevisionId: viewer.providerRevisionId, 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 96d5c660d..f664c571f 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 @@ -4,6 +4,7 @@ import { join } from "node:path" import { expect, it, onTestFinished, vi } from "vitest" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { LearningExecutionBusyError } from "../../../integrations/postgres/with-learning-execution-lock/errors.ts" import { createLearningMcpBackend } from "." const runLearningCommand = vi.hoisted(() => vi.fn()) @@ -84,6 +85,19 @@ it("maps unknown learning errors rejected before serialization runs the command" expect(runLearningCommand).not.toHaveBeenCalled() }) +it("returns a retryable agent error when learning work is already running", async () => { + const backend = createBackend("/private/learning", undefined, () => + Promise.reject(new LearningExecutionBusyError()), + ) + + await expect( + submitSession(backend, { + sessionId: "session-1", + pickAndPolishNotes: [{ localId: "note-1", body: "Keep the labels visible." }], + }), + ).rejects.toThrow("busy: Another learning operation is still running. Try again.") +}) + it("preserves the conflict learning error mapping", async () => { await expectSafeLearningErrorMapping("conflict") }) @@ -187,6 +201,23 @@ it("withholds the text of a learning no one has accepted", async () => { ) }) +it("returns flat metadata without the text of an accepted learning", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const id = "mem_0123456789abcdef01234567" + runLearningCommand.mockResolvedValueOnce({ + record: { id, state: "accepted", text: "Private learning text." }, + status: { recallEligible: true }, + withheld: false, + }) + const backend = createBackend(root) + + const learning = await backend.getLearning({ id }) + + expect(learning).toEqual({ id, state: "accepted", recalled: true, withheld: false }) + expect(JSON.stringify(learning)).not.toContain("Private learning text.") +}) + it("rejects an option-like learning ID before invoking the CLI", async () => { const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) onTestFinished(() => rm(root, { recursive: true, force: true })) @@ -234,7 +265,7 @@ function submitSession(backend: ReturnType, sub function createSessionBackend( root: string, - notes: { grantId(): Promise; received(): Promise }, + notes: { grantId(): Promise; received(receiptId: string): Promise }, events: string[] = [], ) { const input = { @@ -270,9 +301,9 @@ function createSessionBackend( events.push("grant") return notes.grantId() }, - received: async () => { + received: async (receiptId: string) => { events.push("received") - await notes.received() + await notes.received(receiptId) }, } return createLearningMcpBackend(input) @@ -363,12 +394,12 @@ it("imports only supplied Pick & Polish notes as the connected GitHub user", asy ]) }) -it("does not mark notes received when the import adds no episodes or events", async () => { +it("retries the receipt after an idempotent notes import", async () => { const root = await createSessionTestRoot() - const received = vi.fn(async () => {}) - runLearningCommand.mockImplementationOnce(() => - Promise.resolve({ addedEpisodes: 0, addedEvents: 0 }), - ) + const received = vi.fn<(receiptId: string) => Promise>().mockResolvedValue(undefined) + runLearningCommand + .mockImplementationOnce(() => Promise.resolve({ addedEpisodes: 1, addedEvents: 0 })) + .mockImplementationOnce(() => Promise.resolve({ addedEpisodes: 0, addedEvents: 0 })) const backend = createSessionBackend(root, { grantId: () => Promise.resolve("pick-polish-grant"), received, @@ -379,15 +410,19 @@ it("does not mark notes received when the import adds no episodes or events", as thread: { messages: [] }, } - await submitSession(backend, { + const submission = { sessionId: "session-1", task: "Build a checkout form.", user: "github:untrusted-agent-input", messages: [], pickAndPolishNotes: [note], - }) + } + await submitSession(backend, submission) + await submitSession(backend, submission) - expect(received).not.toHaveBeenCalled() + expect(received).toHaveBeenCalledTimes(2) + expect(received.mock.calls[0]?.[0]).toMatch(/^[a-f0-9]{64}$/) + expect(received.mock.calls[1]?.[0]).toBe(received.mock.calls[0]?.[0]) }) it("stores no notes and reports an inactive grant without note consent", async () => { 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 eb19deddb..5b389c393 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 @@ -1,9 +1,11 @@ +import { createHash } from "node:crypto" import { access, mkdtemp, rm, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { join, resolve } from "node:path" import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { LearningExecutionBusyError } from "../../../integrations/postgres/with-learning-execution-lock/errors.ts" import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" import { learningStoreArguments } from "../../learning/learning-store-arguments/index.ts" @@ -56,11 +58,11 @@ export function createLearningMcpBackend(input: { learningsUrl: string notes?: { grantId(): Promise - received(): Promise + received(receiptId: string): Promise } repository: { id: string; githubRepositoryId: bigint } serialize(operation: (signal: AbortSignal) => Promise): Promise - toAgentError: (code: string, message: string) => Error + toAgentError: (code: string, message: string, safeForAgent?: boolean) => Error user?: string }) { const { learning, repository, toAgentError } = input @@ -76,6 +78,12 @@ export function createLearningMcpBackend(input: { ) } + function safeLearningError(error: unknown) { + if (error instanceof LearningExecutionBusyError) + return toAgentError("busy", "Another learning operation is still running. Try again.", true) + return safeLearningCommandError(error) + } + async function storeDirectory() { const applicationRoot = learning.applicationRoot ?? process.cwd() const directory = await validatePrivateStorageRoot( @@ -137,7 +145,7 @@ export function createLearningMcpBackend(input: { try { return await input.serialize((signal) => runCommand(directory, arguments_, signal)) } catch (error) { - throw safeLearningCommandError(error) + throw safeLearningError(error) } } @@ -193,6 +201,7 @@ export function createLearningMcpBackend(input: { throw toAgentError( "unsupported", "Hub does not accept screenshots yet. Report usage without them.", + true, ) const directory = await storeDirectory() if (!directory) @@ -213,31 +222,37 @@ export function createLearningMcpBackend(input: { } const notesConsent = input.notes - return input.serialize(async (signal) => { - const grantId = (await notesConsent?.grantId()) ?? null - if (!grantId) - throw toAgentError( - "grant_inactive", - `This repository doesn't let Hub learn from Pick & Polish notes, so nothing was stored. A repository administrator can turn on "Learn from Pick & Polish notes" in Learnings settings at ${input.learningsUrl}.`, - ) + try { + return await input.serialize(async (signal) => { + const grantId = (await notesConsent?.grantId()) ?? null + if (!grantId) + throw toAgentError( + "grant_inactive", + `This repository doesn't let Hub learn from Pick & Polish notes, so nothing was stored. A repository administrator can turn on "Learn from Pick & Polish notes" in Learnings settings at ${input.learningsUrl}.`, + true, + ) - const directory = await storeDirectory() - if (!directory) - throw toAgentError("not_found", "This repository has no learning store yet.") - const kept = { - sessionId: session.sessionId, - ...(input.user ? { user: `github:${input.user}` } : {}), - messages: [], - pickAndPolishNotes: notes, - } - const result = await withPrivateFile(JSON.stringify(kept), (file) => - runCommand(directory, ["import", "agent-session", file, "--grant", grantId], signal), - ) - const imported = result as { addedEpisodes?: number; addedEvents?: number } - if ((imported.addedEpisodes ?? 0) + (imported.addedEvents ?? 0) > 0) - await notesConsent?.received() - return result - }) + const directory = await storeDirectory() + if (!directory) + throw toAgentError("not_found", "This repository has no learning store yet.") + const kept = { + sessionId: session.sessionId, + ...(input.user ? { user: `github:${input.user}` } : {}), + messages: [], + pickAndPolishNotes: notes, + } + const content = JSON.stringify(kept) + if (content === undefined) throw new Error("Could not serialize Pick & Polish notes.") + const receiptId = createHash("sha256").update(content).digest("hex") + const result = await withPrivateFile(content, (file) => + runCommand(directory, ["import", "agent-session", file, "--grant", grantId], signal), + ) + await notesConsent?.received(receiptId) + return result + }) + } catch (error) { + throw safeLearningError(error) + } }, async listLearnings({ state }: { state?: string[] }) { @@ -262,12 +277,19 @@ export function createLearningMcpBackend(input: { "instruction", ])) as StoredLearning const { record } = item - if (record.state === "accepted" && !item.withheld && item.status.recallEligible) return item + const summary = { + id: record.id, + state: record.state, + recalled: item.status.recallEligible, + withheld: item.withheld, + } + if (record.state === "accepted" && !item.withheld && item.status.recallEligible) + return summary // A learning no one accepted is not guidance, so its text stays with people. - const summary = { id: record.id, state: record.state, withheld: true } - if (record.state !== "proposed") return summary + const withheld = { ...summary, withheld: true } + if (record.state !== "proposed") return withheld return { - ...summary, + ...withheld, decide: { note: "Only a person can decide. Ask a repository administrator to accept or reject it on the Hub Learnings page.", url: input.learningsUrl, diff --git a/hub/server/domains/learning/process-learning-run/index.test.ts b/hub/server/domains/learning/process-learning-run/index.test.ts index 68b69db0a..c7a5d5f67 100644 --- a/hub/server/domains/learning/process-learning-run/index.test.ts +++ b/hub/server/domains/learning/process-learning-run/index.test.ts @@ -14,6 +14,7 @@ function dependencies(overrides: Partial = {}) { id: "11111111-2222-4333-8444-555555555555", repositoryId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", snapshotDigest: "sha256:snapshot", + reviewCommentsDue: true, scheduled: false, state: "QUEUED", startedAt: new Date("2026-11-13T09:59:00Z"), @@ -104,6 +105,24 @@ function dependencies(overrides: Partial = {}) { } describe("processLearningRun()", () => { + it("processes scheduled notes without reading review comments or asking for their consent", async () => { + const deps = dependencies({ expectedScheduled: true }) + deps.run.scheduled = true + deps.run.requestedBy = null + deps.run.requestedByMembershipId = null + deps.run.snapshotDigest = null + deps.run.reviewCommentsDue = false + + await processLearningRun("11111111-2222-4333-8444-555555555555", deps) + + expect(deps.capture).not.toHaveBeenCalled() + expect(deps.reviewCommentConsent).not.toHaveBeenCalled() + expect(deps.commands.some((arguments_) => arguments_[0] === "grants")).toBe(false) + expect(deps.commands.some((arguments_) => arguments_[0] === "import")).toBe(false) + expect(deps.commands.some((arguments_) => arguments_[0] === "label")).toBe(true) + expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) + }) + it("runs for a Hub member with repository administrator authority", async () => { const deps = dependencies() @@ -703,6 +722,75 @@ describe("processLearningRun()", () => { }) }) + it("adopts a legacy repository-admin grant when deployment consent is off", async () => { + const repositoryId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" + const deps = dependencies({ + expectedScheduled: true, + reviewCommentConsent: vi.fn().mockResolvedValue({ + turnedOff: false, + hubAdministrator: null, + repositoryGrantId: null, + }), + runCommand: vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants" && arguments_[1] === "list") { + return Promise.resolve([ + { + grant: { + id: "legacy-repository-grant", + sources: ["hub_review_comments"], + purposes: ["review", "instruction"], + basis: "A repository administrator explicitly requested this learning run.", + grantedBy: { kind: "human", id: "github:mona" }, + }, + activePurposes: ["review", "instruction"], + expired: false, + }, + ]) + } + if (arguments_[0] === "import") return Promise.resolve({ complete: true, problems: [] }) + if (arguments_[0] === "label") { + return Promise.resolve({ + considered: 4, + labeled: 3, + remaining: 1, + usage: { requests: 2, nanoAiu: 2_500_000 }, + }) + } + return Promise.resolve({ + status: "complete", + proposals: [{ id: "proposal-1", updatedAt: "2026-11-13T10:00:00Z" }], + overBudget: 1, + }) + }), + }) + deps.run.scheduled = true + deps.run.requestedBy = null + deps.run.requestedByMembershipId = null + + await processLearningRun("11111111-2222-4333-8444-555555555555", deps) + + expect(deps.recordRepositoryReviewCommentGrant).toHaveBeenCalledWith( + repositoryId, + "legacy-repository-grant", + ) + expect( + vi + .mocked(deps.runCommand) + .mock.calls.some(([arguments_]) => arguments_[0] === "grants" && arguments_[1] === "add"), + ).toBe(false) + expect( + vi + .mocked(deps.runCommand) + .mock.calls.some( + ([arguments_]) => + arguments_[0] === "import" && + arguments_.includes("--grant") && + arguments_.includes("legacy-repository-grant"), + ), + ).toBe(true) + expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) + }) + it("reuses the repository grant established by an administrator's requested run", async () => { const deps = dependencies({ reviewCommentConsent: vi.fn().mockResolvedValue({ diff --git a/hub/server/domains/learning/process-learning-run/index.ts b/hub/server/domains/learning/process-learning-run/index.ts index 1636fdc97..d10fef496 100644 --- a/hub/server/domains/learning/process-learning-run/index.ts +++ b/hub/server/domains/learning/process-learning-run/index.ts @@ -16,6 +16,7 @@ const grantListSchema = z.array( id: z.string().min(1), sources: z.array(z.string()), purposes: z.array(z.string()).default([]), + basis: z.string().optional(), grantedBy: z.object({ kind: z.string(), id: z.string().min(1) }).loose(), }) .loose(), @@ -89,7 +90,8 @@ export async function processLearningRun( getRun(runId: string): Promise<{ id: string repositoryId: string - snapshotDigest: string + snapshotDigest: string | null + reviewCommentsDue: boolean startedAt: Date | null state: "QUEUED" | "RUNNING" | "SUCCEEDED" | "FAILED" scheduled: boolean @@ -180,10 +182,14 @@ export async function processLearningRun( } actor = `human:${requester}` } - const snapshot = await dependencies.capture(current.repositoryId) + const snapshot = current.reviewCommentsDue + ? await dependencies.capture(current.repositoryId) + : null if ( - snapshot.digest !== current.snapshotDigest && - snapshot.legacyDigest !== current.snapshotDigest + snapshot && + (!current.snapshotDigest || + (snapshot.digest !== current.snapshotDigest && + snapshot.legacyDigest !== current.snapshotDigest)) ) { throw new LearningCommandError( "snapshot_changed", @@ -191,111 +197,136 @@ export async function processLearningRun( ) } const store = await dependencies.prepare(current.repositoryId) - if (store.repositoryScope !== snapshot.repositoryScope) { + if (snapshot && store.repositoryScope !== snapshot.repositoryScope) { throw new LearningCommandError( "snapshot_changed", "The repository learning scope changed before this run started. Request another run.", ) } const common = learningStoreArguments(store) - const consent = await dependencies.reviewCommentConsent(current.repositoryId) - if (!consent.turnedOff) { - const grants = grantListSchema.parse( - await dependencies.runCommand(["grants", "list", ...common], { signal }), - ) - const sourceGrants = grants.filter((entry) => - entry.grant.sources.includes("hub_review_comments"), - ) - const humanSourceGrants = sourceGrants.filter( - (entry) => entry.grant.grantedBy.kind === "human", - ) - const consentedGrants = consent.hubAdministrator - ? humanSourceGrants - : humanSourceGrants.filter((entry) => entry.grant.id === consent.repositoryGrantId) - let grantIds = consentedGrants - .filter( - (entry) => - !entry.expired && - entry.activePurposes.includes("review") && - entry.activePurposes.includes("instruction"), + if (snapshot) { + const consent = await dependencies.reviewCommentConsent(current.repositoryId) + if (!consent.turnedOff) { + const grants = grantListSchema.parse( + await dependencies.runCommand(["grants", "list", ...common], { signal }), ) - .map((entry) => entry.grant.id) - if (grantIds.length === 0) { - if ( - !consent.hubAdministrator && - consentedGrants.some((entry) => - entry.grant.purposes.some( - (purpose) => purpose === "review" || purpose === "instruction", - ), - ) - ) { - throw new LearningCommandError( - "grant_inactive", - "Consent to use this repository's review comments ended.", + const sourceGrants = grants.filter((entry) => + entry.grant.sources.includes("hub_review_comments"), + ) + const humanSourceGrants = sourceGrants.filter( + (entry) => entry.grant.grantedBy.kind === "human", + ) + let consentedGrants = consent.hubAdministrator + ? humanSourceGrants + : humanSourceGrants.filter((entry) => entry.grant.id === consent.repositoryGrantId) + if (!consent.hubAdministrator && !consent.repositoryGrantId) { + const legacyGrants = humanSourceGrants.filter( + (entry) => + entry.grant.basis === + "A repository administrator explicitly requested this learning run." && + entry.grant.purposes.includes("review") && + entry.grant.purposes.includes("instruction"), ) + const legacyGrant = + legacyGrants.find( + (entry) => + !entry.expired && + entry.activePurposes.includes("review") && + entry.activePurposes.includes("instruction"), + ) ?? legacyGrants[0] + if (legacyGrant) { + await dependencies.recordRepositoryReviewCommentGrant( + current.repositoryId, + legacyGrant.grant.id, + ) + consentedGrants = [legacyGrant] + } } - const consenter = current.scheduled ? consent.hubAdministrator : actor - if (!consenter) { - throw new LearningCommandError( - "grant_required", - "A Hub administrator must reconnect Copilot, or a repository administrator must request the first learning run.", + let grantIds = consentedGrants + .filter( + (entry) => + !entry.expired && + entry.activePurposes.includes("review") && + entry.activePurposes.includes("instruction"), ) + .map((entry) => entry.grant.id) + if (grantIds.length === 0) { + if ( + !consent.hubAdministrator && + consentedGrants.some((entry) => + entry.grant.purposes.some( + (purpose) => purpose === "review" || purpose === "instruction", + ), + ) + ) { + throw new LearningCommandError( + "grant_inactive", + "Consent to use this repository's review comments ended.", + ) + } + const consenter = current.scheduled ? consent.hubAdministrator : actor + if (!consenter) { + throw new LearningCommandError( + "grant_required", + "A Hub administrator must reconnect Copilot, or a repository administrator must request the first learning run.", + ) + } + const grant = addedGrantSchema.parse( + await dependencies.runCommand( + [ + "grants", + "add", + "--purpose", + "review", + "--purpose", + "instruction", + "--source", + "hub_review_comments", + "--basis", + current.scheduled + ? "A Hub administrator agreed to learn from every repository's review comments when connecting Copilot." + : "A repository administrator explicitly requested this learning run.", + "--by", + consenter, + ...common, + ], + { signal }, + ), + ) + grantIds = [grant.id] + if (!current.scheduled) { + await dependencies.recordRepositoryReviewCommentGrant(current.repositoryId, grant.id) + } } - const grant = addedGrantSchema.parse( - await dependencies.runCommand( - [ - "grants", - "add", - "--purpose", - "review", - "--purpose", - "instruction", - "--source", - "hub_review_comments", - "--basis", - current.scheduled - ? "A Hub administrator agreed to learn from every repository's review comments when connecting Copilot." - : "A repository administrator explicitly requested this learning run.", - "--by", - consenter, - ...common, - ], - { signal }, - ), - ) - grantIds = [grant.id] - if (!current.scheduled) { - await dependencies.recordRepositoryReviewCommentGrant(current.repositoryId, grant.id) - } - } - const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-run-")) - try { - const collectionPath = resolve(temporary, "review-collection.json") - await writeFile(collectionPath, JSON.stringify(snapshot.collection), { mode: 0o600 }) - const imported = importSchema.parse( - await dependencies.runCommand( - [ - "import", - "hub-comments", - collectionPath, - ...grantIds.flatMap((grantId) => ["--grant", grantId]), - "--actor", - "system:replica-hub", - "--redact-deleted", - ...common, - ], - { signal }, - ), - ) - if (!imported.complete) { - throw new LearningCommandError( - "incomplete_collection", - `The repository review snapshot is incomplete: ${imported.problems.join(" ")}`, + const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-run-")) + try { + const collectionPath = resolve(temporary, "review-collection.json") + await writeFile(collectionPath, JSON.stringify(snapshot.collection), { mode: 0o600 }) + const imported = importSchema.parse( + await dependencies.runCommand( + [ + "import", + "hub-comments", + collectionPath, + ...grantIds.flatMap((grantId) => ["--grant", grantId]), + "--actor", + "system:replica-hub", + "--redact-deleted", + ...common, + ], + { signal }, + ), ) + if (!imported.complete) { + throw new LearningCommandError( + "incomplete_collection", + `The repository review snapshot is incomplete: ${imported.problems.join(" ")}`, + ) + } + } finally { + await rm(temporary, { recursive: true }) } - } finally { - await rm(temporary, { recursive: true }) } } @@ -303,21 +334,14 @@ export async function processLearningRun( if (!credential) { throw new LearningCommandError("copilot_not_connected", "Copilot is not connected.") } + const asOf = snapshot?.capturedAt ?? current.startedAt ?? dependencies.now() + const since = new Date(asOf.getTime() - 90 * 24 * 60 * 60 * 1_000).toISOString() let labeled: z.infer try { labeled = labelSchema.parse( await runWithoutRepositoryAuthorityLock(() => dependencies.runCommand( - [ - "label", - "--since", - new Date(snapshot.capturedAt.getTime() - 90 * 24 * 60 * 60 * 1000).toISOString(), - "--limit", - "400", - "--max-requests", - "10", - ...common, - ], + ["label", "--since", since, "--limit", "400", "--max-requests", "10", ...common], { ...credential, signal, timeoutMs: 30 * 60 * 1000 }, ), ), @@ -373,9 +397,9 @@ export async function processLearningRun( [ "consolidate", "--from", - new Date(snapshot.capturedAt.getTime() - 90 * 24 * 60 * 60 * 1000).toISOString(), + since, "--to", - snapshot.capturedAt.toISOString(), + asOf.toISOString(), "--actor", "system:replica-hub", "--max", diff --git a/hub/server/domains/learning/schedule-learning-runs/index.test.ts b/hub/server/domains/learning/schedule-learning-runs/index.test.ts index fe0fa0069..0fa5fb87b 100644 --- a/hub/server/domains/learning/schedule-learning-runs/index.test.ts +++ b/hub/server/domains/learning/schedule-learning-runs/index.test.ts @@ -12,12 +12,10 @@ function dependencies(overrides: Partial = {}): EnabledDepe automaticEnabled: true as const, copilotUsable: vi.fn().mockResolvedValue(true), deleteExpired: vi.fn().mockResolvedValue(undefined), - listDue: vi - .fn() - .mockResolvedValue([ - { id: "11111111-1111-4111-8111-111111111111" }, - { id: "22222222-2222-4222-8222-222222222222" }, - ]), + listDue: vi.fn().mockResolvedValue([ + { id: "11111111-1111-4111-8111-111111111111", reviewCommentsDue: true }, + { id: "22222222-2222-4222-8222-222222222222", reviewCommentsDue: true }, + ]), capture: vi.fn().mockImplementation((repositoryId: string) => Promise.resolve({ digest: `sha256:${repositoryId}`, @@ -81,6 +79,7 @@ describe("scheduleLearningRuns()", () => { expect(deps.create).toHaveBeenNthCalledWith(1, { repositoryId: "11111111-1111-4111-8111-111111111111", scheduled: true, + reviewCommentsDue: true, snapshotDigest: "sha256:11111111-1111-4111-8111-111111111111", reviewActivitySnapshot: { "11111111-1111-4111-8111-111111111111": 1 }, }) @@ -120,6 +119,7 @@ describe("scheduleLearningRuns()", () => { expect(deps.create).toHaveBeenCalledWith({ repositoryId: "22222222-2222-4222-8222-222222222222", scheduled: true, + reviewCommentsDue: true, snapshotDigest: "sha256:available", reviewActivitySnapshot: { available: 1 }, }) @@ -186,7 +186,10 @@ describe("scheduleLearningRuns()", () => { }) it("bounds each automatic dispatch while preserving repository order", async () => { - const repositories = Array.from({ length: 101 }, (_, index) => ({ id: `repository-${index}` })) + const repositories = Array.from({ length: 101 }, (_, index) => ({ + id: `repository-${index}`, + reviewCommentsDue: true, + })) const deps = dependencies({ listDue: vi.fn().mockResolvedValue(repositories), }) @@ -198,4 +201,21 @@ describe("scheduleLearningRuns()", () => { expect(deps.capture).toHaveBeenNthCalledWith(100, "repository-99") expect(deps.capture).not.toHaveBeenCalledWith("repository-100") }) + + it("schedules note-only work without capturing review comments", async () => { + const deps = dependencies({ + listDue: vi.fn().mockResolvedValue([{ id: "notes-only", reviewCommentsDue: false }]), + }) + + await expect(scheduleLearningRuns(deps)).resolves.toEqual({ scheduled: 1 }) + + expect(deps.capture).not.toHaveBeenCalled() + expect(deps.create).toHaveBeenCalledWith({ + repositoryId: "notes-only", + scheduled: true, + reviewCommentsDue: false, + snapshotDigest: null, + reviewActivitySnapshot: {}, + }) + }) }) diff --git a/hub/server/domains/learning/schedule-learning-runs/index.ts b/hub/server/domains/learning/schedule-learning-runs/index.ts index 6c3ca8afd..9f7b20316 100644 --- a/hub/server/domains/learning/schedule-learning-runs/index.ts +++ b/hub/server/domains/learning/schedule-learning-runs/index.ts @@ -12,14 +12,15 @@ type DisabledDependencies = BaseDependencies & { type EnabledDependencies = BaseDependencies & { automaticEnabled: true copilotUsable: () => Promise - listDue: () => Promise> + listDue: () => Promise> capture: ( repositoryId: string, ) => Promise<{ digest: string; reviewActivitySnapshot: Record } | null> create: (input: { repositoryId: string scheduled: true - snapshotDigest: string + reviewCommentsDue: boolean + snapshotDigest: string | null reviewActivitySnapshot: Record }) => Promise<{ run: { id: string }; created: boolean } | null> enqueue: (runId: string) => Promise @@ -41,25 +42,28 @@ export async function scheduleLearningRuns( let scheduled = 0 for (const repository of (await dependencies.listDue()).slice(0, automaticDispatchLimit)) { - let snapshot: Awaited> - try { - snapshot = await dependencies.capture(repository.id) - } catch (error) { - dependencies.reportRepositoryFailure({ - repositoryId: repository.id, - errorType: error instanceof Error ? error.name : "UnknownError", - }) - continue + let snapshot: Awaited> = null + if (repository.reviewCommentsDue) { + try { + snapshot = await dependencies.capture(repository.id) + } catch (error) { + dependencies.reportRepositoryFailure({ + repositoryId: repository.id, + errorType: error instanceof Error ? error.name : "UnknownError", + }) + continue + } } - if (!snapshot) continue + if (repository.reviewCommentsDue && !snapshot) continue let result: Awaited> try { result = await dependencies.create({ repositoryId: repository.id, scheduled: true, - snapshotDigest: snapshot.digest, - reviewActivitySnapshot: snapshot.reviewActivitySnapshot, + reviewCommentsDue: repository.reviewCommentsDue, + snapshotDigest: snapshot?.digest ?? null, + reviewActivitySnapshot: snapshot?.reviewActivitySnapshot ?? {}, }) } catch (error) { dependencies.reportRepositoryFailure({ diff --git a/hub/server/integrations/learning/load-learning-mcp/index.ts b/hub/server/integrations/learning/load-learning-mcp/index.ts index 138336c15..5bdfff79c 100644 --- a/hub/server/integrations/learning/load-learning-mcp/index.ts +++ b/hub/server/integrations/learning/load-learning-mcp/index.ts @@ -9,9 +9,15 @@ export interface LearningMcpServer { export interface LearningMcp { createLearningMcpServer( backend: Record Promise>, - options?: { name?: string; version?: string; onError?: (error: unknown) => void }, + options?: { + name?: string + version?: string + submitEachRequest?: boolean + submitSessionMode?: "conversation" | "notes-only" + onError?: (error: unknown) => void + }, ): LearningMcpServer - LearningError: new (code: string, message: string) => Error + LearningError: new (code: string, message: string, details?: Record) => Error } const loaded = new Map>() diff --git a/hub/server/integrations/mcp/agent-oauth-provider/index.ts b/hub/server/integrations/mcp/agent-oauth-provider/index.ts index 7af308bea..a56b8633f 100644 --- a/hub/server/integrations/mcp/agent-oauth-provider/index.ts +++ b/hub/server/integrations/mcp/agent-oauth-provider/index.ts @@ -1,6 +1,8 @@ import { + InvalidClientMetadataError, InvalidGrantError, InvalidTokenError, + TooManyRequestsError, } from "@modelcontextprotocol/sdk/server/auth/errors.js" import type { OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js" @@ -29,12 +31,18 @@ export function agentOAuthProvider(service: AgentOAuthService): OAuthServerProvi // Agents run on people's machines and cannot keep a secret, so every client is // public and relies on PKCE. registerClient: async (metadata) => { + const redirectUris = metadata.redirect_uris.map(String) + if (redirectUris.length > 10 || redirectUris.some((uri) => Buffer.byteLength(uri) > 2048)) + throw new InvalidClientMetadataError( + "Use at most 10 redirect URIs of up to 2048 bytes each.", + ) const client = { id: (metadata as { client_id?: string }).client_id ?? crypto.randomUUID(), name: (metadata.client_name ?? "Coding agent").slice(0, 200), - redirectUris: metadata.redirect_uris.map(String), + redirectUris, } - await service.registerClient(client) + if (!(await service.registerClient(client))) + throw new TooManyRequestsError("Hub has reached its agent registration limit.") return { ...clientInformation(client), client_id_issued_at: Math.floor(Date.now() / 1000), diff --git a/hub/server/integrations/mcp/agent-oauth-provider/types.ts b/hub/server/integrations/mcp/agent-oauth-provider/types.ts index 37bd0a6ce..73e47ac33 100644 --- a/hub/server/integrations/mcp/agent-oauth-provider/types.ts +++ b/hub/server/integrations/mcp/agent-oauth-provider/types.ts @@ -1,7 +1,11 @@ import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" export interface AgentOAuthService { - registerClient(client: { id: string; name: string; redirectUris: string[] }): Promise + registerClient(client: { + id: string + name: string + redirectUris: string[] + }): Promise<{ id: string } | null> getClient(id: string): Promise<{ id: string; name: string; redirectUris: string[] } | null> startAuthorization(input: { clientId: string diff --git a/hub/server/integrations/postgres/with-learning-execution-lock/errors.ts b/hub/server/integrations/postgres/with-learning-execution-lock/errors.ts new file mode 100644 index 000000000..32a3966b4 --- /dev/null +++ b/hub/server/integrations/postgres/with-learning-execution-lock/errors.ts @@ -0,0 +1,6 @@ +export class LearningExecutionBusyError extends Error { + constructor(options?: ErrorOptions) { + super("Another learning operation is still running.", options) + this.name = "LearningExecutionBusyError" + } +} diff --git a/hub/server/integrations/postgres/with-learning-execution-lock/index.ts b/hub/server/integrations/postgres/with-learning-execution-lock/index.ts index 86d772051..ff24344ae 100644 --- a/hub/server/integrations/postgres/with-learning-execution-lock/index.ts +++ b/hub/server/integrations/postgres/with-learning-execution-lock/index.ts @@ -1,4 +1,5 @@ import { Client } from "pg" +import { LearningExecutionBusyError } from "./errors.ts" export async function withLearningExecutionLock({ databaseUrl, @@ -43,7 +44,7 @@ export async function withLearningExecutionLock({ const result = await client.query<{ locked: boolean }>( "SELECT pg_try_advisory_lock(1919242348, 2) AS locked", ) - if (!result.rows[0]?.locked) throw new Error("Another learning operation is still running.") + if (!result.rows[0]?.locked) throw new LearningExecutionBusyError() await client.query("SELECT pg_advisory_lock_shared(1919242348, 3)") if (protectSessionAuthority) { await client.query("SELECT pg_advisory_lock_shared(1919242348, 4)") diff --git a/hub/server/repositories/agent-clients/create-agent-client/index.ts b/hub/server/repositories/agent-clients/create-agent-client/index.ts index 316ae8658..267f9df20 100644 --- a/hub/server/repositories/agent-clients/create-agent-client/index.ts +++ b/hub/server/repositories/agent-clients/create-agent-client/index.ts @@ -1,8 +1,26 @@ -import type { Prisma } from "../../../generated/prisma/client.ts" +import type { PrismaClient } from "../../../generated/prisma/client.ts" -export function createAgentClient( - database: Pick, +const maximumRetainedClients = 10_000 +const clientRetention = 30 * 24 * 60 * 60 * 1000 +const registrationLockKey = 5_901_241_338_721_113n + +export async function createAgentClient( + database: Pick, data: { id: string; name: string; redirectUris: string[] }, ) { - return database.agentClient.create({ data }) + return database.$transaction(async (transaction) => { + const now = new Date() + + // Keep concurrent anonymous registrations within the retained-client limit. + await transaction.$executeRaw`SELECT pg_advisory_xact_lock(${registrationLockKey})` + await transaction.agentClient.deleteMany({ + where: { + createdAt: { lt: new Date(now.getTime() - clientRetention) }, + authorizations: { none: { expiresAt: { gt: now }, consumedAt: null } }, + connections: { none: { revokedAt: null, inactiveAt: { gt: now } } }, + }, + }) + if ((await transaction.agentClient.count()) >= maximumRetainedClients) return null + return transaction.agentClient.create({ data }) + }) } diff --git a/hub/server/repositories/agent-connections/create-agent-connection/index.ts b/hub/server/repositories/agent-connections/create-agent-connection/index.ts index 2dcb145f8..cb537dc86 100644 --- a/hub/server/repositories/agent-connections/create-agent-connection/index.ts +++ b/hub/server/repositories/agent-connections/create-agent-connection/index.ts @@ -2,7 +2,7 @@ import type { Prisma } from "../../../generated/prisma/client.ts" export function createAgentConnection( database: Pick, - data: Prisma.AgentConnectionUncheckedCreateInput, + data: Prisma.AgentConnectionUncheckedCreateInput & { sessionId: string }, ) { return database.agentConnection.create({ data, diff --git a/hub/server/repositories/agent-connections/list-agent-connections/index.ts b/hub/server/repositories/agent-connections/list-agent-connections/index.ts index 8c55133bb..7e30a00ab 100644 --- a/hub/server/repositories/agent-connections/list-agent-connections/index.ts +++ b/hub/server/repositories/agent-connections/list-agent-connections/index.ts @@ -7,7 +7,12 @@ export function listAgentConnections( ) { const now = new Date() return database.agentConnection.findMany({ - where: { ...owner, revokedAt: null, inactiveAt: { gt: now } }, + where: { + ...owner, + revokedAt: null, + inactiveAt: { gt: now }, + session: { is: { endedAt: null, expiresAt: { gt: now } } }, + }, orderBy: [{ createdAt: "desc" }, { id: "desc" }], select: { id: true, diff --git a/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts b/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts index e16b8a6e2..90b800bb5 100644 --- a/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts +++ b/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts @@ -19,6 +19,7 @@ export async function rotateAgentConnection( refreshDigest: input.refreshDigest, revokedAt: null, inactiveAt: { gt: now }, + session: { is: { endedAt: null, expiresAt: { gt: now } } }, }, data: { tokenDigest: input.tokenDigest, diff --git a/hub/server/repositories/agent-connections/touch-agent-connection/index.ts b/hub/server/repositories/agent-connections/touch-agent-connection/index.ts index e66e59a54..1a280b714 100644 --- a/hub/server/repositories/agent-connections/touch-agent-connection/index.ts +++ b/hub/server/repositories/agent-connections/touch-agent-connection/index.ts @@ -8,7 +8,13 @@ export async function touchAgentConnection( ) { const now = new Date() const [connection] = await database.agentConnection.updateManyAndReturn({ - where: { tokenDigest, revokedAt: null, expiresAt: { gt: now }, inactiveAt: { gt: now } }, + where: { + tokenDigest, + revokedAt: null, + expiresAt: { gt: now }, + inactiveAt: { gt: now }, + session: { is: { endedAt: null, expiresAt: { gt: now } } }, + }, data: { lastUsedAt: now, inactiveAt }, select: { id: true, diff --git a/hub/server/repositories/learning-runs/create-learning-run/index.db.test.ts b/hub/server/repositories/learning-runs/create-learning-run/index.db.test.ts index e9ea47c76..54691ea82 100644 --- a/hub/server/repositories/learning-runs/create-learning-run/index.db.test.ts +++ b/hub/server/repositories/learning-runs/create-learning-run/index.db.test.ts @@ -47,6 +47,7 @@ describe("createLearningRun()", () => { createLearningRun(transaction, { repositoryId, scheduled: true, + reviewCommentsDue: true, snapshotDigest: `sha256:${"a".repeat(64)}`, reviewActivitySnapshot: { scheduled: 1 }, }), @@ -89,6 +90,7 @@ describe("createLearningRun()", () => { createLearningRun(transaction, { repositoryId, scheduled: true, + reviewCommentsDue: true, snapshotDigest: `sha256:${"a".repeat(64)}`, reviewActivitySnapshot: { scheduled: 1 }, }), @@ -110,6 +112,7 @@ describe("createLearningRun()", () => { run: { id: scheduled.run.id, scheduled: false, + reviewCommentsDue: true, requestedById: userId, requestedByMembershipId: membershipId, snapshotDigest: `sha256:${"b".repeat(64)}`, @@ -117,4 +120,26 @@ describe("createLearningRun()", () => { }, }) }) + + it("persists note-only scheduled runs without a review snapshot", async () => { + const repositoryId = randomUUID() + await prisma.repository.create({ + data: { id: repositoryId, nameWithOwner: "team/notes-only", defaultBranch: "main" }, + }) + + const result = await prisma.$transaction((transaction) => + createLearningRun(transaction, { + repositoryId, + scheduled: true, + reviewCommentsDue: false, + snapshotDigest: null, + reviewActivitySnapshot: {}, + }), + ) + + expect(result.run).toMatchObject({ + reviewCommentsDue: false, + snapshotDigest: null, + }) + }) }) diff --git a/hub/server/repositories/learning-runs/create-learning-run/index.ts b/hub/server/repositories/learning-runs/create-learning-run/index.ts index 1e704a175..c979099da 100644 --- a/hub/server/repositories/learning-runs/create-learning-run/index.ts +++ b/hub/server/repositories/learning-runs/create-learning-run/index.ts @@ -9,6 +9,7 @@ export async function createLearningRun( requestedById: string requestedByMembershipId: string scheduled?: false + reviewCommentsDue?: true snapshotDigest: string reviewActivitySnapshot: Prisma.InputJsonValue } @@ -17,13 +18,14 @@ export async function createLearningRun( requestedById?: never requestedByMembershipId?: never scheduled: true - snapshotDigest: string - reviewActivitySnapshot: Prisma.InputJsonValue + reviewCommentsDue: boolean + snapshotDigest: string | null + reviewActivitySnapshot: Prisma.InputJsonValue | typeof Prisma.DbNull }, ) { const id = randomUUID() const created = await database.learningRun.createMany({ - data: { id, ...input }, + data: { id, ...input, reviewCommentsDue: input.reviewCommentsDue ?? true }, skipDuplicates: true, }) let run = await database.learningRun.findFirst({ @@ -44,6 +46,7 @@ export async function createLearningRun( requestedById: input.requestedById, requestedByMembershipId: input.requestedByMembershipId, scheduled: false, + reviewCommentsDue: true, snapshotDigest: input.snapshotDigest, reviewActivitySnapshot: input.reviewActivitySnapshot, }, diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts index e52e0b425..ee0c59465 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts @@ -402,7 +402,72 @@ describe("listDueLearningRepositories()", () => { requireGitHubId: false, hubReviewCommentConsentEnabled: true, }), - ).resolves.toEqual([{ id: consentedId }]) + ).resolves.toEqual([{ id: consentedId, reviewCommentsDue: true }]) + }) + + it("schedules notes without consuming review comments that still need consent", async () => { + const repositoryId = randomUUID() + const notesReceivedAt = new Date("2026-11-18T10:00:00Z") + await prisma.repository.create({ + data: { + id: repositoryId, + nameWithOwner: "team/notes-and-comments", + defaultBranch: "main", + learningSetting: { + create: { + noteGrantId: "pick-polish-grant", + notesReceivedAt, + }, + }, + }, + }) + await createReviewEvidence({ + repositoryId, + updatedAt: new Date("2026-11-18T09:00:00Z"), + }) + + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual([ + { id: repositoryId, reviewCommentsDue: false }, + ]) + + const noteRun = await prisma.learningRun.create({ + data: { + repositoryId, + scheduled: true, + reviewCommentsDue: false, + state: "SUCCEEDED", + commentsRemaining: 1, + snapshotDigest: null, + reviewActivitySnapshot: {}, + createdAt: new Date("2026-11-18T11:00:00Z"), + startedAt: new Date("2026-11-18T11:00:00Z"), + finishedAt: new Date("2026-11-18T11:30:00Z"), + }, + }) + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual([ + { id: repositoryId, reviewCommentsDue: false }, + ]) + await prisma.learningRun.update({ where: { id: noteRun.id }, data: { commentsRemaining: 0 } }) + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual([ + { id: repositoryId, reviewCommentsDue: true }, + ]) + + await prisma.learningRun.create({ + data: { + repositoryId, + scheduled: true, + reviewCommentsDue: true, + state: "FAILED", + snapshotDigest: `sha256:${"a".repeat(64)}`, + failureCode: "grant_required", + failureSummary: "Review comment consent is required.", + createdAt: new Date("2026-11-18T12:00:00Z"), + finishedAt: new Date("2026-11-18T12:30:00Z"), + }, + }) + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual( + [], + ) }) it("finds review evidence committed after snapshot capture with an earlier timestamp", async () => { @@ -462,7 +527,7 @@ describe("listDueLearningRepositories()", () => { } await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual([ - { id: repositoryId }, + { id: repositoryId, reviewCommentsDue: true }, ]) }) }) diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts index fd9ec5478..c079ff425 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts @@ -9,14 +9,21 @@ export function listDueLearningRepositories( }, ) { const limit = input.limit ?? 2_000 - return database.$queryRaw>(Prisma.sql` + return database.$queryRaw>(Prisma.sql` WITH latest_runs AS ( SELECT DISTINCT ON (repository_id) repository_id, - created_at, + created_at + FROM learning_runs + ORDER BY repository_id, created_at DESC, number DESC + ), + latest_review_runs AS ( + SELECT DISTINCT ON (repository_id) + repository_id, comments_remaining, suggestions_remaining FROM learning_runs + WHERE review_comments_due = true ORDER BY repository_id, created_at DESC, number DESC ), latest_successes AS ( @@ -27,6 +34,18 @@ export function listDueLearningRepositories( comments_remaining, suggestions_remaining FROM learning_runs + WHERE state = 'SUCCEEDED' + AND review_comments_due = true + ORDER BY repository_id, finished_at DESC, number DESC + ), + latest_any_successes AS ( + SELECT DISTINCT ON (repository_id) + repository_id, + created_at, + review_comments_due, + comments_remaining, + suggestions_remaining + FROM learning_runs WHERE state = 'SUCCEEDED' ORDER BY repository_id, finished_at DESC, number DESC ), @@ -39,6 +58,7 @@ export function listDueLearningRepositories( failure_code FROM learning_runs WHERE scheduled = true + AND review_comments_due = true ORDER BY repository_id, created_at DESC, number DESC ), latest_explicit_runs AS ( @@ -50,26 +70,93 @@ export function listDueLearningRepositories( WHERE scheduled = false AND requested_by_membership_id IS NOT NULL ORDER BY repository_id, created_at DESC, number DESC + ), + due_sources AS ( + SELECT + repositories.id, + ( + NOT COALESCE(settings.review_comments_turned_off, false) + AND ( + COALESCE(latest_review_runs.comments_remaining, 0) > 0 + OR COALESCE(latest_review_runs.suggestions_remaining, 0) > 0 + OR COALESCE(latest_successes.comments_remaining, 0) > 0 + OR COALESCE(latest_successes.suggestions_remaining, 0) > 0 + OR ( + review_activity.snapshot IS NOT NULL + AND review_activity.snapshot IS DISTINCT FROM latest_successes.review_activity_snapshot + ) + ) + ) AS review_comments_due, + ( + settings.notes_received_at IS NOT NULL + AND ( + latest_any_successes.repository_id IS NULL + OR settings.notes_received_at > latest_any_successes.created_at + OR ( + NOT latest_any_successes.review_comments_due + AND (latest_any_successes.comments_remaining > 0 OR latest_any_successes.suggestions_remaining > 0) + ) + ) + ) AS notes_due, + ( + NOT ( + (${input.hubReviewCommentConsentEnabled ?? false} = true + AND copilot.review_comment_consent_at IS NOT NULL) + OR settings.review_comment_grant_id IS NOT NULL + ) + ) AS review_comment_consent_missing, + ( + latest_automatic_runs.repository_id IS NOT NULL + AND latest_automatic_runs.state = 'FAILED' + AND latest_automatic_runs.failure_code IN ('grant_required', 'grant_inactive') + AND ( + latest_explicit_runs.number IS NULL + OR (latest_explicit_runs.created_at, latest_explicit_runs.number) + < (latest_automatic_runs.created_at, latest_automatic_runs.number) + ) + AND ( + ${input.hubReviewCommentConsentEnabled ?? false} = false + OR copilot.review_comment_consent_at IS NULL + OR copilot.review_comment_consent_at <= latest_automatic_runs.created_at + ) + AND COALESCE(settings.review_comments_turned_off, false) = false + ) AS review_comment_consent_blocked + FROM repositories + LEFT JOIN latest_review_runs + ON latest_review_runs.repository_id = repositories.id + LEFT JOIN latest_successes + ON latest_successes.repository_id = repositories.id + LEFT JOIN latest_any_successes + ON latest_any_successes.repository_id = repositories.id + LEFT JOIN latest_automatic_runs + ON latest_automatic_runs.repository_id = repositories.id + LEFT JOIN latest_explicit_runs + ON latest_explicit_runs.repository_id = repositories.id + LEFT JOIN repository_learning_settings settings + ON settings.repository_id = repositories.id + LEFT JOIN copilot_connections copilot + ON copilot.key = 'global' + LEFT JOIN LATERAL ( + SELECT jsonb_object_agg(id::text, activity_version) AS snapshot + FROM review_threads + WHERE review_threads.repository_id = repositories.id + ) review_activity ON true ) - SELECT repositories.id + SELECT repositories.id, + ( + due_sources.review_comments_due + AND NOT ( + due_sources.notes_due + AND ( + due_sources.review_comment_consent_missing + OR due_sources.review_comment_consent_blocked + ) + ) + ) AS "reviewCommentsDue" FROM repositories + JOIN due_sources ON due_sources.id = repositories.id LEFT JOIN latest_runs ON latest_runs.repository_id = repositories.id - LEFT JOIN latest_successes - ON latest_successes.repository_id = repositories.id - LEFT JOIN latest_automatic_runs - ON latest_automatic_runs.repository_id = repositories.id - LEFT JOIN latest_explicit_runs - ON latest_explicit_runs.repository_id = repositories.id - LEFT JOIN repository_learning_settings settings - ON settings.repository_id = repositories.id - LEFT JOIN copilot_connections copilot - ON copilot.key = 'global' - LEFT JOIN LATERAL ( - SELECT jsonb_object_agg(id::text, activity_version) AS snapshot - FROM review_threads - WHERE review_threads.repository_id = repositories.id - ) review_activity ON true WHERE repositories.removed_at IS NULL AND (${input.requireGitHubId} = false OR repositories.github_repository_id > 0) AND NOT EXISTS ( @@ -78,40 +165,13 @@ export function listDueLearningRepositories( WHERE active_runs.repository_id = repositories.id AND active_runs.state IN ('QUEUED', 'RUNNING') ) - AND NOT ( - latest_automatic_runs.repository_id IS NOT NULL - AND latest_automatic_runs.state = 'FAILED' - AND latest_automatic_runs.failure_code IN ('grant_required', 'grant_inactive') - AND ( - latest_explicit_runs.number IS NULL - OR (latest_explicit_runs.created_at, latest_explicit_runs.number) - < (latest_automatic_runs.created_at, latest_automatic_runs.number) - ) - AND ( - ${input.hubReviewCommentConsentEnabled ?? false} = false - OR copilot.review_comment_consent_at IS NULL - OR copilot.review_comment_consent_at <= latest_automatic_runs.created_at - ) - AND COALESCE(settings.review_comments_turned_off, false) = false - ) AND ( - COALESCE(latest_runs.comments_remaining, 0) > 0 - OR COALESCE(latest_runs.suggestions_remaining, 0) > 0 - OR COALESCE(latest_successes.comments_remaining, 0) > 0 - OR COALESCE(latest_successes.suggestions_remaining, 0) > 0 - OR ( - COALESCE(settings.review_comments_turned_off, false) = false - AND - review_activity.snapshot IS NOT NULL - AND review_activity.snapshot IS DISTINCT FROM latest_successes.review_activity_snapshot - ) - OR ( - settings.notes_received_at IS NOT NULL - AND ( - latest_successes.repository_id IS NULL - OR settings.notes_received_at > latest_successes.created_at - ) - ) + due_sources.review_comments_due + OR due_sources.notes_due + ) + AND NOT ( + due_sources.review_comment_consent_blocked + AND NOT due_sources.notes_due ) ORDER BY latest_runs.created_at ASC NULLS FIRST, repositories.id ASC LIMIT ${limit} diff --git a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts new file mode 100644 index 000000000..1e09f1e8e --- /dev/null +++ b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts @@ -0,0 +1,53 @@ +import { randomUUID } from "node:crypto" +import { expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { recordPickAndPolishNotesReceived } from "." + +it("advances the notes marker only for a new receipt", async () => { + const repository = await prisma.repository.create({ + data: { + nameWithOwner: `team/${randomUUID()}`, + defaultBranch: "main", + learningSetting: { create: { noteGrantId: "pick-polish-grant" } }, + }, + }) + + try { + await recordPickAndPolishNotesReceived(prisma, repository.id, "a".repeat(64)) + const first = await prisma.repositoryLearningSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }) + expect(first.notesReceivedAt).not.toBeNull() + + const olderMarker = new Date("2000-01-01T00:00:00.000Z") + await prisma.repositoryLearningSetting.update({ + where: { repositoryId: repository.id }, + data: { notesReceivedAt: olderMarker }, + }) + await recordPickAndPolishNotesReceived(prisma, repository.id, "a".repeat(64)) + expect( + ( + await prisma.repositoryLearningSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }) + ).notesReceivedAt, + ).toEqual(olderMarker) + + await recordPickAndPolishNotesReceived(prisma, repository.id, "b".repeat(64)) + expect( + ( + await prisma.repositoryLearningSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }) + ).notesReceivedAt?.getTime(), + ).toBeGreaterThan(olderMarker.getTime()) + expect( + await prisma.pickAndPolishNoteReceipt.count({ + where: { repositoryId: repository.id }, + }), + ).toBe(2) + } finally { + await prisma.repository.delete({ where: { id: repository.id } }) + } +}) diff --git a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts index 90dbdc30f..69092ebab 100644 --- a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts +++ b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts @@ -3,9 +3,24 @@ import type { PrismaClient } from "../../../generated/prisma/client.ts" export async function recordPickAndPolishNotesReceived( database: PrismaClient, repositoryId: string, + receiptId: string, ) { - await database.repositoryLearningSetting.updateMany({ - where: { repositoryId }, - data: { notesReceivedAt: new Date() }, + const receivedAt = new Date() + await database.$transaction(async (transaction) => { + await transaction.pickAndPolishNoteReceipt.deleteMany({ + where: { + repositoryId, + receivedAt: { lt: new Date(receivedAt.getTime() - 90 * 24 * 60 * 60 * 1_000) }, + }, + }) + const receipt = await transaction.pickAndPolishNoteReceipt.createMany({ + data: [{ repositoryId, receiptId, receivedAt }], + skipDuplicates: true, + }) + if (receipt.count === 0) return + await transaction.repositoryLearningSetting.update({ + where: { repositoryId }, + data: { notesReceivedAt: receivedAt }, + }) }) } diff --git a/hub/server/routes/agent-connections/client-registration.db.test.ts b/hub/server/routes/agent-connections/client-registration.db.test.ts new file mode 100644 index 000000000..e262e3c5e --- /dev/null +++ b/hub/server/routes/agent-connections/client-registration.db.test.ts @@ -0,0 +1,86 @@ +import { randomBytes, randomUUID } from "node:crypto" +import { once } from "node:events" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" +import { expect, it } from "vitest" + +import { createApp } from "../../create-app" +import { createLogger } from "../../integrations/pino/create-logger" +import { prisma } from "../../integrations/prisma" +import { createAuthenticationRouteDependencies } from "../api/auth/create-authentication-route-dependencies" +import { createProductRouteDependencies } from "../api/product/create-product-route-dependencies" + +it("serializes anonymous client registrations at the retained-client limit", async () => { + const server = createServer() + try { + server.listen(0, "127.0.0.1") + await once(server, "listening") + const applicationOrigin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + server.on( + "request", + createApp({ + authentication: await createAuthenticationRouteDependencies({ + NODE_ENV: "development", + DATABASE_URL: process.env.DATABASE_URL, + HUB_LOCAL_SIGN_IN: "true", + HUB_APPLICATION_ORIGIN: applicationOrigin, + HUB_AUTHENTICATION_ENCRYPTION_KEY: randomBytes(32).toString("base64"), + HUB_BOOTSTRAP_SECRET: "synthetic-bootstrap-secret-for-agent-test", + }), + product: createProductRouteDependencies(), + agentConnections: { + applicationOrigin, + databaseUrl: process.env.DATABASE_URL!, + learning: { + cliPath: "/missing/cli.mjs", + nodePath: "node", + root: "/", + staticDirectories: [], + }, + }, + logger: createLogger({ level: "silent" }), + }), + ) + await prisma.agentClient.createMany({ + data: Array.from({ length: 9_999 }, (_, index) => ({ + id: randomUUID(), + name: `Retained client ${index}`, + redirectUris: ["http://127.0.0.1:9/callback"], + })), + }) + + async function register(name: string, redirectUris = ["http://127.0.0.1:9/callback"]) { + return fetch(`${applicationOrigin}/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + client_name: name, + redirect_uris: redirectUris, + }), + }) + } + + const oversized = await register("Oversized metadata", [ + `http://127.0.0.1:9/${"a".repeat(2050)}`, + ]) + expect(await oversized.json()).toMatchObject({ error: "invalid_client_metadata" }) + + const concurrent = await Promise.all([ + register("First concurrent agent"), + register("Second concurrent agent"), + ]) + expect(concurrent.map(({ status }) => status).sort()).toEqual([201, 400]) + expect(await prisma.agentClient.count()).toBe(10_000) + + const atCapacity = await register("Agent at capacity") + expect(atCapacity.status).toBe(400) + expect(await atCapacity.json()).toMatchObject({ error: "too_many_requests" }) + expect(await prisma.agentClient.count()).toBe(10_000) + } finally { + if (server.listening) { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + } +}, 20_000) diff --git a/hub/server/routes/agent-connections/index.db.test.ts b/hub/server/routes/agent-connections/index.db.test.ts index fe097500f..182c06674 100644 --- a/hub/server/routes/agent-connections/index.db.test.ts +++ b/hub/server/routes/agent-connections/index.db.test.ts @@ -10,18 +10,19 @@ import { prisma } from "../../integrations/prisma" import { createAuthenticationRouteDependencies } from "../api/auth/create-authentication-route-dependencies" import { createProductRouteDependencies } from "../api/product/create-product-route-dependencies" -it("connects an agent with the person's approval and stops it after they revoke it", async () => { +it("connects an agent with a protected Hub session and ends access on sign-out", async () => { const server = createServer() try { server.listen(0, "127.0.0.1") await once(server, "listening") - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + const requestOrigin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + const applicationOrigin = requestOrigin.replace("http:", "https:") const authentication = await createAuthenticationRouteDependencies( { NODE_ENV: "development", DATABASE_URL: process.env.DATABASE_URL, HUB_LOCAL_SIGN_IN: "true", - HUB_APPLICATION_ORIGIN: origin, + HUB_APPLICATION_ORIGIN: applicationOrigin, HUB_AUTHENTICATION_ENCRYPTION_KEY: randomBytes(32).toString("base64"), HUB_BOOTSTRAP_SECRET: "synthetic-bootstrap-secret-for-agent-test", }, @@ -43,10 +44,11 @@ it("connects an agent with the person's approval and stops it after they revoke server.on( "request", createApp({ + trustedProxyHops: 1, authentication, product, agentConnections: { - applicationOrigin: origin, + applicationOrigin, databaseUrl: process.env.DATABASE_URL!, learning: { cliPath: "/missing/cli.mjs", @@ -58,7 +60,7 @@ it("connects an agent with the person's approval and stops it after they revoke logger: createLogger({ level: "silent" }), }), ) - const mcpUrl = `${origin}/mcp/repositories/${repository.id}` + const mcpUrl = `${requestOrigin}/mcp/repositories/${repository.id}` function callMcp(token?: string) { return fetch(mcpUrl, { method: "POST", @@ -74,16 +76,19 @@ it("connects an agent with the person's approval and stops it after they revoke const unauthenticated = await callMcp() expect(unauthenticated.status).toBe(401) expect(unauthenticated.headers.get("www-authenticate")).toContain( - `${origin}/.well-known/oauth-protected-resource/mcp`, + `${applicationOrigin}/.well-known/oauth-protected-resource/mcp`, ) expect( - await (await fetch(`${origin}/.well-known/oauth-protected-resource/mcp`)).json(), - ).toMatchObject({ resource: `${origin}/mcp`, authorization_servers: [`${origin}/`] }) + await (await fetch(`${requestOrigin}/.well-known/oauth-protected-resource/mcp`)).json(), + ).toMatchObject({ + resource: `${applicationOrigin}/mcp`, + authorization_servers: [`${applicationOrigin}/`], + }) const redirectUri = "http://127.0.0.1:9/callback" const registered = (await ( - await fetch(`${origin}/register`, { + await fetch(`${requestOrigin}/register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_name: "Test agent", redirect_uris: [redirectUri] }), @@ -93,7 +98,7 @@ it("connects an agent with the person's approval and stops it after they revoke const verifier = randomBytes(32).toString("base64url") const authorize = await fetch( - `${origin}/authorize?${new URLSearchParams({ + `${requestOrigin}/authorize?${new URLSearchParams({ response_type: "code", client_id: registered.client_id, redirect_uri: redirectUri, @@ -107,17 +112,19 @@ it("connects an agent with the person's approval and stops it after they revoke expect(approvalPath).toMatch(/^\/agents\/approve\/[0-9a-f-]{36}$/) const authorizationId = approvalPath.split("/").at(-1)! const authorizationPath = `/api/agent-connections/authorizations/${authorizationId}` - expect((await fetch(origin + authorizationPath)).status).toBe(401) + expect((await fetch(requestOrigin + authorizationPath)).status).toBe(401) - const start = await fetch(`${origin}/api/auth/local/start`, { + const start = await fetch(`${requestOrigin}/api/auth/local/start`, { method: "POST", redirect: "manual", - headers: { Origin: origin }, + headers: { Origin: applicationOrigin }, body: new URLSearchParams({ return_to: approvalPath }), }) - const callback = await fetch(new URL(start.headers.get("location")!, origin), { + const callbackUrl = new URL(start.headers.get("location")!, applicationOrigin) + const callback = await fetch(`${requestOrigin}${callbackUrl.pathname}${callbackUrl.search}`, { redirect: "manual", headers: { + "X-Forwarded-Proto": "https", Cookie: start.headers .getSetCookie() .map((cookie) => cookie.split(";", 1)[0]) @@ -127,14 +134,14 @@ it("connects an agent with the person's approval and stops it after they revoke expect(callback.headers.get("location")).toBe(approvalPath) const session = callback.headers .getSetCookie() - .find((cookie) => cookie.startsWith("hub_session="))! + .find((cookie) => cookie.startsWith("__Host-hub_session="))! .split(";", 1)[0]! function browser(path: string, method = "GET", body?: unknown) { - return fetch(origin + path, { + return fetch(requestOrigin + path, { method, headers: { Cookie: session, - Origin: origin, + Origin: applicationOrigin, ...(body ? { "Content-Type": "application/json" } : {}), }, body: body ? JSON.stringify(body) : undefined, @@ -160,7 +167,10 @@ it("connects an agent with the person's approval and stops it after they revoke ).toBe(410) function requestTokens(fields: Record) { - return fetch(`${origin}/token`, { method: "POST", body: new URLSearchParams(fields) }) + return fetch(`${requestOrigin}/token`, { + method: "POST", + body: new URLSearchParams(fields), + }) } const codeExchange = { grant_type: "authorization_code", @@ -175,7 +185,7 @@ it("connects an agent with the person's approval and stops it after they revoke expect((await requestTokens({ ...codeExchange, code_verifier: verifier })).status).toBe(400) const otherClient = (await ( - await fetch(`${origin}/register`, { + await fetch(`${requestOrigin}/register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_name: "Other agent", redirect_uris: [redirectUri] }), @@ -209,7 +219,7 @@ it("connects an agent with the person's approval and stops it after they revoke // An agent can also give up its own access through the standard revocation endpoint. const again = await fetch( - `${origin}/authorize?${new URLSearchParams({ + `${requestOrigin}/authorize?${new URLSearchParams({ response_type: "code", client_id: registered.client_id, redirect_uri: redirectUri, @@ -229,7 +239,68 @@ it("connects an agent with the person's approval and stops it after they revoke code_verifier: verifier, }) ).json()) as { access_token: string } - const revoked = await fetch(`${origin}/revoke`, { + + const pendingClient = (await ( + await fetch(`${requestOrigin}/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "Pending agent", redirect_uris: [redirectUri] }), + }) + ).json()) as { client_id: string } + const pendingAuthorization = await fetch( + `${requestOrigin}/authorize?${new URLSearchParams({ + response_type: "code", + client_id: pendingClient.client_id, + redirect_uri: redirectUri, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + })}`, + { redirect: "manual" }, + ) + expect(pendingAuthorization.status).toBe(302) + const pendingAuthorizationId = pendingAuthorization.headers.get("location")!.split("/").at(-1)! + const staleAt = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000) + await prisma.agentClient.update({ + where: { id: registered.client_id }, + data: { createdAt: staleAt }, + }) + await prisma.agentClient.update({ + where: { id: pendingClient.client_id }, + data: { createdAt: staleAt }, + }) + const staleClient = await prisma.agentClient.create({ + data: { + name: "Expired registration", + redirectUris: [redirectUri], + createdAt: staleAt, + }, + }) + const cleanupRegistration = await fetch(`${requestOrigin}/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "New agent", redirect_uris: [redirectUri] }), + }) + expect(cleanupRegistration.status).toBe(201) + expect(await prisma.agentClient.findUnique({ where: { id: staleClient.id } })).toBeNull() + expect( + await prisma.agentClient.findUnique({ where: { id: registered.client_id } }), + ).not.toBeNull() + expect( + await prisma.agentConnection.findFirst({ + where: { + clientId: registered.client_id, + revokedAt: null, + inactiveAt: { gt: new Date() }, + }, + }), + ).not.toBeNull() + expect( + await prisma.agentAuthorization.findUnique({ + where: { id: pendingAuthorizationId }, + }), + ).toMatchObject({ clientId: pendingClient.client_id, consumedAt: null }) + + const revoked = await fetch(`${requestOrigin}/revoke`, { method: "POST", body: new URLSearchParams({ client_id: registered.client_id, @@ -238,11 +309,47 @@ it("connects an agent with the person's approval and stops it after they revoke }) expect(revoked.status).toBe(200) expect((await callMcp(agentTokens.access_token)).status).toBe(401) + + const sessionBoundAuthorization = await fetch( + `${requestOrigin}/authorize?${new URLSearchParams({ + response_type: "code", + client_id: registered.client_id, + redirect_uri: redirectUri, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + })}`, + { redirect: "manual" }, + ) + expect(sessionBoundAuthorization.status).toBe(302) + const sessionBoundPath = `/api/agent-connections/authorizations/${sessionBoundAuthorization.headers.get("location")!.split("/").at(-1)}` + const sessionBoundPending = (await (await browser(sessionBoundPath)).json()) as { + session: string + } + const sessionBoundApproval = (await ( + await browser(`${sessionBoundPath}/approve`, "POST", { + session: sessionBoundPending.session, + }) + ).json()) as { redirectUrl: string } + const sessionBoundTokens = (await ( + await requestTokens({ + ...codeExchange, + code: new URL(sessionBoundApproval.redirectUrl).searchParams.get("code")!, + code_verifier: verifier, + }) + ).json()) as { access_token: string; refresh_token: string } + expect((await callMcp(sessionBoundTokens.access_token)).status).toBe(403) + + const signedOut = await browser("/api/auth/session/sign-out", "POST") + expect(signedOut.status).toBe(204) + expect((await callMcp(sessionBoundTokens.access_token)).status).toBe(401) + expect((await refreshWith(registered.client_id, sessionBoundTokens.refresh_token)).status).toBe( + 400, + ) expect( await prisma.securityAudit.count({ where: { action: { in: ["agent_connection.approve", "agent_connection.revoke"] } }, }), - ).toBe(4) + ).toBe(5) } finally { if (server.listening) { await new Promise((resolve, reject) => { diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 758bf92b6..3a8683690 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -10,8 +10,7 @@ import { type GetCanvasRepositoryPermission, } from "../../domains/canvas/authorization/index.ts" import { canvasDigest } from "../../domains/canvas/credentials/index.ts" -import { hubSessionCookieName } from "../../integrations/express/hub-session-cookie-name/index.ts" -import { readCookie } from "../../integrations/express/read-cookie/index.ts" +import { readHubSessionCookie } from "../../integrations/express/read-hub-session-cookie/index.ts" import { requireOrigin } from "../../integrations/express/require-origin/index.ts" import { GitHubProviderRequestError } from "../../integrations/github/errors.ts" import { loadLearningMcp } from "../../integrations/learning/load-learning-mcp/index.ts" @@ -89,7 +88,7 @@ export function agentConnectionRoutes( } async function browser(request: Request) { - const cookie = readCookie(request, hubSessionCookieName) + const cookie = readHubSessionCookie(request) return cookie ? (await load()).authority.browser(canvasDigest(cookie)) : null } @@ -205,33 +204,23 @@ export function agentConnectionRoutes( notes: { grantId: async () => (await getRepositoryLearningSetting(prisma, repository.id))?.noteGrantId ?? null, - received: () => recordPickAndPolishNotesReceived(prisma, repository.id), + received: (receiptId) => + recordPickAndPolishNotesReceived(prisma, repository.id, receiptId), }, repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, - async serialize(operation) { - try { - return await withLearningExecutionLock({ - databaseUrl, - protectSessionAuthority: true, - run: operation, - }) - } catch (error) { - if ( - error instanceof Error && - error.message === "Another learning operation is still running." - ) - throw new mcp.LearningError( - "busy", - "Hub is busy with other learning work. Try again in a minute.", - ) - throw error - } - }, - toAgentError: (code, message) => new mcp.LearningError(code, message), + serialize: (operation) => + withLearningExecutionLock({ + databaseUrl, + protectSessionAuthority: true, + run: operation, + }), + toAgentError: (code, message, safeForAgent = false) => + new mcp.LearningError(code, message, { safeForAgent }), user: result.viewer.login, }) const server = mcp.createLearningMcpServer(backend, { name: "replica-hub-learning", + submitSessionMode: "notes-only", onError: (error) => logger?.error({ err: error }, "Agent learning tool failed"), }) await handleMcpRequest(server, request, response) diff --git a/hub/vite.config.ts b/hub/vite.config.ts index ed83c66cb..93f82b4ec 100644 --- a/hub/vite.config.ts +++ b/hub/vite.config.ts @@ -8,6 +8,13 @@ import { controlsValidatorPath, } from "./controls-validator-plugin.ts" +const apiProxy = Object.fromEntries( + ["/api", "/mcp", "/register", "/authorize", "/token", "/revoke", "/.well-known"].map((path) => [ + path, + { target: "http://127.0.0.1:3001", ws: true }, + ]), +) + export default defineConfig({ plugins: [reactRouter(), controlsValidatorPlugin()], ssr: { @@ -20,12 +27,12 @@ export default defineConfig({ server: { port: 5173, strictPort: true, - proxy: { "/api": { target: "http://127.0.0.1:3001", ws: true } }, + proxy: apiProxy, }, preview: { port: 5173, strictPort: true, - proxy: { "/api": { target: "http://127.0.0.1:3001", ws: true } }, + proxy: apiProxy, }, resolve: { alias: { ...viteAliases, [controlsValidatorModule]: controlsValidatorPath } }, optimizeDeps: { include: [controlsValidatorModule] }, diff --git a/packages/learning/mcp.d.mts b/packages/learning/mcp.d.mts index bb0793424..f12196027 100644 --- a/packages/learning/mcp.d.mts +++ b/packages/learning/mcp.d.mts @@ -34,8 +34,15 @@ export interface LearningMcpBackend { /** The number of earlier messages when sending a conversation in chunks. */ messageOffset?: number /** Messages in order; a tool message keeps its place, empty. */ - messages: Array<{ role: "user" | "agent" | "tool"; text: string; at?: string }> - outcome?: { status: "success" | "failure" | "partial" | "unknown"; summary?: string } + messages: Array<{ + role: "user" | "agent" | "tool" + text: string + at?: string + }> + outcome?: { + status: "success" | "failure" | "partial" | "unknown" + summary?: string + } /** The notes improvement_results returned, so they become evidence too. */ pickAndPolishNotes?: PickAndPolishNote[] }): Promise @@ -79,6 +86,8 @@ export function createLearningMcpServer( version?: string /** Asks the agent to submit after every request, not when the session ends. */ submitEachRequest?: boolean + /** Limits hosted session submissions to explicitly entered notes. */ + submitSessionMode?: "conversation" | "notes-only" /** Receives original failures for host-side diagnostics; details are not sent to agents. */ onError?: (error: unknown) => void }, diff --git a/packages/learning/src/mcp.mjs b/packages/learning/src/mcp.mjs index 0d3f0b1bb..0ec2caa6f 100644 --- a/packages/learning/src/mcp.mjs +++ b/packages/learning/src/mcp.mjs @@ -13,6 +13,9 @@ const SUBMIT_AT_END = const SUBMIT_EACH_REQUEST = "After you finish each request, call submit_session with the conversation so far, using the same sessionId each time, so feedback can become new learnings. For long conversations send chunks of at most 5,000 messages, setting messageOffset to the number of earlier messages. Do not wait for the session to end. If you completed a Pick & polish batch, also pass the notes returned by improvement_results unchanged as pickAndPolishNotes. Those notes include the confirmed Copilot replies; do not send the earlier immutable batch notes instead." +const SUBMIT_NOTES_ONLY = + "After completing a Pick & polish batch, call submit_session with the same sessionId and the notes returned by improvement_results unchanged as pickAndPolishNotes. Do not send conversations or chat messages." + const SAFE_LEARNING_ERROR_MESSAGES = Object.freeze({ invalid_input: "The request was invalid.", invalid_record: "A learning record is invalid.", @@ -36,14 +39,14 @@ const SAFE_LEARNING_ERROR_MESSAGES = Object.freeze({ unavailable: "The configured service is currently unavailable.", }) -function instructionsFor(submitEachRequest) { +function instructionsFor(submitEachRequest, submitSessionMode) { return `This server holds the learnings a team accepted from past reviews of its prototypes. 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, 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. -${submitEachRequest ? SUBMIT_EACH_REQUEST : SUBMIT_AT_END} +${submitSessionMode === "notes-only" ? SUBMIT_NOTES_ONLY : submitEachRequest ? SUBMIT_EACH_REQUEST : SUBMIT_AT_END} Only a person can accept, reject, edit, or delete a learning. get_learning tells you how a person can decide on a proposed one.` } @@ -141,30 +144,46 @@ const pickAndPolishNote = z.object({ * name?: string * version?: string * submitEachRequest?: boolean + * submitSessionMode?: "conversation" | "notes-only" * onError?: (error: unknown) => void * }} [options] * submitEachRequest asks the agent to submit after every request rather than when - * the session ends. onError receives the original failure for host-side diagnostics; - * the agent sees only a safe summary. + * the session ends. notes-only limits submit_session to Pick & Polish notes. + * onError receives the original failure for host-side diagnostics; the agent sees + * only a safe summary. */ export function createLearningMcpServer( backend, - { name = "replica-learning", version = "0.0.0", submitEachRequest = false, onError } = {}, + { + name = "replica-learning", + version = "0.0.0", + submitEachRequest = false, + submitSessionMode = "conversation", + onError, + } = {}, ) { const canReview = typeof backend.reviewLearnings === "function" - const base = instructionsFor(submitEachRequest) + const base = instructionsFor(submitEachRequest, submitSessionMode) const instructions = canReview ? base + REVIEW_INSTRUCTIONS : base const reviewOffer = canReview ? ` When waitingForReview is above 0, ${REVIEW_OFFER}` : "" const server = new McpServer({ name, version }, { instructions }) function tool(id, config, call) { server.registerTool(id, config, async (input) => { try { - return { content: [{ type: "text", text: JSON.stringify(await call(input), null, 2) }] } + return { + content: [{ type: "text", text: JSON.stringify(await call(input), null, 2) }], + } } catch (error) { onError?.(error) const code = error instanceof LearningError ? error.code : null - const text = Object.hasOwn(SAFE_LEARNING_ERROR_MESSAGES, code) - ? `${code}: ${SAFE_LEARNING_ERROR_MESSAGES[code]}` + const safeMessage = + error instanceof LearningError && error.details?.safeForAgent === true + ? error.message + : Object.hasOwn(SAFE_LEARNING_ERROR_MESSAGES, code) + ? SAFE_LEARNING_ERROR_MESSAGES[code] + : null + const text = safeMessage + ? `${code}: ${safeMessage}` : "The learning store could not complete this request." return { isError: true, content: [{ type: "text", text }] } } @@ -215,39 +234,50 @@ export function createLearningMcpServer( "submit_session", { title: "Submit session", - description: `Stores this session's user and agent messages and its outcome, so feedback in it can become learnings. ${submitEachRequest ? "Call it after you finish each request, not only when the session ends. " : SUBMIT_AT_END + " "}When available, waitingForReview says how many suggestions are waiting for a person's decision. Messages are matched by position. Send the conversation in order, with each tool call or output as an empty tool message, and keep each earlier message's user and time unchanged. For long conversations send chunks of at most 5,000 messages with the same sessionId, setting messageOffset to the number of earlier messages. Resend a chunk if its messages change.${reviewOffer}`, - inputSchema: { - sessionId: z.string(), - task: z.string().optional(), - user: z.string().optional().describe("The person, as github:, if known."), - startedAt: z.string().optional().describe("An ISO 8601 time."), - messageOffset: z - .number() - .int() - .nonnegative() - .safe() - .optional() - .describe("The number of earlier messages when sending a conversation in chunks."), - messages: z.array( - z.object({ - role: z.enum(["user", "agent", "tool"]), - text: z.string().describe("Leave empty for a tool message; it is not stored."), - at: z.string().optional().describe("An ISO 8601 time."), - }), - ), - outcome: z - .object({ - status: z.enum(["success", "failure", "partial", "unknown"]), - summary: z.string().optional(), - }) - .optional(), - pickAndPolishNotes: z - .array(pickAndPolishNote) - .optional() - .describe( - "The notes array returned by improvement_results after you complete a Pick & polish batch, unchanged. It includes the confirmed Copilot replies. Each note is stored once and resending it adds only new replies.", - ), - }, + description: + submitSessionMode === "notes-only" + ? `Stores only Pick & Polish notes for this session. Do not send conversation messages. ${SUBMIT_NOTES_ONLY}` + : `Stores this session's user and agent messages and its outcome, so feedback in it can become learnings. ${submitEachRequest ? "Call it after you finish each request, not only when the session ends. " : SUBMIT_AT_END + " "}When available, waitingForReview says how many suggestions are waiting for a person's decision. Messages are matched by position. Send the conversation in order, with each tool call or output as an empty tool message, and keep each earlier message's user and time unchanged. For long conversations send chunks of at most 5,000 messages with the same sessionId, setting messageOffset to the number of earlier messages. Resend a chunk if its messages change.${reviewOffer}`, + inputSchema: + submitSessionMode === "notes-only" + ? z + .object({ + sessionId: z.string(), + pickAndPolishNotes: z.array(pickAndPolishNote).optional(), + }) + .strict() + : { + sessionId: z.string(), + task: z.string().optional(), + user: z.string().optional().describe("The person, as github:, if known."), + startedAt: z.string().optional().describe("An ISO 8601 time."), + messageOffset: z + .number() + .int() + .nonnegative() + .safe() + .optional() + .describe("The number of earlier messages when sending a conversation in chunks."), + messages: z.array( + z.object({ + role: z.enum(["user", "agent", "tool"]), + text: z.string().describe("Leave empty for a tool message; it is not stored."), + at: z.string().optional().describe("An ISO 8601 time."), + }), + ), + outcome: z + .object({ + status: z.enum(["success", "failure", "partial", "unknown"]), + summary: z.string().optional(), + }) + .optional(), + pickAndPolishNotes: z + .array(pickAndPolishNote) + .optional() + .describe( + "The notes array returned by improvement_results after you complete a Pick & polish batch, unchanged. It includes the confirmed Copilot replies. Each note is stored once and resending it adds only new replies.", + ), + }, annotations: { idempotentHint: true }, }, (input) => backend.submitSession(input), diff --git a/packages/learning/test/mcp.test.mjs b/packages/learning/test/mcp.test.mjs index 582c39999..c774b8de0 100644 --- a/packages/learning/test/mcp.test.mjs +++ b/packages/learning/test/mcp.test.mjs @@ -59,6 +59,77 @@ describe("createLearningMcpServer", () => { } }) + it("keeps conversation submission enabled by default for local Solo", async () => { + const submitted = [] + const { client, server } = await connect({ + submitSession: async (input) => { + submitted.push(input) + return { stored: true } + }, + }) + + try { + const { tools } = await client.listTools() + const submit = tools.find(({ name }) => name === "submit_session") + assert.ok(submit.inputSchema.properties.messages) + assert.match(client.getInstructions(), /call submit_session with the conversation/) + + const submission = { + sessionId: "solo-session", + messages: [{ role: "user", text: "Keep the labels visible." }], + } + const result = await client.callTool({ + name: "submit_session", + arguments: submission, + }) + assert.notEqual(result.isError, true) + assert.deepEqual(submitted, [submission]) + } finally { + await client.close() + await server.close() + } + }) + + it("limits hosted session submissions to Pick & Polish notes", async () => { + const submitted = [] + const { client, server } = await connect( + { + submitSession: async (input) => { + submitted.push(input) + return { stored: true } + }, + }, + { submitSessionMode: "notes-only" }, + ) + + try { + const { tools } = await client.listTools() + const submit = tools.find(({ name }) => name === "submit_session") + assert.deepEqual(Object.keys(submit.inputSchema.properties).sort(), [ + "pickAndPolishNotes", + "sessionId", + ]) + const transcriptInstructions = + /call submit_session with (?:the )?conversation|submit the conversation|send the conversation|messages are matched by position|for long conversations/i + assert.doesNotMatch(client.getInstructions(), transcriptInstructions) + assert.doesNotMatch(submit.description, transcriptInstructions) + + const submission = { + sessionId: "hosted-session", + pickAndPolishNotes: [{ localId: "note-one", body: "Keep the labels visible." }], + } + const result = await client.callTool({ + name: "submit_session", + arguments: submission, + }) + assert.notEqual(result.isError, true) + assert.deepEqual(submitted, [submission]) + } finally { + await client.close() + await server.close() + } + }) + it("preserves and validates Pick & Polish thread offsets", async () => { const submitted = [] const { client, server } = await connect({ @@ -123,7 +194,10 @@ describe("createLearningMcpServer", () => { ) try { - const result = await client.callTool({ name: "get_guidance", arguments: {} }) + const result = await client.callTool({ + name: "get_guidance", + arguments: {}, + }) assert.equal(result.isError, true) assert.equal(result.content[0].text, "The learning store could not complete this request.") assert.strictEqual(reportedError, backendError) @@ -158,11 +232,17 @@ describe("createLearningMcpServer", () => { ) try { - const known = await client.callTool({ name: "get_guidance", arguments: {} }) + const known = await client.callTool({ + name: "get_guidance", + arguments: {}, + }) assert.equal(known.content[0].text, "invalid_input: The request was invalid.") assert.strictEqual(reportedErrors[0], knownError) - const unknown = await client.callTool({ name: "get_guidance", arguments: {} }) + const unknown = await client.callTool({ + name: "get_guidance", + arguments: {}, + }) assert.equal(unknown.content[0].text, "The learning store could not complete this request.") assert.strictEqual(reportedErrors[1], unknownError) assert.equal(reportedErrors.length, 2) @@ -171,4 +251,31 @@ describe("createLearningMcpServer", () => { await server.close() } }) + + it("preserves an explicitly safe host recovery message", async () => { + const recovery = new LearningError( + "grant_inactive", + "A repository administrator can enable Pick & Polish notes in Hub settings.", + { safeForAgent: true }, + ) + const { client, server } = await connect({ + getGuidance: async () => { + throw recovery + }, + }) + + try { + const result = await client.callTool({ + name: "get_guidance", + arguments: {}, + }) + assert.equal( + result.content[0].text, + "grant_inactive: A repository administrator can enable Pick & Polish notes in Hub settings.", + ) + } finally { + await client.close() + await server.close() + } + }) }) From 576ed725b886f30d172eaa0961fd66282ad860f3 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 14:55:02 -0800 Subject: [PATCH 09/32] fix(hub): make Learning consent explicit and settings recoverable Keep deployment consent off by default, describe what connecting Copilot permits, and leave the first manual run available. Return the updated settings and report denied or busy requests consistently. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../hub/routes/administrator-flow.test.tsx | 2 +- .../hub/routes/learnings-flow.test.tsx | 4 +- .../index.test.ts | 2 + .../copilot-connection-page-data/index.ts | 9 +- .../settings-learnings/index.test.ts | 4 +- .../view-models/settings-learnings/index.ts | 8 +- .../copilot-connection-page/index.test.tsx | 5 +- .../pages/copilot-connection-page/stories.tsx | 14 +- .../pages/learning-settings-page/index.tsx | 6 +- hub/client/pages/learnings-page/stories.tsx | 8 +- hub/docs/learning-foundation.md | 6 +- .../migration.sql | 8 +- hub/schema/repository-learning-setting.prisma | 18 +-- hub/server/routes/api/learnings/index.test.ts | 127 +++++++++++++++++- .../learnings/respond-learning-error/index.ts | 8 ++ .../api/learnings/settings/get/index.ts | 8 +- .../api/learnings/settings/patch/index.ts | 2 +- .../present-security-audit/index.test.ts | 4 +- .../present-security-audit/index.ts | 4 + .../azure/post/configure/index.test.ts | 19 +++ infrastructure/azure/post/configure/index.ts | 14 +- 21 files changed, 227 insertions(+), 53 deletions(-) diff --git a/hub/client/application/hub/routes/administrator-flow.test.tsx b/hub/client/application/hub/routes/administrator-flow.test.tsx index 9f2118f10..bc06fb896 100644 --- a/hub/client/application/hub/routes/administrator-flow.test.tsx +++ b/hub/client/application/hub/routes/administrator-flow.test.tsx @@ -663,7 +663,7 @@ describe("administrator frontend integration", () => { fireEvent.click( await screen.findByRole("checkbox", { - name: /confirm connecting Copilot for this Hub/i, + name: /confirm connecting or checking Copilot for this Hub/i, }), ) fireEvent.click(screen.getByRole("button", { name: "Connect Copilot" })) diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index bd463c49b..d6a6e6943 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -262,7 +262,7 @@ describe("Learnings frontend integration", () => { expect(screen.queryByText(/Accepted by @octocat/)).not.toBeInTheDocument() }) - it("leaves finding learnings to the daily run when Hub has one", async () => { + it("keeps the first-run consent action available when Hub has daily runs", async () => { const server = stubHubFetch(...learningsWorkspace()) server.use( http.get(`/api/repositories/2001/learnings`, () => @@ -274,7 +274,7 @@ describe("Learnings frontend integration", () => { expect( await screen.findByRole("link", { name: "Show a visible label above every form field." }), ).toBeVisible() - expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() + expect(await screen.findByRole("button", { name: "Find learnings now" })).toBeVisible() }) it("shows migration redaction follow-ups to the repository administrator after reload", async () => { diff --git a/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts b/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts index 86f083c33..4892a9740 100644 --- a/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts +++ b/hub/client/application/hub/view-models/copilot-connection-page-data/index.test.ts @@ -51,6 +51,8 @@ describe("copilotConnectionPageData()", () => { if (data.accessDenied) throw new Error("The administrator must receive connection controls.") expect(data.credentialLabel).toBeNull() expect(data.connect?.label).toBe("Connect Copilot") + expect(data.connect?.consequence).toMatch(/deployment-wide review-comment consent is enabled/) + expect(data.connect?.confirmLabel).toMatch(/connecting or checking Copilot/) expect([data.description, data.connect?.consequence].join(" ")).not.toMatch( /operator-provided token|configured token/i, ) diff --git a/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts b/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts index 6bf64d73a..7fa703040 100644 --- a/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts +++ b/hub/client/application/hub/view-models/copilot-connection-page-data/index.ts @@ -8,6 +8,8 @@ export function copilotConnectionPageData( ): CopilotConnectionPageData { const verification = "Hub checks your live administrator session again after Copilot answers, before saving the change." + const reviewCommentConsent = + "If deployment-wide review-comment consent is enabled, connecting or checking Copilot records your consent to learn from comments in every repository. Repository administrators can turn this off for their repository." return { administrationWorkspace: workspace, heading: "Copilot", @@ -51,9 +53,10 @@ export function copilotConnectionPageData( ? "Check and connect Copilot" : "Connect Copilot", consequence: status.credentialIdentity - ? `Hub asks Copilot to verify a fresh credential for the ${status.credentialIdentity.organization} organization through GitHub App ${status.credentialIdentity.appId}. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply.` - : "Hub asks Copilot to verify the configured credential. Later learning runs may send review comment text without reviewer identity. The available local providers attribute usage to the signed-in account or user-token identity.", - confirmLabel: "I understand and confirm connecting Copilot for this Hub.", + ? `Hub asks Copilot to verify a fresh credential for the ${status.credentialIdentity.organization} organization through GitHub App ${status.credentialIdentity.appId}. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply. ${reviewCommentConsent}` + : `Hub asks Copilot to verify the configured credential. Later learning runs may send review comment text without reviewer identity. The available local providers attribute usage to the signed-in account or user-token identity. ${reviewCommentConsent}`, + confirmLabel: + "I understand this review-comment consent behavior and confirm connecting or checking Copilot for this Hub.", verification, }, disconnect: status.savedConnection diff --git a/hub/client/application/hub/view-models/settings-learnings/index.test.ts b/hub/client/application/hub/view-models/settings-learnings/index.test.ts index 8cc539a53..89e29cc41 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.test.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.test.ts @@ -117,7 +117,7 @@ describe("settingsLearnings()", () => { expect(result).not.toHaveProperty("run") }) - it("leaves finding learnings to the daily run when Hub has one", () => { + it("keeps an explicit run available when Hub has daily runs", () => { const state = mockState(false) const result = settingsLearnings( @@ -128,6 +128,6 @@ describe("settingsLearnings()", () => { ) if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.run).toBeNull() + expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) }) }) 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 b428e96b5..ef72b98eb 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -73,13 +73,9 @@ export function settingsLearnings( !state.solo && state.capabilities.administerRepository ? `/repositories/${repositoryId}/learnings/settings` : null, - // Daily runs keep the page to the library. A Hub without them still needs a way - // to look for learnings. + // Keep an explicit run available so repository admins can establish first-run consent. run: - !state.solo && - !state.automaticRunsEnabled && - state.permissions.requestRun && - state.runAvailable + !state.solo && state.permissions.requestRun && state.runAvailable ? { path: `/repositories/${repositoryId}/learnings/runs` } : null, loadError: state.loadError, diff --git a/hub/client/pages/copilot-connection-page/index.test.tsx b/hub/client/pages/copilot-connection-page/index.test.tsx index 3361484f7..7370fcca9 100644 --- a/hub/client/pages/copilot-connection-page/index.test.tsx +++ b/hub/client/pages/copilot-connection-page/index.test.tsx @@ -19,8 +19,11 @@ describe("CopilotConnectionPage()", () => { renderPage(story.args.data) expect(screen.getByRole("heading", { name: "Copilot is not connected" })).toBeInTheDocument() expect(screen.getByText(/signed-in account or user-token identity/)).toBeInTheDocument() + expect( + screen.getByText(/deployment-wide review-comment consent is enabled/), + ).toBeInTheDocument() const checkbox = screen.getByRole("checkbox", { - name: "I understand and confirm connecting Copilot for this Hub.", + name: "I understand this review-comment consent behavior and confirm connecting or checking Copilot for this Hub.", }) expect(checkbox).toBeRequired() expect(checkbox).not.toBeChecked() diff --git a/hub/client/pages/copilot-connection-page/stories.tsx b/hub/client/pages/copilot-connection-page/stories.tsx index df91cba0e..f4d34a7db 100644 --- a/hub/client/pages/copilot-connection-page/stories.tsx +++ b/hub/client/pages/copilot-connection-page/stories.tsx @@ -27,12 +27,14 @@ const shared = { const verification = "Hub checks your live administrator session again after Copilot answers, before saving the change." +const reviewCommentConsent = + "If deployment-wide review-comment consent is enabled, connecting or checking Copilot records your consent to learn from comments in every repository. Repository administrators can turn this off for their repository." const connect = { label: "Connect Copilot", - consequence: - "Hub asks Copilot to verify the configured credential. Later learning runs may send review comment text without reviewer identity. The available local providers attribute usage to the signed-in account or user-token identity.", - confirmLabel: "I understand and confirm connecting Copilot for this Hub.", + consequence: `Hub asks Copilot to verify the configured credential. Later learning runs may send review comment text without reviewer identity. The available local providers attribute usage to the signed-in account or user-token identity. ${reviewCommentConsent}`, + confirmLabel: + "I understand this review-comment consent behavior and confirm connecting or checking Copilot for this Hub.", verification, } @@ -84,8 +86,7 @@ export const OrganizationInstallation: Story = { "Copilot usage is billed to the github organization through GitHub App 12345. Organization model policy, budget, and installation revocation continue to apply.", connect: { ...connect, - consequence: - "Hub asks Copilot to verify a fresh credential for the github organization through GitHub App 12345. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply.", + consequence: `Hub asks Copilot to verify a fresh credential for the github organization through GitHub App 12345. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply. ${reviewCommentConsent}`, }, }, }, @@ -100,8 +101,7 @@ export const ConnectedOrganizationInstallation: Story = { connect: { ...connect, label: "Check Copilot connection", - consequence: - "Hub asks Copilot to verify a fresh credential for the github organization through GitHub App 12345. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply.", + consequence: `Hub asks Copilot to verify a fresh credential for the github organization through GitHub App 12345. Later learning runs may send review comment text without reviewer identity. The organization's Copilot model policy, budget, and App installation revocation continue to apply. ${reviewCommentConsent}`, }, }, }, diff --git a/hub/client/pages/learning-settings-page/index.tsx b/hub/client/pages/learning-settings-page/index.tsx index 1840fba3f..ce8cf99e8 100644 --- a/hub/client/pages/learning-settings-page/index.tsx +++ b/hub/client/pages/learning-settings-page/index.tsx @@ -75,7 +75,7 @@ export function LearningSettingsPage({ onChange: (change: LearningSettingsChange) => void }) { return ( -
+
- + Learning settings @@ -113,6 +113,6 @@ export function LearningSettingsPage({ onChange={(allowed) => onChange({ notes: allowed })} setting={data.notes} /> -
+ ) } diff --git a/hub/client/pages/learnings-page/stories.tsx b/hub/client/pages/learnings-page/stories.tsx index 5833b03ec..2db17f493 100644 --- a/hub/client/pages/learnings-page/stories.tsx +++ b/hub/client/pages/learnings-page/stories.tsx @@ -20,7 +20,9 @@ const meta = { export default meta type Story = StoryObj -export const Default: Story = {} +export const Default: Story = { + args: { data: { ...data, run: { path: "/repositories/2001/learnings/runs" } } }, +} export const AccessDenied: Story = { args: { @@ -143,10 +145,6 @@ export const CopilotRefused: Story = { }, } -export const WithoutDailyRuns: Story = { - args: { data: { ...data, run: { path: "/repositories/2001/learnings/runs" } } }, -} - export const LocalLearning: Story = { args: { data: { diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 50595d03c..9ce6a65a7 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -107,11 +107,11 @@ The run endpoint requires a usable Copilot connection. It captures and digests o Operators may opt in to automatic runs with `REPLICA_LEARNING_AUTOMATIC_RUNS=true`. One stable BullMQ schedule discovers due repositories daily at 02:00 UTC. Discovery is a no-op while the saved Copilot connection is unavailable, refused, or no longer owned by an administrator. A repository is due when its current thread activity versions differ from the review activity snapshot persisted with its last successful run, new Pick & Polish notes arrived after that run, or its most recent successful or partially completed run left comments or suggestions unfinished. This comparison does not depend on review or run timestamps, so a review transaction that commits after snapshot capture remains due even when it assigned its timestamps earlier. Repositories without a successful run become due after their first review evidence. -Discovery skips repositories without a GitHub ID and removed or disconnected repositories. It captures the normal complete review snapshot before creating a run, so repository removal during discovery is skipped and later review drift becomes the same visible `snapshot_changed` run failure as an explicit request. A repository whose latest automatic run found missing or ended consent stays out of automatic discovery until a newer explicit administrator run or a newer deployment-wide Copilot consent supersedes that failure. Turning review-comment learning off also lets scheduled work continue without importing comments. It creates at most one active run per repository and dispatches at most 100 due repositories per sweep, ordered by their least recent run with never-run repositories first. A capture or run-creation failure for one repository is reported and does not block later repositories. Automatic jobs stay on the scheduled queue below maintenance-job priority. Before claiming one under the global learning execution lock, the processor defers to queued or recovered user-requested work on the on-demand queue. +Discovery skips repositories without a GitHub ID and removed or disconnected repositories. Review-comment runs capture the normal complete snapshot before creating a run, so repository removal during discovery is skipped and later review drift becomes the same visible `snapshot_changed` run failure as an explicit request. When only Pick & Polish notes are due and review-comment consent is unavailable, Hub schedules note-only work without reading review comments or changing their last successful snapshot. Review-comment work remains due until separately consented. A repository whose latest automatic review-comment run found missing or ended consent stays out of automatic review-comment discovery until a newer explicit administrator run or a newer deployment-wide Copilot consent supersedes that failure; separately consented notes can still run. Turning review-comment learning off also stops future comment imports. The scheduler creates at most one active run per repository and dispatches at most 100 due repositories per sweep, ordered by their least recent run with never-run repositories first. A capture or run-creation failure for one repository is reported and does not block later repositories. Automatic jobs stay on the scheduled queue below maintenance-job priority. Before claiming one under the global learning execution lock, the processor defers to queued or recovered user-requested work on the on-demand queue. The one-minute recovery sweep re-enqueues queued and interrupted running records on their original queue. Enqueue failures for newly discovered automatic runs are persisted as visible failed runs. Completed run records are retained for 90 days. Each repository's latest run and latest successful scheduling watermark are kept when older records are removed. Schedule setup uses one stable scheduler ID, so repeated setup updates the daily schedule instead of duplicating it. -The worker claims a queued run only once under the learning execution lock. It recaptures the snapshot and refuses drift, prepares the private store, and imports with `--redact-deleted`. An explicit repository-administrator run can establish repository-specific review-comment consent. A scheduled run reuses that grant or creates one only under active deployment-wide Hub-administrator consent. It labels at most 400 comments and ten Copilot requests and consolidates at most ten suggestions over the previous 90 days. It records partial label counts and AI-credit usage even when a later request fails. An incomplete collection, changed snapshot, ended or missing consent, refused credential, or unreadable package result becomes a visible failed run. +The worker claims a queued run only once under the learning execution lock. Review-comment runs recapture the snapshot and refuse drift before importing with `--redact-deleted`; note-only runs skip review-comment capture and import. An explicit repository-administrator run can establish repository-specific review-comment consent. A scheduled review-comment run reuses that grant or creates one only under active deployment-wide Hub-administrator consent. It labels at most 400 comments and ten Copilot requests and consolidates at most ten suggestions over the previous 90 days. It records partial label counts and AI-credit usage even when a later request fails. An incomplete collection, changed snapshot, ended or missing consent, refused credential, or unreadable package result becomes a visible failed run. Soft deletion queues an idempotent package redaction job after the review transaction commits. The recovery sweep also finds deleted review comments, and every later import uses `--redact-deleted`, so a transient queue failure cannot make a deleted body permanently eligible. @@ -133,7 +133,7 @@ The agent gets the same tools and instructions as `replica-learning mcp` in the 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. -Tokens use the same lifetimes as Canvas connections. An approval request expires after 10 minutes. Access tokens last seven days, refresh tokens rotate on use, and a connection unused for 30 days ends. Hub stores only digests of codes and tokens. Every agent is a public OAuth client that relies on PKCE, because agents run on people's machines and cannot keep a secret. +Tokens use the same lifetimes as Canvas connections. An approval request expires after 10 minutes. Access tokens last seven days, refresh tokens rotate on use, and a connection unused for 30 days ends. Hub stores only digests of codes and tokens. Every agent is a public OAuth client that relies on PKCE, because agents run on people's machines and cannot keep a secret. Hub retains at most 10,000 dynamic client registrations and removes unused registrations older than 30 days when accepting a new one; clients with pending authorizations or active connections are preserved. The OAuth endpoints are `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource/mcp`, `/register`, `/authorize`, `/token`, and `/revoke`. The browser endpoints are: diff --git a/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql b/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql index 23abce38b..c55342d9b 100644 --- a/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql +++ b/hub/schema/migrations/20261224120000_repository_learning_settings/migration.sql @@ -25,11 +25,11 @@ CREATE UNIQUE INDEX "repository_learning_settings_repository_id_key" ON "repository_learning_settings"("repository_id"); -- CreateIndex -CREATE INDEX "repository_learning_settings_notes_changed_by_membership_id_idx" +CREATE INDEX "repository_learning_settings_notes_membership_idx" ON "repository_learning_settings"("notes_changed_by_membership_id"); -- CreateIndex -CREATE INDEX "repository_learning_settings_review_comments_changed_by_membership_id_idx" +CREATE INDEX "repository_learning_settings_review_membership_idx" ON "repository_learning_settings"("review_comments_changed_by_membership_id"); -- AddForeignKey @@ -40,12 +40,12 @@ ON DELETE CASCADE ON UPDATE CASCADE; -- AddForeignKey ALTER TABLE "repository_learning_settings" -ADD CONSTRAINT "repository_learning_settings_notes_changed_by_membership_id_fkey" +ADD CONSTRAINT "repository_learning_settings_notes_membership_fkey" FOREIGN KEY ("notes_changed_by_membership_id") REFERENCES "memberships"("id") ON DELETE SET NULL ON UPDATE CASCADE; -- AddForeignKey ALTER TABLE "repository_learning_settings" -ADD CONSTRAINT "repository_learning_settings_review_comments_changed_by_membership_id_fkey" +ADD CONSTRAINT "repository_learning_settings_review_membership_fkey" FOREIGN KEY ("review_comments_changed_by_membership_id") REFERENCES "memberships"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/hub/schema/repository-learning-setting.prisma b/hub/schema/repository-learning-setting.prisma index a82886a4e..b22a7da76 100644 --- a/hub/schema/repository-learning-setting.prisma +++ b/hub/schema/repository-learning-setting.prisma @@ -1,20 +1,20 @@ model RepositoryLearningSetting { // ID columns - id String @id @default(uuid()) @db.Uuid - repositoryId String @unique @map("repository_id") @db.Uuid - notesChangedByMembershipId String? @map("notes_changed_by_membership_id") @db.Uuid + id String @id @default(uuid()) @db.Uuid + repositoryId String @unique @map("repository_id") @db.Uuid + notesChangedByMembershipId String? @map("notes_changed_by_membership_id") @db.Uuid reviewCommentsChangedByMembershipId String? @map("review_comments_changed_by_membership_id") @db.Uuid // Relations - repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) - notesChangedByMembership Membership? @relation("NoteConsentChangedBy", fields: [notesChangedByMembershipId], references: [id], onDelete: SetNull) - reviewCommentsChangedByMembership Membership? @relation("ReviewCommentConsentChangedBy", fields: [reviewCommentsChangedByMembershipId], references: [id], onDelete: SetNull) + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + notesChangedByMembership Membership? @relation("NoteConsentChangedBy", fields: [notesChangedByMembershipId], references: [id], onDelete: SetNull, map: "repository_learning_settings_notes_membership_fkey") + reviewCommentsChangedByMembership Membership? @relation("ReviewCommentConsentChangedBy", fields: [reviewCommentsChangedByMembershipId], references: [id], onDelete: SetNull, map: "repository_learning_settings_review_membership_fkey") // Attribute columns noteGrantId String? @map("note_grant_id") @db.VarChar(255) reviewCommentGrantId String? @map("review_comment_grant_id") @db.VarChar(255) notesChangedAt DateTime? @map("notes_changed_at") @db.Timestamptz(3) - notesReceivedAt DateTime? @map("notes_received_at") @db.Timestamptz(3) + notesReceivedAt DateTime? @map("notes_received_at") @db.Timestamptz(3) reviewCommentsTurnedOff Boolean @default(false) @map("review_comments_turned_off") reviewCommentsChangedAt DateTime? @map("review_comments_changed_at") @db.Timestamptz(3) @@ -22,7 +22,7 @@ model RepositoryLearningSetting { createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) - @@index([notesChangedByMembershipId]) - @@index([reviewCommentsChangedByMembershipId]) + @@index([notesChangedByMembershipId], map: "repository_learning_settings_notes_membership_idx") + @@index([reviewCommentsChangedByMembershipId], map: "repository_learning_settings_review_membership_idx") @@map("repository_learning_settings") } diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index 22f7a7d8a..4c7e86e7e 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -7,11 +7,14 @@ import { describe, expect, it, vi } from "vitest" import { hashAuthenticationValue } from "../../../domains/authentication/hash-authentication-value" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { LearningExecutionBusyError } from "../../../integrations/postgres/with-learning-execution-lock/errors.ts" 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 getLearningHistory } from "./history/get/index.ts" import { post as postRun } from "./runs/post/index.ts" +import { get as getLearningSettings } from "./settings/get/index.ts" +import { patch as patchLearningSettings } from "./settings/patch/index.ts" import type { LearningsRouteDependencies } from "./types.ts" const repositoryId = "11111111-2222-4333-8444-555555555555" @@ -68,7 +71,7 @@ function dependencies( } async function withRoute( - method: "get" | "post", + method: "get" | "post" | "patch", path: string, handler: RequestHandler, operation: (baseUrl: string) => Promise, @@ -76,7 +79,8 @@ async function withRoute( const app = express() app.use(express.json()) if (method === "get") app.get(path, handler) - else app.post(path, handler) + else if (method === "post") app.post(path, handler) + else app.patch(path, handler) const server = createServer(app) server.listen(0, "127.0.0.1") await once(server, "listening") @@ -93,6 +97,125 @@ async function withRoute( const headers = { cookie: "hub_session=current-session" } describe("learning routes", () => { + it("audits a denied initial Learning settings request", async () => { + const auditRepositoryAdministrationDenial = vi.fn().mockResolvedValue(undefined) + const deps = dependencies({ + authorizeRepositoryAdministration: vi.fn().mockResolvedValue(false), + auditRepositoryAdministrationDenial, + }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/settings", + getLearningSettings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/settings`, + { headers }, + ) + + expect(response.status).toBe(403) + expect(auditRepositoryAdministrationDenial).toHaveBeenCalledWith({ + actorMembershipId: session.membershipId, + operation: "learning_settings", + repositoryId, + }) + }, + ) + }) + + it("maps Learning settings read conflicts through the shared error responder", async () => { + const deps = dependencies({ + getLearningSettings: vi + .fn() + .mockRejectedValue( + new LearningsError( + 503, + "repository_authority_unavailable", + "Repository access is temporarily unavailable. Try again.", + ), + ), + }) + + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/settings", + getLearningSettings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/settings`, + { headers }, + ) + + expect(response.status).toBe(503) + expect(await response.json()).toEqual({ + code: "repository_authority_unavailable", + error: "Repository access is temporarily unavailable. Try again.", + }) + }, + ) + }) + + it("returns the repository with saved Learning settings", async () => { + const deps = dependencies({ + changeLearningSettings: vi.fn().mockResolvedValue({ + notes: { allowed: true, changedBy: "mona", changedAt: "2026-11-18T10:00:00Z" }, + reviewComments: { allowed: true, changedBy: null, changedAt: null }, + }), + }) + + await withRoute( + "patch", + "/api/repositories/:repositoryId/learnings/settings", + patchLearningSettings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/settings`, + { + method: "PATCH", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ notes: true }), + }, + ) + + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ + repository, + notes: { allowed: true, changedBy: "mona" }, + reviewComments: { allowed: true }, + }) + }, + ) + }) + + it("returns retryable feedback when a Learning settings update is busy", async () => { + const deps = dependencies({ + changeLearningSettings: vi.fn().mockRejectedValue(new LearningExecutionBusyError()), + }) + + await withRoute( + "patch", + "/api/repositories/:repositoryId/learnings/settings", + patchLearningSettings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/settings`, + { + method: "PATCH", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ notes: true }), + }, + ) + + expect(response.status).toBe(409) + expect(await response.json()).toEqual({ + code: "learning_busy", + error: "Learning work is already running. Try again shortly.", + }) + }, + ) + }) + it("returns retryable feedback when repository authority cannot be read", async () => { const deps = dependencies({ authorizeRepositoryAdministration: vi diff --git a/hub/server/routes/api/learnings/respond-learning-error/index.ts b/hub/server/routes/api/learnings/respond-learning-error/index.ts index cb5856bd3..db3fca23b 100644 --- a/hub/server/routes/api/learnings/respond-learning-error/index.ts +++ b/hub/server/routes/api/learnings/respond-learning-error/index.ts @@ -1,12 +1,20 @@ import type { Response } from "express" import { LearningCommandError } from "../../../../integrations/learning/run-learning-command/errors.ts" +import { LearningExecutionBusyError } from "../../../../integrations/postgres/with-learning-execution-lock/errors.ts" import { LearningsError } from "../errors.ts" const staleCodes = new Set(["digest_mismatch", "stale_digest", "stale_review"]) const notFoundCodes = new Set(["not_found", "memory_not_found"]) export function respondLearningError(response: Response, error: unknown): boolean { + if (error instanceof LearningExecutionBusyError) { + response.status(409).json({ + code: "learning_busy", + error: "Learning work is already running. Try again shortly.", + }) + return true + } if (error instanceof LearningsError) { response.status(error.status).json({ code: error.code, error: error.message }) return true diff --git a/hub/server/routes/api/learnings/settings/get/index.ts b/hub/server/routes/api/learnings/settings/get/index.ts index 14ba5510d..83f01441b 100644 --- a/hub/server/routes/api/learnings/settings/get/index.ts +++ b/hub/server/routes/api/learnings/settings/get/index.ts @@ -2,6 +2,7 @@ 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" export function get(dependencies: LearningsRouteDependencies): RequestHandler { @@ -30,6 +31,11 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { repositoryId: repository.id, })) ) { + await dependencies.auditRepositoryAdministrationDenial({ + actorMembershipId: initial.membershipId, + operation: "learning_settings", + repositoryId: repository.id, + }) response.status(403).json({ code: "repository_administrator_required", error: "Repository administrator access is required.", @@ -65,7 +71,7 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { } response.json({ repository, ...settings }) } catch (error) { - next(error) + if (!respondLearningError(response, error)) next(error) } } } diff --git a/hub/server/routes/api/learnings/settings/patch/index.ts b/hub/server/routes/api/learnings/settings/patch/index.ts index c740f0c7f..bf5c764ee 100644 --- a/hub/server/routes/api/learnings/settings/patch/index.ts +++ b/hub/server/routes/api/learnings/settings/patch/index.ts @@ -90,7 +90,7 @@ export function patch(dependencies: LearningsRouteDependencies): RequestHandler response.status(403).json(denied) return } - response.json(updated) + response.json({ repository, ...updated }) } catch (error) { if (!respondLearningError(response, error)) next(error) } diff --git a/hub/server/routes/api/security-audits/present-security-audit/index.test.ts b/hub/server/routes/api/security-audits/present-security-audit/index.test.ts index 0e1c6398e..16d7c7a6f 100644 --- a/hub/server/routes/api/security-audits/present-security-audit/index.test.ts +++ b/hub/server/routes/api/security-audits/present-security-audit/index.test.ts @@ -553,7 +553,9 @@ describe("presentSecurityAudit()", () => { outcome: "success", }), }, - ...(["learning_overview", "learning_run", "learning_decision"] as const).map((operation) => ({ + ...( + ["learning_overview", "learning_run", "learning_decision", "learning_settings"] as const + ).map((operation) => ({ label: `repository administration ${operation} denial`, event: { actorMembershipId, 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 f41bbd3e9..f30670594 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 @@ -69,6 +69,10 @@ function actorFor(record: SecurityAuditListRecord) { const parsed = actorContextSchema.safeParse(record.context) return parsed.success ? { membershipId: parsed.data.actorMembershipId } : null } + case "repository.administration.learning_settings.denied": { + const parsed = actorContextSchema.safeParse(record.context) + return parsed.success ? { membershipId: parsed.data.actorMembershipId } : null + } case "prototype.registered": case "share_link.created": case "canvas_pairing.create": diff --git a/infrastructure/azure/post/configure/index.test.ts b/infrastructure/azure/post/configure/index.test.ts index e63dce2f8..e07cd1784 100644 --- a/infrastructure/azure/post/configure/index.test.ts +++ b/infrastructure/azure/post/configure/index.test.ts @@ -311,12 +311,31 @@ it("saves deployment-wide review-comment consent for the next Copilot connection expect.stringMatching(/reconnect Copilot while disabled to clear it/i), expect.any(Array), ) + expect(vi.mocked(test.ui.select).mock.calls[0]?.[1].map(({ value }) => value)).toEqual([ + "false", + "true", + "exit", + ]) expect(test.inputs.runtime_environment_variables).not.toHaveProperty( "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT", ) await test.finish() }) +it("does not replace Key Vault-backed Learning consent with a plain runtime setting", async () => { + const test = await scenario() + const key = "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT" + test.inputs.runtime_secret_references![key] = test.reference("learning-review-comment-consent") + + await expect( + configurePostSetup(test.context, "learning", test.inputs, test.deployment), + ).rejects.toThrow(`${key} is stored as a Key Vault secret reference`) + + expect(test.ui.select).not.toHaveBeenCalled() + expect(test.inputs.runtime_environment_variables).not.toHaveProperty(key) + await test.finish() +}) + it("saves an explicit repository-admin-first choice as deployment consent off", async () => { const test = await scenario() vi.mocked(test.ui.select).mockImplementation(async (_message, options) => diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index f626e7b64..9e3ea0aff 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -94,6 +94,10 @@ export async function configurePostSetup( context.onPrepared?.(() => progress.finish()) if (action === "learning") { const key = "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT" + if (Object.hasOwn(inputs.runtime_secret_references ?? {}, key)) + throw new Error( + `${key} is stored as a Key Vault secret reference. Change it through the authorized Key Vault process before configuring Learning consent.`, + ) const existing = inputs.runtime_environment_variables?.[key] ?? deployment.environment[key] ?? "false" if (!["true", "false"].includes(existing)) @@ -104,8 +108,14 @@ export async function configurePostSetup( (await recoveryUI.select( "Allow a Hub administrator who connects Copilot to consent to learning from review comments in every repository? Repository administrators can turn it off for their repository. Pick & Polish notes still need repository-specific consent in Learning settings. Disabling this switch stops deployment-wide consent immediately but keeps the saved consent; reconnect Copilot while disabled to clear it, or re-enabling later will reactivate it.", [ - { label: "Enable deployment-wide review-comment consent", value: "true" }, - { label: "Require each repository's administrator to start the first run", value: "false" }, + { + label: "Require each repository's administrator to start the first run", + value: "false", + }, + { + label: "Enable deployment-wide review-comment consent", + value: "true", + }, { label: "Save and exit", value: "exit" }, ], )) From 4432c640aaf11fcc5080ba749321a22c18ce73cd Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 14:56:12 -0800 Subject: [PATCH 10/32] fix(hub): retain separate scheduling history for notes and comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/docs/learning-foundation.md | 4 ++-- .../delete-expired-learning-runs/index.db.test.ts | 15 ++++++++++++++- .../delete-expired-learning-runs/index.ts | 8 ++++---- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 9ce6a65a7..4000727e3 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -109,7 +109,7 @@ Operators may opt in to automatic runs with `REPLICA_LEARNING_AUTOMATIC_RUNS=tru Discovery skips repositories without a GitHub ID and removed or disconnected repositories. Review-comment runs capture the normal complete snapshot before creating a run, so repository removal during discovery is skipped and later review drift becomes the same visible `snapshot_changed` run failure as an explicit request. When only Pick & Polish notes are due and review-comment consent is unavailable, Hub schedules note-only work without reading review comments or changing their last successful snapshot. Review-comment work remains due until separately consented. A repository whose latest automatic review-comment run found missing or ended consent stays out of automatic review-comment discovery until a newer explicit administrator run or a newer deployment-wide Copilot consent supersedes that failure; separately consented notes can still run. Turning review-comment learning off also stops future comment imports. The scheduler creates at most one active run per repository and dispatches at most 100 due repositories per sweep, ordered by their least recent run with never-run repositories first. A capture or run-creation failure for one repository is reported and does not block later repositories. Automatic jobs stay on the scheduled queue below maintenance-job priority. Before claiming one under the global learning execution lock, the processor defers to queued or recovered user-requested work on the on-demand queue. -The one-minute recovery sweep re-enqueues queued and interrupted running records on their original queue. Enqueue failures for newly discovered automatic runs are persisted as visible failed runs. Completed run records are retained for 90 days. Each repository's latest run and latest successful scheduling watermark are kept when older records are removed. Schedule setup uses one stable scheduler ID, so repeated setup updates the daily schedule instead of duplicating it. +The one-minute recovery sweep re-enqueues queued and interrupted running records on their original queue. Enqueue failures for newly discovered automatic runs are persisted as visible failed runs. Completed run records are retained for 90 days. Hub keeps the latest attempt and success for review-comment runs and note-only runs separately, so a newer note submission cannot erase the last review snapshot. Schedule setup uses one stable scheduler ID, so repeated setup updates the daily schedule instead of duplicating it. The worker claims a queued run only once under the learning execution lock. Review-comment runs recapture the snapshot and refuse drift before importing with `--redact-deleted`; note-only runs skip review-comment capture and import. An explicit repository-administrator run can establish repository-specific review-comment consent. A scheduled review-comment run reuses that grant or creates one only under active deployment-wide Hub-administrator consent. It labels at most 400 comments and ten Copilot requests and consolidates at most ten suggestions over the previous 90 days. It records partial label counts and AI-credit usage even when a later request fails. An incomplete collection, changed snapshot, ended or missing consent, refused credential, or unreadable package result becomes a visible failed run. @@ -165,4 +165,4 @@ The environment-token mode may obtain its secret through a platform secret refer ## Current limits -GitHub is the only repository-authority provider in this version; Entra, local sessions, and Hub administrator assignments do not synthesize repository administration. Automatic discovery is deployment-wide rather than configurable per repository. Scheduled runs need an active repository-specific grant or a Hub administrator's active deployment-wide consent; otherwise a repository administrator must request the first run for that repository. The package remains authoritative for consent, evidence eligibility, lifecycle, recall, and redaction. +GitHub is the only repository-authority provider in this version; Entra, local sessions, and Hub administrator assignments do not synthesize repository administration. Automatic discovery is deployment-wide rather than configurable per repository. To use review comments, a scheduled run needs an active repository-specific grant or a Hub administrator's active deployment-wide consent. Note-only runs need neither form of review-comment consent. The package remains authoritative for consent, evidence eligibility, lifecycle, recall, and redaction. diff --git a/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.db.test.ts b/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.db.test.ts index 3f72643aa..5f46c06de 100644 --- a/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.db.test.ts +++ b/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.db.test.ts @@ -89,6 +89,17 @@ describe("deleteExpiredLearningRuns()", () => { createdAt: new Date("2026-03-01T09:00:00Z"), }, }) + const latestNotes = await prisma.learningRun.create({ + data: { + repositoryId, + scheduled: true, + reviewCommentsDue: false, + state: "SUCCEEDED", + startedAt: new Date("2026-04-01T09:00:00Z"), + finishedAt: new Date("2026-04-01T10:00:00Z"), + createdAt: new Date("2026-04-01T09:00:00Z"), + }, + }) await deleteExpiredLearningRuns(prisma, new Date("2026-08-20T10:00:00Z")) @@ -96,7 +107,9 @@ describe("deleteExpiredLearningRuns()", () => { where: { repositoryId }, select: { id: true }, }) - expect(new Set(retained.map(({ id }) => id))).toEqual(new Set([latestSuccess.id, latestRun.id])) + expect(new Set(retained.map(({ id }) => id))).toEqual( + new Set([latestSuccess.id, latestRun.id, latestNotes.id]), + ) await expect(prisma.learningRun.findUnique({ where: { id: oldest.id } })).resolves.toBeNull() }) }) diff --git a/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.ts b/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.ts index bfdf83df5..3c9a9600e 100644 --- a/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.ts +++ b/hub/server/repositories/learning-runs/delete-expired-learning-runs/index.ts @@ -11,17 +11,17 @@ export function deleteExpiredLearningRuns( AND id NOT IN ( SELECT id FROM ( - SELECT DISTINCT ON (repository_id) id + SELECT DISTINCT ON (repository_id, review_comments_due) id FROM learning_runs - ORDER BY repository_id, created_at DESC, number DESC + ORDER BY repository_id, review_comments_due, created_at DESC, number DESC ) latest_runs UNION SELECT id FROM ( - SELECT DISTINCT ON (repository_id) id + SELECT DISTINCT ON (repository_id, review_comments_due) id FROM learning_runs WHERE state = 'SUCCEEDED' - ORDER BY repository_id, finished_at DESC, number DESC + ORDER BY repository_id, review_comments_due, finished_at DESC, number DESC ) latest_successes ) `) From f78425d5612bb7d2a387efff6b39723047cfd24f Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:06:35 -0800 Subject: [PATCH 11/32] test(hub): use the stable theme provider for agent connections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The standalone agent page uses Primer components, not Hub theme state. Its test no longer depends on the location of Hub’s theme provider on the stack base. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/client/pages/agent-connections-page/index.test.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/hub/client/pages/agent-connections-page/index.test.tsx b/hub/client/pages/agent-connections-page/index.test.tsx index 9471050e9..5a6ef860c 100644 --- a/hub/client/pages/agent-connections-page/index.test.tsx +++ b/hub/client/pages/agent-connections-page/index.test.tsx @@ -1,8 +1,7 @@ +import { ThemeProvider } from "@primer/react-brand" import { fireEvent, render, screen, within } from "@testing-library/react" import { describe, expect, it, vi } from "vitest" -import { HubThemeProvider } from "@hooks/use-hub-theme" - import { AgentConnectionsPage } from "." describe("AgentConnectionsPage()", () => { @@ -20,7 +19,7 @@ describe("AgentConnectionsPage()", () => { connections: [], }} />, - { wrapper: HubThemeProvider }, + { wrapper: ThemeProvider }, ) const config = screen.getByLabelText("Hub MCP configuration") @@ -61,7 +60,7 @@ describe("AgentConnectionsPage()", () => { ], }} />, - { wrapper: HubThemeProvider }, + { wrapper: ThemeProvider }, ) fireEvent.click(screen.getByRole("button", { name: "Revoke Local MCP client access" })) From d03524ac5f5106ed3d05e614a2b2de29f524c3f4 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:10:57 -0800 Subject: [PATCH 12/32] fix(hub): keep MCP diagnostics out of agent output and logs Return fixed host recovery messages by error code. Do not log request errors or let their text become instructions for the agent. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../create-learning-mcp-backend/index.ts | 6 ++---- .../learning/load-learning-mcp/index.ts | 3 ++- hub/server/routes/agent-connections/index.ts | 15 ++++++++++---- packages/learning/mcp.d.mts | 2 ++ packages/learning/src/mcp.mjs | 10 ++++------ packages/learning/test/mcp.test.mjs | 20 +++++++++++++------ 6 files changed, 35 insertions(+), 21 deletions(-) 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 5b389c393..aad08cc31 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 @@ -62,7 +62,7 @@ export function createLearningMcpBackend(input: { } repository: { id: string; githubRepositoryId: bigint } serialize(operation: (signal: AbortSignal) => Promise): Promise - toAgentError: (code: string, message: string, safeForAgent?: boolean) => Error + toAgentError: (code: string, message: string) => Error user?: string }) { const { learning, repository, toAgentError } = input @@ -80,7 +80,7 @@ export function createLearningMcpBackend(input: { function safeLearningError(error: unknown) { if (error instanceof LearningExecutionBusyError) - return toAgentError("busy", "Another learning operation is still running. Try again.", true) + return toAgentError("busy", "Another learning operation is still running. Try again.") return safeLearningCommandError(error) } @@ -201,7 +201,6 @@ export function createLearningMcpBackend(input: { throw toAgentError( "unsupported", "Hub does not accept screenshots yet. Report usage without them.", - true, ) const directory = await storeDirectory() if (!directory) @@ -229,7 +228,6 @@ export function createLearningMcpBackend(input: { throw toAgentError( "grant_inactive", `This repository doesn't let Hub learn from Pick & Polish notes, so nothing was stored. A repository administrator can turn on "Learn from Pick & Polish notes" in Learnings settings at ${input.learningsUrl}.`, - true, ) const directory = await storeDirectory() diff --git a/hub/server/integrations/learning/load-learning-mcp/index.ts b/hub/server/integrations/learning/load-learning-mcp/index.ts index 5bdfff79c..063b60f74 100644 --- a/hub/server/integrations/learning/load-learning-mcp/index.ts +++ b/hub/server/integrations/learning/load-learning-mcp/index.ts @@ -14,10 +14,11 @@ export interface LearningMcp { version?: string submitEachRequest?: boolean submitSessionMode?: "conversation" | "notes-only" + errorMessages?: Readonly> onError?: (error: unknown) => void }, ): LearningMcpServer - LearningError: new (code: string, message: string, details?: Record) => Error + LearningError: new (code: string, message: string) => Error } const loaded = new Map>() diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 3a8683690..51f4cf2bd 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -190,6 +190,8 @@ export function agentConnectionRoutes( return status(response, 403, "Repository access was denied.") const mcp = await loadLearningMcp(learning.cliPath) const token = request.auth!.token + const learningsUrl = new URL(`/repositories/${repository.id}/learnings`, applicationOrigin) + .href const backend = createLearningMcpBackend({ async confirmAccess() { const current = await (await load()).connections.verify(token) @@ -200,7 +202,7 @@ export function agentConnectionRoutes( }, connectionId: result.connection.id, learning, - learningsUrl: new URL(`/repositories/${repository.id}/learnings`, applicationOrigin).href, + learningsUrl, notes: { grantId: async () => (await getRepositoryLearningSetting(prisma, repository.id))?.noteGrantId ?? null, @@ -214,14 +216,19 @@ export function agentConnectionRoutes( protectSessionAuthority: true, run: operation, }), - toAgentError: (code, message, safeForAgent = false) => - new mcp.LearningError(code, message, { safeForAgent }), + toAgentError: (code, message) => new mcp.LearningError(code, message), user: result.viewer.login, }) const server = mcp.createLearningMcpServer(backend, { name: "replica-hub-learning", submitSessionMode: "notes-only", - onError: (error) => logger?.error({ err: error }, "Agent learning tool failed"), + errorMessages: { + access_denied: "This agent connection no longer has access. Reconnect in Hub.", + busy: "Another learning operation is still running. Try again.", + grant_inactive: `An active repository grant is required. For Pick & Polish notes, ask a repository administrator to enable them in Learning settings at ${learningsUrl}.`, + unsupported: "Hub does not support this operation. For usage reports, omit screenshots.", + }, + onError: () => logger?.error("Agent learning tool failed"), }) await handleMcpRequest(server, request, response) }), diff --git a/packages/learning/mcp.d.mts b/packages/learning/mcp.d.mts index f12196027..fc662a10d 100644 --- a/packages/learning/mcp.d.mts +++ b/packages/learning/mcp.d.mts @@ -88,6 +88,8 @@ export function createLearningMcpServer( submitEachRequest?: boolean /** Limits hosted session submissions to explicitly entered notes. */ submitSessionMode?: "conversation" | "notes-only" + /** Fixed recovery instructions keyed by error code. Never use request or error text. */ + errorMessages?: Readonly> /** Receives original failures for host-side diagnostics; details are not sent to agents. */ onError?: (error: unknown) => void }, diff --git a/packages/learning/src/mcp.mjs b/packages/learning/src/mcp.mjs index 0ec2caa6f..d57b6b111 100644 --- a/packages/learning/src/mcp.mjs +++ b/packages/learning/src/mcp.mjs @@ -145,6 +145,7 @@ const pickAndPolishNote = z.object({ * version?: string * submitEachRequest?: boolean * submitSessionMode?: "conversation" | "notes-only" + * errorMessages?: Readonly> * onError?: (error: unknown) => void * }} [options] * submitEachRequest asks the agent to submit after every request rather than when @@ -159,10 +160,12 @@ export function createLearningMcpServer( version = "0.0.0", submitEachRequest = false, submitSessionMode = "conversation", + errorMessages, onError, } = {}, ) { const canReview = typeof backend.reviewLearnings === "function" + const safeMessages = { ...SAFE_LEARNING_ERROR_MESSAGES, ...errorMessages } const base = instructionsFor(submitEachRequest, submitSessionMode) const instructions = canReview ? base + REVIEW_INSTRUCTIONS : base const reviewOffer = canReview ? ` When waitingForReview is above 0, ${REVIEW_OFFER}` : "" @@ -176,12 +179,7 @@ export function createLearningMcpServer( } catch (error) { onError?.(error) const code = error instanceof LearningError ? error.code : null - const safeMessage = - error instanceof LearningError && error.details?.safeForAgent === true - ? error.message - : Object.hasOwn(SAFE_LEARNING_ERROR_MESSAGES, code) - ? SAFE_LEARNING_ERROR_MESSAGES[code] - : null + const safeMessage = code && Object.hasOwn(safeMessages, code) ? safeMessages[code] : null const text = safeMessage ? `${code}: ${safeMessage}` : "The learning store could not complete this request." diff --git a/packages/learning/test/mcp.test.mjs b/packages/learning/test/mcp.test.mjs index c774b8de0..e051c5160 100644 --- a/packages/learning/test/mcp.test.mjs +++ b/packages/learning/test/mcp.test.mjs @@ -252,17 +252,25 @@ describe("createLearningMcpServer", () => { } }) - it("preserves an explicitly safe host recovery message", async () => { + it("uses the host's fixed recovery message instead of the thrown error text", async () => { const recovery = new LearningError( "grant_inactive", - "A repository administrator can enable Pick & Polish notes in Hub settings.", + "Private note body that must not reach the agent.", { safeForAgent: true }, ) - const { client, server } = await connect({ - getGuidance: async () => { - throw recovery + const { client, server } = await connect( + { + getGuidance: async () => { + throw recovery + }, }, - }) + { + errorMessages: { + grant_inactive: + "A repository administrator can enable Pick & Polish notes in Hub settings.", + }, + }, + ) try { const result = await client.callTool({ From 81f38c07e9d2c46d569d4c5d1acb48f48ea5686a Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:31:31 -0800 Subject: [PATCH 13/32] fix(hub): protect OAuth request logs and type notes-only MCP inputs Exclude OAuth payloads before parsing and ensure a transcript-only backend cannot be paired with the hosted notes schema. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/server/create-app/index.test.ts | 14 +++++++++++- hub/server/create-app/index.ts | 4 ++++ packages/learning/mcp.d.mts | 35 +++++++++++++++++++---------- packages/learning/test/mcp.test.mjs | 6 +++++ 4 files changed, 46 insertions(+), 13 deletions(-) diff --git a/hub/server/create-app/index.test.ts b/hub/server/create-app/index.test.ts index f4e80cc25..09502fdeb 100644 --- a/hub/server/create-app/index.test.ts +++ b/hub/server/create-app/index.test.ts @@ -614,7 +614,7 @@ describe("createApp()", () => { } }) - it("omits MCP request bodies from logs before parsing", async () => { + it("omits MCP requests and OAuth token exchanges from logs before parsing", async () => { const records: Record[] = [] const logger = createLogger({ destination: { write: (line) => records.push(parseRecord(line)) }, @@ -688,6 +688,18 @@ describe("createApp()", () => { expect(JSON.stringify(records)).not.toMatch( /private-pick-and-polish-note|malformed-private-note/, ) + const token = await fetch(`http://127.0.0.1:${port}/token`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + code: "private-fixture-code", + code_verifier: "private-fixture-verifier", + }), + }) + await token.arrayBuffer() + await vi.waitFor(() => expect(records).toHaveLength(3)) + expect(records[2]).not.toHaveProperty("body") + expect(JSON.stringify(records[2])).not.toContain("private-fixture") } finally { await new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())) diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 356ee89c1..b987956e8 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -53,6 +53,10 @@ export function createApp({ [ "/api/canvas", "/api/agent-connections", + "/authorize", + "/register", + "/token", + "/revoke", "/mcp", "/api/auth", "/canvas/pair", diff --git a/packages/learning/mcp.d.mts b/packages/learning/mcp.d.mts index fc662a10d..45134f978 100644 --- a/packages/learning/mcp.d.mts +++ b/packages/learning/mcp.d.mts @@ -78,19 +78,30 @@ export type McpScreenshot = ({ file: string; data?: never } | { data: string; fi capturedAt: string } +interface LearningMcpOptions { + name?: string + version?: string + /** Asks the agent to submit after every request, not when the session ends. */ + submitEachRequest?: boolean + /** Fixed recovery instructions keyed by error code. Never use request or error text. */ + errorMessages?: Readonly> + /** Receives original failures for host-side diagnostics; details are not sent to agents. */ + onError?: (error: unknown) => void +} + +export interface NotesOnlyLearningMcpBackend extends Omit { + submitSession: (input: { + sessionId: string + pickAndPolishNotes?: PickAndPolishNote[] + }) => Promise +} + /** Builds the learning MCP server around a host's backend. Connect a transport. */ export function createLearningMcpServer( backend: LearningMcpBackend, - options?: { - name?: string - version?: string - /** Asks the agent to submit after every request, not when the session ends. */ - submitEachRequest?: boolean - /** Limits hosted session submissions to explicitly entered notes. */ - submitSessionMode?: "conversation" | "notes-only" - /** Fixed recovery instructions keyed by error code. Never use request or error text. */ - errorMessages?: Readonly> - /** Receives original failures for host-side diagnostics; details are not sent to agents. */ - onError?: (error: unknown) => void - }, + options?: LearningMcpOptions & { submitSessionMode?: "conversation" }, +): McpServer +export function createLearningMcpServer( + backend: NotesOnlyLearningMcpBackend, + options: LearningMcpOptions & { submitSessionMode: "notes-only" }, ): McpServer diff --git a/packages/learning/test/mcp.test.mjs b/packages/learning/test/mcp.test.mjs index e051c5160..732552323 100644 --- a/packages/learning/test/mcp.test.mjs +++ b/packages/learning/test/mcp.test.mjs @@ -118,6 +118,12 @@ describe("createLearningMcpServer", () => { sessionId: "hosted-session", pickAndPolishNotes: [{ localId: "note-one", body: "Keep the labels visible." }], } + const conversation = await client.callTool({ + name: "submit_session", + arguments: { ...submission, messages: [{ role: "user", text: "Private conversation" }] }, + }) + assert.equal(conversation.isError, true) + assert.deepEqual(submitted, []) const result = await client.callTool({ name: "submit_session", arguments: submission, From 8e509d973b51be13ad8b29eadb1abc159ed8d6b4 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:33:27 -0800 Subject: [PATCH 14/32] test(azure): cover Learning consent post-setup and recovery Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/post/index.test.ts | 65 +++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index 5e7a91c96..d78506691 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -1135,6 +1135,71 @@ it("advances a configured GitHub provider from the verified database revision on expect(test.uploads).toEqual([]) }) +it.each([ + { outcome: "enables", consent: "true", live: "false" }, + { outcome: "disables", consent: "false", live: "true" }, +])("$outcome Learning consent without changing other runtime settings", async ({ consent, live }) => { + const test = await scenario() + const key = "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT" + test.state.environment[key] = live + const environment = { ...test.state.environment } + vi.mocked(test.ui.select).mockResolvedValue(consent) + + await postSetupAzure(test.target, { + action: "learning", + run: test.run, + ui: test.ui, + request: test.request, + }) + + const saved = JSON.parse(await readFile(test.inputsPath, "utf8")) as PostInputs + expect(saved.runtime_environment_variables).toEqual({ + ...test.inputs.runtime_environment_variables, + [key]: consent, + }) + expect(test.state.environment).toEqual({ ...environment, [key]: consent }) +}) + +it("resumes saved Learning consent and links the operator to Copilot on the deployed Hub", async () => { + const test = await scenario() + const progress = await postSetupProgress( + { config: test.target.config, directory: test.directory, ui: test.ui }, + "learning", + test.inputs, + ) + await progress.saveAnswer("learningConsent", "true") + test.state.recovery = "resume" + + const result = await postSetupAzure(test.target, { + action: "learning", + run: test.run, + ui: test.ui, + request: test.request, + }) + + expect(test.ui.select).toHaveBeenCalledOnce() + expect(test.state.environment.REPLICA_LEARNING_REVIEW_COMMENT_CONSENT).toBe("true") + expect(result).toContain(`${test.origin}/settings/copilot`) + expect(result).not.toContain("/settings/github/setup") +}) + +it("rejects an unrelated change to proxy settings before applying Learning consent", async () => { + const test = await scenario() + test.state.environment.HUB_TRUSTED_PROXY_HOPS = "3" + + await expect( + postSetupAzure(test.target, { + action: "learning", + run: test.run, + ui: test.ui, + request: test.request, + }), + ).rejects.toThrow(/unrelated deployed runtime settings/i) + + expectNoDeploymentMutation(test) + expect(await readFile(test.inputsPath, "utf8")).toBe(test.original) +}) + it("does not apply an unrelated stale proxy setting during GitHub configuration", async () => { const test = await scenario() await configuredGithub(test) From 2bbe0777bc917d7bc785b25e2361f7ea671b1416 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:35:15 -0800 Subject: [PATCH 15/32] fix(azure): link directly to the deployed Hub after consent setup Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/post/index.test.ts | 13 +++++-------- infrastructure/azure/post/index.ts | 2 +- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index d78506691..acfb48672 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -1135,15 +1135,12 @@ it("advances a configured GitHub provider from the verified database revision on expect(test.uploads).toEqual([]) }) -it.each([ - { outcome: "enables", consent: "true", live: "false" }, - { outcome: "disables", consent: "false", live: "true" }, -])("$outcome Learning consent without changing other runtime settings", async ({ consent, live }) => { +it("disables Learning consent without changing other runtime settings", async () => { const test = await scenario() const key = "REPLICA_LEARNING_REVIEW_COMMENT_CONSENT" - test.state.environment[key] = live + test.state.environment[key] = "true" const environment = { ...test.state.environment } - vi.mocked(test.ui.select).mockResolvedValue(consent) + vi.mocked(test.ui.select).mockResolvedValue("false") await postSetupAzure(test.target, { action: "learning", @@ -1155,9 +1152,9 @@ it.each([ const saved = JSON.parse(await readFile(test.inputsPath, "utf8")) as PostInputs expect(saved.runtime_environment_variables).toEqual({ ...test.inputs.runtime_environment_variables, - [key]: consent, + [key]: "false", }) - expect(test.state.environment).toEqual({ ...environment, [key]: consent }) + expect(test.state.environment).toEqual({ ...environment, [key]: "false" }) }) it("resumes saved Learning consent and links the operator to Copilot on the deployed Hub", async () => { diff --git a/infrastructure/azure/post/index.ts b/infrastructure/azure/post/index.ts index 6fcf986ca..bb3cce548 100644 --- a/infrastructure/azure/post/index.ts +++ b/infrastructure/azure/post/index.ts @@ -634,7 +634,7 @@ export async function postSetupAzure( ? "GitHub sign-in is enabled. Verify the App connection, administrator enrollment, OAuth callback and signed webhooks separately." : action === "sign-in" ? "Setup access is available. GitHub sign-in remains dependent on the configured App credentials." - : "Learning consent was saved. Connect or reconnect Copilot in /settings/copilot to record the administrator's consent; reconnect while the setting is off to clear it." + : `Learning consent was saved. Connect or reconnect Copilot at ${publicOrigin}/settings/copilot to record the administrator's consent; reconnect while the setting is off to clear it.` const setupUrl = action === "sign-in" || action === "github" ? `${publicOrigin}/settings/github/setup` : "" return `${config.name}: ${action === "restart" ? "active Hub revision restarted" : "post-setup configuration applied"} using the unchanged deployed image.\n${setupUrl}\n${result}${bootstrapFile ? `\nBootstrap secret saved privately: ${bootstrapFile}. Escrow it before removing this local copy.` : ""}` } catch (error) { From a836bc6f4dd5f7d905b5b9037baaa94a6f3a5afc Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:35:26 -0800 Subject: [PATCH 16/32] fix(hub): confirm learning consent and refresh agent approvals Explain ongoing repository comment imports before a manual run and the note storage allowed by agent approval. After an account switch, show the current approval session without replaying the decision. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../hub/routes/agent-approval-flow.test.tsx | 44 ++++++++++ .../hub/routes/agent-approval/index.tsx | 4 +- .../routes/learning-settings-flow.test.tsx | 80 +++++++++++++++++++ .../hub/routes/learnings-flow.test.tsx | 19 ++++- .../hub/routes/route-naming.test.tsx | 3 +- .../settings-learnings/index.test.ts | 4 +- .../view-models/settings-learnings/index.ts | 5 +- .../pages/agent-connections-page/index.tsx | 6 +- hub/client/pages/learnings-page/index.tsx | 8 +- .../request-learning-run/index.tsx | 55 +++++++++++++ hub/client/pages/learnings-page/stories.tsx | 15 +++- hub/client/pages/learnings-page/styles.css | 10 +-- hub/client/pages/learnings-page/types.ts | 3 +- hub/docs/frontend.md | 4 + 14 files changed, 236 insertions(+), 24 deletions(-) create mode 100644 hub/client/application/hub/routes/agent-approval-flow.test.tsx create mode 100644 hub/client/application/hub/routes/learning-settings-flow.test.tsx create mode 100644 hub/client/pages/learnings-page/request-learning-run/index.tsx diff --git a/hub/client/application/hub/routes/agent-approval-flow.test.tsx b/hub/client/application/hub/routes/agent-approval-flow.test.tsx new file mode 100644 index 000000000..b4a811187 --- /dev/null +++ b/hub/client/application/hub/routes/agent-approval-flow.test.tsx @@ -0,0 +1,44 @@ +import { fireEvent, screen } from "@testing-library/react" +import { describe, expect, it } from "vitest" + +import { http, stubHubFetch } from "@/test/stub-hub-fetch" + +import { renderHubFlow } from "./fixtures/render-hub-flow" + +describe("Agent approval", () => { + it("shows the current account and requires a new decision after an account switch", async () => { + const id = "7c9e6679-7425-40de-944b-e07fc1f90ae7" + const authorization = `/api/agent-connections/authorizations/${id}` + let account = { signedInAs: "octocat", session: "original-session" } + const decisions: unknown[] = [] + const api = stubHubFetch( + http.get(authorization, () => + Response.json({ + agent: "Local MCP client", + redirectUri: "http://127.0.0.1:8123/callback", + expiresAt: "2026-11-30T12:05:00Z", + ...account, + }), + ), + http.post(`${authorization}/approve`, async ({ request }) => { + decisions.push(await request.json()) + return Response.json({ error: "The signed-in account changed." }, { status: 409 }) + }), + ) + const router = await renderHubFlow(api, `/agents/approve/${id}`) + expect(screen.getByText("@octocat")).toBeVisible() + + account = { signedInAs: "mona", session: "current-session" } + await router.settle(() => + fireEvent.click(screen.getByRole("button", { name: "Approve access" })), + ) + + expect(decisions).toEqual([{ session: "original-session" }]) + expect(screen.getByText("@mona")).toBeVisible() + expect(screen.getByText(/submit Pick & Polish notes/i)).toHaveTextContent( + /only for repositories where an administrator has allowed note storage/i, + ) + const approve = screen.getByRole("button", { name: "Approve access" }) + expect(new FormData(approve.form!).get("session")).toBe("current-session") + }) +}) diff --git a/hub/client/application/hub/routes/agent-approval/index.tsx b/hub/client/application/hub/routes/agent-approval/index.tsx index 9609fd993..cdbf0f624 100644 --- a/hub/client/application/hub/routes/agent-approval/index.tsx +++ b/hub/client/application/hub/routes/agent-approval/index.tsx @@ -69,7 +69,9 @@ export async function clientAction({ request, params }: Route.ClientActionArgs) // The agent listens on its own address, so the browser leaves Hub to finish. return redirect(redirectUrl) } catch (error) { - if (error instanceof ApiRequestError && error.status === 401) return redirect(browserPath) + if (error instanceof ApiRequestError && [401, 409].includes(error.status)) { + return redirect(browserPath) + } return canvasActionError(error) } } diff --git a/hub/client/application/hub/routes/learning-settings-flow.test.tsx b/hub/client/application/hub/routes/learning-settings-flow.test.tsx new file mode 100644 index 000000000..8471b8e6e --- /dev/null +++ b/hub/client/application/hub/routes/learning-settings-flow.test.tsx @@ -0,0 +1,80 @@ +import { fireEvent, screen, waitFor, within } from "@testing-library/react" +import { describe, expect, it, onTestFinished } from "vitest" + +import type { LearningSettingsInput } from "@application/hub/learnings-contracts/types" +import { deferred } from "@/test/deferred" +import { http, stubHubFetch } from "@/test/stub-hub-fetch" + +import { authenticatedWorkspace } from "./fixtures/authenticated-workspace" +import { renderHubFlow } from "./fixtures/render-hub-flow" + +const repository = { id: "2001", nameWithOwner: "github/prototype", defaultBranch: "main" } +const settings = `/repositories/${repository.id}/learnings/settings` + +function response(notes: boolean, reviewComments: boolean) { + return Response.json({ + repository, + notes: { allowed: notes, changedBy: null, changedAt: null }, + reviewComments: { allowed: reviewComments, changedBy: null, changedAt: null }, + }) +} + +describe("Learning settings", () => { + it("saves each consent choice separately and shows the refreshed settings", async () => { + let notesAllowed = false + let commentsAllowed = true + const changes: unknown[] = [] + const api = stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(`/api${settings}`, () => response(notesAllowed, commentsAllowed)), + http.patch(`/api${settings}`, async ({ request }) => { + const change = (await request.json()) as LearningSettingsInput + changes.push(change) + notesAllowed = change.notes ?? notesAllowed + commentsAllowed = change.reviewComments ?? commentsAllowed + return response(notesAllowed, commentsAllowed) + }), + ) + const router = await renderHubFlow(api, settings) + const notes = screen.getByRole("switch", { name: "Learn from Pick & Polish notes" }) + const comments = screen.getByRole("switch", { name: "Learn from review comments" }) + + await router.settle(() => fireEvent.click(notes)) + expect(changes).toEqual([{ notes: true }]) + expect(notes).toBeChecked() + expect(comments).toBeChecked() + + await router.settle(() => fireEvent.click(comments)) + expect(changes).toEqual([{ notes: true }, { reviewComments: false }]) + expect(notes).toBeChecked() + expect(comments).not.toBeChecked() + }) + + it("blocks both switches during a save and restores the saved choices after failure", async () => { + const pending = deferred() + onTestFinished(() => pending.resolve()) + const api = stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(`/api${settings}`, () => response(false, true)), + http.patch(`/api${settings}`, async () => { + await pending.promise + return Response.json({ error: "Hub could not save this setting." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(api, settings) + const notes = screen.getByRole("switch", { name: "Learn from Pick & Polish notes" }) + const comments = screen.getByRole("switch", { name: "Learn from review comments" }) + + fireEvent.click(notes) + await waitFor(() => expect(notes).toBeDisabled()) + expect(comments).toBeDisabled() + await router.settle(() => pending.resolve()) + + const page = within(screen.getByRole("region", { name: "Learning settings" })) + expect(page.getByRole("alert")).toHaveTextContent("Hub could not save this setting.") + expect(notes).not.toBeChecked() + expect(comments).toBeChecked() + expect(notes).toBeEnabled() + expect(comments).toBeEnabled() + }) +}) diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index d6a6e6943..5b57e175a 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -299,7 +299,7 @@ describe("Learnings frontend integration", () => { expect(screen.getByText(notice)).toBeVisible() }) - it("posts a run only to the dedicated repository endpoint", async () => { + it("asks before allowing current and future review-comment imports", async () => { const server = stubHubFetch(...learningsWorkspace()) const runRequests = vi.fn() server.use( @@ -314,11 +314,24 @@ describe("Learnings frontend integration", () => { ) const router = await renderHubFlow(server, "/repositories/2001/learnings") + const run = screen.getByRole("button", { name: "Find learnings now" }) + fireEvent.click(run) + const confirmation = screen.getByRole("dialog") + expect(confirmation).toHaveTextContent("github/prototype") + expect(confirmation).toHaveTextContent(/review comments.*this run and future runs/i) + fireEvent.click(within(confirmation).getByRole("button", { name: "Cancel" })) + await router.settle() + expect(runRequests).not.toHaveBeenCalled() + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + + fireEvent.click(run) await router.settle(() => - fireEvent.click(screen.getByRole("button", { name: "Find learnings now" })), + fireEvent.click( + within(screen.getByRole("dialog")).getByRole("button", { name: "Confirm and run" }), + ), ) - expect(runRequests).toHaveBeenCalledWith({ contentType: null, text: "" }) + expect(runRequests).toHaveBeenCalledExactlyOnceWith({ contentType: null, text: "" }) expect(await screen.findByText("Hub will look for learnings shortly.")).toBeVisible() }) diff --git a/hub/client/application/hub/routes/route-naming.test.tsx b/hub/client/application/hub/routes/route-naming.test.tsx index f51abc92a..144035c4c 100644 --- a/hub/client/application/hub/routes/route-naming.test.tsx +++ b/hub/client/application/hub/routes/route-naming.test.tsx @@ -158,7 +158,8 @@ describe("Hub primary route names", () => { }), ) const router = await renderHubFlow(api, `${path}?repositoryId=${first.id}`) - const run = screen.getByRole("button", { name: "Find learnings now" }) + fireEvent.click(screen.getByRole("button", { name: "Find learnings now" })) + const run = within(screen.getByRole("dialog")).getByRole("button", { name: "Confirm and run" }) expect(new URL(run.closest("form")!.action).pathname).toBe(`${path}/runs`) await router.settle(() => fireEvent.click(run)) await router.settle(async () => diff --git a/hub/client/application/hub/view-models/settings-learnings/index.test.ts b/hub/client/application/hub/view-models/settings-learnings/index.test.ts index 89e29cc41..25db90f39 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.test.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.test.ts @@ -75,7 +75,7 @@ describe("settingsLearnings()", () => { expect(result.accessDenied).toBe(false) if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) + expect(result.run?.path).toBe("/repositories/2001/learnings/runs") expect(result.administrationLinks).toEqual([]) }) @@ -128,6 +128,6 @@ describe("settingsLearnings()", () => { ) if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.run).toEqual({ path: "/repositories/2001/learnings/runs" }) + expect(result.run?.path).toBe("/repositories/2001/learnings/runs") }) }) 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 ef72b98eb..57f5ba73f 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -76,7 +76,10 @@ export function settingsLearnings( // Keep an explicit run available so repository admins can establish first-run consent. run: !state.solo && state.permissions.requestRun && state.runAvailable - ? { path: `/repositories/${repositoryId}/learnings/runs` } + ? { + path: `/repositories/${repositoryId}/learnings/runs`, + repositoryName: repository.nameWithOwner, + } : null, loadError: state.loadError, identityNotice: diff --git a/hub/client/pages/agent-connections-page/index.tsx b/hub/client/pages/agent-connections-page/index.tsx index d557590cf..f14e0e6d9 100644 --- a/hub/client/pages/agent-connections-page/index.tsx +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -42,8 +42,10 @@ export function AgentConnectionsPage({ )} You are signed in as @{data.signedInAs}. This agent can read guidance - and report which learnings it applied for repositories you can access. Hub checks access - on every request; only people can accept or change learnings. + and report which learnings it applied for repositories you can access. It can also + submit Pick & Polish notes. Hub stores those notes only for repositories where an + administrator has allowed note storage. Hub checks access on every request; only people + can accept or change learnings. This does not allow session-message storage, screenshot storage, or automated screenshot diff --git a/hub/client/pages/learnings-page/index.tsx b/hub/client/pages/learnings-page/index.tsx index 4622d8127..c1422e28c 100644 --- a/hub/client/pages/learnings-page/index.tsx +++ b/hub/client/pages/learnings-page/index.tsx @@ -9,6 +9,7 @@ import { LearningActivityGrid } from "@features/learning-activity-grid" import { LearningsLibrary } from "@features/learnings-library" import { RepositoryWorkspace } from "@features/repository-workspace" +import { RequestLearningRun } from "./request-learning-run" import type { LearningsPageData } from "./types" import "./styles.css" @@ -47,12 +48,7 @@ function LearningsContent({ data }: { data: Extract {data.run ? ( -
- - -
+ ) : null} {data.settingsPath ? ( + {confirming ? ( + setConfirming(false)} + > + +
setConfirming(false)} + > + + + +
+
+ ) : null} + + ) +} diff --git a/hub/client/pages/learnings-page/stories.tsx b/hub/client/pages/learnings-page/stories.tsx index 2db17f493..017987a9e 100644 --- a/hub/client/pages/learnings-page/stories.tsx +++ b/hub/client/pages/learnings-page/stories.tsx @@ -21,7 +21,20 @@ export default meta type Story = StoryObj export const Default: Story = { - args: { data: { ...data, run: { path: "/repositories/2001/learnings/runs" } } }, + args: { + data: { + ...data, + run: { path: "/repositories/2001/learnings/runs", repositoryName: "github/prototype" }, + }, + }, +} + +export const RunConfirmation: Story = { + ...Default, + play: async ({ canvas, userEvent }) => { + await userEvent.click(canvas.getByRole("button", { name: "Find learnings now" })) + await canvas.findByRole("dialog", { name: "Find learnings now?" }) + }, } export const AccessDenied: Story = { diff --git a/hub/client/pages/learnings-page/styles.css b/hub/client/pages/learnings-page/styles.css index 29cb1e1a7..9105a7bdf 100644 --- a/hub/client/pages/learnings-page/styles.css +++ b/hub/client/pages/learnings-page/styles.css @@ -6,7 +6,8 @@ padding: 1.5rem; } -.learnings-page__header-actions { +.learnings-page__header-actions, +.learnings-page__run-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; @@ -42,8 +43,7 @@ font-weight: 600; } -.learnings-page__header-actions { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; +.learnings-page__run-actions { + justify-content: flex-end; + margin-block-start: 1.25rem; } diff --git a/hub/client/pages/learnings-page/types.ts b/hub/client/pages/learnings-page/types.ts index 1a91dd7dc..59cb192fb 100644 --- a/hub/client/pages/learnings-page/types.ts +++ b/hub/client/pages/learnings-page/types.ts @@ -21,8 +21,7 @@ export type LearningsPageData = localLearningSetupCommand: string | null activity: LearningActivityDay[] today: string - /** Only for Hubs without daily runs, which otherwise could never find learnings. */ - run: { path: string } | null + run: { path: string; repositoryName: string } | null agentsPath: string | null /** Null for people who can change neither the budget nor this repository. */ settingsPath: string | null diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index a03c79dfb..605061ba0 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -28,6 +28,10 @@ Workspace navigation carries `repositoryId` into Hub-wide pages. The ID selects Analytics and Learnings belong to `/repositories/:repositoryId/analytics` and `/repositories/:repositoryId/learnings`. Their path identifier selects the repository for reads and form submissions, even if a query parameter names another repository. Malformed identifiers return 404 on Analytics and 400 on Learnings. Both return 404 for an unavailable repository. Hub-wide Public sharing uses `/settings/sharing`. Security audit keeps its existing `/settings/audit?scope=hub` and `/settings/audit?scope=repository&repositoryId=...` URLs. +On Learnings, **Find learnings now** asks a repository administrator to confirm before requesting a run. The confirmation names the repository and explains that permission to import its review comments also applies to future runs. **Learning settings** can stop future imports; requesting a run does not override that choice. + +The agent approval page explains that agents can submit Pick & Polish notes only where a repository administrator allows note storage. If you switch accounts before approving or canceling, Hub shows the new account and asks you to choose again. + Hub does not show the [decision-model control plane](decision-model-control-plane.md) yet; it is available only through its API. Old `/settings/analytics` and `/settings/learnings` links redirect to the selected repository's canonical page, retaining other query parameters. Without `repositoryId`, they select the first accessible repository; invalid or unavailable explicit context remains an error. `/admin/sharing` redirects to `/settings/sharing`, preserving its query parameters. From 79b50c3feec20a61e0067056e011176910182fc6 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:36:31 -0800 Subject: [PATCH 17/32] fix(hub): import Pick & Polish notes in retry-safe batches Use committed note and reply event versions as receipts so retries can finish marking learning work without rescheduling unchanged evidence. Split large batches without renumbering replies and attribute human feedback to the authenticated submitter. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../migration.sql | 8 +- .../pick-and-polish-note-receipt.prisma | 15 ++- .../create-learning-mcp-backend/index.test.ts | 103 ++++++++------ .../create-learning-mcp-backend/index.ts | 59 +++++--- .../submit-notes.db.test.ts | 126 ++++++++++++++++++ .../pick-and-polish-note-batches/index.ts | 70 ++++++++++ .../index.db.test.ts | 29 +++- .../index.ts | 14 +- hub/server/routes/agent-connections/index.ts | 6 +- packages/learning/index.d.mts | 2 + packages/learning/src/mcp.mjs | 2 +- .../learning/src/sources/agent-sessions.mjs | 12 +- packages/learning/src/store.mjs | 29 ++-- packages/learning/test/agent-session.test.mjs | 42 ++++++ 14 files changed, 412 insertions(+), 105 deletions(-) create mode 100644 hub/server/domains/agent-connections/create-learning-mcp-backend/submit-notes.db.test.ts create mode 100644 hub/server/domains/agent-connections/pick-and-polish-note-batches/index.ts diff --git a/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql b/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql index e9a5b0f94..1f6c8110b 100644 --- a/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql +++ b/hub/schema/migrations/20261223171000_pick_and_polish_note_receipts/migration.sql @@ -1,14 +1,16 @@ -- CreateTable CREATE TABLE "pick_and_polish_note_receipts" ( + "id" UUID NOT NULL, "repository_id" UUID NOT NULL, "receipt_id" VARCHAR(64) NOT NULL, - "received_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT "pick_and_polish_note_receipts_pkey" PRIMARY KEY ("repository_id", "receipt_id") + CONSTRAINT "pick_and_polish_note_receipts_pkey" PRIMARY KEY ("id") ); -- CreateIndex -CREATE INDEX "pick_and_polish_note_receipts_repository_id_received_at_idx" ON "pick_and_polish_note_receipts"("repository_id", "received_at"); +CREATE UNIQUE INDEX "pick_and_polish_note_receipts_repository_id_receipt_id_key" ON "pick_and_polish_note_receipts"("repository_id", "receipt_id"); -- AddForeignKey ALTER TABLE "pick_and_polish_note_receipts" ADD CONSTRAINT "pick_and_polish_note_receipts_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/pick-and-polish-note-receipt.prisma b/hub/schema/pick-and-polish-note-receipt.prisma index 3588b9469..88186a19b 100644 --- a/hub/schema/pick-and-polish-note-receipt.prisma +++ b/hub/schema/pick-and-polish-note-receipt.prisma @@ -1,13 +1,18 @@ model PickAndPolishNoteReceipt { + // 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 - repositoryId String @map("repository_id") @db.Uuid - receiptId String @map("receipt_id") @db.VarChar(64) - receivedAt DateTime @default(now()) @map("received_at") @db.Timestamptz(3) + receiptId String @map("receipt_id") @db.VarChar(64) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) - @@id([repositoryId, receiptId]) - @@index([repositoryId, receivedAt]) + @@unique([repositoryId, receiptId]) @@map("pick_and_polish_note_receipts") } 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 f664c571f..ea7c73a07 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 @@ -265,16 +265,26 @@ function submitSession(backend: ReturnType, sub function createSessionBackend( root: string, - notes: { grantId(): Promise; received(receiptId: string): Promise }, + notes: { grantId(): Promise; received(receiptIds: string[]): Promise }, events: string[] = [], ) { - const input = { + return createLearningMcpBackend({ confirmAccess: () => { events.push("access") return Promise.resolve(true) }, connectionId: "connection", - notes, + notes: { + user: "ana-designer", + grantId: async () => { + events.push("grant") + return notes.grantId() + }, + received: async (receiptIds) => { + events.push("received") + await notes.received(receiptIds) + }, + }, learning: { applicationRoot: join(root, "app"), cliPath: "replica-learning", @@ -294,19 +304,7 @@ function createSessionBackend( } }, toAgentError: (code: string, message: string) => new Error(`${code}: ${message}`), - user: "ana-designer", - } - input.notes = { - grantId: async () => { - events.push("grant") - return notes.grantId() - }, - received: async (receiptId: string) => { - events.push("received") - await notes.received(receiptId) - }, - } - return createLearningMcpBackend(input) + }) } async function createSessionTestRoot() { @@ -327,11 +325,7 @@ it("imports only supplied Pick & Polish notes as the connected GitHub user", asy const file = arguments_[arguments_.indexOf("agent-session") + 1]! const parsed: unknown = JSON.parse(await readFile(file, "utf8")) imported = parsed as Record - return { addedEpisodes: 1, addedEvents: 0 } - }) - runLearningCommand.mockImplementationOnce(() => { - events.push("import") - return Promise.resolve({ addedEpisodes: 0, addedEvents: 1 }) + return { addedEpisodes: 2, addedEvents: 2, noteEventIds: ["request", "reply"] } }) const backend = createSessionBackend( root, @@ -354,10 +348,6 @@ it("imports only supplied Pick & Polish notes as the connected GitHub user", asy messages: [{ role: "user", text: "Do not store this private chat." }], pickAndPolishNotes: [note], }) - await submitSession(backend, { - sessionId: "session-2", - pickAndPolishNotes: [note], - }) expect(imported).toMatchObject({ sessionId: "session-1", @@ -375,7 +365,7 @@ it("imports only supplied Pick & Polish notes as the connected GitHub user", asy "github.com/repositories/1", ]), ) - expect(received).toHaveBeenCalledTimes(2) + expect(received).toHaveBeenCalledExactlyOnceWith(["request", "reply"]) expect(events).toEqual([ "serialize:start", "grant", @@ -384,22 +374,16 @@ it("imports only supplied Pick & Polish notes as the connected GitHub user", asy "access", "received", "serialize:end", - "serialize:start", - "grant", - "access", - "import", - "access", - "received", - "serialize:end", ]) }) -it("retries the receipt after an idempotent notes import", async () => { +it("retries the same stored evidence after an import commits but its receipt fails", async () => { const root = await createSessionTestRoot() - const received = vi.fn<(receiptId: string) => Promise>().mockResolvedValue(undefined) + const received = vi.fn().mockRejectedValueOnce(new Error("marker unavailable")) + const noteEventIds = ["request"] runLearningCommand - .mockImplementationOnce(() => Promise.resolve({ addedEpisodes: 1, addedEvents: 0 })) - .mockImplementationOnce(() => Promise.resolve({ addedEpisodes: 0, addedEvents: 0 })) + .mockResolvedValueOnce({ addedEpisodes: 2, addedEvents: 1, noteEventIds }) + .mockResolvedValueOnce({ addedEpisodes: 0, addedEvents: 0, noteEventIds }) const backend = createSessionBackend(root, { grantId: () => Promise.resolve("pick-polish-grant"), received, @@ -417,12 +401,47 @@ it("retries the receipt after an idempotent notes import", async () => { messages: [], pickAndPolishNotes: [note], } - await submitSession(backend, submission) - await submitSession(backend, submission) + await expect(submitSession(backend, submission)).rejects.toThrow("marker unavailable") + await expect(submitSession(backend, submission)).resolves.toEqual({ + addedEpisodes: 0, + addedEvents: 0, + }) + expect(received.mock.calls).toEqual([[noteEventIds], [noteEventIds]]) +}) - expect(received).toHaveBeenCalledTimes(2) - expect(received.mock.calls[0]?.[0]).toMatch(/^[a-f0-9]{64}$/) - expect(received.mock.calls[1]?.[0]).toBe(received.mock.calls[0]?.[0]) +it("rejects ambiguous or overflowing positions before importing any chunk", async () => { + const root = await createSessionTestRoot() + const backend = createSessionBackend(root, { + grantId: () => Promise.resolve("grant"), + received: vi.fn(), + }) + const notes = Array.from({ length: 200 }, (_, i) => ({ localId: `n-${i}`, body: "A request." })) + const badOffset = { + localId: "long-thread", + thread: { + messageOffset: Number.MAX_SAFE_INTEGER - 200, + messages: Array.from({ length: 201 }, (_, i) => ({ + id: `r-${i}`, + role: "author", + body: "A reply.", + })), + }, + } + const repeatedReply = { + ...badOffset, + thread: { + messages: [...badOffset.thread.messages, { id: "r-0", role: "author", body: "Edited." }], + }, + } + for (const last of [notes[0], badOffset, repeatedReply]) { + await expect( + submitSession(backend, { + sessionId: "session", + pickAndPolishNotes: [...notes, last], + }), + ).rejects.toThrow("invalid_input") + } + expect(runLearningCommand).not.toHaveBeenCalled() }) it("stores no notes and reports an inactive grant without note consent", async () => { 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 aad08cc31..6ff0b4890 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 @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto" import { access, mkdtemp, rm, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { join, resolve } from "node:path" @@ -8,6 +7,10 @@ import { LearningCommandError } from "../../../integrations/learning/run-learnin import { LearningExecutionBusyError } from "../../../integrations/postgres/with-learning-execution-lock/errors.ts" import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" import { learningStoreArguments } from "../../learning/learning-store-arguments/index.ts" +import { + pickAndPolishNoteBatches, + type SubmittedNote, +} from "../pick-and-polish-note-batches/index.ts" const agentErrorCodes = new Set([ "conflict", @@ -34,6 +37,14 @@ interface StoredLearning { withheld: boolean } +interface NoteImportSummary { + sessionId: string + episodeId: string + addedEpisodes: number + addedEvents: number + skippedMessages: number +} + /** Writes private text to a file only this process can read, and removes it afterwards. */ async function withPrivateFile(content: string, operation: (file: string) => Promise) { const folder = await mkdtemp(join(tmpdir(), "replica-agent-")) @@ -57,13 +68,13 @@ export function createLearningMcpBackend(input: { learning: LearningSettings learningsUrl: string notes?: { + user: string grantId(): Promise - received(receiptId: string): Promise + received(receiptIds: string[]): Promise } repository: { id: string; githubRepositoryId: bigint } serialize(operation: (signal: AbortSignal) => Promise): Promise toAgentError: (code: string, message: string) => Error - user?: string }) { const { learning, repository, toAgentError } = input const actor = `agent:hub-connection-${input.connectionId}` @@ -210,7 +221,7 @@ export function createLearningMcpBackend(input: { ) }, - async submitSession(session: { sessionId: string; pickAndPolishNotes?: unknown[] }) { + async submitSession(session: { sessionId: string; pickAndPolishNotes?: SubmittedNote[] }) { const notes = session.pickAndPolishNotes ?? [] if (notes.length === 0) return { @@ -224,7 +235,7 @@ export function createLearningMcpBackend(input: { try { return await input.serialize(async (signal) => { const grantId = (await notesConsent?.grantId()) ?? null - if (!grantId) + if (!notesConsent || !grantId) throw toAgentError( "grant_inactive", `This repository doesn't let Hub learn from Pick & Polish notes, so nothing was stored. A repository administrator can turn on "Learn from Pick & Polish notes" in Learnings settings at ${input.learningsUrl}.`, @@ -233,20 +244,32 @@ export function createLearningMcpBackend(input: { const directory = await storeDirectory() if (!directory) throw toAgentError("not_found", "This repository has no learning store yet.") - const kept = { - sessionId: session.sessionId, - ...(input.user ? { user: `github:${input.user}` } : {}), - messages: [], - pickAndPolishNotes: notes, - } - const content = JSON.stringify(kept) - if (content === undefined) throw new Error("Could not serialize Pick & Polish notes.") - const receiptId = createHash("sha256").update(content).digest("hex") - const result = await withPrivateFile(content, (file) => - runCommand(directory, ["import", "agent-session", file, "--grant", grantId], signal), + const batches = pickAndPolishNoteBatches(notes, (message) => + toAgentError("invalid_input", message), ) - await notesConsent?.received(receiptId) - return result + let summary: NoteImportSummary | undefined + for (const batch of batches) { + const content = JSON.stringify({ + sessionId: session.sessionId, + user: `github:${notesConsent.user}`, + messages: [], + pickAndPolishNotes: batch, + }) + const { noteEventIds, ...result } = (await withPrivateFile(content, (file) => + runCommand(directory, ["import", "agent-session", file, "--grant", grantId], signal), + )) as NoteImportSummary & { noteEventIds: string[] } + if (!Array.isArray(noteEventIds)) + throw new Error("The learning import did not return Pick & Polish event IDs.") + // A retry can add no events but still finish marking a committed chunk. + await notesConsent.received(noteEventIds) + if (!summary) summary = result + else { + summary.addedEpisodes += result.addedEpisodes + summary.addedEvents += result.addedEvents + summary.skippedMessages += result.skippedMessages + } + } + return summary }) } catch (error) { throw safeLearningError(error) diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/submit-notes.db.test.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/submit-notes.db.test.ts new file mode 100644 index 000000000..042d0c873 --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/submit-notes.db.test.ts @@ -0,0 +1,126 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { expect, it, onTestFinished } from "vitest" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" +import { prisma } from "../../../integrations/prisma" +import { recordPickAndPolishNotesReceived } from "../../../repositories/learning-settings/record-pick-and-polish-notes-received" +import { learningStoreArguments } from "../../learning/learning-store-arguments" +import { createLearningMcpBackend } from "." + +it("imports a full results batch with the submitter's identity and original reply positions", async () => { + const repository = await prisma.repository.create({ + data: { + nameWithOwner: "team/checkout", + defaultBranch: "main", + learningSetting: { create: {} }, + }, + }) + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/hosted-notes-")) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const directory = join(root, "repositories", repository.id) + await mkdir(directory, { recursive: true, mode: 0o700 }) + await writeFile( + join(directory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + }), + { mode: 0o600 }, + ) + const learning = { + root, + cliPath: resolve("../packages/learning/bin/replica-learning.mjs"), + nodePath: process.execPath, + staticDirectories: [], + } + const store = learningStoreArguments({ + directory, + repositoryId: repository.id, + repositoryScope: "github.com/repositories/123", + }) + const grant = (await runLearningCommand( + [ + "grants", + "add", + "--purpose", + "review", + "--source", + "agent_session", + "--basis", + "Allow notes for review.", + "--by", + "github:designer", + ...store, + ], + learning, + )) as { id: string } + const backend = createLearningMcpBackend({ + connectionId: "test", + learningsUrl: "https://hub.example/learnings", + learning, + repository: { id: repository.id, githubRepositoryId: 123n }, + confirmAccess: () => Promise.resolve(true), + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + notes: { + user: "designer", + grantId: () => Promise.resolve(grant.id), + received: (ids) => recordPickAndPolishNotesReceived(prisma, repository.id, ids), + }, + }) + const otherNotes = Array.from({ length: 200 }, (_, i) => ({ + localId: `n-${i}`, + body: `Note ${i}`, + })) + const replies = Array.from({ length: 201 }, (_, i) => ({ + id: `r-${i}`, + role: i === 0 ? ("copilot" as const) : ("author" as const), + author: { login: "claimed-reviewer" }, + body: `Reply ${i}`, + })) + const longNote = { + localId: "thread", + body: "Keep a label.", + thread: { + originalAuthor: { login: "claimed-reviewer" }, + messageOffset: 500, + messages: replies, + }, + } + + await expect( + backend.submitSession({ + sessionId: "one", + pickAndPolishNotes: [...otherNotes, longNote], + }), + ).resolves.toMatchObject({ addedEpisodes: 202, addedEvents: 402 }) + const where = { repositoryId: repository.id } + const first = await prisma.repositoryLearningSetting.findUniqueOrThrow({ where }) + expect(first.notesReceivedAt).not.toBeNull() + await expect( + backend.submitSession({ + sessionId: "two", + pickAndPolishNotes: [longNote, ...otherNotes], + }), + ).resolves.toMatchObject({ addedEvents: 0 }) + expect( + (await prisma.repositoryLearningSetting.findUniqueOrThrow({ where })).notesReceivedAt, + ).toEqual(first.notesReceivedAt) + expect(await prisma.pickAndPolishNoteReceipt.count({ where })).toBe(402) + + const observations = (await runLearningCommand( + ["observations", "--purpose", "review", ...store], + learning, + )) as { + events: { actor: { id: string }; payload: { text: string; sequence: number } }[] + } + const byText = new Map(observations.events.map((event) => [event.payload.text, event])) + expect(byText.get("Keep a label.")?.actor.id).toBe("github:designer") + expect(byText.get("Reply 0")?.actor.id).toBe("agent:hub-connection-test") + expect(byText.get("Reply 200")).toMatchObject({ + actor: { id: "github:designer" }, + payload: { sequence: 701 }, + }) +}, 30_000) diff --git a/hub/server/domains/agent-connections/pick-and-polish-note-batches/index.ts b/hub/server/domains/agent-connections/pick-and-polish-note-batches/index.ts new file mode 100644 index 000000000..217e4bc72 --- /dev/null +++ b/hub/server/domains/agent-connections/pick-and-polish-note-batches/index.ts @@ -0,0 +1,70 @@ +interface NoteReply { + id: string + role: "author" | "copilot" + body: string +} + +export interface SubmittedNote { + localId: string + body?: string | null + anchor?: unknown + thread?: { messageOffset?: number; messages?: NoteReply[] } | null +} + +const importLimit = 200 + +/** + * The importer accepts at most 200 notes and 200 replies per thread. Keep each + * reply's original position, but not the unverified author names from the agent. + * The importer then attributes human messages to the authenticated session user. + */ +export function* pickAndPolishNoteBatches( + notes: SubmittedNote[], + invalid: (message: string) => Error, +) { + // Two versions at one position could land in different chunks and create another + // edit on every retry. Reject ambiguous submissions before the first import. + const noteIds = new Set() + for (const { localId, body, thread } of notes) { + if (noteIds.has(localId)) throw invalid("Pick & Polish notes must have different local IDs.") + noteIds.add(localId) + const replies = thread?.messages ?? [] + if (!Number.isSafeInteger((thread?.messageOffset ?? 0) + replies.length)) + throw invalid("A Pick & Polish thread exceeds the position limit.") + const positions = new Set(body?.trim() ? ["request"] : []) + for (const { id } of replies) { + if (positions.has(id)) throw invalid("A Pick & Polish note repeats a message ID.") + positions.add(id) + } + } + + let batch: SubmittedNote[] = [] + for (const { localId, body, anchor, thread } of notes) { + const replies = thread?.messages ?? [] + for (let offset = 0; offset === 0 || offset < replies.length; offset += importLimit) { + // Two slices of the same note must not share an import. + if (batch.length === importLimit || offset > 0) { + yield batch + batch = [] + } + batch.push({ + localId, + body, + anchor, + ...(thread + ? { + thread: { + messageOffset: (thread.messageOffset ?? 0) + offset, + messages: replies.slice(offset, offset + importLimit).map(({ id, role, body }) => ({ + id, + role, + body, + })), + }, + } + : {}), + }) + } + } + if (batch.length) yield batch +} diff --git a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts index 1e09f1e8e..7eb2cbc42 100644 --- a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts +++ b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.db.test.ts @@ -4,7 +4,7 @@ import { expect, it } from "vitest" import { prisma } from "../../../integrations/prisma" import { recordPickAndPolishNotesReceived } from "." -it("advances the notes marker only for a new receipt", async () => { +it("ignores reordered or regrouped evidence but advances the marker for a new reply", async () => { const repository = await prisma.repository.create({ data: { nameWithOwner: `team/${randomUUID()}`, @@ -14,7 +14,7 @@ it("advances the notes marker only for a new receipt", async () => { }) try { - await recordPickAndPolishNotesReceived(prisma, repository.id, "a".repeat(64)) + await recordPickAndPolishNotesReceived(prisma, repository.id, ["note-a", "reply-a", "note-b"]) const first = await prisma.repositoryLearningSetting.findUniqueOrThrow({ where: { repositoryId: repository.id }, }) @@ -25,7 +25,8 @@ it("advances the notes marker only for a new receipt", async () => { where: { repositoryId: repository.id }, data: { notesReceivedAt: olderMarker }, }) - await recordPickAndPolishNotesReceived(prisma, repository.id, "a".repeat(64)) + await recordPickAndPolishNotesReceived(prisma, repository.id, ["note-b", "note-a", "reply-a"]) + await recordPickAndPolishNotesReceived(prisma, repository.id, ["reply-a"]) expect( ( await prisma.repositoryLearningSetting.findUniqueOrThrow({ @@ -34,7 +35,7 @@ it("advances the notes marker only for a new receipt", async () => { ).notesReceivedAt, ).toEqual(olderMarker) - await recordPickAndPolishNotesReceived(prisma, repository.id, "b".repeat(64)) + await recordPickAndPolishNotesReceived(prisma, repository.id, ["note-b", "reply-b"]) expect( ( await prisma.repositoryLearningSetting.findUniqueOrThrow({ @@ -46,8 +47,26 @@ it("advances the notes marker only for a new receipt", async () => { await prisma.pickAndPolishNoteReceipt.count({ where: { repositoryId: repository.id }, }), - ).toBe(2) + ).toBe(4) } finally { await prisma.repository.delete({ where: { id: repository.id } }) } }) + +it("can mark the same evidence after a failed marker update", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: `team/${randomUUID()}`, defaultBranch: "main" }, + }) + function record() { + return recordPickAndPolishNotesReceived(prisma, repository.id, ["note"]) + } + + await expect(record()).rejects.toThrow() + await prisma.repositoryLearningSetting.create({ data: { repositoryId: repository.id } }) + await record() + + const settings = await prisma.repositoryLearningSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }) + expect(settings.notesReceivedAt).not.toBeNull() +}) diff --git a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts index 69092ebab..c9e4159d3 100644 --- a/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts +++ b/hub/server/repositories/learning-settings/record-pick-and-polish-notes-received/index.ts @@ -3,24 +3,18 @@ import type { PrismaClient } from "../../../generated/prisma/client.ts" export async function recordPickAndPolishNotesReceived( database: PrismaClient, repositoryId: string, - receiptId: string, + receiptIds: string[], ) { - const receivedAt = new Date() + if (receiptIds.length === 0) return await database.$transaction(async (transaction) => { - await transaction.pickAndPolishNoteReceipt.deleteMany({ - where: { - repositoryId, - receivedAt: { lt: new Date(receivedAt.getTime() - 90 * 24 * 60 * 60 * 1_000) }, - }, - }) const receipt = await transaction.pickAndPolishNoteReceipt.createMany({ - data: [{ repositoryId, receiptId, receivedAt }], + data: receiptIds.map((receiptId) => ({ repositoryId, receiptId })), skipDuplicates: true, }) if (receipt.count === 0) return await transaction.repositoryLearningSetting.update({ where: { repositoryId }, - data: { notesReceivedAt: receivedAt }, + data: { notesReceivedAt: new Date() }, }) }) } diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 51f4cf2bd..9d8500331 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -204,10 +204,11 @@ export function agentConnectionRoutes( learning, learningsUrl, notes: { + user: result.viewer.login, grantId: async () => (await getRepositoryLearningSetting(prisma, repository.id))?.noteGrantId ?? null, - received: (receiptId) => - recordPickAndPolishNotesReceived(prisma, repository.id, receiptId), + received: (receiptIds) => + recordPickAndPolishNotesReceived(prisma, repository.id, receiptIds), }, repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, serialize: (operation) => @@ -217,7 +218,6 @@ export function agentConnectionRoutes( run: operation, }), toAgentError: (code, message) => new mcp.LearningError(code, message), - user: result.viewer.login, }) const server = mcp.createLearningMcpServer(backend, { name: "replica-hub-learning", diff --git a/packages/learning/index.d.mts b/packages/learning/index.d.mts index 89ee5bc12..0a75bf758 100644 --- a/packages/learning/index.d.mts +++ b/packages/learning/index.d.mts @@ -1115,6 +1115,8 @@ export interface LearningStore { sessionId: string addedEpisodes: number addedEvents: number + /** Stored request and reply versions when notes were supplied, including retries. */ + noteEventIds?: string[] skippedMessages: number }> appendObservations( diff --git a/packages/learning/src/mcp.mjs b/packages/learning/src/mcp.mjs index d57b6b111..a896f7f95 100644 --- a/packages/learning/src/mcp.mjs +++ b/packages/learning/src/mcp.mjs @@ -14,7 +14,7 @@ const SUBMIT_EACH_REQUEST = "After you finish each request, call submit_session with the conversation so far, using the same sessionId each time, so feedback can become new learnings. For long conversations send chunks of at most 5,000 messages, setting messageOffset to the number of earlier messages. Do not wait for the session to end. If you completed a Pick & polish batch, also pass the notes returned by improvement_results unchanged as pickAndPolishNotes. Those notes include the confirmed Copilot replies; do not send the earlier immutable batch notes instead." const SUBMIT_NOTES_ONLY = - "After completing a Pick & polish batch, call submit_session with the same sessionId and the notes returned by improvement_results unchanged as pickAndPolishNotes. Do not send conversations or chat messages." + "After completing a Pick & polish batch, call submit_session with the same sessionId and the notes returned by improvement_results as pickAndPolishNotes. Do not send conversations or chat messages. If the request is too large to send, split the notes across calls. To split one long thread, preserve note and reply IDs and add the number of earlier replies in this batch to its original thread.messageOffset (default 0). Keep the note and reply text unchanged." const SAFE_LEARNING_ERROR_MESSAGES = Object.freeze({ invalid_input: "The request was invalid.", diff --git a/packages/learning/src/sources/agent-sessions.mjs b/packages/learning/src/sources/agent-sessions.mjs index 409757981..84bbe1606 100644 --- a/packages/learning/src/sources/agent-sessions.mjs +++ b/packages/learning/src/sources/agent-sessions.mjs @@ -344,6 +344,7 @@ export function noteEpisode({ note, session, scope, grantIds, principal, importe */ export function noteEvents({ note, session, scope, episodeId, principal, existing, now }) { const { add, added, firstAt } = timeline({ episodeId, scope, existing }) + const noteEventIds = [] for (const [index, entry] of note.entries.entries()) { const person = entry.role === "author" const actor = !person @@ -351,7 +352,7 @@ export function noteEvents({ note, session, scope, episodeId, principal, existin : entry.login ? { kind: "human", id: `github:${entry.login}`, role: "user", asserted: true } : session.user - add( + const id = add( entry.position, person ? "user_message" : "agent_message", firstAt(entry.position) ?? now, @@ -363,8 +364,9 @@ export function noteEvents({ note, session, scope, episodeId, principal, existin }, (latest) => latest.payload.text === entry.text, ) + if (id) noteEventIds.push(id) } - return added + return { added, noteEventIds } } /** @@ -391,10 +393,11 @@ function timeline({ episodeId, scope, existing }) { const versions = history(position) const latest = versions.at(-1) if (versions.some((version) => version.payload === undefined)) return - if (latest && compare(latest)) return + if (latest && compare(latest)) return latest.id + const id = eventId(episodeId, position, latest?.id ?? null) added.push({ schemaVersion: SCHEMA_VERSIONS.event, - id: eventId(episodeId, position, latest?.id ?? null), + id, episodeId, scope, type, @@ -403,6 +406,7 @@ function timeline({ episodeId, scope, existing }) { payload, ...(latest ? { supersedes: latest.id } : {}), }) + return id } /** When a position's first version was recorded, if it has one. */ function firstAt(position) { diff --git a/packages/learning/src/store.mjs b/packages/learning/src/store.mjs index 9ea74be9a..b9406a82e 100644 --- a/packages/learning/src/store.mjs +++ b/packages/learning/src/store.mjs @@ -2201,8 +2201,8 @@ class LearningStore { existing, now, }).map(sealEvent) - // Each Pick & polish note is its own episode, found the same way after a - // migration. + const noteEventIds = [] + // Like the session, a note keeps its episode ID after a scope migration. for (const note of session.notes) { const noteCandidates = [context.scope, ...legacyScopes].map((scope) => noteEpisodeId(scope, note.localId), @@ -2226,21 +2226,21 @@ class LearningStore { const noteExisting = storedNote ? await this.#read("events", context, { episodeIds: [noteId] }) : [] - events.push( - ...noteEvents({ - note, - session, - scope: context.scope, - episodeId: noteId, - principal: context.principal, - existing: noteExisting, - now, - }).map(sealEvent), - ) + const noteResult = noteEvents({ + note, + session, + scope: context.scope, + episodeId: noteId, + principal: context.principal, + existing: noteExisting, + now, + }) + events.push(...noteResult.added.map(sealEvent)) + noteEventIds.push(...noteResult.noteEventIds) } for (const episode of episodes) assertValid("episode", episode) for (const event of events) assertValid("event", event) - return { episodeId, episodes, events, episodeIdentity } + return { episodeId, episodes, events, episodeIdentity, noteEventIds } } const append = async (prepared) => { if (!prepared.episodes.length && !prepared.events.length) return { episodes: 0, events: 0 } @@ -2327,6 +2327,7 @@ class LearningStore { sessionId: session.sessionId, addedEpisodes: added.episodes, addedEvents: added.events, + ...(input.pickAndPolishNotes === undefined ? {} : { noteEventIds: prepared.noteEventIds }), skippedMessages: session.skipped, } } diff --git a/packages/learning/test/agent-session.test.mjs b/packages/learning/test/agent-session.test.mjs index ec1cf04e8..c701fafda 100644 --- a/packages/learning/test/agent-session.test.mjs +++ b/packages/learning/test/agent-session.test.mjs @@ -1058,6 +1058,48 @@ describe("agent sessions", () => { ) }) + it("returns the stored note and reply versions even when a retry adds nothing", async () => { + const store = await createLearningStore({ provider: createInMemoryProvider() }) + const grant = await store.addGrant(designer(), { + purposes: ["review"], + sources: ["agent_session"], + basis: "The team agreed to review its notes.", + }) + function submit(sessionId, notes) { + return store.importAgentSession( + COPILOT, + { sessionId, messages: [], pickAndPolishNotes: notes }, + { grantIds: [grant.id] }, + ) + } + const first = { localId: "first", body: "Make the button larger." } + const second = { localId: "second", body: "Keep the label." } + function reply(body) { + return { ...first, thread: { messages: [{ id: "reply", role: "copilot", body }] } } + } + + const original = await submit("one", [first, second, { localId: "empty", body: " " }]) + const reordered = await submit("two", [second, first]) + assert.equal(original.noteEventIds.length, 2) + assert.deepEqual(new Set(reordered.noteEventIds), new Set(original.noteEventIds)) + + const partial = await submit("three", [first]) + assert.equal(partial.noteEventIds.length, 1) + assert.ok(original.noteEventIds.includes(partial.noteEventIds[0])) + const answered = await submit("four", [reply("Done.")]) + const edited = await submit("five", [reply("Increased it to 44px.")]) + const restored = await submit("six", [reply("Done.")]) + const retry = await submit("six", [reply(" Done. ")]) + const versions = [answered, edited, restored].map(({ noteEventIds }) => { + assert.equal(noteEventIds.length, 2) + assert.ok(noteEventIds.includes(partial.noteEventIds[0])) + return noteEventIds.find((id) => !partial.noteEventIds.includes(id)) + }) + assert.equal(new Set(versions).size, 3) + assert.equal(retry.addedEvents, 0) + assert.deepEqual(retry.noteEventIds, restored.noteEventIds) + }) + it("does not revert a concurrent correction to another Pick & polish note", async () => { const provider = createInMemoryProvider() const store = await createLearningStore({ From 338115753df54b3f2209132e543bdec81f99fd23 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:41:26 -0800 Subject: [PATCH 18/32] fix(hub): enforce current consent throughout learning runs Limit processing to permitted grants and reconcile note consent after interrupted saves. Keep review checkpoints tied to real imports and let unfinished notes continue independently. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/docs/learning-foundation.md | 10 +- .../change-pick-and-polish-consent/index.ts | 51 ++- .../process-learning-run/index.test.ts | 72 ++++- .../learning/process-learning-run/index.ts | 292 +++++++++++------- .../create-learning-run/index.ts | 6 +- .../finish-learning-run/index.ts | 17 +- .../index.db.test.ts | 112 +++++++ .../list-due-learning-repositories/index.ts | 23 +- .../index.db.test.ts | 45 +++ .../get-review-comment-consent/index.ts | 34 +- .../is-effective-administrator/index.ts | 19 +- .../index.ts | 22 +- .../repository-authority.db.test.ts | 101 +++++- hub/server/routes/api/learnings/index.test.ts | 23 +- .../api/learnings/settings/patch/index.ts | 4 +- .../effective-administrator-filter/index.ts | 19 ++ 16 files changed, 655 insertions(+), 195 deletions(-) create mode 100644 hub/server/repositories/learning-settings/get-review-comment-consent/index.db.test.ts create mode 100644 hub/server/utils/effective-administrator-filter/index.ts diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 4000727e3..d0fbf8786 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -85,7 +85,7 @@ The browser contracts are: - `GET /api/repositories/:repositoryId/learnings` - `GET /api/repositories/:repositoryId/learnings/settings` -- `PATCH /api/repositories/:repositoryId/learnings/settings` with `{ "notes": true }` or `{ "reviewComments": false }` +- `PATCH /api/repositories/:repositoryId/learnings/settings` changes one setting at a time: `{ "notes": true }` or `{ "reviewComments": false }`. Retrying a note change after an interrupted save reconciles the grant already recorded in the learning store. - `POST /api/repositories/:repositoryId/learnings/runs` - `POST /api/repositories/:repositoryId/learnings/:learningId/decision` - `GET /api/repositories/:repositoryId/learnings/:learningId/history` @@ -103,15 +103,17 @@ The browser decision route supports accept, reject, retire, edit, and reinstate. The share route takes `{ "shared": true }` to share a learning and `{ "shared": false }` to stop sharing it. It requires Hub administration and the source repository's administrator boundary, rechecked in the same transaction that records the change. Sharing a learning that is not active and usable by agents returns `409`. -The run endpoint requires a usable Copilot connection. It captures and digests one complete repeatable-read repository review snapshot, creates or reuses the repository's active run, writes its typed request audit, and enqueues one idempotent on-demand job. An administrator can promote a queued automatic run into an explicit run; running or already explicit work cannot be replaced. Enqueue failure marks a newly created or promoted run failed. +The run endpoint requires a usable Copilot connection. When review imports are on, it captures and digests one complete repeatable-read repository review snapshot. It creates or reuses the repository's active run, records the request in the security audit, and enqueues one idempotent on-demand job. An administrator can promote a queued automatic run into an explicit run; running or already explicit work cannot be replaced. Enqueue failure marks a newly created or promoted run failed. -Operators may opt in to automatic runs with `REPLICA_LEARNING_AUTOMATIC_RUNS=true`. One stable BullMQ schedule discovers due repositories daily at 02:00 UTC. Discovery is a no-op while the saved Copilot connection is unavailable, refused, or no longer owned by an administrator. A repository is due when its current thread activity versions differ from the review activity snapshot persisted with its last successful run, new Pick & Polish notes arrived after that run, or its most recent successful or partially completed run left comments or suggestions unfinished. This comparison does not depend on review or run timestamps, so a review transaction that commits after snapshot capture remains due even when it assigned its timestamps earlier. Repositories without a successful run become due after their first review evidence. +Operators may opt in to automatic runs with `REPLICA_LEARNING_AUTOMATIC_RUNS=true`. One stable BullMQ schedule discovers due repositories daily at 02:00 UTC. Discovery is a no-op while the saved Copilot connection is unavailable, refused, or no longer owned by an administrator. A review is due when its thread activity differs from the last successful run that actually imported reviews. This comparison does not depend on timestamps: a review committed after capture remains due even if it assigned its timestamps earlier. Newly received notes and unfinished labels or suggestions also make a repository due. A capped run that included notes can continue with notes alone if review learning is now off. Discovery skips repositories without a GitHub ID and removed or disconnected repositories. Review-comment runs capture the normal complete snapshot before creating a run, so repository removal during discovery is skipped and later review drift becomes the same visible `snapshot_changed` run failure as an explicit request. When only Pick & Polish notes are due and review-comment consent is unavailable, Hub schedules note-only work without reading review comments or changing their last successful snapshot. Review-comment work remains due until separately consented. A repository whose latest automatic review-comment run found missing or ended consent stays out of automatic review-comment discovery until a newer explicit administrator run or a newer deployment-wide Copilot consent supersedes that failure; separately consented notes can still run. Turning review-comment learning off also stops future comment imports. The scheduler creates at most one active run per repository and dispatches at most 100 due repositories per sweep, ordered by their least recent run with never-run repositories first. A capture or run-creation failure for one repository is reported and does not block later repositories. Automatic jobs stay on the scheduled queue below maintenance-job priority. Before claiming one under the global learning execution lock, the processor defers to queued or recovered user-requested work on the on-demand queue. The one-minute recovery sweep re-enqueues queued and interrupted running records on their original queue. Enqueue failures for newly discovered automatic runs are persisted as visible failed runs. Completed run records are retained for 90 days. Hub keeps the latest attempt and success for review-comment runs and note-only runs separately, so a newer note submission cannot erase the last review snapshot. Schedule setup uses one stable scheduler ID, so repeated setup updates the daily schedule instead of duplicating it. -The worker claims a queued run only once under the learning execution lock. Review-comment runs recapture the snapshot and refuse drift before importing with `--redact-deleted`; note-only runs skip review-comment capture and import. An explicit repository-administrator run can establish repository-specific review-comment consent. A scheduled review-comment run reuses that grant or creates one only under active deployment-wide Hub-administrator consent. It labels at most 400 comments and ten Copilot requests and consolidates at most ten suggestions over the previous 90 days. It records partial label counts and AI-credit usage even when a later request fails. An incomplete collection, changed snapshot, ended or missing consent, refused credential, or unreadable package result becomes a visible failed run. +The worker claims a queued run only once under the learning execution lock. Review-comment runs recapture the snapshot and refuse drift before importing with `--redact-deleted`; note-only runs skip review-comment capture and import. An explicit repository-administrator run can establish repository-specific review-comment consent. A scheduled review-comment run reuses that grant or creates one only if the person who gave deployment-wide consent is still a Hub administrator. Both labeling and consolidation use only the grants permitted for this run. A note-only run cannot use stored review comments, even if an old deployment grant remains in the package store. + +Each run labels at most 400 comments with at most ten Copilot requests and consolidates at most ten suggestions over the previous 90 days. It records partial label counts and AI-credit usage even when a later request fails. Missing review pages fail a review run but do not block a run limited to delivered notes. A changed snapshot, ended or missing consent, refused credential, or unreadable package result becomes a visible failed run. Soft deletion queues an idempotent package redaction job after the review transaction commits. The recovery sweep also finds deleted review comments, and every later import uses `--redact-deleted`, so a transient queue failure cannot make a deleted body permanently eligible. diff --git a/hub/server/domains/learning/change-pick-and-polish-consent/index.ts b/hub/server/domains/learning/change-pick-and-polish-consent/index.ts index 51495fb2c..97da36fc1 100644 --- a/hub/server/domains/learning/change-pick-and-polish-consent/index.ts +++ b/hub/server/domains/learning/change-pick-and-polish-consent/index.ts @@ -5,6 +5,16 @@ import { learningStoreArguments } from "../learning-store-arguments/index.ts" import { prepareLearningStore } from "../prepare-learning-store/index.ts" const grantSchema = z.object({ id: z.string().min(1).max(255) }).loose() +const listedGrants = z.array( + z.object({ + grant: grantSchema.extend({ + basis: z.string(), + grantedBy: z.object({ kind: z.string() }), + sources: z.array(z.string()), + }), + activePurposes: z.array(z.string()), + }), +) const purposes = ["review", "instruction"] as const const basis = "A repository administrator allowed Hub to learn from Pick & Polish notes agents send." @@ -37,6 +47,41 @@ export async function changePickAndPolishConsent(input: { } const common = learningStoreArguments(store) const purposeArguments = purposes.flatMap((purpose) => ["--purpose", purpose]) + // The package may have committed even if Hub never saved the returned ID. + const managed = listedGrants + .parse(await runLearningCommand(["grants", "list", ...common], options)) + .filter( + ({ grant }) => + grant.basis === basis && + grant.grantedBy.kind === "human" && + grant.sources.length === 1 && + grant.sources[0] === "agent_session", + ) + const usable = managed.filter(({ activePurposes }) => + purposes.every((purpose) => activePurposes.includes(purpose)), + ) + const retained = input.allowed + ? (usable.find(({ grant }) => grant.id === input.grantId) ?? usable[0]) + : undefined + for (const { grant, activePurposes } of managed) { + if (grant.id === retained?.grant.id) continue + const ending = purposes.filter((purpose) => activePurposes.includes(purpose)) + if (ending.length) { + await runLearningCommand( + [ + "grants", + "withdraw", + grant.id, + ...ending.flatMap((p) => ["--purpose", p]), + "--by", + input.actor, + ...common, + ], + options, + ) + } + } + if (retained) return retained.grant.id if (input.allowed) { const grant = grantSchema.parse( await runLearningCommand( @@ -57,11 +102,5 @@ export async function changePickAndPolishConsent(input: { ) return grant.id } - if (input.grantId) { - await runLearningCommand( - ["grants", "withdraw", input.grantId, ...purposeArguments, "--by", input.actor, ...common], - options, - ) - } return null } diff --git a/hub/server/domains/learning/process-learning-run/index.test.ts b/hub/server/domains/learning/process-learning-run/index.test.ts index c7a5d5f67..092f9634e 100644 --- a/hub/server/domains/learning/process-learning-run/index.test.ts +++ b/hub/server/domains/learning/process-learning-run/index.test.ts @@ -60,6 +60,7 @@ function dependencies(overrides: Partial = {}) { turnedOff: false, hubAdministrator: null, repositoryGrantId: null, + noteGrantId: "note-grant", }), recordRepositoryReviewCommentGrant: vi.fn().mockResolvedValue(undefined), now: vi.fn(() => new Date("2026-11-13T10:00:00Z")), @@ -105,21 +106,30 @@ function dependencies(overrides: Partial = {}) { } describe("processLearningRun()", () => { - it("processes scheduled notes without reading review comments or asking for their consent", async () => { + it("labels and consolidates only the note grant on a scheduled notes run", async () => { const deps = dependencies({ expectedScheduled: true }) deps.run.scheduled = true deps.run.requestedBy = null deps.run.requestedByMembershipId = null deps.run.snapshotDigest = null deps.run.reviewCommentsDue = false + const command = deps.runCommand + deps.runCommand = async (...args) => { + const result = await command(...args) + return args[0][0] === "consolidate" ? { status: "incomplete", proposals: [] } : result + } await processLearningRun("11111111-2222-4333-8444-555555555555", deps) expect(deps.capture).not.toHaveBeenCalled() - expect(deps.reviewCommentConsent).not.toHaveBeenCalled() expect(deps.commands.some((arguments_) => arguments_[0] === "grants")).toBe(false) expect(deps.commands.some((arguments_) => arguments_[0] === "import")).toBe(false) - expect(deps.commands.some((arguments_) => arguments_[0] === "label")).toBe(true) + for (const phase of ["label", "consolidate"]) { + const command = deps.commands.find((args) => args[0] === phase)! + expect(command.flatMap((arg, i) => (arg === "--grant" ? [command[i + 1]] : []))).toEqual([ + "note-grant", + ]) + } expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) }) @@ -172,6 +182,7 @@ describe("processLearningRun()", () => { expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED", + reviewCommentsImported: true, suggestions: 1, suggestionsRemaining: 1, }, @@ -668,12 +679,44 @@ describe("processLearningRun()", () => { expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) }) + it("stops before import if deployment consent ends after granting access", async () => { + const active = { + turnedOff: false, + hubAdministrator: "human:mona", + repositoryGrantId: null, + noteGrantId: null, + } + const deps = dependencies({ expectedScheduled: true }) + deps.run.scheduled = true + let activeAdministrator: string | null = active.hubAdministrator + vi.mocked(deps.reviewCommentConsent).mockImplementation(() => + Promise.resolve({ + ...active, + hubAdministrator: activeAdministrator, + }), + ) + const command = deps.runCommand + deps.runCommand = async (...args) => { + const result = await command(...args) + if (args[0][1] === "add") activeAdministrator = null + return result + } + + await processLearningRun(deps.run.id, deps) + + expect(deps.commands.some((args) => args[0] === "import")).toBe(false) + expect(deps.finished[0]).toMatchObject({ + input: { state: "FAILED", failureCode: "grant_inactive" }, + }) + }) + it("does not import review comments after a repository administrator turns them off", async () => { const deps = dependencies({ reviewCommentConsent: vi.fn().mockResolvedValue({ turnedOff: true, hubAdministrator: "human:mona", repositoryGrantId: null, + noteGrantId: null, }), }) @@ -681,8 +724,10 @@ describe("processLearningRun()", () => { expect(deps.commands.some((arguments_) => arguments_[0] === "grants")).toBe(false) expect(deps.commands.some((arguments_) => arguments_[0] === "import")).toBe(false) - expect(deps.commands.some((arguments_) => arguments_[0] === "consolidate")).toBe(true) - expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) + expect(deps.commands.some((args) => ["label", "consolidate"].includes(args[0]!))).toBe(false) + expect(deps.finished[0]).toMatchObject({ + input: { state: "SUCCEEDED", reviewCommentsImported: false }, + }) }) it("does not reuse a deployment-wide grant after deployment consent is disabled", async () => { @@ -797,6 +842,7 @@ describe("processLearningRun()", () => { turnedOff: false, hubAdministrator: null, repositoryGrantId: "repository-grant", + noteGrantId: "note-grant", }), runCommand: vi.fn((arguments_: string[]) => { if (arguments_[0] === "grants" && arguments_[1] === "list") { @@ -810,6 +856,15 @@ describe("processLearningRun()", () => { activePurposes: ["review", "instruction"], expired: false, }, + { + grant: { + id: "old-deployment-grant", + sources: ["hub_review_comments"], + grantedBy: { kind: "human", id: "github:admin" }, + }, + activePurposes: ["review", "instruction"], + expired: false, + }, ]) } if (arguments_[0] === "import") return Promise.resolve({ complete: true, problems: [] }) @@ -837,6 +892,13 @@ describe("processLearningRun()", () => { expect( vi.mocked(deps.runCommand).mock.calls.some(([arguments_]) => arguments_[0] === "import"), ).toBe(true) + for (const phase of ["label", "consolidate"]) { + const command = vi.mocked(deps.runCommand).mock.calls.find(([args]) => args[0] === phase)![0] + expect(command.flatMap((arg, i) => (arg === "--grant" ? [command[i + 1]] : []))).toEqual([ + "repository-grant", + "note-grant", + ]) + } expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) }) }) diff --git a/hub/server/domains/learning/process-learning-run/index.ts b/hub/server/domains/learning/process-learning-run/index.ts index d10fef496..8f4d53896 100644 --- a/hub/server/domains/learning/process-learning-run/index.ts +++ b/hub/server/domains/learning/process-learning-run/index.ts @@ -47,7 +47,7 @@ const labelSchema = z .loose() const consolidateSchema = z .object({ - status: z.string(), + status: z.enum(["complete", "incomplete"]), proposals: z.array(z.object({ updatedAt: z.string().optional() }).loose()), overBudget: z.number().int().nonnegative().optional(), }) @@ -76,6 +76,7 @@ export async function processLearningRun( input: | { state: "SUCCEEDED" + reviewCommentsImported: boolean suggestions: number suggestionsRemaining: number finishedAt: Date @@ -105,6 +106,7 @@ export async function processLearningRun( turnedOff: boolean hubAdministrator: string | null repositoryGrantId: string | null + noteGrantId: string | null }> recordRepositoryReviewCommentGrant(repositoryId: string, grantId: string): Promise prepare(repositoryId: string): Promise<{ @@ -182,9 +184,11 @@ export async function processLearningRun( } actor = `human:${requester}` } - const snapshot = current.reviewCommentsDue - ? await dependencies.capture(current.repositoryId) - : null + const consent = await dependencies.reviewCommentConsent(current.repositoryId) + const snapshot = + current.reviewCommentsDue && !consent.turnedOff + ? await dependencies.capture(current.repositoryId) + : null if ( snapshot && (!current.snapshotDigest || @@ -204,129 +208,149 @@ export async function processLearningRun( ) } const common = learningStoreArguments(store) - if (snapshot) { - const consent = await dependencies.reviewCommentConsent(current.repositoryId) - if (!consent.turnedOff) { - const grants = grantListSchema.parse( - await dependencies.runCommand(["grants", "list", ...common], { signal }), - ) - const sourceGrants = grants.filter((entry) => - entry.grant.sources.includes("hub_review_comments"), + let reviewGrantIds: string[] = [] + async function recheckDeploymentConsent(ids: string[]) { + if (!ids.length || !consent.hubAdministrator) return + const latest = await dependencies.reviewCommentConsent(store.repositoryId) + if ( + latest.turnedOff || + (!latest.hubAdministrator && ids.some((id) => id !== latest.repositoryGrantId)) + ) { + throw new LearningCommandError( + "grant_inactive", + "Consent to use this repository's review comments ended.", ) - const humanSourceGrants = sourceGrants.filter( - (entry) => entry.grant.grantedBy.kind === "human", + } + } + if (snapshot) { + const grants = grantListSchema.parse( + await dependencies.runCommand(["grants", "list", ...common], { signal }), + ) + const sourceGrants = grants.filter( + (entry) => + entry.grant.sources.length === 1 && entry.grant.sources[0] === "hub_review_comments", + ) + const humanSourceGrants = sourceGrants.filter( + (entry) => entry.grant.grantedBy.kind === "human", + ) + let consentedGrants = consent.hubAdministrator + ? humanSourceGrants + : humanSourceGrants.filter((entry) => entry.grant.id === consent.repositoryGrantId) + if (!consent.hubAdministrator && !consent.repositoryGrantId) { + const legacyGrants = humanSourceGrants.filter( + (entry) => + entry.grant.basis === + "A repository administrator explicitly requested this learning run." && + entry.grant.purposes.includes("review") && + entry.grant.purposes.includes("instruction"), ) - let consentedGrants = consent.hubAdministrator - ? humanSourceGrants - : humanSourceGrants.filter((entry) => entry.grant.id === consent.repositoryGrantId) - if (!consent.hubAdministrator && !consent.repositoryGrantId) { - const legacyGrants = humanSourceGrants.filter( - (entry) => - entry.grant.basis === - "A repository administrator explicitly requested this learning run." && - entry.grant.purposes.includes("review") && - entry.grant.purposes.includes("instruction"), - ) - const legacyGrant = - legacyGrants.find( - (entry) => - !entry.expired && - entry.activePurposes.includes("review") && - entry.activePurposes.includes("instruction"), - ) ?? legacyGrants[0] - if (legacyGrant) { - await dependencies.recordRepositoryReviewCommentGrant( - current.repositoryId, - legacyGrant.grant.id, - ) - consentedGrants = [legacyGrant] - } - } - let grantIds = consentedGrants - .filter( + const legacyGrant = + legacyGrants.find( (entry) => !entry.expired && entry.activePurposes.includes("review") && entry.activePurposes.includes("instruction"), + ) ?? legacyGrants[0] + if (legacyGrant) { + await dependencies.recordRepositoryReviewCommentGrant( + current.repositoryId, + legacyGrant.grant.id, ) - .map((entry) => entry.grant.id) - if (grantIds.length === 0) { - if ( - !consent.hubAdministrator && - consentedGrants.some((entry) => - entry.grant.purposes.some( - (purpose) => purpose === "review" || purpose === "instruction", - ), - ) - ) { - throw new LearningCommandError( - "grant_inactive", - "Consent to use this repository's review comments ended.", - ) - } - const consenter = current.scheduled ? consent.hubAdministrator : actor - if (!consenter) { - throw new LearningCommandError( - "grant_required", - "A Hub administrator must reconnect Copilot, or a repository administrator must request the first learning run.", - ) - } - const grant = addedGrantSchema.parse( - await dependencies.runCommand( - [ - "grants", - "add", - "--purpose", - "review", - "--purpose", - "instruction", - "--source", - "hub_review_comments", - "--basis", - current.scheduled - ? "A Hub administrator agreed to learn from every repository's review comments when connecting Copilot." - : "A repository administrator explicitly requested this learning run.", - "--by", - consenter, - ...common, - ], - { signal }, + consentedGrants = [legacyGrant] + } + } + let grantIds = consentedGrants + .filter( + (entry) => + !entry.expired && + entry.activePurposes.includes("review") && + entry.activePurposes.includes("instruction"), + ) + .map((entry) => entry.grant.id) + if (grantIds.length === 0) { + if ( + !consent.hubAdministrator && + consentedGrants.some((entry) => + entry.grant.purposes.some( + (purpose) => purpose === "review" || purpose === "instruction", ), ) - grantIds = [grant.id] - if (!current.scheduled) { - await dependencies.recordRepositoryReviewCommentGrant(current.repositoryId, grant.id) - } + ) { + throw new LearningCommandError( + "grant_inactive", + "Consent to use this repository's review comments ended.", + ) + } + const deployment = + current.scheduled && consent.hubAdministrator + ? await dependencies.reviewCommentConsent(current.repositoryId) + : null + const consenter = current.scheduled + ? deployment && !deployment.turnedOff && deployment.hubAdministrator + : actor + if (!consenter) { + throw new LearningCommandError( + "grant_required", + "A Hub administrator must reconnect Copilot, or a repository administrator must request the first learning run.", + ) } + const grant = addedGrantSchema.parse( + await dependencies.runCommand( + [ + "grants", + "add", + "--purpose", + "review", + "--purpose", + "instruction", + "--source", + "hub_review_comments", + "--basis", + current.scheduled + ? "A Hub administrator agreed to learn from every repository's review comments when connecting Copilot." + : "A repository administrator explicitly requested this learning run.", + "--by", + consenter, + ...common, + ], + { signal }, + ), + ) + grantIds = [grant.id] + if (!current.scheduled) { + await dependencies.recordRepositoryReviewCommentGrant(current.repositoryId, grant.id) + } + } - const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-run-")) - try { - const collectionPath = resolve(temporary, "review-collection.json") - await writeFile(collectionPath, JSON.stringify(snapshot.collection), { mode: 0o600 }) - const imported = importSchema.parse( - await dependencies.runCommand( - [ - "import", - "hub-comments", - collectionPath, - ...grantIds.flatMap((grantId) => ["--grant", grantId]), - "--actor", - "system:replica-hub", - "--redact-deleted", - ...common, - ], - { signal }, - ), + const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-run-")) + try { + const collectionPath = resolve(temporary, "review-collection.json") + await writeFile(collectionPath, JSON.stringify(snapshot.collection), { mode: 0o600 }) + await recheckDeploymentConsent(grantIds) + const imported = importSchema.parse( + await dependencies.runCommand( + [ + "import", + "hub-comments", + collectionPath, + ...grantIds.flatMap((grantId) => ["--grant", grantId]), + "--actor", + "system:replica-hub", + "--redact-deleted", + ...common, + ], + { signal }, + ), + ) + if (!imported.complete) { + throw new LearningCommandError( + "incomplete_collection", + `The repository review snapshot is incomplete: ${imported.problems.join(" ")}`, ) - if (!imported.complete) { - throw new LearningCommandError( - "incomplete_collection", - `The repository review snapshot is incomplete: ${imported.problems.join(" ")}`, - ) - } - } finally { - await rm(temporary, { recursive: true }) } + reviewGrantIds = grantIds + } finally { + await rm(temporary, { recursive: true }) } } @@ -334,17 +358,41 @@ export async function processLearningRun( if (!credential) { throw new LearningCommandError("copilot_not_connected", "Copilot is not connected.") } + const grantIds = [...reviewGrantIds, ...(consent.noteGrantId ? [consent.noteGrantId] : [])] + if (!grantIds.length) { + // An omitted --grant means all grants to the package, not none. + await dependencies.finish(runId, { + state: "SUCCEEDED", + reviewCommentsImported: false, + suggestions: 0, + suggestionsRemaining: 0, + finishedAt: dependencies.now(), + }) + return + } + const grantArguments = grantIds.flatMap((id) => ["--grant", id]) const asOf = snapshot?.capturedAt ?? current.startedAt ?? dependencies.now() const since = new Date(asOf.getTime() - 90 * 24 * 60 * 60 * 1_000).toISOString() let labeled: z.infer try { labeled = labelSchema.parse( - await runWithoutRepositoryAuthorityLock(() => - dependencies.runCommand( - ["label", "--since", since, "--limit", "400", "--max-requests", "10", ...common], + await runWithoutRepositoryAuthorityLock(async () => { + await recheckDeploymentConsent(reviewGrantIds) + return dependencies.runCommand( + [ + "label", + "--since", + since, + "--limit", + "400", + "--max-requests", + "10", + ...grantArguments, + ...common, + ], { ...credential, signal, timeoutMs: 30 * 60 * 1000 }, - ), - ), + ) + }), ) } catch (error) { if (error instanceof LearningCommandError && error.result) { @@ -392,6 +440,7 @@ export async function processLearningRun( "The repository learning scope changed during this run. Request another run.", ) } + await recheckDeploymentConsent(reviewGrantIds) const consolidated = consolidateSchema.parse( await dependencies.runCommand( [ @@ -404,12 +453,14 @@ export async function processLearningRun( "system:replica-hub", "--max", "10", + ...grantArguments, ...common, ], { signal }, ), ) - if (consolidated.status !== "complete") { + // The package's window coverage describes Hub reviews, not delivered notes. + if (reviewGrantIds.length && consolidated.status === "incomplete") { throw new LearningCommandError( "incomplete_collection", "The learning store did not collect the complete review window.", @@ -417,6 +468,7 @@ export async function processLearningRun( } await dependencies.finish(runId, { state: "SUCCEEDED", + reviewCommentsImported: reviewGrantIds.length > 0, suggestions: consolidated.proposals.filter((proposal) => { if (!proposal.updatedAt || !current.startedAt) return false const updatedAt = Date.parse(proposal.updatedAt) diff --git a/hub/server/repositories/learning-runs/create-learning-run/index.ts b/hub/server/repositories/learning-runs/create-learning-run/index.ts index c979099da..bb42a0546 100644 --- a/hub/server/repositories/learning-runs/create-learning-run/index.ts +++ b/hub/server/repositories/learning-runs/create-learning-run/index.ts @@ -9,8 +9,8 @@ export async function createLearningRun( requestedById: string requestedByMembershipId: string scheduled?: false - reviewCommentsDue?: true - snapshotDigest: string + reviewCommentsDue?: boolean + snapshotDigest: string | null reviewActivitySnapshot: Prisma.InputJsonValue } | { @@ -46,7 +46,7 @@ export async function createLearningRun( requestedById: input.requestedById, requestedByMembershipId: input.requestedByMembershipId, scheduled: false, - reviewCommentsDue: true, + reviewCommentsDue: input.reviewCommentsDue ?? true, snapshotDigest: input.snapshotDigest, reviewActivitySnapshot: input.reviewActivitySnapshot, }, diff --git a/hub/server/repositories/learning-runs/finish-learning-run/index.ts b/hub/server/repositories/learning-runs/finish-learning-run/index.ts index 737d32786..de005a79a 100644 --- a/hub/server/repositories/learning-runs/finish-learning-run/index.ts +++ b/hub/server/repositories/learning-runs/finish-learning-run/index.ts @@ -1,4 +1,4 @@ -import type { Prisma } from "../../../generated/prisma/client.ts" +import { Prisma } from "../../../generated/prisma/client.ts" export function finishLearningRun( database: Pick, @@ -6,6 +6,7 @@ export function finishLearningRun( input: | { state: "SUCCEEDED" + reviewCommentsImported: boolean suggestions: number suggestionsRemaining: number finishedAt: Date @@ -19,6 +20,18 @@ export function finishLearningRun( ) { return database.learningRun.updateMany({ where: { id: runId, state: { in: ["QUEUED", "RUNNING"] } }, - data: input, + data: + input.state === "FAILED" + ? input + : { + state: input.state, + finishedAt: input.finishedAt, + suggestions: input.suggestions, + suggestionsRemaining: input.suggestionsRemaining, + reviewCommentsDue: input.reviewCommentsImported, + ...(input.reviewCommentsImported + ? {} + : { snapshotDigest: null, reviewActivitySnapshot: Prisma.DbNull }), + }, }) } diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts index ee0c59465..87d7d7486 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest" import { createReviewCommentLearningSource } from "../../../domains/learning/create-review-comment-learning-source" import { prisma } from "../../../integrations/prisma" +import { finishLearningRun } from "../finish-learning-run" import { listDueLearningRepositories } from "." async function createReviewEvidence(input: { repositoryId: string; updatedAt: Date }) { @@ -470,6 +471,117 @@ describe("listDueLearningRepositories()", () => { ) }) + it.each([ + { + source: "explicit notes", + scheduled: false, + imported: false, + commentsRemaining: 2, + suggestionsRemaining: 0, + }, + { + source: "mixed", + scheduled: true, + imported: true, + commentsRemaining: 0, + suggestionsRemaining: 1, + }, + { + source: "partially failed", + scheduled: true, + imported: true, + commentsRemaining: 1, + suggestionsRemaining: 0, + }, + ])("resumes unfinished notes from a $source run with review imports off", async (run) => { + const repositoryId = randomUUID() + const beforeRun = new Date("2026-11-18T10:00:00Z") + await prisma.repository.create({ + data: { + id: repositoryId, + nameWithOwner: "team/capped-notes", + defaultBranch: "main", + learningSetting: { + create: { + noteGrantId: "note-grant", + notesReceivedAt: beforeRun, + reviewCommentsTurnedOff: true, + }, + }, + }, + }) + const thread = await createReviewEvidence({ repositoryId, updatedAt: beforeRun }) + await prisma.learningRun.create({ + data: { + repositoryId, + state: "SUCCEEDED", + reviewCommentsDue: false, + createdAt: new Date("2026-11-18T10:15:00Z"), + startedAt: new Date("2026-11-18T10:15:00Z"), + finishedAt: new Date("2026-11-18T10:30:00Z"), + }, + }) + const active = await prisma.learningRun.create({ + data: { + repositoryId, + scheduled: run.scheduled, + state: "RUNNING", + createdAt: new Date("2026-11-18T11:00:00Z"), + startedAt: new Date("2026-11-18T11:00:00Z"), + reviewCommentsDue: true, + reviewActivitySnapshot: { [thread.id]: thread.activityVersion }, + commentsRemaining: run.commentsRemaining, + }, + }) + await finishLearningRun( + prisma, + active.id, + run.source === "partially failed" + ? { + state: "FAILED", + failureCode: "failed", + failureSummary: "Labeling was interrupted.", + finishedAt: new Date("2026-11-18T11:30:00Z"), + } + : { + state: "SUCCEEDED", + reviewCommentsImported: run.imported, + suggestions: 0, + suggestionsRemaining: run.suggestionsRemaining, + finishedAt: new Date("2026-11-18T11:30:00Z"), + }, + ) + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual([ + { id: repositoryId, reviewCommentsDue: false }, + ]) + }) + + it("still discovers unchanged reviews after a successful run skipped their import", async () => { + const repositoryId = randomUUID() + await prisma.repository.create({ + data: { id: repositoryId, nameWithOwner: "team/skipped-reviews", defaultBranch: "main" }, + }) + const thread = await createReviewEvidence({ repositoryId, updatedAt: new Date() }) + const run = await prisma.learningRun.create({ + data: { + repositoryId, + state: "RUNNING", + startedAt: new Date(), + reviewActivitySnapshot: { [thread.id]: thread.activityVersion }, + }, + }) + await finishLearningRun(prisma, run.id, { + state: "SUCCEEDED", + reviewCommentsImported: false, + suggestions: 0, + suggestionsRemaining: 0, + finishedAt: new Date(), + }) + await expect(listDueLearningRepositories(prisma, { requireGitHubId: false })).resolves.toEqual([ + { id: repositoryId, reviewCommentsDue: true }, + ]) + }) + it("finds review evidence committed after snapshot capture with an earlier timestamp", async () => { const repositoryId = randomUUID() await prisma.repository.create({ diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts index c079ff425..a87b0f712 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts @@ -13,7 +13,9 @@ export function listDueLearningRepositories( WITH latest_runs AS ( SELECT DISTINCT ON (repository_id) repository_id, - created_at + created_at, + comments_remaining, + suggestions_remaining FROM learning_runs ORDER BY repository_id, created_at DESC, number DESC ), @@ -42,7 +44,6 @@ export function listDueLearningRepositories( SELECT DISTINCT ON (repository_id) repository_id, created_at, - review_comments_due, comments_remaining, suggestions_remaining FROM learning_runs @@ -74,6 +75,7 @@ export function listDueLearningRepositories( due_sources AS ( SELECT repositories.id, + latest_runs.created_at AS last_run_at, ( NOT COALESCE(settings.review_comments_turned_off, false) AND ( @@ -88,14 +90,15 @@ export function listDueLearningRepositories( ) ) AS review_comments_due, ( - settings.notes_received_at IS NOT NULL + settings.note_grant_id IS NOT NULL + AND settings.notes_received_at IS NOT NULL AND ( latest_any_successes.repository_id IS NULL OR settings.notes_received_at > latest_any_successes.created_at - OR ( - NOT latest_any_successes.review_comments_due - AND (latest_any_successes.comments_remaining > 0 OR latest_any_successes.suggestions_remaining > 0) - ) + OR latest_any_successes.comments_remaining > 0 + OR latest_any_successes.suggestions_remaining > 0 + OR latest_runs.comments_remaining > 0 + OR latest_runs.suggestions_remaining > 0 ) ) AS notes_due, ( @@ -122,6 +125,8 @@ export function listDueLearningRepositories( AND COALESCE(settings.review_comments_turned_off, false) = false ) AS review_comment_consent_blocked FROM repositories + LEFT JOIN latest_runs + ON latest_runs.repository_id = repositories.id LEFT JOIN latest_review_runs ON latest_review_runs.repository_id = repositories.id LEFT JOIN latest_successes @@ -155,8 +160,6 @@ export function listDueLearningRepositories( ) AS "reviewCommentsDue" FROM repositories JOIN due_sources ON due_sources.id = repositories.id - LEFT JOIN latest_runs - ON latest_runs.repository_id = repositories.id WHERE repositories.removed_at IS NULL AND (${input.requireGitHubId} = false OR repositories.github_repository_id > 0) AND NOT EXISTS ( @@ -173,7 +176,7 @@ export function listDueLearningRepositories( due_sources.review_comment_consent_blocked AND NOT due_sources.notes_due ) - ORDER BY latest_runs.created_at ASC NULLS FIRST, repositories.id ASC + ORDER BY due_sources.last_run_at ASC NULLS FIRST, repositories.id ASC LIMIT ${limit} `) } diff --git a/hub/server/repositories/learning-settings/get-review-comment-consent/index.db.test.ts b/hub/server/repositories/learning-settings/get-review-comment-consent/index.db.test.ts new file mode 100644 index 000000000..10cf00bec --- /dev/null +++ b/hub/server/repositories/learning-settings/get-review-comment-consent/index.db.test.ts @@ -0,0 +1,45 @@ +import { randomUUID } from "node:crypto" +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { getReviewCommentConsent } from "." + +describe("getReviewCommentConsent()", () => { + it("stops relying on deployment consent when the connector loses administrator authority", async () => { + const user = await prisma.user.create({ + data: { profile: { create: { provider: "github", login: "mona" } } }, + }) + const identity = await prisma.externalIdentity.create({ + data: { userId: user.id, issuer: "https://github.com", provider: "github", subject: "1" }, + }) + const membership = await prisma.membership.create({ data: { userId: user.id } }) + const assignment = await prisma.membershipAssignment.create({ + data: { + membershipId: membership.id, + externalIdentityId: identity.id, + role: "ADMINISTRATOR", + source: "HUB_ADMINISTRATOR", + }, + }) + await prisma.copilotConnection.create({ + data: { + connectedByMembershipId: membership.id, + credentialDigest: "a".repeat(64), + credentialProvider: "environment_token", + verifiedAt: new Date(), + reviewCommentConsentAt: new Date(), + }, + }) + const repositoryId = randomUUID() + await expect(getReviewCommentConsent(prisma, repositoryId, true)).resolves.toMatchObject({ + hubAdministrator: "human:mona", + }) + await prisma.membershipAssignment.update({ + where: { id: assignment.id }, + data: { lifecycle: "REVOKED" }, + }) + await expect(getReviewCommentConsent(prisma, repositoryId, true)).resolves.toMatchObject({ + hubAdministrator: null, + }) + }) +}) diff --git a/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts b/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts index a1cb0393a..6456dc6e7 100644 --- a/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts +++ b/hub/server/repositories/learning-settings/get-review-comment-consent/index.ts @@ -1,4 +1,5 @@ import type { Prisma } from "../../../generated/prisma/client.ts" +import { effectiveAdministratorFilter } from "../../../utils/effective-administrator-filter/index.ts" export async function getReviewCommentConsent( database: Pick, @@ -8,27 +9,28 @@ export async function getReviewCommentConsent( const [setting, connection] = await Promise.all([ database.repositoryLearningSetting.findUnique({ where: { repositoryId }, - select: { reviewCommentsTurnedOff: true, reviewCommentGrantId: true }, - }), - database.copilotConnection.findUnique({ - where: { key: "global" }, - select: { - reviewCommentConsentAt: true, - connectedByMembership: { - select: { lifecycle: true, user: { select: { profile: { select: { login: true } } } } }, - }, - }, + select: { reviewCommentsTurnedOff: true, reviewCommentGrantId: true, noteGrantId: true }, }), + deploymentConsentEnabled + ? database.copilotConnection.findFirst({ + where: { + key: "global", + reviewCommentConsentAt: { not: null }, + connectedByMembership: effectiveAdministratorFilter, + }, + select: { + connectedByMembership: { + select: { user: { select: { profile: { select: { login: true } } } } }, + }, + }, + }) + : null, ]) - const administrator = - deploymentConsentEnabled && connection?.reviewCommentConsentAt - ? connection.connectedByMembership - : null - const login = - administrator?.lifecycle === "ACTIVE" ? administrator.user.profile?.login : undefined + const login = connection?.connectedByMembership.user.profile?.login return { turnedOff: setting?.reviewCommentsTurnedOff ?? false, hubAdministrator: login ? `human:${login}` : null, repositoryGrantId: setting?.reviewCommentGrantId ?? null, + noteGrantId: setting?.noteGrantId ?? null, } } diff --git a/hub/server/repositories/memberships/is-effective-administrator/index.ts b/hub/server/repositories/memberships/is-effective-administrator/index.ts index ad0f036a6..793d4f0fc 100644 --- a/hub/server/repositories/memberships/is-effective-administrator/index.ts +++ b/hub/server/repositories/memberships/is-effective-administrator/index.ts @@ -1,27 +1,12 @@ import type { Prisma } from "../../../generated/prisma/client.ts" +import { effectiveAdministratorFilter } from "../../../utils/effective-administrator-filter/index.ts" export async function isEffectiveAdministrator( database: Pick, membershipId: string, ) { const membership = await database.membership.findFirst({ - where: { - id: membershipId, - lifecycle: "ACTIVE", - assignments: { - some: { - lifecycle: "ACTIVE", - role: "ADMINISTRATOR", - OR: [ - { source: { in: ["BOOTSTRAP", "HUB_ADMINISTRATOR"] } }, - { - source: "AUTHENTICATION_PROVIDER", - providerRevision: { selectedBy: { is: { enabled: true } } }, - }, - ], - }, - }, - }, + where: { id: membershipId, ...effectiveAdministratorFilter }, select: { id: true }, }) return membership !== null 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 cae86f2c5..350a7b5b2 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 @@ -271,7 +271,7 @@ export async function createLearningsRouteDependencies( } const grantId = setting?.noteGrantId ?? null - if (input.notes !== undefined && input.notes !== Boolean(grantId)) { + if (input.notes !== undefined) { const nextGrantId = await changePickAndPolishConsent({ ...configuration, actor: input.actor, @@ -281,6 +281,7 @@ export async function createLearningsRouteDependencies( repositoryScope, signal, }) + if (nextGrantId === grantId) return const saved = await withAuthority((transaction) => saveRepositoryLearningSetting(transaction, input.repositoryId, { noteGrantId: nextGrantId, @@ -411,7 +412,7 @@ export async function createLearningsRouteDependencies( "Repository administrator access is required.", ) } - await getLearningRepositoryScope(prisma, repositoryId) + const repositoryScope = await getLearningRepositoryScope(prisma, repositoryId) if ((await getCopilot()).state !== "connected") { throw new LearningsError( 409, @@ -419,9 +420,14 @@ export async function createLearningsRouteDependencies( "Connect Copilot before looking for learnings.", ) } - let snapshot + const setting = await getRepositoryLearningSetting(prisma, repositoryId) + let snapshot: Awaited< + ReturnType + > | null try { - snapshot = await source.captureCompleteSnapshot({ repositoryId }) + snapshot = setting?.reviewCommentsTurnedOff + ? null + : await source.captureCompleteSnapshot({ repositoryId }) } catch (error) { if ( error instanceof LearningCommandError && @@ -460,7 +466,8 @@ export async function createLearningsRouteDependencies( return null } if ( - snapshot.repositoryScope !== (await getLearningRepositoryScope(transaction, repositoryId)) + (snapshot?.repositoryScope ?? repositoryScope) !== + (await getLearningRepositoryScope(transaction, repositoryId)) ) { throw new LearningCommandError( "repository_scope_unavailable", @@ -471,8 +478,9 @@ export async function createLearningsRouteDependencies( repositoryId, requestedById, requestedByMembershipId: actorMembershipId, - snapshotDigest: snapshot.digest, - reviewActivitySnapshot: snapshot.reviewActivitySnapshot, + reviewCommentsDue: snapshot !== null, + snapshotDigest: snapshot?.digest ?? null, + reviewActivitySnapshot: snapshot?.reviewActivitySnapshot ?? {}, }) if (result.created || result.promoted) { await createSecurityAudit(transaction, { diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts index e5744f02c..46cd5a7d0 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts @@ -1,14 +1,19 @@ import { once } from "node:events" +import { randomUUID } from "node:crypto" +import { rm } from "node:fs/promises" import { createServer } from "node:http" import type { AddressInfo } from "node:net" +import { resolve } from "node:path" import pino from "pino" -import { describe, expect, it, vi } from "vitest" +import { describe, expect, it, onTestFinished, vi } from "vitest" import { createApp } from "../../../../create-app" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value" +import { createCopilotCredentialProvider } from "../../../../domains/copilot-credentials/create-copilot-credential-provider" import { executeLearningDecision } from "../../../../domains/learning/execute-learning-decision" import { findSoloLearningStore } from "../../../../domains/learning/find-solo-learning-store" import { getLearningOverview } from "../../../../domains/learning/get-learning-overview" +import { runLearningCommand } from "../../../../integrations/learning/run-learning-command" import { prisma } from "../../../../integrations/prisma" import { getDatabaseUrl } from "../../../../../test/database/get-database-url" import { createLearningsRouteDependencies } from "." @@ -429,7 +434,7 @@ describe("learning decision repository authority", () => { }) describe("learning settings repository authority", () => { - it("does not change review-comment consent after a Hub admin loses repository admin access", async () => { + async function consentFixture(environment: NodeJS.ProcessEnv = {}) { const provider = await prisma.authenticationProvider.create({ data: { key: "github", enabled: false }, }) @@ -494,14 +499,23 @@ describe("learning settings repository authority", () => { await prisma.repositoryLearningSetting.create({ data: { repositoryId: repository.id, reviewCommentsTurnedOff: false }, }) + const root = resolve(`storage/.consent-test-${randomUUID()}`) + onTestFinished(() => rm(root, { force: true, recursive: true })) const learnings = await createLearningsRouteDependencies( { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl(), + REPLICA_LEARNING_ROOT: root, + ...environment, }, { restore: vi.fn() }, pino({ level: "silent" }), ) + return { accessGrant, membership, repository, sessionDigest, learnings, root } + } + + it("does not change review-comment consent after a Hub admin loses repository admin access", async () => { + const { accessGrant, membership, repository, sessionDigest, learnings } = await consentFixture() await prisma.repositoryAccessGrant.update({ data: { accessLevel: "READ" }, where: { id: accessGrant.id }, @@ -535,4 +549,87 @@ describe("learning settings repository authority", () => { reviewCommentsChangedByMembershipId: null, }) }) + + it.each([true, false])( + "reconciles an unsaved note grant when retrying notes=%s", + async (notes) => { + const { membership, repository, sessionDigest, learnings, root } = await consentFixture() + const request = { + actor: "human:mona", + actorMembershipId: membership.id, + repositoryId: repository.id, + sessionDigest, + } + await prisma.$executeRaw`ALTER TABLE repository_learning_settings ADD CONSTRAINT test_failed_grant_save CHECK (note_grant_id IS NULL)` + try { + await expect( + learnings.changeLearningSettings({ ...request, notes: true }), + ).rejects.toThrow() + } finally { + await prisma.$executeRaw`ALTER TABLE repository_learning_settings DROP CONSTRAINT test_failed_grant_save` + } + function listGrants() { + return runLearningCommand( + [ + "grants", + "list", + "--dir", + resolve(root, "repositories", repository.id), + "--repository", + "github.com/repositories/19", + ], + { cliPath: resolve("../packages/learning/bin/replica-learning.mjs") }, + ) + } + await expect(listGrants()).resolves.toEqual([ + expect.objectContaining({ + activePurposes: ["review", "instruction"], + }), + ]) + await expect(learnings.changeLearningSettings({ ...request, notes })).resolves.toMatchObject({ + notes: { allowed: notes }, + }) + await learnings.changeLearningSettings({ ...request, notes: false }) + await expect(listGrants()).resolves.toEqual([expect.objectContaining({ activePurposes: [] })]) + }, + ) + + it("promotes a queued run without a review snapshot when review imports are off", async () => { + const environment = { REPLICA_COPILOT_AUTHENTICATION: "ambient-cli" } + const { membership, repository, sessionDigest, learnings } = await consentFixture(environment) + const credential = createCopilotCredentialProvider(environment) + await prisma.copilotConnection.create({ + data: { + connectedByMembershipId: membership.id, + credentialDigest: credential.configurationDigest!, + credentialProvider: credential.key, + verifiedAt: new Date(), + }, + }) + await prisma.repositoryLearningSetting.update({ + where: { repositoryId: repository.id }, + data: { reviewCommentsTurnedOff: true }, + }) + const scheduled = await prisma.learningRun.create({ + data: { + repositoryId: repository.id, + scheduled: true, + snapshotDigest: `sha256:${"a".repeat(64)}`, + reviewActivitySnapshot: { queued: 1 }, + }, + }) + await learnings.requestRun!({ + actorMembershipId: membership.id, + repositoryId: repository.id, + requestedById: membership.userId, + sessionDigest, + }) + await expect( + prisma.learningRun.findUniqueOrThrow({ where: { id: scheduled.id } }), + ).resolves.toMatchObject({ + scheduled: false, + reviewCommentsDue: false, + snapshotDigest: null, + }) + }) }) diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index 4c7e86e7e..46596264c 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -188,11 +188,32 @@ describe("learning routes", () => { ) }) + it("rejects a combined consent change before applying either setting", async () => { + const changeLearningSettings = vi.fn() + const deps = dependencies({ changeLearningSettings }) + await withRoute( + "patch", + "/api/repositories/:repositoryId/learnings/settings", + patchLearningSettings(deps), + async (baseUrl) => { + const response = await fetch( + `${baseUrl}/api/repositories/${repositoryId}/learnings/settings`, + { + method: "PATCH", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ notes: false, reviewComments: true }), + }, + ) + expect(response.status).toBe(422) + expect(changeLearningSettings).not.toHaveBeenCalled() + }, + ) + }) + it("returns retryable feedback when a Learning settings update is busy", async () => { const deps = dependencies({ changeLearningSettings: vi.fn().mockRejectedValue(new LearningExecutionBusyError()), }) - await withRoute( "patch", "/api/repositories/:repositoryId/learnings/settings", diff --git a/hub/server/routes/api/learnings/settings/patch/index.ts b/hub/server/routes/api/learnings/settings/patch/index.ts index bf5c764ee..4211fad65 100644 --- a/hub/server/routes/api/learnings/settings/patch/index.ts +++ b/hub/server/routes/api/learnings/settings/patch/index.ts @@ -12,7 +12,7 @@ const changeSchema = z reviewComments: z.boolean().optional(), }) .strict() - .refine((value) => Object.keys(value).length > 0) + .refine((value) => Object.keys(value).length === 1) const denied = { code: "repository_administrator_required", @@ -33,7 +33,7 @@ export function patch(dependencies: LearningsRouteDependencies): RequestHandler if (!change.success) { response.status(422).json({ code: "invalid_learning_settings", - error: "Choose at least one Learning setting to change.", + error: "Choose one Learning setting to change at a time.", }) return } diff --git a/hub/server/utils/effective-administrator-filter/index.ts b/hub/server/utils/effective-administrator-filter/index.ts new file mode 100644 index 000000000..51e38899b --- /dev/null +++ b/hub/server/utils/effective-administrator-filter/index.ts @@ -0,0 +1,19 @@ +import type { Prisma } from "../../generated/prisma/client.ts" + +/** Provider-assigned authority ends when its revision is no longer selected and enabled. */ +export const effectiveAdministratorFilter = { + lifecycle: "ACTIVE", + assignments: { + some: { + lifecycle: "ACTIVE", + role: "ADMINISTRATOR", + OR: [ + { source: { in: ["BOOTSTRAP", "HUB_ADMINISTRATOR"] } }, + { + source: "AUTHENTICATION_PROVIDER", + providerRevision: { selectedBy: { is: { enabled: true } } }, + }, + ], + }, + }, +} satisfies Prisma.MembershipWhereInput From 9d06cb381527b3939a5c90e4ae1dd355ad6f00ab Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:56:30 -0800 Subject: [PATCH 19/32] fix(azure): retain the verified Hub URL after restart Show the Hub origin after a restart, the Copilot page after Learning setup, and GitHub setup after sign-in changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/post/index.test.ts | 3 ++- infrastructure/azure/post/index.ts | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index acfb48672..66f50f061 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -887,12 +887,13 @@ it.each([ it("restarts only the traffic-serving revision without Terraform or rewriting stale saved inputs", async () => { const test = await scenario() - await postSetupAzure(test.target, { + const result = await postSetupAzure(test.target, { action: "restart", run: test.run, ui: test.ui, request: test.request, }) + expect(result.split("\n")).toContain(test.origin) expect(test.run.mock.calls.filter(([executable]) => executable === "terraform")).toEqual([]) const restarts = test.run.mock.calls.filter( diff --git a/infrastructure/azure/post/index.ts b/infrastructure/azure/post/index.ts index bb3cce548..5a656fdca 100644 --- a/infrastructure/azure/post/index.ts +++ b/infrastructure/azure/post/index.ts @@ -634,8 +634,10 @@ export async function postSetupAzure( ? "GitHub sign-in is enabled. Verify the App connection, administrator enrollment, OAuth callback and signed webhooks separately." : action === "sign-in" ? "Setup access is available. GitHub sign-in remains dependent on the configured App credentials." - : `Learning consent was saved. Connect or reconnect Copilot at ${publicOrigin}/settings/copilot to record the administrator's consent; reconnect while the setting is off to clear it.` - const setupUrl = action === "sign-in" || action === "github" ? `${publicOrigin}/settings/github/setup` : "" + : "Learning consent was saved. Connect or reconnect Copilot to record the administrator's consent; reconnect while the setting is off to clear it." + const setupUrl = action === "restart" ? publicOrigin + : action === "learning" ? `${publicOrigin}/settings/copilot` + : `${publicOrigin}/settings/github/setup` return `${config.name}: ${action === "restart" ? "active Hub revision restarted" : "post-setup configuration applied"} using the unchanged deployed image.\n${setupUrl}\n${result}${bootstrapFile ? `\nBootstrap secret saved privately: ${bootstrapFile}. Escrow it before removing this local copy.` : ""}` } catch (error) { if (changesStarted) { From 8369c2bd43ca61183bb999445806747bc7bd7a88 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 18:20:01 -0800 Subject: [PATCH 20/32] fix(learning): recover decisions against the original local store Resolve suggested-update dismissals from their operation receipts and keep store-bound reads and decisions pinned to the original checkout. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- packages/learning/README.md | 1 + packages/learning/src/cli.mjs | 31 +++++++++++-- packages/learning/src/solo-store.mjs | 6 +-- packages/learning/test/cli.test.mjs | 67 +++++++++++++++++++++++++++- 4 files changed, 96 insertions(+), 9 deletions(-) diff --git a/packages/learning/README.md b/packages/learning/README.md index c63661f0e..5fef94861 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -61,6 +61,7 @@ node /packages/learning/bin/replica-learning.mjs doctor | `propose-update ` | Suggests new wording for an accepted learning when scored uses keep showing the same issue. See [Suggest learning updates](#suggest-learning-updates) | | `updates ` | Lists a learning's suggested updates, oldest first, each `open`, `applied`, `dismissed`, or `stale` | | `apply-update --operation-id `, `dismiss-update [--operation-id ]` | Records a person's decision on a suggested update. `apply-update` makes the suggested wording, or the person's edit of it from `--title-file` and `--content-file`, the learning's next version | +| `operation-status --operation-id [--dismissal ]` | Checks whether that exact decision was saved without returning private wording. A dismissal has its own receipt rather than a new learning version. | | `delete --reason ` | Removes a learning for good: every version, the records of its deliveries and use, their screenshots, and its suggested updates. 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. Stop other operations on the repository first. Naming the repository again guards against deleting the wrong store. The local screenshot store also removes images left by failed reports. Images that another repository sharing the data directory still uses are kept. Copies outside the store, such as exports, are not touched | diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index e8c3e2b06..597271a43 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -76,7 +76,7 @@ Inspect recalled; --purpose instruction shows what agents see show [--history] [--purpose

] One learning, its evidence, and its digests - operation-status --operation-id + operation-status --operation-id [--dismissal ] Whether one host decision operation is in intact history verify Re-check every record's schema, digest, and history migrate Set up PostgreSQL using REPLICA_LEARNING_MIGRATION_DATABASE_URL @@ -226,6 +226,7 @@ const OPTIONS = { grant: { type: "string", multiple: true }, "expected-origin": { type: "string" }, "solo-store": { type: "string" }, + dismissal: { type: "string" }, wait: { type: "boolean" }, "require-session-evaluation": { type: "boolean" }, "automatic-analysis": { type: "boolean" }, @@ -407,7 +408,7 @@ export async function main( requestBudget, } if (positionals[0] === "inspect-solo-store") { - if (!values.dir) throw new UsageError("Inspect a Solo store with --dir.") + if (!values.dir) throw new UsageError("Inspect a local learning store with --dir.") const identity = await inspectSoloStore(path.resolve(cwd, values.dir)) out(identity, identity.repositoryScope) return 0 @@ -429,10 +430,17 @@ export async function main( "recall", "observations", "show", + "usage", + "outcomes", + "updates", + "apply-update", + "dismiss-update", ].includes(positionals[0]) || !/^sha256:[a-f0-9]{64}$/.test(values["solo-store"]) ) - throw new UsageError("Use the inspected Solo store key with --dir and --repository.") + throw new UsageError( + "Use the inspected local learning store key with --dir and --repository.", + ) return ( (await withSoloStore( { @@ -1483,7 +1491,22 @@ async function operationStatus(session) { const operationId = session.values["operation-id"] if (!operationId) throw new UsageError("Name the host operation with --operation-id.") const { store } = await open(session) - const result = await store.findMemoryOperation(context(session, actor(session)), id, operationId) + const principal = context(session, actor(session)) + const proposal = session.values.dismissal + // A dismissal doesn't change the learning. Check its own receipt without + // returning proposal wording from a historical Solo scope. + const result = proposal + ? { + state: (await store.updatesFor(principal, { memoryId: id })).some( + (item) => + item.id === proposal && + item.state === "dismissed" && + item.decision?.operationId === operationId, + ) + ? "dismissed" + : null, + } + : await store.findMemoryOperation(principal, id, operationId) session.out( result, result.state ? `${operationId}: ${result.state}` : `${operationId}: not found`, diff --git a/packages/learning/src/solo-store.mjs b/packages/learning/src/solo-store.mjs index 59f10a620..0ebfe4e80 100644 --- a/packages/learning/src/solo-store.mjs +++ b/packages/learning/src/solo-store.mjs @@ -83,11 +83,11 @@ export async function inspectSoloStore(directory) { if (environment.legacyScope?.host !== "github.com") throw new LearningError( "solo_store_unusable", - "This checkout has neither a local learning ID nor a GitHub origin. Check its origin and .replica/learning/config.json, then rerun Solo setup.", + "This checkout has neither a local learning ID nor a GitHub origin. Check its origin and .replica/learning/config.json, then rerun local learning setup.", ) throw new LearningError( "solo_identity_unresolved", - "Start Solo in this checkout with the Copilot CLI command printed by setup, then reload.", + "Start local learning mode in this checkout with the Copilot CLI command printed by setup, then reload.", ) } return { repositoryScope, storeKey } @@ -101,7 +101,7 @@ export async function withSoloStore({ directory, repository, storeKey, historica if (current.storeKey !== storeKey || (!historical && current.repositoryScope !== repository)) throw new LearningError( "repository_scope_unavailable", - "The Solo learning store changed. Reload before trying again.", + "The local learning store changed. Reload before trying again.", ) // Only operation-status can read a historical scope, never a different provider. return run({ diff --git a/packages/learning/test/cli.test.mjs b/packages/learning/test/cli.test.mjs index f05d0dee6..1abd2ab39 100644 --- a/packages/learning/test/cli.test.mjs +++ b/packages/learning/test/cli.test.mjs @@ -383,6 +383,8 @@ describe("replica-learning CLI: the first learning milestone", () => { await ok(repo, ["inspect-solo-store", "--dir", directory, "--json"]) ).json() const store = ["--dir", directory, "--repository", repositoryScope, "--solo-store", storeKey] + const usage = ["usage", "--commit", "a".repeat(40), "--json", ...store] + assert.deepEqual((await ok(repo, usage)).json(), { reports: [] }) const operationId = randomUUID() const decision = [ "accept", @@ -424,6 +426,7 @@ describe("replica-learning CLI: the first learning milestone", () => { writeFileSync(configPath, JSON.stringify(switched)) }) assert.match((await lateDecision).stderr, /repository_scope_unavailable/) + assert.match((await cli(repo, usage)).stderr, /repository_scope_unavailable/) function receipt(id) { return ["operation-status", proposal.id, "--operation-id", id, "--json", ...store] @@ -3727,8 +3730,7 @@ describe("replica-learning CLI: guard rails", () => { } }) - it("offers update commands when MCP elicitation is unavailable", async () => { - const repo = checkout("mcp-update-review-no-elicitation") + async function acceptedWithUpdates(repo) { const { grant, proposal } = await learnFromReviews(repo) await ok(repo, [ "accept", @@ -3801,6 +3803,67 @@ describe("replica-learning CLI: guard rails", () => { } finally { await store.close() } + return { grant, proposal, update, laterUpdate } + } + + it("reviews an update in the pinned Solo store and recovers only its own dismissal", async () => { + const repo = realpathSync(checkout("solo-update-recovery")) + const { proposal, update, laterUpdate } = await acceptedWithUpdates(repo) + const directory = path.join(repo, ".replica", "learning") + const { repositoryScope, storeKey } = ( + await ok(repo, ["inspect-solo-store", "--dir", directory, "--json"]) + ).json() + const store = [ + "--dir", + directory, + "--repository", + repositoryScope, + "--solo-store", + storeKey, + "--json", + ] + const operationId = randomUUID() + assert.equal((await ok(repo, ["outcomes", proposal.id, ...store])).json().outcomes.length, 2) + assert.equal((await ok(repo, ["updates", proposal.id, ...store])).json().updates.length, 2) + await ok(repo, [ + "dismiss-update", + update.proposal.id, + "--by", + "github:ana-designer", + "--reason", + "Keep it.", + "--operation-id", + operationId, + ...store, + ]) + const configPath = path.join(directory, "config.json") + const config = JSON.parse(readFileSync(configPath, "utf8")) + writeFileSync(configPath, JSON.stringify({ ...config, localRepository: { id: randomUUID() } })) + assert.match( + (await cli(repo, ["updates", proposal.id, ...store])).stderr, + /repository_scope_unavailable/, + ) + async function receipt(id, operation) { + return ( + await ok(repo, [ + "operation-status", + proposal.id, + "--operation-id", + operation, + "--dismissal", + id, + ...store, + ]) + ).json() + } + assert.deepEqual(await receipt(update.proposal.id, operationId), { state: "dismissed" }) + assert.deepEqual(await receipt(laterUpdate.proposal.id, operationId), { state: null }) + assert.deepEqual(await receipt(update.proposal.id, randomUUID()), { state: null }) + }) + + it("offers update commands when MCP elicitation is unavailable", async () => { + const repo = checkout("mcp-update-review-no-elicitation") + const { grant, proposal, update, laterUpdate } = await acceptedWithUpdates(repo) const mcp = await connect(repo, ["--actor", "agent:copilot", "--grant", grant.id]) try { From f31a1c40daa8528310e0a4116227045da70ca2b5 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 18:21:16 -0800 Subject: [PATCH 21/32] fix(hub): reconnect Learning activity, sharing, and evaluation data Restore the reviewed data paths behind the Learning UI. Keep private run details, shared versions, and screenshot evidence behind their current authority and consent checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/schema/agent-screenshot.prisma | 20 + hub/schema/evaluation-setting.prisma | 15 + hub/schema/learning-activity-day.prisma | 22 + hub/schema/learning-decision-operation.prisma | 1 + hub/schema/learning-evaluation-run.prisma | 27 + .../learning-reviewer-verification.prisma | 22 + hub/schema/learning-score-request.prisma | 21 + hub/schema/learning-score-trigger.enum.prisma | 4 + hub/schema/learning-share.prisma | 25 + hub/schema/learning-update-request.prisma | 20 + hub/schema/learning-update-run.prisma | 25 + hub/schema/membership.prisma | 3 + .../migration.sql | 31 + .../migration.sql | 27 + .../migration.sql | 63 ++ .../migration.sql | 53 ++ .../migration.sql | 36 + .../migration.sql | 43 ++ .../migration.sql | 9 + hub/schema/prototype.prisma | 1 + .../repository-evaluation-setting.prisma | 24 + hub/schema/repository.prisma | 9 + hub/server/create-app/index.test.ts | 5 +- hub/server/create-app/index.ts | 3 +- .../create-learning-mcp-backend/index.test.ts | 98 ++- .../create-learning-mcp-backend/index.ts | 73 +- .../save-agent-screenshot/index.ts | 31 + .../read-copilot-connection-status/index.ts | 45 ++ .../allows-session-evaluation/index.ts | 25 + .../change-evaluation-consent/index.test.ts | 52 ++ .../change-evaluation-consent/index.ts | 114 +++ .../consented-screenshot-pair/index.ts | 23 + .../index.test.ts | 6 + .../create-learning-job-processors/index.ts | 515 ++++++++++--- .../index.test.ts | 55 ++ .../index.ts | 27 + .../execute-learning-decision/index.test.ts | 98 +++ .../execute-learning-decision/index.ts | 125 ++-- .../learning/find-learning-store/index.ts | 38 + .../get-applied-learnings/index.test.ts | 66 ++ .../learning/get-applied-learnings/index.ts | 107 +++ .../get-learning-history/index.test.ts | 123 +++- .../learning/get-learning-history/index.ts | 235 +++++- .../learning/get-learning-overview/index.ts | 20 +- .../learning/jobs/delete-agent-screenshots.ts | 12 + .../learning/jobs/propose-learning-update.ts | 13 + .../learning/jobs/propose-learning-updates.ts | 13 + .../learning/jobs/score-applied-learnings.ts | 12 + .../learning-store-arguments/index.ts | 4 +- .../index.test.ts | 3 +- .../list-local-learning-activity/index.ts | 3 + .../propose-learning-update/index.test.ts | 140 ++++ .../learning/propose-learning-update/index.ts | 142 ++++ .../read-shareable-learnings/index.test.ts | 37 + .../read-shareable-learnings/index.ts | 89 +++ .../index.test.ts | 32 + .../index.ts | 32 +- .../index.db.test.ts | 81 +++ .../record-finished-learning-run/index.ts | 15 + .../index.db.test.ts | 154 ++++ .../record-reviewer-verification/index.ts | 53 ++ .../resolve-learning-references/index.ts | 11 +- .../review-comment-learning-source/types.ts | 1 + .../score-applied-learnings/index.test.ts | 364 ++++++++++ .../learning/score-applied-learnings/index.ts | 232 ++++++ .../summarize-learning-evidence/index.ts | 20 + hub/server/domains/learning/types.ts | 73 ++ .../create-review-comment-service/index.ts | 10 + hub/server/index.ts | 7 +- .../index.test.ts | 18 + .../create-github-actions-client/index.ts | 19 + .../create-agent-screenshot/index.ts | 17 + .../delete-agent-screenshot/index.ts | 5 + .../find-consented-agent-screenshots/index.ts | 28 + .../list-agent-screenshot-grants/index.ts | 21 + .../list-grant-agent-screenshots/index.ts | 13 + .../index.ts | 15 + .../initialize-evaluation-setting/index.ts | 8 + .../index.ts | 21 + .../update-evaluation-budget/index.ts | 15 + .../list-learning-activity-days/index.ts | 22 + .../index.db.test.ts | 70 ++ .../index.ts | 67 ++ .../record-learning-activity-day/index.ts | 22 + .../index.ts | 4 +- .../finish-learning-evaluation-run/index.ts | 16 + .../start-learning-evaluation-run/index.ts | 20 + .../index.db.test.ts | 40 ++ .../sum-learning-evaluation-credits/index.ts | 24 + .../index.ts | 12 + .../index.ts | 18 + .../index.db.test.ts | 39 + .../index.ts | 44 ++ .../delete-learning-score-request/index.ts | 18 + .../find-learning-score-request/index.ts | 12 + .../index.db.test.ts | 58 ++ .../index.ts | 50 ++ .../record-learning-score-request/index.ts | 17 + .../list-learning-shares/index.ts | 29 + .../save-learning-share/index.ts | 31 + .../withdraw-learning-share/index.ts | 14 + .../index.db.test.ts | 22 + .../delete-learning-update-request/index.ts | 14 + .../find-learning-update-request/index.ts | 11 + .../list-learning-update-requests/index.ts | 9 + .../record-learning-update-request/index.ts | 16 + .../index.db.test.ts | 36 + .../index.ts | 15 + .../index.ts | 14 + .../finish-learning-update-run/index.ts | 16 + .../start-learning-update-run/index.ts | 11 + .../list-successful-commit-builds/index.ts | 47 ++ .../index.ts | 31 + .../find-review-thread-feedback/index.ts | 24 + .../create-security-audit/types.ts | 19 +- .../get-security-audit-data/index.ts | 12 + .../parse-security-audit-event/index.ts | 21 +- .../parse-security-audit-event/types.ts | 2 + .../routes/agent-connections/index.db.test.ts | 21 +- hub/server/routes/agent-connections/index.ts | 28 +- hub/server/routes/agent-connections/types.ts | 4 + .../routes/api/learnings/applied/get/index.ts | 63 ++ .../applied-learnings.db.test.ts | 96 +++ .../evaluation-settings.db.test.ts | 219 ++++++ .../index.ts | 677 +++++++++++++++++- .../learning-outcomes.db.test.ts | 191 +++++ .../learning-shares.db.test.ts | 249 +++++++ .../repository-authority.db.test.ts | 43 +- .../solo-setup.db.test.ts | 2 +- .../api/learnings/decision/post/index.ts | 17 + .../evaluation-budget/patch/index.ts | 55 ++ .../api/learnings/evaluations/get/index.ts | 83 +++ .../api/learnings/evaluations/patch/index.ts | 113 +++ hub/server/routes/api/learnings/get/index.ts | 29 +- hub/server/routes/api/learnings/index.test.ts | 427 ++++++++++- .../api/learnings/screenshots/get/index.ts | 71 ++ .../routes/api/learnings/share/post/index.ts | 111 +++ hub/server/routes/api/learnings/types.ts | 97 ++- .../routes/api/product-index/index.db.test.ts | 1 + .../index.ts | 3 + .../present-security-audit/index.ts | 3 + hub/server/routes/index.ts | 38 +- .../utils/evaluation-setting-key/index.ts | 1 + hub/server/utils/format-ai-credits/index.ts | 8 + hub/server/utils/start-of-utc-month/index.ts | 4 + hub/server/workers/configuration.test.ts | 9 +- hub/server/workers/configuration.ts | 11 + hub/server/workers/github-recovery.test.ts | 1 + .../index.db.test.ts | 78 ++ 149 files changed, 7564 insertions(+), 254 deletions(-) create mode 100644 hub/schema/agent-screenshot.prisma create mode 100644 hub/schema/evaluation-setting.prisma create mode 100644 hub/schema/learning-activity-day.prisma create mode 100644 hub/schema/learning-evaluation-run.prisma create mode 100644 hub/schema/learning-reviewer-verification.prisma create mode 100644 hub/schema/learning-score-request.prisma create mode 100644 hub/schema/learning-score-trigger.enum.prisma create mode 100644 hub/schema/learning-share.prisma create mode 100644 hub/schema/learning-update-request.prisma create mode 100644 hub/schema/learning-update-run.prisma create mode 100644 hub/schema/migrations/20261224130000_learning_activity_days/migration.sql create mode 100644 hub/schema/migrations/20261224140000_learning_shares/migration.sql create mode 100644 hub/schema/migrations/20261224170000_evaluation_settings/migration.sql create mode 100644 hub/schema/migrations/20261225090000_learning_evaluation_runs/migration.sql create mode 100644 hub/schema/migrations/20261226090000_reviewer_verified_scores/migration.sql create mode 100644 hub/schema/migrations/20261227090000_learning_update_runs/migration.sql create mode 100644 hub/schema/migrations/20261228090000_learning_update_decisions/migration.sql create mode 100644 hub/schema/repository-evaluation-setting.prisma create mode 100644 hub/server/domains/agent-connections/save-agent-screenshot/index.ts create mode 100644 hub/server/domains/copilot-connection/read-copilot-connection-status/index.ts create mode 100644 hub/server/domains/learning/allows-session-evaluation/index.ts create mode 100644 hub/server/domains/learning/change-evaluation-consent/index.test.ts create mode 100644 hub/server/domains/learning/change-evaluation-consent/index.ts create mode 100644 hub/server/domains/learning/consented-screenshot-pair/index.ts create mode 100644 hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.test.ts create mode 100644 hub/server/domains/learning/delete-withdrawn-agent-screenshots/index.ts create mode 100644 hub/server/domains/learning/find-learning-store/index.ts create mode 100644 hub/server/domains/learning/get-applied-learnings/index.test.ts create mode 100644 hub/server/domains/learning/get-applied-learnings/index.ts create mode 100644 hub/server/domains/learning/jobs/delete-agent-screenshots.ts create mode 100644 hub/server/domains/learning/jobs/propose-learning-update.ts create mode 100644 hub/server/domains/learning/jobs/propose-learning-updates.ts create mode 100644 hub/server/domains/learning/jobs/score-applied-learnings.ts create mode 100644 hub/server/domains/learning/propose-learning-update/index.test.ts create mode 100644 hub/server/domains/learning/propose-learning-update/index.ts create mode 100644 hub/server/domains/learning/read-shareable-learnings/index.test.ts create mode 100644 hub/server/domains/learning/read-shareable-learnings/index.ts create mode 100644 hub/server/domains/learning/record-finished-learning-run/index.db.test.ts create mode 100644 hub/server/domains/learning/record-finished-learning-run/index.ts create mode 100644 hub/server/domains/learning/record-reviewer-verification/index.db.test.ts create mode 100644 hub/server/domains/learning/record-reviewer-verification/index.ts create mode 100644 hub/server/domains/learning/score-applied-learnings/index.test.ts create mode 100644 hub/server/domains/learning/score-applied-learnings/index.ts create mode 100644 hub/server/domains/learning/summarize-learning-evidence/index.ts create mode 100644 hub/server/repositories/agent-screenshots/create-agent-screenshot/index.ts create mode 100644 hub/server/repositories/agent-screenshots/delete-agent-screenshot/index.ts create mode 100644 hub/server/repositories/agent-screenshots/find-consented-agent-screenshots/index.ts create mode 100644 hub/server/repositories/agent-screenshots/list-agent-screenshot-grants/index.ts create mode 100644 hub/server/repositories/agent-screenshots/list-grant-agent-screenshots/index.ts create mode 100644 hub/server/repositories/evaluation-settings/get-repository-evaluation-setting/index.ts create mode 100644 hub/server/repositories/evaluation-settings/initialize-evaluation-setting/index.ts create mode 100644 hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts create mode 100644 hub/server/repositories/evaluation-settings/update-evaluation-budget/index.ts create mode 100644 hub/server/repositories/learning-activity-days/list-learning-activity-days/index.ts create mode 100644 hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.db.test.ts create mode 100644 hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.ts create mode 100644 hub/server/repositories/learning-activity-days/record-learning-activity-day/index.ts create mode 100644 hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts create mode 100644 hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts create mode 100644 hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts create mode 100644 hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts create mode 100644 hub/server/repositories/learning-reviewer-verifications/list-learning-reviewer-verifications/index.ts create mode 100644 hub/server/repositories/learning-reviewer-verifications/save-learning-reviewer-verification/index.ts create mode 100644 hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.db.test.ts create mode 100644 hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts create mode 100644 hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts create mode 100644 hub/server/repositories/learning-score-requests/find-learning-score-request/index.ts create mode 100644 hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts create mode 100644 hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts create mode 100644 hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts create mode 100644 hub/server/repositories/learning-shares/list-learning-shares/index.ts create mode 100644 hub/server/repositories/learning-shares/save-learning-share/index.ts create mode 100644 hub/server/repositories/learning-shares/withdraw-learning-share/index.ts create mode 100644 hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts create mode 100644 hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts create mode 100644 hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts create mode 100644 hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts create mode 100644 hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts create mode 100644 hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts create mode 100644 hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts create mode 100644 hub/server/repositories/learning-update-runs/find-latest-learning-update-result/index.ts create mode 100644 hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts create mode 100644 hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts create mode 100644 hub/server/repositories/prototype-index/list-successful-commit-builds/index.ts create mode 100644 hub/server/repositories/prototypes/find-newest-successful-build-after/index.ts create mode 100644 hub/server/repositories/review-comments/find-review-thread-feedback/index.ts create mode 100644 hub/server/routes/api/learnings/applied/get/index.ts create mode 100644 hub/server/routes/api/learnings/create-learnings-route-dependencies/applied-learnings.db.test.ts create mode 100644 hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts create mode 100644 hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-outcomes.db.test.ts create mode 100644 hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-shares.db.test.ts create mode 100644 hub/server/routes/api/learnings/evaluation-budget/patch/index.ts create mode 100644 hub/server/routes/api/learnings/evaluations/get/index.ts create mode 100644 hub/server/routes/api/learnings/evaluations/patch/index.ts create mode 100644 hub/server/routes/api/learnings/screenshots/get/index.ts create mode 100644 hub/server/routes/api/learnings/share/post/index.ts create mode 100644 hub/server/utils/evaluation-setting-key/index.ts create mode 100644 hub/server/utils/format-ai-credits/index.ts create mode 100644 hub/server/utils/start-of-utc-month/index.ts create mode 100644 hub/test/database/learning-activity-days-migration/index.db.test.ts 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/learning-activity-day.prisma b/hub/schema/learning-activity-day.prisma new file mode 100644 index 000000000..c04fd3636 --- /dev/null +++ b/hub/schema/learning-activity-day.prisma @@ -0,0 +1,22 @@ +model LearningActivityDay { + // 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 + date DateTime @db.Date + runs Int + commentsAnalyzed Int @map("comments_analyzed") + commentsTagged Int @map("comments_tagged") + suggestions Int + + // 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, date]) + @@map("learning_activity_days") +} diff --git a/hub/schema/learning-decision-operation.prisma b/hub/schema/learning-decision-operation.prisma index 74a3a57e2..c40ac6563 100644 --- a/hub/schema/learning-decision-operation.prisma +++ b/hub/schema/learning-decision-operation.prisma @@ -10,6 +10,7 @@ model LearningDecisionOperation { // Attribute columns learningId String @map("learning_id") @db.VarChar(255) + proposalId String? @map("proposal_id") @db.VarChar(255) decision String @db.VarChar(20) repositoryScope String? @map("repository_scope") @db.VarChar(500) soloStoreKey String? @map("solo_store_key") @db.VarChar(71) diff --git a/hub/schema/learning-evaluation-run.prisma b/hub/schema/learning-evaluation-run.prisma new file mode 100644 index 000000000..962a18a8f --- /dev/null +++ b/hub/schema/learning-evaluation-run.prisma @@ -0,0 +1,27 @@ +model LearningEvaluationRun { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + usedLearningId String @map("used_learning_id") @db.VarChar(255) + operationId String @unique @map("operation_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + trigger LearningScoreTrigger @default(USAGE) + state LearningRunState @default(RUNNING) + copilotRequests Int @default(0) @map("copilot_requests") + aiCredits Decimal @default(0) @map("ai_credits") @db.Decimal(20, 9) + scoreId String? @map("score_id") @db.VarChar(255) + failureCode String? @map("failure_code") @db.VarChar(60) + finishedAt DateTime? @map("finished_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([repositoryId, usedLearningId, trigger]) + @@index([finishedAt]) + @@map("learning_evaluation_runs") +} diff --git a/hub/schema/learning-reviewer-verification.prisma b/hub/schema/learning-reviewer-verification.prisma new file mode 100644 index 000000000..b324ba5a9 --- /dev/null +++ b/hub/schema/learning-reviewer-verification.prisma @@ -0,0 +1,22 @@ +model LearningReviewerVerification { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + prototypeId String @map("prototype_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + prototype Prototype @relation(fields: [prototypeId], references: [id], onDelete: Cascade) + + // Attribute columns + commitSha String @map("commit_sha") @db.VarChar(64) + verifiedAt DateTime @map("verified_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([prototypeId, commitSha]) + @@index([repositoryId, commitSha]) + @@map("learning_reviewer_verifications") +} diff --git a/hub/schema/learning-score-request.prisma b/hub/schema/learning-score-request.prisma new file mode 100644 index 000000000..7eb3d8d94 --- /dev/null +++ b/hub/schema/learning-score-request.prisma @@ -0,0 +1,21 @@ +model LearningScoreRequest { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + commitSha String @map("commit_sha") @db.VarChar(64) + // Raised by each repeat report, so scoring only drops the request version it read. + revision Int @default(0) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([repositoryId, commitSha]) + @@index([createdAt]) + @@map("learning_score_requests") +} diff --git a/hub/schema/learning-score-trigger.enum.prisma b/hub/schema/learning-score-trigger.enum.prisma new file mode 100644 index 000000000..c6d24aa59 --- /dev/null +++ b/hub/schema/learning-score-trigger.enum.prisma @@ -0,0 +1,4 @@ +enum LearningScoreTrigger { + USAGE + REVIEWER_VERIFICATION +} diff --git a/hub/schema/learning-share.prisma b/hub/schema/learning-share.prisma new file mode 100644 index 000000000..7f0db9d35 --- /dev/null +++ b/hub/schema/learning-share.prisma @@ -0,0 +1,25 @@ +model LearningShare { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + sharedByMembershipId String? @map("shared_by_membership_id") @db.Uuid + withdrawnByMembershipId String? @map("withdrawn_by_membership_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + sharedByMembership Membership? @relation("LearningShareSharedBy", fields: [sharedByMembershipId], references: [id], onDelete: SetNull) + withdrawnByMembership Membership? @relation("LearningShareWithdrawnBy", fields: [withdrawnByMembershipId], references: [id], onDelete: SetNull) + + // Attribute columns + digest String @db.VarChar(71) + learningId String @map("learning_id") @db.VarChar(255) + sharedAt DateTime @map("shared_at") @db.Timestamptz(3) + withdrawnAt DateTime? @map("withdrawn_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([repositoryId, learningId]) + @@map("learning_shares") +} diff --git a/hub/schema/learning-update-request.prisma b/hub/schema/learning-update-request.prisma new file mode 100644 index 000000000..b2f017fbb --- /dev/null +++ b/hub/schema/learning-update-request.prisma @@ -0,0 +1,20 @@ +model LearningUpdateRequest { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + memoryId String @map("memory_id") @db.VarChar(255) + // Raised by each new score, so a check only drops the request version it saw. + revision Int @default(0) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@unique([repositoryId, memoryId]) + @@map("learning_update_requests") +} diff --git a/hub/schema/learning-update-run.prisma b/hub/schema/learning-update-run.prisma new file mode 100644 index 000000000..668c3d80a --- /dev/null +++ b/hub/schema/learning-update-run.prisma @@ -0,0 +1,25 @@ +model LearningUpdateRun { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @map("repository_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + memoryId String @map("memory_id") @db.VarChar(255) + state LearningRunState @default(RUNNING) + result String? @db.VarChar(30) + copilotRequests Int @default(0) @map("copilot_requests") + aiCredits Decimal @default(0) @map("ai_credits") @db.Decimal(20, 9) + failureCode String? @map("failure_code") @db.VarChar(60) + finishedAt DateTime? @map("finished_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@index([finishedAt]) + @@index([repositoryId, memoryId, createdAt]) + @@map("learning_update_runs") +} diff --git a/hub/schema/membership.prisma b/hub/schema/membership.prisma index 1369074fb..926fb5e8a 100644 --- a/hub/schema/membership.prisma +++ b/hub/schema/membership.prisma @@ -4,12 +4,15 @@ model Membership { userId String @unique @map("user_id") @db.Uuid // Relations + screenshotConsentChanges RepositoryEvaluationSetting[] @relation("ScreenshotConsentChangedBy") user User @relation(fields: [userId], references: [id], onDelete: Restrict) assignments MembershipAssignment[] sessions HubSession[] sensitiveAuthorizations SensitiveAuthorization[] repositoryAccessGrants RepositoryAccessGrant[] copilotConnections CopilotConnection[] + sharedLearnings LearningShare[] @relation("LearningShareSharedBy") + withdrawnLearningShares LearningShare[] @relation("LearningShareWithdrawnBy") learningRuns LearningRun[] decisionTrainingJobs DecisionTrainingJob[] decisionModelPromotions DecisionModelPromotion[] diff --git a/hub/schema/migrations/20261224130000_learning_activity_days/migration.sql b/hub/schema/migrations/20261224130000_learning_activity_days/migration.sql new file mode 100644 index 000000000..d951952d5 --- /dev/null +++ b/hub/schema/migrations/20261224130000_learning_activity_days/migration.sql @@ -0,0 +1,31 @@ +CREATE TABLE "learning_activity_days" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "date" DATE NOT NULL, + "runs" INTEGER NOT NULL, + "comments_analyzed" INTEGER NOT NULL, + "comments_tagged" INTEGER NOT NULL, + "suggestions" INTEGER NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_activity_days_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "learning_activity_days_repository_id_date_key" +ON "learning_activity_days"("repository_id", "date"); + +ALTER TABLE "learning_activity_days" ADD CONSTRAINT "learning_activity_days_repository_id_fkey" +FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") +ON DELETE CASCADE ON UPDATE CASCADE; + +-- Retain daily counts before finished runs expire, without copying private run details. +INSERT INTO "learning_activity_days" ( + "id", "repository_id", "date", "runs", "comments_analyzed", "comments_tagged", "suggestions" +) +SELECT gen_random_uuid(), "repository_id", + (COALESCE("started_at", "created_at") AT TIME ZONE 'UTC')::DATE AS "day", + COUNT(*), SUM("comments_considered"), SUM("comments_labeled"), SUM("suggestions") +FROM "learning_runs" +WHERE "state" IN ('SUCCEEDED', 'FAILED') +GROUP BY "repository_id", "day"; diff --git a/hub/schema/migrations/20261224140000_learning_shares/migration.sql b/hub/schema/migrations/20261224140000_learning_shares/migration.sql new file mode 100644 index 000000000..6da4f3a7f --- /dev/null +++ b/hub/schema/migrations/20261224140000_learning_shares/migration.sql @@ -0,0 +1,27 @@ +-- CreateTable +CREATE TABLE "learning_shares" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "shared_by_membership_id" UUID, + "withdrawn_by_membership_id" UUID, + "digest" VARCHAR(71) NOT NULL, + "learning_id" VARCHAR(255) NOT NULL, + "shared_at" TIMESTAMPTZ(3) NOT NULL, + "withdrawn_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_shares_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_shares_repository_id_learning_id_key" ON "learning_shares"("repository_id", "learning_id"); + +-- AddForeignKey +ALTER TABLE "learning_shares" ADD CONSTRAINT "learning_shares_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_shares" ADD CONSTRAINT "learning_shares_shared_by_membership_id_fkey" FOREIGN KEY ("shared_by_membership_id") REFERENCES "memberships"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_shares" ADD CONSTRAINT "learning_shares_withdrawn_by_membership_id_fkey" FOREIGN KEY ("withdrawn_by_membership_id") REFERENCES "memberships"("id") ON DELETE SET NULL ON UPDATE CASCADE; 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..4412352e0 --- /dev/null +++ b/hub/schema/migrations/20261224170000_evaluation_settings/migration.sql @@ -0,0 +1,63 @@ +-- 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), + "retiring_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/migrations/20261225090000_learning_evaluation_runs/migration.sql b/hub/schema/migrations/20261225090000_learning_evaluation_runs/migration.sql new file mode 100644 index 000000000..9ccc22207 --- /dev/null +++ b/hub/schema/migrations/20261225090000_learning_evaluation_runs/migration.sql @@ -0,0 +1,53 @@ +-- AlterTable +ALTER TABLE "repository_evaluation_settings" ADD COLUMN "evaluation_grant_id" VARCHAR(255); + +-- CreateTable +CREATE TABLE "learning_evaluation_runs" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "used_learning_id" VARCHAR(255) NOT NULL, + "operation_id" UUID NOT NULL, + "state" "LearningRunState" NOT NULL DEFAULT 'RUNNING', + "copilot_requests" INTEGER NOT NULL DEFAULT 0, + "ai_credits" DECIMAL(20,9) NOT NULL DEFAULT 0, + "score_id" VARCHAR(255), + "failure_code" VARCHAR(60), + "finished_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_evaluation_runs_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "learning_score_requests" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "commit_sha" VARCHAR(64) NOT NULL, + "revision" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_score_requests_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_evaluation_runs_operation_id_key" ON "learning_evaluation_runs"("operation_id"); + +-- CreateIndex +CREATE INDEX "learning_evaluation_runs_finished_at_idx" ON "learning_evaluation_runs"("finished_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_evaluation_runs_repository_id_used_learning_id_key" ON "learning_evaluation_runs"("repository_id", "used_learning_id"); + +-- CreateIndex +CREATE INDEX "learning_score_requests_created_at_idx" ON "learning_score_requests"("created_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_score_requests_repository_id_commit_sha_key" ON "learning_score_requests"("repository_id", "commit_sha"); + +-- AddForeignKey +ALTER TABLE "learning_evaluation_runs" ADD CONSTRAINT "learning_evaluation_runs_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_score_requests" ADD CONSTRAINT "learning_score_requests_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/migrations/20261226090000_reviewer_verified_scores/migration.sql b/hub/schema/migrations/20261226090000_reviewer_verified_scores/migration.sql new file mode 100644 index 000000000..e18e03c23 --- /dev/null +++ b/hub/schema/migrations/20261226090000_reviewer_verified_scores/migration.sql @@ -0,0 +1,36 @@ +-- CreateEnum +CREATE TYPE "LearningScoreTrigger" AS ENUM ('USAGE', 'REVIEWER_VERIFICATION'); + +-- DropIndex +DROP INDEX "learning_evaluation_runs_repository_id_used_learning_id_key"; + +-- AlterTable +ALTER TABLE "learning_evaluation_runs" ADD COLUMN "trigger" "LearningScoreTrigger" NOT NULL DEFAULT 'USAGE'; + +-- CreateTable +CREATE TABLE "learning_reviewer_verifications" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "prototype_id" UUID NOT NULL, + "commit_sha" VARCHAR(64) NOT NULL, + "verified_at" TIMESTAMPTZ(3) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_reviewer_verifications_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "learning_reviewer_verifications_repository_id_commit_sha_idx" ON "learning_reviewer_verifications"("repository_id", "commit_sha"); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_reviewer_verifications_prototype_id_commit_sha_key" ON "learning_reviewer_verifications"("prototype_id", "commit_sha"); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_evaluation_runs_repository_id_used_learning_id_tri_key" ON "learning_evaluation_runs"("repository_id", "used_learning_id", "trigger"); + +-- AddForeignKey +ALTER TABLE "learning_reviewer_verifications" ADD CONSTRAINT "learning_reviewer_verifications_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_reviewer_verifications" ADD CONSTRAINT "learning_reviewer_verifications_prototype_id_fkey" FOREIGN KEY ("prototype_id") REFERENCES "prototypes"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/migrations/20261227090000_learning_update_runs/migration.sql b/hub/schema/migrations/20261227090000_learning_update_runs/migration.sql new file mode 100644 index 000000000..deeb31de8 --- /dev/null +++ b/hub/schema/migrations/20261227090000_learning_update_runs/migration.sql @@ -0,0 +1,43 @@ +-- CreateTable +CREATE TABLE "learning_update_requests" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "memory_id" VARCHAR(255) NOT NULL, + "revision" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_update_requests_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "learning_update_runs" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "memory_id" VARCHAR(255) NOT NULL, + "state" "LearningRunState" NOT NULL DEFAULT 'RUNNING', + "result" VARCHAR(30), + "copilot_requests" INTEGER NOT NULL DEFAULT 0, + "ai_credits" DECIMAL(20,9) NOT NULL DEFAULT 0, + "failure_code" VARCHAR(60), + "finished_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "learning_update_runs_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "learning_update_requests_repository_id_memory_id_key" ON "learning_update_requests"("repository_id", "memory_id"); + +-- CreateIndex +CREATE INDEX "learning_update_runs_finished_at_idx" ON "learning_update_runs"("finished_at"); + +-- CreateIndex +CREATE INDEX "learning_update_runs_repository_id_memory_id_created_at_idx" ON "learning_update_runs"("repository_id", "memory_id", "created_at"); + +-- AddForeignKey +ALTER TABLE "learning_update_requests" ADD CONSTRAINT "learning_update_requests_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "learning_update_runs" ADD CONSTRAINT "learning_update_runs_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/migrations/20261228090000_learning_update_decisions/migration.sql b/hub/schema/migrations/20261228090000_learning_update_decisions/migration.sql new file mode 100644 index 000000000..02ea9bd9f --- /dev/null +++ b/hub/schema/migrations/20261228090000_learning_update_decisions/migration.sql @@ -0,0 +1,9 @@ +-- AlterTable +ALTER TABLE "learning_decision_operations" ADD COLUMN "proposal_id" VARCHAR(255); + +ALTER TABLE "learning_decision_operations" +DROP CONSTRAINT "learning_decision_operations_decision_check"; + +ALTER TABLE "learning_decision_operations" +ADD CONSTRAINT "learning_decision_operations_decision_check" +CHECK ("decision" IN ('accept', 'reject', 'retire', 'edit', 'reinstate', 'apply_update', 'dismiss_update')); diff --git a/hub/schema/prototype.prisma b/hub/schema/prototype.prisma index f19c55be6..fc0740d39 100644 --- a/hub/schema/prototype.prisma +++ b/hub/schema/prototype.prisma @@ -7,6 +7,7 @@ model Prototype { currentBuildId String? @map("current_build_id") @db.Uuid // Relations + learningVerifications LearningReviewerVerification[] repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Restrict) author User? @relation(fields: [authorId], references: [id], onDelete: Restrict) builds Build[] @relation("PrototypeBuilds") diff --git a/hub/schema/repository-evaluation-setting.prisma b/hub/schema/repository-evaluation-setting.prisma new file mode 100644 index 000000000..3e08d441b --- /dev/null +++ b/hub/schema/repository-evaluation-setting.prisma @@ -0,0 +1,24 @@ +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("ScreenshotConsentChangedBy", fields: [screenshotsChangedByMembershipId], references: [id], onDelete: SetNull) + + // Attribute columns + enabled Boolean @default(false) + evaluationGrantId String? @map("evaluation_grant_id") @db.VarChar(255) + screenshotGrantId String? @map("screenshot_grant_id") @db.VarChar(255) + retiringScreenshotGrantId String? @map("retiring_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 d9dd55e42..1a8a85efb 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -4,7 +4,16 @@ model Repository { canvasId Int @unique @default(autoincrement()) @map("canvas_id") // Relations + evaluationSetting RepositoryEvaluationSetting? + agentScreenshots AgentScreenshot[] + learningEvaluationRuns LearningEvaluationRun[] + learningScoreRequests LearningScoreRequest[] + learningVerifications LearningReviewerVerification[] + learningUpdateRequests LearningUpdateRequest[] + learningUpdateRuns LearningUpdateRun[] + learningShares LearningShare[] learningRuns LearningRun[] + learningActivityDays LearningActivityDay[] learningDecisionOperations LearningDecisionOperation[] decisionModelConfiguration DecisionModelConfiguration? decisionReviewSnapshot DecisionReviewSnapshot? diff --git a/hub/server/create-app/index.test.ts b/hub/server/create-app/index.test.ts index 09502fdeb..b061c5c2f 100644 --- a/hub/server/create-app/index.test.ts +++ b/hub/server/create-app/index.test.ts @@ -676,13 +676,14 @@ describe("createApp()", () => { headers: { "content-type": "application/json" }, body: '{"note":"malformed-private-note"', }) - expect(malformed.status).toBe(400) + // Even malformed bodies do not reach the larger MCP parser without a token. + expect(malformed.status).toBe(401) expect(malformed.headers.get("cache-control")).toBe("no-store") await malformed.arrayBuffer() await vi.waitFor(() => expect(records).toHaveLength(2)) expect(records[0]).toMatchObject({ method: "POST", statusCode: 401, outcome: "completed" }) - expect(records[1]).toMatchObject({ method: "POST", statusCode: 400, outcome: "completed" }) + expect(records[1]).toMatchObject({ method: "POST", statusCode: 401, outcome: "completed" }) expect(records[0]).not.toHaveProperty("body") expect(records[1]).not.toHaveProperty("body") expect(JSON.stringify(records)).not.toMatch( diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index b987956e8..a44c73c38 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -53,6 +53,7 @@ export function createApp({ [ "/api/canvas", "/api/agent-connections", + "/api/learnings", "/authorize", "/register", "/token", @@ -76,7 +77,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\/repositories\/[^/]+\/?$)(?!\/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 ea7c73a07..f5fbec51b 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 @@ -253,7 +253,7 @@ 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() }) @@ -473,3 +473,99 @@ it("stores no notes and reports an inactive grant without note consent", async ( ), ).toBe(false) }) + +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") }) +}) + +it("asks Hub to score the commit an agent reports usage for", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockResolvedValueOnce({ recorded: 1 }) + const requestScore = vi.fn() + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(true), + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + learningDatabaseUrl: "postgresql://learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + requestScore, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + await backend.reportUsage({ commitSha: "a".repeat(40), used: [] }) + + expect(requestScore).toHaveBeenCalledWith("a".repeat(40)) +}) 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 6ff0b4890..2ae7fd3ab 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 @@ -31,6 +31,11 @@ interface LearningSettings { staticDirectories: string[] } +interface Screenshot { + data?: unknown + file?: unknown +} + interface StoredLearning { record: { id: string; state: string } status: { recallEligible: boolean } @@ -73,6 +78,11 @@ export function createLearningMcpBackend(input: { received(receiptIds: string[]): Promise } repository: { id: string; githubRepositoryId: bigint } + requestScore?(commitSha: string): Promise + screenshots?: { + grantId(): Promise + save(input: { grantId: string; bytes: Uint8Array }): Promise + } serialize(operation: (signal: AbortSignal) => Promise): Promise toAgentError: (code: string, message: string) => Error }) { @@ -179,8 +189,9 @@ export function createLearningMcpBackend(input: { limit?: number session?: { id: string; label?: string } }) { + 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, [ @@ -201,24 +212,66 @@ export function createLearningMcpBackend(input: { } // Only the framed text was recorded as delivered, so the raw learnings stay out. return { + screenshotsAllowed, guidanceId: result.guidanceId, text: result.text, learnings: result.memories.map(({ id, deliveryId }) => ({ id, deliveryId })), } }, - async reportUsage(report: { used: { before?: unknown; after?: unknown }[] }) { - if (report.used.some((item) => item.before !== undefined || item.after !== undefined)) + async reportUsage(report: { + commitSha?: unknown + 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 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]), - ) + try { + return await input.serialize(async (signal) => { + 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.") + const result = await withPrivateFile(JSON.stringify(report), (file) => + runCommand( + directory, + ["report-usage", file, ...(grantId ? ["--grant", grantId] : [])], + signal, + ), + ) + // 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"), + }) + } + } + if ( + typeof report.commitSha === "string" && + /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(report.commitSha) + ) + await input.requestScore?.(report.commitSha) + return result + }) + } catch (error) { + throw safeLearningError(error) + } }, async submitSession(session: { sessionId: string; pickAndPolishNotes?: SubmittedNote[] }) { 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/copilot-connection/read-copilot-connection-status/index.ts b/hub/server/domains/copilot-connection/read-copilot-connection-status/index.ts new file mode 100644 index 000000000..0d809b92c --- /dev/null +++ b/hub/server/domains/copilot-connection/read-copilot-connection-status/index.ts @@ -0,0 +1,45 @@ +import { getCopilotConnectionState } from "../../../repositories/copilot-connection-states/get-copilot-connection-state/index.ts" +import { getCopilotConnection } from "../../../repositories/copilot-connections/get-copilot-connection/index.ts" +import { isEffectiveAdministrator } from "../../../repositories/memberships/is-effective-administrator/index.ts" +import { getCopilotConnectionStatus } from "../get-copilot-connection-status/index.ts" +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Reads the saved Copilot connection and decides whether Hub can use it now. Returns + * null when the connection state is missing, so each caller picks how to handle that. + */ +export async function readCopilotConnectionStatus( + database: Pick< + Prisma.TransactionClient, + "copilotConnection" | "copilotConnectionState" | "membership" + >, + credentialProvider: Parameters[1], +) { + const connection = await getCopilotConnection(database) + const state = await getCopilotConnectionState(database) + if (!state) return null + const status = getCopilotConnectionStatus( + connection + ? { + connectedBy: { + login: connection.connectedByMembership.user.profile?.login ?? null, + membershipId: connection.connectedByMembershipId, + name: connection.connectedByMembership.user.profile?.name ?? null, + }, + credentialDigest: connection.credentialDigest, + credentialProvider: connection.credentialProvider, + verifiedAt: connection.verifiedAt, + } + : null, + credentialProvider, + connection + ? await isEffectiveAdministrator(database, connection.connectedByMembershipId) + : false, + { + credentialDigest: state.refusedCredentialDigest, + credentialProvider: state.refusedCredentialProvider, + refusedAt: state.refusedAt, + }, + ) + return { connection, state, status } +} diff --git a/hub/server/domains/learning/allows-session-evaluation/index.ts b/hub/server/domains/learning/allows-session-evaluation/index.ts new file mode 100644 index 000000000..754da5eb1 --- /dev/null +++ b/hub/server/domains/learning/allows-session-evaluation/index.ts @@ -0,0 +1,25 @@ +import { z } from "zod" + +const grants = z.array( + z.object({ + grant: z.object({ + sources: z.array(z.string()), + evidenceFrom: z.string().optional(), + evidenceUntil: z.string().optional(), + }), + activePurposes: z.array(z.string()), + }), +) + +/** A commit has no known session time, so a time-limited chat grant cannot cover it. */ +export function allowsSessionEvaluation(value: unknown) { + return grants + .parse(value) + .some( + ({ grant, activePurposes }) => + grant.sources.includes("agent_session") && + activePurposes.includes("evaluation") && + !grant.evidenceFrom && + !grant.evidenceUntil, + ) +} diff --git a/hub/server/domains/learning/change-evaluation-consent/index.test.ts b/hub/server/domains/learning/change-evaluation-consent/index.test.ts new file mode 100644 index 000000000..d6ba837b0 --- /dev/null +++ b/hub/server/domains/learning/change-evaluation-consent/index.test.ts @@ -0,0 +1,52 @@ +import { randomUUID } from "node:crypto" +import { mkdir, rm } from "node:fs/promises" +import { resolve } from "node:path" +import { expect, it, onTestFinished } from "vitest" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" +import { learningStoreArguments } from "../learning-store-arguments" +import { prepareLearningStore } from "../prepare-learning-store" +import { changeEvaluationConsent } from "." + +it("keeps the existing review and note grants when changing evaluation consent", async () => { + const root = resolve(".local", `evaluation-consent-${randomUUID()}`) + await mkdir(root, { mode: 0o700, recursive: true }) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const settings = { + actor: "human:mona", + root, + repositoryId: randomUUID(), + repositoryScope: "github.com/repositories/123", + staticDirectories: [], + cliPath: resolve("../packages/learning/bin/replica-learning.mjs"), + nodePath: process.execPath, + } + const store = learningStoreArguments( + await prepareLearningStore({ ...settings, repositoryKey: settings.repositoryId }), + ) + function run(args: string[]) { + return runLearningCommand([...args, ...store], settings) + } + for (const source of ["agent_session", "hub_review_comments"]) { + await run([ + "grants", + "add", + "--purpose", + "review", + "--purpose", + "instruction", + "--source", + source, + "--basis", + "Existing source consent.", + "--by", + settings.actor, + ]) + } + const original = await run(["grants", "list"]) + const input = { ...settings, source: "hub_review_comments" as const } + const grantId = await changeEvaluationConsent({ ...input, grantId: null, allowed: true }) + await changeEvaluationConsent({ ...input, grantId, allowed: false }) + const remaining = (await run(["grants", "list"])) as Array<{ activePurposes: string[] }> + expect(remaining.filter(({ activePurposes }) => activePurposes.length)).toEqual(original) +}, 30_000) diff --git a/hub/server/domains/learning/change-evaluation-consent/index.ts b/hub/server/domains/learning/change-evaluation-consent/index.ts new file mode 100644 index 000000000..e2d627dae --- /dev/null +++ b/hub/server/domains/learning/change-evaluation-consent/index.ts @@ -0,0 +1,114 @@ +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() + +const bases = { + agent_screenshots: + "A repository administrator allowed agents to take screenshots and Hub to analyze them.", + hub_review_comments: + "A repository administrator turned on automated evaluations of applied learnings.", +} + +// Neither grant authorizes importing new evidence or sending guidance to agents. +const purposes = { + agent_screenshots: ["evaluation"], + hub_review_comments: ["evaluation"], +} + +/** + * Turns one repository consent on or off in its learning store: screenshots or the + * review comments behind learnings an evaluator scores. The store keeps the + * grant with who changed it, and refuses use once it is withdrawn, so Hub's own setting can + * never allow more than the store does. Returns the active grant. + */ +export async function changeEvaluationConsent(input: { + actor: string + allowed: boolean + cliPath: string + grantId: string | null + learningDatabaseUrl?: string + nodePath: string + repositoryId: string + repositoryScope: string + root: string + signal?: AbortSignal + source: keyof typeof bases + 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) + const purposeArguments = purposes[input.source].flatMap((purpose) => ["--purpose", purpose]) + // If a package write succeeded but the Hub transaction did not, retire that orphan. + // Match our own single-purpose grants, never source-import grants or note consent. + const managed = z + .array( + z.object({ + grant: addedGrantSchema.extend({ + basis: z.string(), + purposes: z.array(z.string()), + sources: z.array(z.string()), + grantedBy: z.object({ kind: z.string() }), + }), + activePurposes: z.array(z.string()), + }), + ) + .parse(await runLearningCommand(["grants", "list", ...common], options)) + .filter( + ({ grant, activePurposes }) => + grant.basis === bases[input.source] && + grant.grantedBy.kind === "human" && + grant.sources.length === 1 && + grant.sources[0] === input.source && + grant.purposes.length === 1 && + activePurposes.includes("evaluation"), + ) + const retained = input.allowed + ? managed.find(({ grant }) => grant.id === input.grantId) + : undefined + for (const { grant } of managed) { + if (grant.id === retained?.grant.id) continue + await runLearningCommand( + ["grants", "withdraw", grant.id, ...purposeArguments, "--by", input.actor, ...common], + options, + ) + } + if (retained) return retained.grant.id + if (input.allowed) { + const grant = addedGrantSchema.parse( + await runLearningCommand( + [ + "grants", + "add", + ...purposeArguments, + ...(input.source === "agent_screenshots" ? ["--evidence-from", "now"] : []), + "--source", + input.source, + "--basis", + bases[input.source], + "--by", + input.actor, + ...common, + ], + options, + ), + ) + return grant.id + } + return null +} diff --git a/hub/server/domains/learning/consented-screenshot-pair/index.ts b/hub/server/domains/learning/consented-screenshot-pair/index.ts new file mode 100644 index 000000000..17ad2df80 --- /dev/null +++ b/hub/server/domains/learning/consented-screenshot-pair/index.ts @@ -0,0 +1,23 @@ +import type { findConsentedAgentScreenshots } from "../../../repositories/agent-screenshots/find-consented-agent-screenshots/index.ts" + +export function consentedScreenshot( + consented: Awaited>, + 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 } +} + +// Leaves out each screenshot the current consent does not cover. +export function consentedScreenshotPair( + consented: Awaited>, + screenshots: Partial< + Record<"before" | "after", { sha256: string; route: string; consentGrantId?: string }> + >, +) { + const before = consentedScreenshot(consented, screenshots.before) + const after = consentedScreenshot(consented, screenshots.after) + return { ...(before ? { before } : {}), ...(after ? { after } : {}) } +} 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..d54e8f13b 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,9 +13,12 @@ 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() }, + learningScoreRequest: { deleteMany: vi.fn(), findMany: vi.fn() }, } vi.mock("../../../integrations/prisma", () => ({ prisma })) @@ -111,7 +114,10 @@ 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.learningScoreRequest.findMany.mockResolvedValue([]) prisma.reviewComment.findMany.mockResolvedValue([ { publicId: 101, 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 f5ab1b203..009bf775a 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -1,8 +1,42 @@ +import { readGitHubAppConfiguration } from "../../authentication/read-github-app-configuration/index.ts" +import { readCopilotConnectionStatus } from "../../copilot-connection/read-copilot-connection-status/index.ts" +import { deleteWithdrawnAgentScreenshots } from "../delete-withdrawn-agent-screenshots/index.ts" +import { deleteAgentScreenshotsJob } from "../jobs/delete-agent-screenshots.ts" +import { proposeLearningUpdateJob } from "../jobs/propose-learning-update.ts" +import { proposeLearningUpdatesJob } from "../jobs/propose-learning-updates.ts" +import { scoreAppliedLearningsJob } from "../jobs/score-applied-learnings.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" +import { proposeLearningUpdate } from "../propose-learning-update/index.ts" +import { scoreAppliedLearnings } from "../score-applied-learnings/index.ts" +import { createConfiguredArtifactStorage } from "../../artifacts/create-configured-artifact-storage/index.ts" +import { createGitHubActionsClient } from "../../../integrations/github/create-github-actions-client/index.ts" +import { GitHubCommitLookupError } from "../../../integrations/github/errors.ts" +import { deleteAgentScreenshot } from "../../../repositories/agent-screenshots/delete-agent-screenshot/index.ts" +import { findConsentedAgentScreenshots } from "../../../repositories/agent-screenshots/find-consented-agent-screenshots/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 { initializeEvaluationSetting } from "../../../repositories/evaluation-settings/initialize-evaluation-setting/index.ts" +import { finishLearningEvaluationRun } from "../../../repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts" +import { startLearningEvaluationRun } from "../../../repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts" +import { sumLearningEvaluationCredits } from "../../../repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts" +import { deleteExpiredLearningScoreRequests } from "../../../repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts" +import { listLearningReviewerVerifications } from "../../../repositories/learning-reviewer-verifications/list-learning-reviewer-verifications/index.ts" +import { deleteLearningScoreRequest } from "../../../repositories/learning-score-requests/delete-learning-score-request/index.ts" +import { findLearningScoreRequest } from "../../../repositories/learning-score-requests/find-learning-score-request/index.ts" +import { deleteLearningUpdateRequest } from "../../../repositories/learning-update-requests/delete-learning-update-request/index.ts" +import { findLearningUpdateRequest } from "../../../repositories/learning-update-requests/find-learning-update-request/index.ts" +import { listLearningUpdateRequests } from "../../../repositories/learning-update-requests/list-learning-update-requests/index.ts" +import { recordLearningUpdateRequest } from "../../../repositories/learning-update-requests/record-learning-update-request/index.ts" +import { closeAbandonedLearningUpdateRuns } from "../../../repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts" +import { finishLearningUpdateRun } from "../../../repositories/learning-update-runs/finish-learning-update-run/index.ts" +import { startLearningUpdateRun } from "../../../repositories/learning-update-runs/start-learning-update-run/index.ts" +import { listReadyLearningScoreRequests } from "../../../repositories/learning-score-requests/list-ready-learning-score-requests/index.ts" +import { startOfUtcMonth } from "../../../utils/start-of-utc-month/index.ts" import { randomUUID } from "node:crypto" import type { Logger } from "pino" import { resolveLocalSignInEnvironment } from "../../authentication/resolve-local-sign-in-environment/index.ts" -import { getCopilotConnectionStatus } from "../../copilot-connection/get-copilot-connection-status/index.ts" 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" @@ -18,6 +52,7 @@ import { processReviewCommentRedaction } from "../process-review-comment-redacti import { redactLegacyReviewComment } from "../redact-legacy-review-comment/index.ts" import { recoverLearningRunJobs } from "../recover-learning-run-jobs/index.ts" import { reconcileLearningDecisionOperation } from "../reconcile-learning-decision-operation/index.ts" +import { recordFinishedLearningRun } from "../record-finished-learning-run/index.ts" import { getSoloLearningDirectory } from "../get-solo-learning-directory/index.ts" import { readAutomaticLearningRunsEnabled } from "../read-automatic-learning-runs-enabled/index.ts" import { readLearningConfiguration } from "../read-learning-configuration/index.ts" @@ -30,7 +65,6 @@ 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 { 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" import { recordCopilotCredentialRefusal } from "../../../repositories/copilot-connection-states/record-copilot-credential-refusal/index.ts" @@ -50,7 +84,6 @@ import { listQueuedLearningRuns } from "../../../repositories/learning-runs/list import { deleteLearningDecisionOperation } from "../../../repositories/learning-decision-operations/delete-learning-decision-operation/index.ts" import { listLearningDecisionOperations } from "../../../repositories/learning-decision-operations/list-learning-decision-operations/index.ts" import { updateLearningRunProgress } from "../../../repositories/learning-runs/update-learning-run-progress/index.ts" -import { isEffectiveAdministrator } from "../../../repositories/memberships/is-effective-administrator/index.ts" import { lockGitHubRepositoryAccessState } from "../../../repositories/github-repository-access-states/lock-github-repository-access-state/index.ts" import { listDeletedReviewComments } from "../../../repositories/review-comments/list-deleted-review-comments/index.ts" import { markReviewCommentLearningRedacted } from "../../../repositories/review-comments/mark-review-comment-learning-redacted/index.ts" @@ -96,40 +129,68 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg return dependenciesPromise } + /** + * Gives a job the store access every learning job needs, so each one opens stores, + * runs commands and takes the shared lock the same way. + */ + function storeAccess({ + configuration, + databaseUrl, + prisma, + }: Awaited>) { + return { + prepare: async (repositoryId: string) => + prepareLearningStore({ + applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, + repositoryKey: repositoryId, + repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), + root: configuration.root, + staticDirectories: configuration.staticDirectories, + }), + runCommand: ( + arguments_: string[], + options?: Omit< + Parameters[1], + "cliPath" | "learningDatabaseUrl" | "nodePath" + >, + ) => + runLearningCommand(arguments_, { + cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, + nodePath: configuration.nodePath, + ...options, + }), + withLock: ( + operation: Parameters>[0]["run"], + ) => withLearningExecutionLock({ databaseUrl, run: operation }), + } + } + + // Scoring and drafting need the store's evaluation grant, which a repository turned on + // before grants existed gets on its next settings save, and a repository Hub can + // still reach. + function evaluationsEnabled(prisma: PrismaClient, repositoryId: string) { + return prisma.$transaction(async (transaction) => { + await lockGitHubRepositoryAccessState(transaction) + const setting = await getRepositoryEvaluationSetting(transaction, repositoryId) + return ( + Boolean(setting?.enabled && setting.evaluationGrantId) && + (await isLearningRunRepositoryAvailable(transaction, repositoryId, true)) + ) + }) + } + async function copilotUsable() { const { configuration, prisma } = await dependencies() - const connection = await getCopilotConnection(prisma) - const state = await getCopilotConnectionState(prisma) - if (!state) return false - return getCopilotConnectionStatus( - connection - ? { - connectedBy: { - login: connection.connectedByMembership.user.profile?.login ?? null, - membershipId: connection.connectedByMembershipId, - name: connection.connectedByMembership.user.profile?.name ?? null, - }, - credentialDigest: connection.credentialDigest, - credentialProvider: connection.credentialProvider, - verifiedAt: connection.verifiedAt, - } - : null, - configuration.copilotCredentialProvider, - connection - ? await isEffectiveAdministrator(prisma, connection.connectedByMembershipId) - : false, - { - credentialDigest: state.refusedCredentialDigest, - credentialProvider: state.refusedCredentialProvider, - refusedAt: state.refusedAt, - }, - ).connected + const read = await readCopilotConnectionStatus(prisma, configuration.copilotCredentialProvider) + return read?.status.connected ?? false } - async function processRun(runId: string, scheduled: boolean) { - const { configuration, databaseUrl, prisma, source } = await dependencies() - const stored = await getLearningRun(prisma, runId) - if (!stored || stored.scheduled !== scheduled) return + // Learning runs and scoring both fetch a fresh Copilot credential and record a refusal + // only against the connection that credential came from, so a newer connection made + // meanwhile is never marked as refused. + function createCopilotCredentialSession() { let credentialSnapshot: | { connectionId: string @@ -138,38 +199,38 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg credentialProvider: string } | undefined - return await processLearningRun(runId, { - expectedScheduled: scheduled, - claim: (id, startedAt, expectedScheduled) => - claimLearningRun(prisma, id, startedAt, expectedScheduled), - capture: (repositoryId) => source.captureCompleteSnapshot({ repositoryId }), - finish: (id, input) => finishLearningRun(prisma, id, input), - getRun: (id) => getLearningRun(prisma, id), - hasPendingUserRun: () => hasPendingUserLearningRun(prisma), - reviewCommentConsent: (repositoryId) => - getReviewCommentConsent(prisma, repositoryId, configuration.reviewCommentConsent), - recordRepositoryReviewCommentGrant: (repositoryId, grantId) => - saveRepositoryLearningSetting(prisma, repositoryId, { reviewCommentGrantId: grantId }), - isRepositoryAvailable: (repositoryId) => - prisma.$transaction(async (transaction) => { - await lockGitHubRepositoryAccessState(transaction) - return isLearningRunRepositoryAvailable(transaction, repositoryId, true) - }), - now: () => new Date(), - authorizeRepositoryAdministration: (membershipId, repositoryId) => - authorizeRepositoryAdministration(prisma, { membershipId, repositoryId }), - prepare: async (repositoryId) => - prepareLearningStore({ - applicationRoot: process.cwd(), - learningDatabaseUrl: configuration.learningDatabaseUrl, - repositoryKey: repositoryId, - repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), - root: configuration.root, - staticDirectories: configuration.staticDirectories, - }), + return { + credential: async () => { + const { configuration, prisma } = await dependencies() + const read = await readCopilotConnectionStatus( + prisma, + configuration.copilotCredentialProvider, + ) + if (!read) return null + const { connection, state, status } = read + if (!status.connected || !connection) return null + credentialSnapshot = { + connectionId: connection.id, + generation: state.generation, + credentialDigest: connection.credentialDigest, + credentialProvider: connection.credentialProvider, + } + try { + return await configuration.copilotCredentialProvider.getCredential() + } catch (error) { + if ( + error instanceof CopilotCredentialError && + (error.code === "installation_revoked" || error.code === "permission_denied") + ) { + throw new LearningCommandError(error.code, error.message, { cause: error }) + } + throw error + } + }, refuseCredential: async () => { if (!credentialSnapshot) return const snapshot = credentialSnapshot + const { prisma } = await dependencies() await prisma.$transaction(async (transaction) => { const state = await lockCopilotConnectionState(transaction) const connection = await getCopilotConnection(transaction) @@ -204,61 +265,45 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg }) }) }, - runCommand: (arguments_, options) => - runLearningCommand(arguments_, { - cliPath: configuration.cliPath, - learningDatabaseUrl: configuration.learningDatabaseUrl, - nodePath: configuration.nodePath, - ...options, + } + } + + async function processRun(runId: string, scheduled: boolean) { + const loaded = await dependencies() + const { configuration, prisma, source } = loaded + const store = storeAccess(loaded) + const stored = await getLearningRun(prisma, runId) + if (!stored || stored.scheduled !== scheduled) return + const copilot = createCopilotCredentialSession() + return await processLearningRun(runId, { + expectedScheduled: scheduled, + claim: (id, startedAt, expectedScheduled) => + claimLearningRun(prisma, id, startedAt, expectedScheduled), + capture: (repositoryId) => source.captureCompleteSnapshot({ repositoryId }), + finish: (id, input) => + recordFinishedLearningRun(prisma, id, (transaction) => + finishLearningRun(transaction, id, input), + ), + getRun: (id) => getLearningRun(prisma, id), + hasPendingUserRun: () => hasPendingUserLearningRun(prisma), + reviewCommentConsent: (repositoryId) => + getReviewCommentConsent(prisma, repositoryId, configuration.reviewCommentConsent), + recordRepositoryReviewCommentGrant: (repositoryId, grantId) => + saveRepositoryLearningSetting(prisma, repositoryId, { reviewCommentGrantId: grantId }), + isRepositoryAvailable: (repositoryId) => + prisma.$transaction(async (transaction) => { + await lockGitHubRepositoryAccessState(transaction) + return isLearningRunRepositoryAvailable(transaction, repositoryId, true) }), - credential: async () => { - const connection = await getCopilotConnection(prisma) - const state = await getCopilotConnectionState(prisma) - if (!state) return null - const status = getCopilotConnectionStatus( - connection - ? { - connectedBy: { - login: connection.connectedByMembership.user.profile?.login ?? null, - membershipId: connection.connectedByMembershipId, - name: connection.connectedByMembership.user.profile?.name ?? null, - }, - credentialDigest: connection.credentialDigest, - credentialProvider: connection.credentialProvider, - verifiedAt: connection.verifiedAt, - } - : null, - configuration.copilotCredentialProvider, - connection - ? await isEffectiveAdministrator(prisma, connection.connectedByMembershipId) - : false, - { - credentialDigest: state.refusedCredentialDigest, - credentialProvider: state.refusedCredentialProvider, - refusedAt: state.refusedAt, - }, - ) - if (!status.connected || !connection) return null - credentialSnapshot = { - connectionId: connection.id, - generation: state.generation, - credentialDigest: connection.credentialDigest, - credentialProvider: connection.credentialProvider, - } - try { - return await configuration.copilotCredentialProvider.getCredential() - } catch (error) { - if ( - error instanceof CopilotCredentialError && - (error.code === "installation_revoked" || error.code === "permission_denied") - ) { - throw new LearningCommandError(error.code, error.message, { cause: error }) - } - throw error - } - }, + now: () => new Date(), + authorizeRepositoryAdministration: (membershipId, repositoryId) => + authorizeRepositoryAdministration(prisma, { membershipId, repositoryId }), + prepare: store.prepare, + refuseCredential: copilot.refuseCredential, + runCommand: store.runCommand, + credential: copilot.credential, updateProgress: (id, input) => updateLearningRunProgress(prisma, id, input), - withLock: (operation) => withLearningExecutionLock({ databaseUrl, run: operation }), + withLock: store.withLock, }) } @@ -310,6 +355,31 @@ 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}`, + ) + } + // Agents can report usage before or after the Build for that commit finishes, so + // requests wait here until both exist. Unbuilt ones are dropped after 30 days. + await deleteExpiredLearningScoreRequests( + prisma, + new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), + ) + // Scoring is automatic work, so it waits behind anything a person asked for. + for (const request of await listReadyLearningScoreRequests(prisma)) { + await enqueueRecoverableJob( + scheduledQueue, + scoreAppliedLearningsJob, + request, + `learning-score-${request.repositoryId}-${request.commitSha}`, + { priority: automaticLearningRunPriority }, + ) + } for (const operation of await listLearningDecisionOperations(prisma)) { try { await reconcileLearningDecisionOperation(operation, { @@ -325,7 +395,13 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg type: "learning_decision", actorMembershipId: operation.actorMembershipId, decision: operation.decision as - "accept" | "reject" | "retire" | "edit" | "reinstate", + | "accept" + | "reject" + | "retire" + | "edit" + | "reinstate" + | "apply_update" + | "dismiss_update", learningId: operation.learningId, operationId: operation.id, outcome: input.outcome, @@ -338,7 +414,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg const directory = !configuration.learningDatabaseUrl && (await getSoloLearningDirectory(prisma, repositoryId)) - if (!directory) throw new Error("The original Solo store is unavailable.") + if (!directory) throw new Error("The original local learning store is unavailable.") return { directory } } if (repositoryScope !== (await getLearningRepositoryScope(prisma, repositoryId))) @@ -423,7 +499,9 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg priority: automaticLearningRunPriority, }), fail: async (runId, error) => { - const failed = await failScheduledLearningRunEnqueue(prisma, runId, new Date()) + const failed = await recordFinishedLearningRun(prisma, runId, (transaction) => + failScheduledLearningRunEnqueue(transaction, runId, new Date()), + ) if (failed.count === 0) return logger.error( { @@ -477,5 +555,204 @@ 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 () => { + const setting = await getRepositoryEvaluationSetting(prisma, input.repositoryId) + return setting?.enabled ? setting.screenshotGrantId : null + }, + deleteRecord: (id) => deleteAgentScreenshot(prisma, id), + grantId: input.grantId, + list: () => listGrantAgentScreenshots(prisma, input), + storage: { delete: async (key) => (await artifactStorage()).delete(key) }, + }) + }) + + async function withinBudget(prisma: PrismaClient) { + const budget = (await initializeEvaluationSetting(prisma)).monthlyBudgetCredits + const used = await sumLearningEvaluationCredits(prisma, startOfUtcMonth(new Date())) + return used ? used.lessThan(budget) : budget.greaterThan(0) + } + + const score = createJobProcessor(scoreAppliedLearningsJob, async (request, context) => { + const loaded = await dependencies() + const { prisma } = loaded + const store = storeAccess(loaded) + const repository = { repositoryId: request.repositoryId, commitSha: request.commitSha } + // Read before the store's usage, so a report that lands while scoring runs raises the + // revision and keeps its request for another pass. + const pending = await findLearningScoreRequest(prisma, repository) + if (!pending) return + const copilot = createCopilotCredentialSession() + try { + const result = await scoreAppliedLearnings({ + commitSha: request.commitSha, + credential: copilot.credential, + deleteRequest: () => + deleteLearningScoreRequest(prisma, { ...repository, revision: pending.revision }), + finish: (runId, input) => finishLearningEvaluationRun(prisma, runId, input), + hasPendingUserRun: () => hasPendingUserLearningRun(prisma), + isEnabled: () => evaluationsEnabled(prisma, request.repositoryId), + now: () => new Date(), + prepare: async () => learningStoreArguments(await store.prepare(request.repositoryId)), + readDiff: async () => { + const credentials = readGitHubAppConfiguration( + resolveLocalSignInEnvironment(environment), + ).appCredentials + const githubRepositoryId = (await findRepositoryGitHubId(prisma, request.repositoryId)) + ?.githubRepositoryId + if (!credentials || !githubRepositoryId) return null + try { + return await createGitHubActionsClient({ + appId: credentials.appId, + installationId: credentials.installationId, + privateKey: credentials.privateKey, + githubRepositoryId: Number(githubRepositoryId), + }).getCommitDiff(request.commitSha) + } catch (error) { + // A commit GitHub no longer has is scored on what remains. + if ( + error instanceof GitHubCommitLookupError && + (error.statusCode === 404 || error.statusCode === 422) + ) + return null + throw error + } + }, + readScreenshot: async (sha256, grantId) => { + const consented = await findConsentedAgentScreenshots(prisma, { + repositoryId: request.repositoryId, + sha256s: [sha256], + }) + const storageKey = consented?.storageKeys.get(sha256) + if (!storageKey || consented?.grantId !== grantId) return null + const read = await (await artifactStorage()).read(storageKey) + if (read.status === "ok") return read.bytes + if (read.status === "not-found") return null + // An outage would change the score, so the attempt is retried later instead. + throw new Error(`Hub could not read an agent screenshot: ${read.status}.`) + }, + refuseCredential: copilot.refuseCredential, + requestUpdate: (memoryId) => + recordLearningUpdateRequest(prisma, { repositoryId: request.repositoryId, memoryId }), + runCommand: store.runCommand, + start: (usedLearningId, trigger) => + startLearningEvaluationRun(prisma, { + repositoryId: request.repositoryId, + usedLearningId, + trigger, + }), + verifications: async () => { + const consent = await getReviewCommentConsent( + prisma, + request.repositoryId, + loaded.configuration.reviewCommentConsent, + ) + if (consent.turnedOff || (!consent.hubAdministrator && !consent.repositoryGrantId)) + return [] + return listLearningReviewerVerifications(prisma, repository) + }, + withinBudget: () => withinBudget(prisma), + withLock: store.withLock, + }) + if (result === "deferred") return await context.defer(30_000) + if (result === "paused") + logger.info( + repository, + "Applied learning scoring is paused until Copilot or budget returns", + ) + } catch (error) { + if ( + error instanceof Error && + error.message === "Another learning operation is still running." + ) + return await context.defer(30_000) + throw error + } + }) + + // The daily job only queues one check per flagged learning, so other scheduled work + // runs between checks and one repository's failure doesn't hold up the rest. + const proposeUpdates = createJobProcessor(proposeLearningUpdatesJob, async () => { + const { databaseUrl, prisma } = await dependencies() + const queue = createJobQueue({ name: "scheduled", databaseUrl, logger }) + try { + for (const request of await listLearningUpdateRequests(prisma)) + await enqueueRecoverableJob( + queue, + proposeLearningUpdateJob, + { requestId: request.id }, + `learning-update-${request.id}`, + { priority: automaticLearningRunPriority }, + ) + } finally { + await queue.close() + } + }) + + const proposeUpdate = createJobProcessor(proposeLearningUpdateJob, async (input, context) => { + const loaded = await dependencies() + const { configuration, prisma } = loaded + const store = storeAccess(loaded) + const request = await findLearningUpdateRequest(prisma, input.requestId) + if (!request) return + try { + const result = await proposeLearningUpdate(request, { + activeScreenshotGrant: async () => { + const setting = await getRepositoryEvaluationSetting(prisma, request.repositoryId) + return setting?.enabled ? setting.screenshotGrantId : null + }, + closeAbandoned: (finishedAt) => closeAbandonedLearningUpdateRuns(prisma, finishedAt), + credential: async () => { + if (!(await copilotUsable())) return null + return configuration.copilotCredentialProvider.getCredential() + }, + deleteRequest: (observed) => deleteLearningUpdateRequest(prisma, observed), + finish: (runId, finished) => finishLearningUpdateRun(prisma, runId, finished), + isEnabled: (repositoryId) => evaluationsEnabled(prisma, repositoryId), + now: () => new Date(), + prepare: async (repositoryId) => learningStoreArguments(await store.prepare(repositoryId)), + runCommand: store.runCommand, + start: (started) => startLearningUpdateRun(prisma, started), + withinBudget: () => withinBudget(prisma), + withLock: store.withLock, + }) + if (result === "paused") + logger.info( + { repositoryId: request.repositoryId }, + "Learning update suggestions are paused until Copilot or budget returns", + ) + } catch (error) { + if ( + error instanceof Error && + error.message === "Another learning operation is still running." + ) + return await context.defer(30_000) + throw error + } + }) + + return { + run, + scheduledRun, + recover, + redact, + schedule, + deleteScreenshots, + score, + proposeUpdates, + proposeUpdate, + } } diff --git a/hub/server/domains/learning/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/execute-learning-decision/index.test.ts b/hub/server/domains/learning/execute-learning-decision/index.test.ts index b0fa5f474..65f8da6ca 100644 --- a/hub/server/domains/learning/execute-learning-decision/index.test.ts +++ b/hub/server/domains/learning/execute-learning-decision/index.test.ts @@ -214,4 +214,102 @@ describe("executeLearningDecision()", () => { }), ).rejects.toMatchObject({ code: "EACCES" }) }) + it("applies a suggested update with its operation ID and private wording", async () => { + vi.mocked(validatePrivateStorageRoot).mockResolvedValue("/private/learning/repository") + vi.mocked(runLearningCommand) + .mockResolvedValueOnce({ updates: [{ id: "upd_1", state: "open" }] }) + .mockImplementationOnce(async (arguments_) => { + expect(arguments_).toEqual( + expect.arrayContaining([ + "apply-update", + "upd_1", + "--operation-id", + "33333333-3333-4333-8333-333333333333", + ]), + ) + const index = arguments_.indexOf("--content-file") + expect(await readFile(arguments_[index + 1]!, "utf8")).toBe("Put labels above inputs.") + return { stored: true } + }) + + const result = await executeLearningDecision({ + actor: "human:mona", + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + decision: { + decision: "apply_update", + proposalId: "upd_1", + content: "Put labels above inputs.", + reason: "The suggestion matches what reviewers asked for.", + }, + learningDatabaseUrl: "postgresql://learning.example/replica", + learningId: "mem_1", + nodePath: "/node", + operationId: "33333333-3333-4333-8333-333333333333", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }) + + expect(result.notice).toBe("Suggested update applied.") + expect(vi.mocked(runLearningCommand).mock.calls[0]![0]).toEqual( + expect.arrayContaining(["updates", "mem_1"]), + ) + }) + + it("refuses a suggested update that belongs to another learning", async () => { + vi.mocked(validatePrivateStorageRoot).mockResolvedValue("/private/learning/repository") + vi.mocked(runLearningCommand) + .mockReset() + .mockResolvedValueOnce({ updates: [{ id: "upd_1", state: "open" }] }) + + await expect( + executeLearningDecision({ + actor: "human:mona", + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + decision: { decision: "dismiss_update", proposalId: "upd_other", reason: "Not needed." }, + learningDatabaseUrl: "postgresql://learning.example/replica", + learningId: "mem_1", + nodePath: "/node", + operationId: "33333333-3333-4333-8333-333333333333", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }), + ).rejects.toMatchObject({ code: "not_found" }) + expect(runLearningCommand).toHaveBeenCalledTimes(1) + }) + + it("refuses a suggested update another administrator already decided", async () => { + vi.mocked(validatePrivateStorageRoot).mockResolvedValue("/private/learning/repository") + vi.mocked(runLearningCommand) + .mockReset() + .mockResolvedValueOnce({ updates: [{ id: "upd_1", state: "applied" }] }) + + await expect( + executeLearningDecision({ + actor: "human:mona", + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + decision: { + decision: "apply_update", + proposalId: "upd_1", + content: "Put labels above inputs.", + reason: "The suggestion matches what reviewers asked for.", + }, + learningDatabaseUrl: "postgresql://learning.example/replica", + learningId: "mem_1", + nodePath: "/node", + operationId: "33333333-3333-4333-8333-333333333333", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }), + ).rejects.toMatchObject({ code: "stale_review" }) + expect(runLearningCommand).toHaveBeenCalledTimes(1) + }) }) diff --git a/hub/server/domains/learning/execute-learning-decision/index.ts b/hub/server/domains/learning/execute-learning-decision/index.ts index 44d659dd2..73e4e8832 100644 --- a/hub/server/domains/learning/execute-learning-decision/index.ts +++ b/hub/server/domains/learning/execute-learning-decision/index.ts @@ -1,3 +1,4 @@ +import { z } from "zod" import { access, mkdtemp, rm, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { resolve } from "node:path" @@ -9,6 +10,10 @@ import { learningStoreArguments } from "../learning-store-arguments/index.ts" import { learningIdSchema } from "../learning-id/index.ts" import type { LearningDecision } from "../types.ts" +const updatesSchema = z + .object({ updates: z.array(z.object({ id: z.string(), state: z.string() }).loose()) }) + .loose() + export async function executeLearningDecision(input: { actor: string applicationRoot?: string @@ -46,65 +51,97 @@ export async function executeLearningDecision(input: { throw new LearningCommandError("not_found", "That learning no longer exists.") } } - const arguments_ = [input.decision.decision, input.learningId] - arguments_.push("--operation-id", input.operationId) - if (input.decision.decision !== "retire") { - arguments_.push("--digest", input.decision.digest) + const store = learningStoreArguments({ + directory, + repositoryId: input.soloDirectory ? undefined : input.repositoryId, + repositoryScope: input.repositoryScope, + soloStoreKey: input.soloStoreKey, + }) + const commandOptions = { + cliPath: input.cliPath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), + nodePath: input.nodePath, + signal: input.signal, + } + const decision = input.decision + const arguments_: string[] = [] + if (decision.decision === "apply_update" || decision.decision === "dismiss_update") { + // The package finds a suggestion by its own ID, so check it belongs to this learning. + const { updates } = updatesSchema.parse( + await runLearningCommand(["updates", input.learningId, ...store], commandOptions), + ) + const update = updates.find(({ id }) => id === decision.proposalId) + if (!update) { + throw new LearningCommandError("not_found", "That suggested update no longer exists.") + } + // The package treats a repeated decision as done, which would hide that another + // administrator already chose differently. + if (update.state !== "open") { + throw new LearningCommandError( + "stale_review", + "That suggested update was already decided. Refresh to see the latest.", + ) + } + arguments_.push( + decision.decision.replace("_", "-"), + decision.proposalId, + "--operation-id", + input.operationId, + ) + } else { + arguments_.push(decision.decision, input.learningId, "--operation-id", input.operationId) + if (decision.decision !== "retire") arguments_.push("--digest", decision.digest) } arguments_.push("--by", input.actor) let temporaryDirectory: string | undefined try { - if (input.decision.decision !== "accept") { + if (decision.decision !== "accept" || decision.content !== undefined) { temporaryDirectory = await mkdtemp(resolve(tmpdir(), "replica-learning-decision-")) - const reasonPath = resolve(temporaryDirectory, "reason.txt") - await writeFile(reasonPath, input.decision.reason, { mode: 0o600 }) + } + if (decision.decision !== "accept") { + const reasonPath = resolve(temporaryDirectory!, "reason.txt") + await writeFile(reasonPath, decision.reason, { mode: 0o600 }) arguments_.push("--reason-file", reasonPath) } if ( - (input.decision.decision === "accept" || input.decision.decision === "edit") && - input.decision.content !== undefined + (decision.decision === "accept" || + decision.decision === "edit" || + decision.decision === "apply_update") && + decision.content !== undefined ) { - temporaryDirectory ??= await mkdtemp(resolve(tmpdir(), "replica-learning-decision-")) - const contentPath = resolve(temporaryDirectory, "content.txt") - await writeFile(contentPath, input.decision.content, { mode: 0o600 }) + const contentPath = resolve(temporaryDirectory!, "content.txt") + await writeFile(contentPath, decision.content, { mode: 0o600 }) arguments_.push("--content-file", contentPath) } - if (input.decision.decision === "edit" && input.decision.title !== undefined) { - temporaryDirectory ??= await mkdtemp(resolve(tmpdir(), "replica-learning-decision-")) - const titlePath = resolve(temporaryDirectory, "title.txt") - await writeFile(titlePath, input.decision.title, { mode: 0o600 }) + if ( + (decision.decision === "edit" || decision.decision === "apply_update") && + decision.title !== undefined + ) { + const titlePath = resolve(temporaryDirectory!, "title.txt") + await writeFile(titlePath, decision.title, { mode: 0o600 }) arguments_.push("--title-file", titlePath) } - await runLearningCommand( - [ - ...arguments_, - ...learningStoreArguments({ - directory, - repositoryId: input.soloDirectory ? undefined : input.repositoryId, - repositoryScope: input.repositoryScope, - soloStoreKey: input.soloStoreKey, - }), - ], - { - cliPath: input.cliPath, - ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), - nodePath: input.nodePath, - signal: input.signal, - }, - ) + const result = await runLearningCommand([...arguments_, ...store], commandOptions) + if ( + (decision.decision === "apply_update" || decision.decision === "dismiss_update") && + !z.object({ stored: z.boolean() }).parse(result).stored + ) { + throw new LearningCommandError( + "stale_review", + "That suggested update was already decided. Refresh to see the latest.", + ) + } } finally { if (temporaryDirectory) await rm(temporaryDirectory, { recursive: true }) } - return { - notice: - input.decision.decision === "accept" - ? "Learning accepted." - : input.decision.decision === "reject" - ? "Suggestion rejected." - : input.decision.decision === "retire" - ? "Learning retired." - : input.decision.decision === "edit" - ? "Learning updated." - : "Learning reinstated.", + const notices = { + accept: "Learning accepted.", + reject: "Suggestion rejected.", + retire: "Learning retired.", + edit: "Learning updated.", + reinstate: "Learning reinstated.", + apply_update: "Suggested update applied.", + dismiss_update: "Suggested update dismissed.", } + return { notice: notices[decision.decision] } } diff --git a/hub/server/domains/learning/find-learning-store/index.ts b/hub/server/domains/learning/find-learning-store/index.ts new file mode 100644 index 000000000..f6da03aba --- /dev/null +++ b/hub/server/domains/learning/find-learning-store/index.ts @@ -0,0 +1,38 @@ +import { access } from "node:fs/promises" +import { resolve } from "node:path" + +import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" + +/** + * Finds a repository's private learning folder. Without a shared database, a repository + * that never used learnings has no store yet, so readers get null rather than an error. + * Local Hub passes a local learning store found in the checkout instead. + */ +export async function findLearningStore(input: { + applicationRoot?: string + learningDatabaseUrl?: string + repositoryId: string + root: string + soloDirectory?: string + staticDirectories: string[] +}): Promise { + if (input.soloDirectory) return input.soloDirectory + 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) return directory + try { + await access(resolve(directory, "config.json")) + return directory + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return null + } +} 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 000000000..537454af0 --- /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 000000000..4b354e1dd --- /dev/null +++ b/hub/server/domains/learning/get-applied-learnings/index.ts @@ -0,0 +1,107 @@ +import { z } from "zod" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { findLearningStore } from "../find-learning-store/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 + /** A local learning store in a checkout, used in place of Hub's own. */ + soloDirectory?: string + soloStoreKey?: string + staticDirectories: string[] +}): Promise { + const directory = await findLearningStore(input) + if (!directory) { + return [] + } + const { reports } = usageSchema.parse( + await runLearningCommand( + [ + "usage", + "--commit", + input.commitSha, + ...learningStoreArguments({ + directory, + repositoryId: input.soloDirectory ? undefined : input.repositoryId, + repositoryScope: input.repositoryScope, + soloStoreKey: input.soloStoreKey, + }), + ], + { + 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/get-learning-history/index.test.ts b/hub/server/domains/learning/get-learning-history/index.test.ts index ec14be426..87c327330 100644 --- a/hub/server/domains/learning/get-learning-history/index.test.ts +++ b/hub/server/domains/learning/get-learning-history/index.test.ts @@ -63,6 +63,7 @@ describe("getLearningHistory()", () => { retired: { at: "2026-11-04T00:00:00.000Z", reason: "No longer true." }, }, { version: 7, state: "accepted", withheld: true }, + { withheld: true }, ], }) @@ -83,7 +84,7 @@ describe("getLearningHistory()", () => { [3, "edited", "mona"], [5, "edited", "mona"], [6, "retired", null], - [7, "accepted", null], + [7, "reinstated", null], ]) expect(result.decisions[2]?.reason).toBe("Clearer wording.") expect(vi.mocked(runLearningCommand).mock.calls[0]?.[0]).toEqual( @@ -300,4 +301,124 @@ describe("getLearningHistory()", () => { }) expect(JSON.stringify(result)).not.toContain("Private session text.") }) + it("shows earlier wording with its own scores and only open suggested updates", async () => { + const outcome = { + commitSha: "a".repeat(40), + prototypeId: "proto_1", + efficiency: 2, + followed: "followed", + reasoning: "The labels moved inside the fields.", + issue: "The rule did not say where the label goes.", + scoredAt: "2026-11-05T00:00:00.000Z", + inputs: ["build_diff"], + } + const open = { + id: "upd_open", + state: "open", + issue: "The rule did not say where the label goes.", + content: "Put labels above inputs.", + reasoning: "Builds kept placing labels inside inputs.", + support: ["score_new"], + } + vi.mocked(runLearningCommand) + .mockResolvedValueOnce({ + withheld: false, + record: {}, + versions: [ + { version: 1, state: "accepted", contentDigest: "old", content: "Label fields." }, + // Wording changed before approval never reached agents. + { version: 2, state: "proposed", contentDigest: "draft", content: "Label it." }, + { version: 3, state: "accepted", contentDigest: "new", content: "Label every field." }, + ], + }) + .mockResolvedValueOnce({ + outcomes: [ + { ...outcome, id: "score_old", usedLearningId: "use_1", version: 1 }, + { + ...outcome, + id: "score_new", + usedLearningId: "use_2", + version: 3, + commitSha: "b".repeat(64), + }, + ], + }) + .mockResolvedValueOnce({ + updates: [ + { ...open, id: "upd_dismissed", state: "dismissed" }, + // The package hides wording whose scores may no longer be read. + { id: "upd_withheld", state: "open", withheld: true, support: [] }, + open, + ], + }) + + const result = await getLearningHistory({ + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + learningId: "mem_1", + nodePath: "/node", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }) + + expect(result.outcomes.map(({ id }) => id)).toEqual(["score_new"]) + expect(result.earlierGuidance).toEqual([ + { + version: 1, + title: null, + content: "Label fields.", + outcomes: [expect.objectContaining({ id: "score_old" })], + }, + ]) + expect(result.updates).toEqual([ + { + id: "upd_open", + issue: "The rule did not say where the label goes.", + title: null, + content: "Put labels above inputs.", + reasoning: "Builds kept placing labels inside inputs.", + support: [expect.objectContaining({ id: "score_new", commitSha: "b".repeat(64) })], + }, + ]) + }) + + it("counts distinct local sessions rather than fetching their private messages", async () => { + function session(sessionId: string, episodeId: string) { + return { episodeId, eventIds: [episodeId], source: { kind: "agent_session", sessionId } } + } + vi.mocked(runLearningCommand).mockResolvedValue({ + withheld: false, + record: { + evidence: [ + session("private-session-a", "note-a"), + session("private-session-a", "note-b"), + session("private-session-b", "chat-b"), + ], + contradictions: [session("private-session-a", "note-c")], + }, + }) + const result = await getLearningHistory({ + cliPath: "/cli", + nodePath: "/node", + repositoryId: "repo", + repositoryScope: "github.com/repositories/123", + learningId: "mem_1", + root: "/private", + soloDirectory: "/checkout/.replica/learning", + soloStoreKey: `sha256:${"c".repeat(64)}`, + staticDirectories: [], + evidenceSource: { resolveEvidence: vi.fn() }, + }) + expect(result).toMatchObject({ + sessions: { supporting: 2, opposing: 1 }, + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + }) + expect(JSON.stringify(result)).not.toContain("private-session") + expect(runLearningCommand).toHaveBeenCalledOnce() + }) }) diff --git a/hub/server/domains/learning/get-learning-history/index.ts b/hub/server/domains/learning/get-learning-history/index.ts index 76f71e506..c885b0389 100644 --- a/hub/server/domains/learning/get-learning-history/index.ts +++ b/hub/server/domains/learning/get-learning-history/index.ts @@ -8,9 +8,16 @@ import { LearningCommandError } from "../../../integrations/learning/run-learnin import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" import { learningStoreArguments } from "../learning-store-arguments/index.ts" import { learningIdSchema } from "../learning-id/index.ts" +import { summarizeLearningEvidence } from "../summarize-learning-evidence/index.ts" import { referenceSchema, resolveLearningReferences } from "../resolve-learning-references/index.ts" import type { ReviewCommentLearningSource } from "../review-comment-learning-source/types.ts" -import type { LearningDecisionRecord, LearningEvidence } from "../types.ts" +import type { + EarlierLearningGuidance, + ReportedLearningOutcome, + LearningUpdateSuggestion, + LearningDecisionRecord, + LearningEvidence, +} from "../types.ts" const decisionSchema = z .object({ @@ -24,8 +31,11 @@ const decisionSchema = z .optional() const versionSchema = z .object({ - version: z.number().int().positive(), - state: z.enum(["proposed", "accepted", "rejected", "retired"]), + version: z.number().int().positive().optional(), + state: z.enum(["proposed", "accepted", "rejected", "retired"]).optional(), + contentDigest: z.string().optional(), + title: z.string().optional(), + content: z.string().optional(), withheld: z.literal(true).optional(), updatedAt: z.string().optional(), proposal: z @@ -53,6 +63,55 @@ const showSchema = z }) .loose() +const screenshotSchema = z + .object({ + sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/), + route: z.string(), + consentGrantId: z.string().optional(), + }) + .loose() +const outcomesSchema = z + .object({ + outcomes: z.array( + z + .object({ + id: z.string().min(1), + usedLearningId: z.string().min(1), + version: z.number().int().positive(), + inputs: z.array(z.string()), + commitSha: z.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/), + prototypeId: z.string().optional(), + efficiency: z.number().int().min(1).max(4), + followed: z.enum(["followed", "not_followed", "unclear"]), + reasoning: z.string(), + issue: z.string().optional(), + scoredAt: z.string().min(1), + before: screenshotSchema.optional(), + after: screenshotSchema.optional(), + }) + .loose(), + ), + }) + .loose() +const updatesSchema = z + .object({ + updates: z.array( + z + .object({ + id: z.string().min(1), + state: z.string(), + // The package leaves out wording whose scores may no longer be read. + issue: z.string().optional(), + title: z.string().optional(), + content: z.string().optional(), + reasoning: z.string().optional(), + support: z.array(z.string()), + }) + .loose(), + ), + }) + .loose() + function login(identity: string | undefined) { return identity?.replace(/^(?:github|human):/, "") || null } @@ -65,6 +124,11 @@ function decisions(versions: z.infer[]) { const result: LearningDecisionRecord[] = [] let previous: z.infer | undefined for (const version of versions) { + // Damaged versions may have no trustworthy version number or state. + if (!version.version || !version.state) { + previous = version + continue + } const accepted = version.accepted if (version.state === "proposed" && !previous) { result.push({ @@ -84,10 +148,12 @@ function decisions(versions: z.infer[]) { version: version.version, state: "accepted", change: - accepted?.decision === "edit" - ? "edited" - : accepted?.decision === "reinstate" - ? "reinstated" + previous?.state === "rejected" || + previous?.state === "retired" || + accepted?.decision === "reinstate" + ? "reinstated" + : accepted?.decision === "edit" + ? "edited" : "accepted", by: login(accepted?.by?.id), at: accepted?.at ?? version.updatedAt ?? null, @@ -131,7 +197,12 @@ export async function getLearningHistory(input: { soloStoreKey?: string staticDirectories: string[] }): Promise<{ + sessions?: { supporting: number; opposing: number } + reviewableUpdate: boolean decisions: LearningDecisionRecord[] + outcomes: ReportedLearningOutcome[] + earlierGuidance: EarlierLearningGuidance[] + updates: LearningUpdateSuggestion[] evidence: LearningEvidence[] otherEvidenceCount: number contradictions: LearningEvidence[] @@ -173,7 +244,61 @@ export async function getLearningHistory(input: { commandOptions, ), ) - const history = decisions(shown.versions ?? []) + const versions = shown.versions ?? [] + const history = decisions(versions) + const readable = + !shown.withheld && + !versions.at(-1)?.withheld && + !!versions.at(-1)?.contentDigest && + versions.some((version) => version.state === "accepted" && !version.withheld) + const scored = !readable + ? [] + : outcomesSchema + .parse( + await runLearningCommand( + ["outcomes", input.learningId, ...commonArguments], + commandOptions, + ), + ) + .outcomes.filter( + (score) => !score.inputs.includes("screenshots") || score.before || score.after, + ) + const wording = versions.at(-1)?.contentDigest + const outcomes = wording ? outcomesOf(scored, versions, wording) : [] + const earlierGuidance = !readable || !wording ? [] : earlier(scored, versions, wording) + // Only an accepted learning can take new wording, so other states never show one. + const updates = + !readable || versions.at(-1)?.state !== "accepted" + ? [] + : updatesSchema + .parse( + await runLearningCommand( + ["updates", input.learningId, ...commonArguments], + commandOptions, + ), + ) + .updates.flatMap((update) => { + // Hub checks each supporting score before showing the wording, so a score + // it cannot read leaves the suggestion unchecked and hidden. + const support = update.support.map((id) => scored.find((score) => score.id === id)) + return update.state === "open" && + update.support.length > 0 && + update.issue !== undefined && + update.content !== undefined && + update.reasoning !== undefined && + support.every((score) => score !== undefined) + ? [ + { + id: update.id, + issue: update.issue, + title: update.title ?? null, + content: update.content, + reasoning: update.reasoning, + support: support.map(reported), + }, + ] + : [] + }) const supporting = shown.withheld ? [] : (shown.record.evidence ?? []) const opposing = shown.withheld ? [] : (shown.record.contradictions ?? []) const resolved = await resolveLearningReferences([...supporting, ...opposing], { @@ -184,11 +309,101 @@ export async function getLearningHistory(input: { }) const evidence = resolved.slice(0, supporting.length) const contradictions = resolved.slice(supporting.length) + const supportSummary = summarizeLearningEvidence(supporting, evidence, !!input.soloDirectory) + const opposingSummary = summarizeLearningEvidence(opposing, contradictions, !!input.soloDirectory) return { + ...(input.soloDirectory + ? { sessions: { supporting: supportSummary.sessions, opposing: opposingSummary.sessions } } + : {}), + outcomes, + earlierGuidance, + updates, + reviewableUpdate: readable && versions.at(-1)?.state === "accepted", decisions: history, evidence: evidence.flat(), - otherEvidenceCount: evidence.filter((items) => items.length === 0).length, + otherEvidenceCount: supportSummary.unavailable, contradictions: contradictions.flat(), - otherContradictionsCount: contradictions.filter((items) => items.length === 0).length, + otherContradictionsCount: opposingSummary.unavailable, + } +} + +// Each wording agents were given before the current one, newest first, so people can +// compare how older guidance was scored with the guidance agents get now. +function earlier( + outcomes: z.infer["outcomes"], + versions: z.infer[], + current: string, +): EarlierLearningGuidance[] { + const latest = new Map>() + for (const version of versions) { + // Proposed wording that was changed before approval never reached agents. + if ( + version.state === "accepted" && + version.contentDigest && + version.contentDigest !== current + ) { + // Moving a repeated wording to the end keeps the list ordered by its last use. + latest.delete(version.contentDigest) + latest.set(version.contentDigest, version) + } + } + return [...latest.entries()].reverse().flatMap(([wording, version]) => + version.version === undefined || version.withheld || version.content === undefined + ? [] + : [ + { + version: version.version, + title: version.title ?? null, + content: version.content, + outcomes: outcomesOf(outcomes, versions, wording), + }, + ], + ) +} + +// Scores of other wording say nothing about this guidance. Retiring and reinstating add +// versions with the same wording, so match the wording, not the number. +function outcomesOf( + outcomes: z.infer["outcomes"], + versions: z.infer[], + wording: string, +): ReportedLearningOutcome[] { + const current = new Set( + versions + .filter((entry) => !entry.withheld && entry.contentDigest === wording) + .map((entry) => entry.version), + ) + const matching = outcomes.filter((outcome) => current.has(outcome.version)) + // A reviewer's confirmation scores the same use again. The newer score replaces the + // earlier one so the use isn't counted twice. + const last = new Map(matching.map((outcome, index) => [outcome.usedLearningId, index])) + return matching + .filter((outcome, index) => last.get(outcome.usedLearningId) === index) + .map(reported) +} + +function reported( + outcome: z.infer["outcomes"][number], +): ReportedLearningOutcome { + return { + id: outcome.id, + source: outcome.inputs.includes("reviewer_verification") ? "reviewer_confirmed" : "automated", + commitSha: outcome.commitSha, + prototypeId: outcome.prototypeId ?? null, + efficiency: outcome.efficiency, + followed: outcome.followed, + reasoning: outcome.reasoning, + issue: outcome.issue ?? null, + scoredAt: outcome.scoredAt, + ...(outcome.before ? { before: screenshot(outcome.before) } : {}), + ...(outcome.after ? { after: screenshot(outcome.after) } : {}), + } +} + +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/get-learning-overview/index.ts b/hub/server/domains/learning/get-learning-overview/index.ts index 9752c6e91..3999ebb72 100644 --- a/hub/server/domains/learning/get-learning-overview/index.ts +++ b/hub/server/domains/learning/get-learning-overview/index.ts @@ -6,6 +6,7 @@ import { runLearningCommand } from "../../../integrations/learning/run-learning- import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" import { learningStoreArguments } from "../learning-store-arguments/index.ts" +import { summarizeLearningEvidence } from "../summarize-learning-evidence/index.ts" import { referenceSchema, resolveLearningReferences } from "../resolve-learning-references/index.ts" import type { ReviewCommentLearningSource } from "../review-comment-learning-source/types.ts" import type { AcceptedLearning, LearningSuggestion, RejectedLearning } from "../types.ts" @@ -226,7 +227,22 @@ export async function getLearningOverview(input: { const boundary = referenceOffset + evidenceReferences.length const evidence = resolved.slice(referenceOffset, boundary) const contradictions = resolved.slice(boundary, referenceOffset + itemReferences.length) + const supportSummary = summarizeLearningEvidence( + evidenceReferences, + evidence, + !!input.soloDirectory, + ) + const opposingSummary = summarizeLearningEvidence( + itemReferences.slice(evidenceReferences.length), + contradictions, + !!input.soloDirectory, + ) suggestions.push({ + ...(input.soloDirectory + ? { + sessions: { supporting: supportSummary.sessions, opposing: opposingSummary.sessions }, + } + : {}), id: item.record.id, title: item.record.title ?? null, content, @@ -239,9 +255,9 @@ export async function getLearningOverview(input: { : null, replaces: replacementTargets(item), evidence: evidence.flat(), - otherEvidenceCount: evidence.filter((items) => items.length === 0).length, + otherEvidenceCount: supportSummary.unavailable, contradictions: contradictions.flat(), - otherContradictionsCount: contradictions.filter((items) => items.length === 0).length, + otherContradictionsCount: opposingSummary.unavailable, }) referenceOffset += itemReferences.length } 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/domains/learning/jobs/propose-learning-update.ts b/hub/server/domains/learning/jobs/propose-learning-update.ts new file mode 100644 index 000000000..09148f539 --- /dev/null +++ b/hub/server/domains/learning/jobs/propose-learning-update.ts @@ -0,0 +1,13 @@ +import { z } from "zod" + +import { automaticLearningRunPriority } from "./priorities.ts" + +export const proposeLearningUpdateJob = { + name: "learning.propose-update", + schema: z.object({ requestId: z.uuid() }).strict(), + options: { + attempts: 3, + backoff: { type: "exponential", delay: 60_000 }, + priority: automaticLearningRunPriority, + }, +} diff --git a/hub/server/domains/learning/jobs/propose-learning-updates.ts b/hub/server/domains/learning/jobs/propose-learning-updates.ts new file mode 100644 index 000000000..72e3eac7e --- /dev/null +++ b/hub/server/domains/learning/jobs/propose-learning-updates.ts @@ -0,0 +1,13 @@ +import { z } from "zod" + +import { automaticLearningRunPriority } from "./priorities.ts" + +export const proposeLearningUpdatesJob = { + name: "learning.propose-updates", + schema: z.object({}).strict(), + options: { + attempts: 3, + backoff: { type: "exponential", delay: 60_000 }, + priority: automaticLearningRunPriority, + }, +} diff --git a/hub/server/domains/learning/jobs/score-applied-learnings.ts b/hub/server/domains/learning/jobs/score-applied-learnings.ts new file mode 100644 index 000000000..04fecaea6 --- /dev/null +++ b/hub/server/domains/learning/jobs/score-applied-learnings.ts @@ -0,0 +1,12 @@ +import { z } from "zod" + +export const scoreAppliedLearningsJob = { + name: "learning.score-applied-learnings", + schema: z + .object({ + repositoryId: z.uuid(), + commitSha: z.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/), + }) + .strict(), + options: { attempts: 3, backoff: { type: "fixed", delay: 60_000 } }, +} diff --git a/hub/server/domains/learning/learning-store-arguments/index.ts b/hub/server/domains/learning/learning-store-arguments/index.ts index 1181fa1d5..cfd8497ca 100644 --- a/hub/server/domains/learning/learning-store-arguments/index.ts +++ b/hub/server/domains/learning/learning-store-arguments/index.ts @@ -15,11 +15,11 @@ export function learningStoreArguments(store: { store.repositoryScope, ) ) { - throw new Error("The repository learning scope must contain a GitHub or local Solo ID.") + throw new Error("The repository learning scope must contain a GitHub or local learning ID.") } const args = ["--dir", store.directory, "--repository", store.repositoryScope] if (store.repositoryId) return [...args, "--legacy-repository", `github.com/repositories/${store.repositoryId}`] - if (!store.soloStoreKey) throw new Error("A Solo store needs its inspected identity.") + if (!store.soloStoreKey) throw new Error("A local learning store needs its inspected identity.") return [...args, "--solo-store", store.soloStoreKey] } diff --git a/hub/server/domains/learning/list-local-learning-activity/index.test.ts b/hub/server/domains/learning/list-local-learning-activity/index.test.ts index 9002a938a..22312e14c 100644 --- a/hub/server/domains/learning/list-local-learning-activity/index.test.ts +++ b/hub/server/domains/learning/list-local-learning-activity/index.test.ts @@ -29,11 +29,12 @@ describe("listLocalLearningActivity()", () => { run("2026-03-02T09:00:00.000Z", "succeeded", [4, 3, 1]), "not json", run("2026-03-05T10:00:00.000Z", "succeeded", [2, 2, 0]), + run("2026-03-06T00:01:00.000Z", "succeeded", [1, 0, 0]), ].join("\n"), ) await expect( - listLocalLearningActivity(directory, new Date("2026-01-01T00:00:00.000Z")), + listLocalLearningActivity(directory, new Date("2026-01-01"), new Date("2026-03-05")), ).resolves.toEqual([ { date: "2026-03-02", diff --git a/hub/server/domains/learning/list-local-learning-activity/index.ts b/hub/server/domains/learning/list-local-learning-activity/index.ts index 0b6294364..c4fd478c8 100644 --- a/hub/server/domains/learning/list-local-learning-activity/index.ts +++ b/hub/server/domains/learning/list-local-learning-activity/index.ts @@ -20,6 +20,7 @@ const runSchema = z export async function listLocalLearningActivity( directory: string, from: Date, + through: Date, ): Promise { const path = resolve(directory, "activity.jsonl") let text: string @@ -38,12 +39,14 @@ export async function listLocalLearningActivity( } const days = new Map() + const lastDate = through.toISOString().slice(0, 10) for (const line of text.split("\n")) { const run = parseRun(line) if (!run) continue const startedAt = new Date(run.startedAt).toISOString() if (new Date(startedAt) < from) continue const date = startedAt.slice(0, 10) + if (date > lastDate) continue const day = days.get(date) const latest = !day || startedAt >= day.startedAt days.set(date, { diff --git a/hub/server/domains/learning/propose-learning-update/index.test.ts b/hub/server/domains/learning/propose-learning-update/index.test.ts new file mode 100644 index 000000000..c5e6365f3 --- /dev/null +++ b/hub/server/domains/learning/propose-learning-update/index.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it, vi } from "vitest" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors" +import { proposeLearningUpdate } from "." + +async function withLock(operation: (signal: AbortSignal) => Promise) { + return await operation(new AbortController().signal) +} + +const request = { id: "request-1", repositoryId: "repository-1", memoryId: "memory-1", revision: 2 } + +describe("proposeLearningUpdate", () => { + it("records the check's result and cost, then drops the flag it saw", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((args: string[]) => + args[0] === "outcomes" + ? Promise.resolve({ outcomes: [] }) + : Promise.resolve({ state: "proposed", usage: { requests: 1, nanoAiu: 500_000_000 } }), + ) + + const result = await proposeLearningUpdate(request, { + activeScreenshotGrant: () => Promise.resolve(null), + closeAbandoned: () => Promise.resolve(), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-27T03:00:00Z"), + prepare: () => Promise.resolve(["--store", "hub"]), + runCommand, + start: () => Promise.resolve({ id: "run-1" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("done") + expect(runCommand.mock.calls.at(-1)).toEqual([ + ["propose-update", "memory-1", "--store", "hub"], + expect.objectContaining({ githubToken: "token" }), + ]) + expect(finish).toHaveBeenCalledWith("run-1", { + state: "SUCCEEDED", + result: "proposed", + aiCredits: "0.5", + copilotRequests: 1, + finishedAt: new Date("2026-12-27T03:00:00Z"), + }) + expect(deleteRequest).toHaveBeenCalledWith(request) + }) + + it("keeps the flag when Copilot is down, after recording what the attempt spent", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + + const result = await proposeLearningUpdate(request, { + activeScreenshotGrant: () => Promise.resolve(null), + closeAbandoned: () => Promise.resolve(), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-27T03:00:00Z"), + prepare: () => Promise.resolve([]), + runCommand: (args) => + args[0] === "outcomes" + ? Promise.resolve({ outcomes: [] }) + : Promise.reject( + new LearningCommandError("unavailable", "Copilot is unavailable.", { + result: { usage: { requests: 1, nanoAiu: 0 } }, + }), + ), + start: () => Promise.resolve({ id: "run-1" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("paused") + expect(finish).toHaveBeenCalledWith( + "run-1", + expect.objectContaining({ state: "FAILED", failureCode: "unavailable", copilotRequests: 1 }), + ) + expect(deleteRequest).not.toHaveBeenCalled() + }) + + it("closes abandoned checks and drops the flag once evaluations are off", async () => { + const closeAbandoned = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn() + + const result = await proposeLearningUpdate(request, { + activeScreenshotGrant: () => Promise.resolve(null), + closeAbandoned, + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish: () => Promise.resolve(), + isEnabled: () => Promise.resolve(false), + now: () => new Date("2026-12-27T03:00:00Z"), + prepare: () => Promise.resolve([]), + runCommand, + start: () => Promise.resolve({ id: "run-1" }), + withinBudget: () => Promise.resolve(true), + withLock, + }) + + expect(result).toBe("done") + expect(closeAbandoned).toHaveBeenCalledWith(new Date("2026-12-27T03:00:00Z")) + expect(runCommand).not.toHaveBeenCalled() + expect(deleteRequest).toHaveBeenCalledWith(request) + }) + it("does not send an issue derived from a withdrawn screenshot to Copilot", async () => { + const runCommand = vi.fn(() => + Promise.resolve({ + outcomes: [ + { + inputs: ["screenshots"], + after: { sha256: `sha256:${"a".repeat(64)}`, consentGrantId: "previous" }, + }, + ], + }), + ) + const credential = vi.fn() + await proposeLearningUpdate(request, { + activeScreenshotGrant: () => Promise.resolve("replacement"), + closeAbandoned: vi.fn(), + credential, + deleteRequest: vi.fn(), + finish: vi.fn(), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + runCommand, + start: vi.fn(), + withinBudget: () => Promise.resolve(true), + withLock, + }) + expect(credential).not.toHaveBeenCalled() + expect(runCommand).toHaveBeenCalledOnce() + }) +}) diff --git a/hub/server/domains/learning/propose-learning-update/index.ts b/hub/server/domains/learning/propose-learning-update/index.ts new file mode 100644 index 000000000..a76120ce9 --- /dev/null +++ b/hub/server/domains/learning/propose-learning-update/index.ts @@ -0,0 +1,142 @@ +import { z } from "zod" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { formatAiCredits } from "../../../utils/format-ai-credits/index.ts" +import { allowsSessionEvaluation } from "../allows-session-evaluation/index.ts" + +const screenshot = z.object({ + sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/), + consentGrantId: z.string().optional(), +}) +const history = z.object({ + outcomes: z.array( + z.object({ + inputs: z.array(z.string()), + before: screenshot.optional(), + after: screenshot.optional(), + }), + ), +}) + +const spentSchema = z + .object({ + usage: z + .object({ + requests: z.number().int().nonnegative(), + nanoAiu: z.number().int().nonnegative(), + }) + .loose(), + }) + .loose() +const proposedSchema = spentSchema.extend({ + state: z.enum(["insufficient_evidence", "up_to_date", "no_change", "proposed"]), +}) + +type Request = { id: string; repositoryId: string; memoryId: string; revision: number } + +/** + * Checks one flagged learning for a suggested update and records what the check cost, + * even when it fails, so spending is never undercounted. Returns "paused" when Copilot or + * the budget is unavailable, so the flag waits for the next day. + */ +export async function proposeLearningUpdate( + request: Request, + dependencies: { + closeAbandoned(finishedAt: Date): Promise + credential(): Promise<{ githubToken?: string } | null> + deleteRequest(request: Request): Promise + finish( + runId: string, + input: { aiCredits: string; copilotRequests: number; finishedAt: Date } & ( + { state: "SUCCEEDED"; result: string } | { state: "FAILED"; failureCode: string } + ), + ): Promise + isEnabled(repositoryId: string): Promise + now(): Date + prepare(repositoryId: string): Promise + runCommand( + arguments_: string[], + options: { githubToken?: string; signal: AbortSignal; timeoutMs?: number }, + ): Promise + start(input: { repositoryId: string; memoryId: string }): Promise<{ id: string }> + withinBudget(): Promise + activeScreenshotGrant(): Promise + withLock(operation: (signal: AbortSignal) => Promise): Promise + }, +): Promise<"done" | "paused"> { + // The ID is passed to the package as an argument, so it must never read as an option. + if (request.memoryId.startsWith("-")) { + await dependencies.deleteRequest(request) + return "done" + } + const outcome = await dependencies.withLock(async (signal) => { + // Runs are only written under this lock, so any still running were abandoned. + await dependencies.closeAbandoned(dependencies.now()) + // Checked under the lock, so turning evaluations off or removing the repository stops + // the check, and a score running at the same time can't overspend the budget. + if (!(await dependencies.isEnabled(request.repositoryId))) return "disabled" + if (!(await dependencies.withinBudget())) return "paused" + const store = await dependencies.prepare(request.repositoryId) + // A drafter sees issues written by the scorer. Do not send text derived from + // screenshots or commit diffs that the repository no longer allows it to see. + const { outcomes } = history.parse( + await dependencies.runCommand(["outcomes", request.memoryId, ...store], { signal }), + ) + const photographed = outcomes.filter((score) => score.inputs.includes("screenshots")) + if (photographed.length) { + const active = await dependencies.activeScreenshotGrant() + if ( + !active || + photographed.some(({ before, after }) => { + const shots = [before, after].filter((shot) => shot !== undefined) + return !shots.length || shots.some((shot) => shot.consentGrantId !== active) + }) + ) + return "disabled" + } + if ( + outcomes.some((score) => score.inputs.includes("build_diff")) && + !allowsSessionEvaluation( + await dependencies.runCommand(["grants", "list", ...store], { signal }), + ) + ) { + return "disabled" + } + const credential = await dependencies.credential() + if (!credential) return "paused" + const run = await dependencies.start(request) + try { + const proposed = proposedSchema.parse( + await dependencies.runCommand(["propose-update", request.memoryId, ...store], { + ...credential, + signal, + timeoutMs: 10 * 60 * 1000, + }), + ) + await dependencies.finish(run.id, { + state: "SUCCEEDED", + result: proposed.state, + aiCredits: formatAiCredits(proposed.usage.nanoAiu), + copilotRequests: proposed.usage.requests, + finishedAt: dependencies.now(), + }) + return "done" + } catch (error) { + if (!(error instanceof LearningCommandError) || error.code === "cancelled") throw error + const spent = spentSchema.safeParse(error.result) + await dependencies.finish(run.id, { + state: "FAILED", + failureCode: error.code.slice(0, 60), + aiCredits: spent.success ? formatAiCredits(spent.data.usage.nanoAiu) : "0", + copilotRequests: spent.success ? spent.data.usage.requests : 0, + finishedAt: dependencies.now(), + }) + // An outage says nothing about the learning, so its flag waits for Copilot. + return error.code === "unavailable" || error.code === "unauthorized" ? "paused" : "done" + } + }) + if (outcome === "paused") return "paused" + // Turning evaluations off means nothing more is suggested, so the flag is dropped too. + await dependencies.deleteRequest(request) + return "done" +} diff --git a/hub/server/domains/learning/read-shareable-learnings/index.test.ts b/hub/server/domains/learning/read-shareable-learnings/index.test.ts new file mode 100644 index 000000000..12d6bc8cc --- /dev/null +++ b/hub/server/domains/learning/read-shareable-learnings/index.test.ts @@ -0,0 +1,37 @@ +import { expect, it, vi } from "vitest" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" +import { findLearningStore } from "../find-learning-store" +import { readShareableLearnings } from "." + +vi.mock("../find-learning-store", () => ({ findLearningStore: vi.fn() })) +vi.mock("../../../integrations/learning/run-learning-command", () => ({ + runLearningCommand: vi.fn(), +})) + +it("returns only accepted wording whose evidence permits publication and instruction", async () => { + vi.mocked(findLearningStore).mockResolvedValue("/private/learning") + const digest = `sha256:${"a".repeat(64)}` + vi.mocked(runLearningCommand).mockImplementation((args) => { + const publication = args[args.indexOf("--purpose") + 1] === "publication" + return Promise.resolve( + ["review-only", "publish-only", "eligible"].map((id) => ({ + withheld: publication && id === "review-only", + status: { recallEligible: id !== "publish-only", problems: [] }, + record: { id, digest, state: "accepted", content: id, evidence: ["Private source"] }, + })), + ) + }) + + const result = await readShareableLearnings({ + cliPath: "/cli", + nodePath: "/node", + root: "/private", + repositoryId: "repo", + repositoryScope: "github.com/repositories/123", + learningIds: ["review-only", "publish-only", "eligible"], + staticDirectories: [], + }) + + expect(result).toEqual([{ id: "eligible", digest, title: null, content: "eligible" }]) +}) diff --git a/hub/server/domains/learning/read-shareable-learnings/index.ts b/hub/server/domains/learning/read-shareable-learnings/index.ts new file mode 100644 index 000000000..556e534fc --- /dev/null +++ b/hub/server/domains/learning/read-shareable-learnings/index.ts @@ -0,0 +1,89 @@ +import { z } from "zod" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { findLearningStore } from "../find-learning-store/index.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" + +const memorySchema = z + .object({ + withheld: z.boolean(), + record: z + .object({ + id: z.string().min(1), + digest: z + .string() + .regex(/^sha256:[0-9a-f]{64}$/) + .optional(), + state: z.string(), + title: z.string().optional(), + content: z.string().optional(), + }) + .loose(), + status: z.object({ recallEligible: z.boolean(), problems: z.array(z.string()) }).loose(), + }) + .loose() + +/** + * Reads the learnings a repository could share: accepted, intact and given to its own + * agents. Only the explicitly shared version may leave its source repository. + */ +export async function readShareableLearnings(input: { + applicationRoot?: string + cliPath: string + learningDatabaseUrl?: string + learningIds: string[] + nodePath: string + repositoryId: string + repositoryScope: string + root: string + staticDirectories: string[] + signal?: AbortSignal + timeoutMs?: number +}) { + if (!input.learningIds.length) return [] + const directory = await findLearningStore(input) + if (!directory) { + return [] + } + const raw = await runLearningCommand( + [ + "memories", + "--purpose", + "publication", + "--state", + "accepted", + ...learningStoreArguments({ + directory, + repositoryId: input.repositoryId, + repositoryScope: input.repositoryScope, + }), + ], + { + cliPath: input.cliPath, + nodePath: input.nodePath, + signal: input.signal, + ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}), + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), + }, + ) + const wanted = new Set(input.learningIds) + return z + .array(memorySchema) + .parse(raw) + .filter( + (item) => + wanted.has(item.record.id) && + item.record.state === "accepted" && + item.record.content !== undefined && + item.record.digest !== undefined && + !item.withheld && + item.status.recallEligible && + item.status.problems.length === 0, + ) + .map(({ record }) => ({ + id: record.id, + digest: record.digest, + title: record.title ?? null, + content: record.content ?? null, + })) +} diff --git a/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts b/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts index b80be962b..5bcb026ba 100644 --- a/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts +++ b/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts @@ -127,4 +127,36 @@ describe("reconcileLearningDecisionOperation()", () => { }), ) }) + it("looks up the exact dismissal receipt in the originally pinned Solo store", async () => { + const finish = vi.fn() + const runCommand = vi.fn().mockResolvedValue({ state: "dismissed" }) + const key = `sha256:${"c".repeat(64)}` + await reconcileLearningDecisionOperation( + { ...operation, decision: "dismiss_update", proposalId: "upd_12345678", soloStoreKey: key }, + { + finish, + runCommand, + prepare: vi.fn().mockResolvedValue({ directory: "/original" }), + withLock: (run) => run(new AbortController().signal), + }, + ) + expect(runCommand).toHaveBeenCalledWith( + [ + "operation-status", + operation.learningId, + "--operation-id", + operation.id, + "--dismissal", + "upd_12345678", + "--dir", + "/original", + "--repository", + operation.repositoryScope, + "--solo-store", + key, + ], + expect.anything(), + ) + expect(finish).toHaveBeenCalledWith(expect.objectContaining({ outcome: "succeeded" })) + }) }) diff --git a/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts b/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts index a4ba55042..11824966f 100644 --- a/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts +++ b/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts @@ -5,7 +5,7 @@ import { learningStoreArguments } from "../learning-store-arguments/index.ts" const resultSchema = z .object({ - state: z.enum(["proposed", "accepted", "rejected", "retired"]).nullable(), + state: z.enum(["proposed", "accepted", "rejected", "retired", "dismissed"]).nullable(), }) .loose() @@ -18,6 +18,7 @@ export async function reconcileLearningDecisionOperation( repositoryId: string repositoryScope: string | null soloStoreKey: string | null + proposalId?: string | null }, dependencies: { finish(input: { @@ -44,31 +45,42 @@ export async function reconcileLearningDecisionOperation( reinstate: "accepted", reject: "rejected", retire: "retired", + apply_update: "accepted", + dismiss_update: "dismissed", }[operation.decision] - if (!expected) throw new Error("The pending learning decision is invalid.") + if ( + !expected || + ((operation.decision === "dismiss_update" || operation.decision === "apply_update") && + !operation.proposalId) + ) + throw new Error("The pending learning decision is invalid.") const { repositoryId, repositoryScope, soloStoreKey } = operation if (!repositoryScope) throw new Error("The original learning decision scope is unknown.") await dependencies.withLock(async (signal) => { let outcome: "succeeded" | "failed" = "failed" let reason = "interrupted_or_failed" const store = await dependencies.prepare({ repositoryId, repositoryScope, soloStoreKey }) - const result = resultSchema.parse( + const args = learningStoreArguments({ + ...store, + repositoryScope, + soloStoreKey: soloStoreKey ?? undefined, + }) + const state = resultSchema.parse( await dependencies.runCommand( [ "operation-status", operation.learningId, "--operation-id", operation.id, - ...learningStoreArguments({ - ...store, - repositoryScope, - soloStoreKey: soloStoreKey ?? undefined, - }), + ...(operation.decision === "dismiss_update" && operation.proposalId + ? ["--dismissal", operation.proposalId] + : []), + ...args, ], { signal }, ), - ) - if (result.state === expected) { + ).state + if (state === expected) { outcome = "succeeded" reason = "" } diff --git a/hub/server/domains/learning/record-finished-learning-run/index.db.test.ts b/hub/server/domains/learning/record-finished-learning-run/index.db.test.ts new file mode 100644 index 000000000..5ed8f091e --- /dev/null +++ b/hub/server/domains/learning/record-finished-learning-run/index.db.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { listLearningActivityDays } from "../../../repositories/learning-activity-days/list-learning-activity-days" +import { failScheduledLearningRunEnqueue } from "../../../repositories/learning-runs/fail-scheduled-learning-run-enqueue" +import { finishLearningRun } from "../../../repositories/learning-runs/finish-learning-run" +import { recordFinishedLearningRun } from "." + +describe("recordFinishedLearningRun()", () => { + it("keeps daily counts after run details expire without counting retries twice", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/activity", defaultBranch: "main" }, + }) + const repositoryId = repository.id + const startedAt = new Date("2026-12-31T23:30:00Z") + const finishedAt = new Date("2027-01-01T00:10:00Z") + const review = await prisma.learningRun.create({ + data: { + repositoryId, + state: "RUNNING", + startedAt, + commentsConsidered: 5, + commentsLabeled: 3, + }, + }) + await recordFinishedLearningRun(prisma, review.id, (transaction) => + finishLearningRun(transaction, review.id, { + state: "SUCCEEDED", + reviewCommentsImported: true, + suggestions: 1, + suggestionsRemaining: 0, + finishedAt, + }), + ) + const notes = await prisma.learningRun.create({ + data: { repositoryId, state: "RUNNING", reviewCommentsDue: false, startedAt }, + }) + function finishNotes() { + return recordFinishedLearningRun(prisma, notes.id, async (transaction) => { + await transaction.$executeRaw`SET LOCAL TIME ZONE 'Asia/Tokyo'` + return finishLearningRun(transaction, notes.id, { + state: "SUCCEEDED", + reviewCommentsImported: false, + suggestions: 2, + suggestionsRemaining: 0, + finishedAt, + }) + }) + } + await Promise.all([finishNotes(), finishNotes()]) + const queued = await prisma.learningRun.create({ + data: { repositoryId, scheduled: true, createdAt: startedAt }, + }) + await recordFinishedLearningRun(prisma, queued.id, (transaction) => + failScheduledLearningRunEnqueue(transaction, queued.id, finishedAt), + ) + await prisma.learningRun.deleteMany({ where: { repositoryId } }) + + await expect( + prisma.$transaction(async (transaction) => { + await transaction.$executeRaw`SET LOCAL TIME ZONE 'America/Los_Angeles'` + return listLearningActivityDays( + transaction, + repositoryId, + new Date("2026-01-01"), + new Date("2026-12-31"), + ) + }), + ).resolves.toEqual([ + { date: "2026-12-31", runs: 3, commentsAnalyzed: 5, commentsTagged: 3, suggestions: 3 }, + ]) + await expect( + listLearningActivityDays( + prisma, + repositoryId, + new Date("2027-01-01"), + new Date("2027-12-31"), + ), + ).resolves.toEqual([]) + }) +}) diff --git a/hub/server/domains/learning/record-finished-learning-run/index.ts b/hub/server/domains/learning/record-finished-learning-run/index.ts new file mode 100644 index 000000000..273ece3f1 --- /dev/null +++ b/hub/server/domains/learning/record-finished-learning-run/index.ts @@ -0,0 +1,15 @@ +import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts" +import { recordLearningActivityDay } from "../../../repositories/learning-activity-days/record-learning-activity-day/index.ts" + +/** Keep the daily totals and the one-time transition to a finished state together. */ +export function recordFinishedLearningRun( + prisma: PrismaClient, + runId: string, + finish: (transaction: Prisma.TransactionClient) => Promise<{ count: number }>, +) { + return prisma.$transaction(async (transaction) => { + const result = await finish(transaction) + if (result.count === 1) await recordLearningActivityDay(transaction, runId) + return result + }) +} diff --git a/hub/server/domains/learning/record-reviewer-verification/index.db.test.ts b/hub/server/domains/learning/record-reviewer-verification/index.db.test.ts new file mode 100644 index 000000000..1e61e6c4b --- /dev/null +++ b/hub/server/domains/learning/record-reviewer-verification/index.db.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { recordReviewerVerification } from "." + +describe("recordReviewerVerification", () => { + it("asks to score the Build that started last when the reviewer resolves their own thread", async () => { + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 31n, nameWithOwner: "octo/verified" }, + }) + const prototype = await prisma.prototype.create({ + data: { repositoryId: repository.id, branchName: "checkout" }, + }) + // Hub found Build 3's run late, so it started before Build 2. + const builds = [] + for (const [number, day] of [ + [1, 1], + [2, 3], + [3, 2], + ] as const) { + builds.push( + await prisma.build.create({ + data: { + prototypeId: prototype.id, + number, + state: "successful", + commitSha: String(number).repeat(40), + workflowCreatedAt: new Date(`2026-12-0${day}T00:00:00Z`), + }, + }), + ) + } + const reviewer = await prisma.user.create({ data: {} }) + const thread = await prisma.reviewThread.create({ + data: { + repositoryId: repository.id, + prototypeId: prototype.id, + buildId: builds[0]!.id, + anchor: { kind: "area", route: { pathname: "/" } }, + comments: { + create: { authorId: reviewer.id, authorLogin: "reviewer", body: "Label the field." }, + }, + }, + }) + const verifiedAt = new Date("2026-12-04T00:00:00Z") + + await recordReviewerVerification(prisma, { + threadId: thread.id, + resolverId: reviewer.id, + verifiedAt, + }) + expect( + await prisma.learningReviewerVerification.count({ where: { repositoryId: repository.id } }), + ).toBe(0) + await prisma.repositoryEvaluationSetting.create({ + data: { repositoryId: repository.id, enabled: true, evaluationGrantId: "evaluation" }, + }) + await recordReviewerVerification(prisma, { + threadId: thread.id, + resolverId: reviewer.id, + verifiedAt, + }) + expect( + await prisma.learningReviewerVerification.count({ where: { repositoryId: repository.id } }), + ).toBe(0) + await prisma.repositoryLearningSetting.create({ + data: { repositoryId: repository.id, reviewCommentGrantId: "review" }, + }) + await recordReviewerVerification(prisma, { + threadId: thread.id, + resolverId: reviewer.id, + verifiedAt, + }) + + expect( + await prisma.learningReviewerVerification.findMany({ + where: { repositoryId: repository.id }, + select: { prototypeId: true, commitSha: true, verifiedAt: true }, + }), + ).toEqual([{ prototypeId: prototype.id, commitSha: "2".repeat(40), verifiedAt }]) + expect( + await prisma.learningScoreRequest.findMany({ + where: { repositoryId: repository.id }, + select: { commitSha: true }, + }), + ).toEqual([{ commitSha: "2".repeat(40) }]) + }) + + it("ignores someone else resolving the thread and threads with no later Build", async () => { + const repository = await prisma.repository.create({ + data: { + defaultBranch: "main", + githubRepositoryId: 32n, + nameWithOwner: "octo/unverified", + evaluationSetting: { create: { enabled: true, evaluationGrantId: "eval" } }, + learningSetting: { create: { reviewCommentGrantId: "review" } }, + }, + }) + const prototype = await prisma.prototype.create({ + data: { repositoryId: repository.id, branchName: "checkout" }, + }) + const first = await prisma.build.create({ + data: { + prototypeId: prototype.id, + number: 1, + state: "successful", + commitSha: "1".repeat(40), + }, + }) + const latest = await prisma.build.create({ + data: { + prototypeId: prototype.id, + number: 2, + state: "successful", + commitSha: "2".repeat(40), + }, + }) + const reviewer = await prisma.user.create({ data: {} }) + const someoneElse = await prisma.user.create({ data: {} }) + async function createThread(buildId: string) { + return prisma.reviewThread.create({ + data: { + repositoryId: repository.id, + prototypeId: prototype.id, + buildId, + anchor: { kind: "area", route: { pathname: "/" } }, + comments: { + create: { authorId: reviewer.id, authorLogin: "reviewer", body: "Label the field." }, + }, + }, + }) + } + const resolvedByOthers = await createThread(first.id) + const onNewestBuild = await createThread(latest.id) + + await recordReviewerVerification(prisma, { + threadId: resolvedByOthers.id, + resolverId: someoneElse.id, + verifiedAt: new Date(), + }) + await recordReviewerVerification(prisma, { + threadId: onNewestBuild.id, + resolverId: reviewer.id, + verifiedAt: new Date(), + }) + + expect( + await prisma.learningReviewerVerification.count({ where: { repositoryId: repository.id } }), + ).toBe(0) + expect( + await prisma.learningScoreRequest.count({ where: { repositoryId: repository.id } }), + ).toBe(0) + }) +}) diff --git a/hub/server/domains/learning/record-reviewer-verification/index.ts b/hub/server/domains/learning/record-reviewer-verification/index.ts new file mode 100644 index 000000000..10099596a --- /dev/null +++ b/hub/server/domains/learning/record-reviewer-verification/index.ts @@ -0,0 +1,53 @@ +import { getReviewCommentConsent } from "../../../repositories/learning-settings/get-review-comment-consent/index.ts" +import { getRepositoryEvaluationSetting } from "../../../repositories/evaluation-settings/get-repository-evaluation-setting/index.ts" +import type { Prisma } from "../../../generated/prisma/client.ts" +import { saveLearningReviewerVerification } from "../../../repositories/learning-reviewer-verifications/save-learning-reviewer-verification/index.ts" +import { recordLearningScoreRequest } from "../../../repositories/learning-score-requests/record-learning-score-request/index.ts" +import { findNewestSuccessfulBuildAfter } from "../../../repositories/prototypes/find-newest-successful-build-after/index.ts" +import { findReviewThreadFeedback } from "../../../repositories/review-comments/find-review-thread-feedback/index.ts" + +/** + * Asks for a fresh score when the person who gave review feedback resolves their own + * thread. That is the clearest sign the change after their feedback worked. The newest + * successful Build after the feedback Build stands in for the change. When there's no + * later Build, nothing changed, so there's nothing to verify. + */ +export async function recordReviewerVerification( + transaction: Pick< + Prisma.TransactionClient, + | "copilotConnection" + | "repositoryLearningSetting" + | "repositoryEvaluationSetting" + | "build" + | "learningReviewerVerification" + | "learningScoreRequest" + | "reviewThread" + >, + input: { threadId: string; resolverId: string; verifiedAt: Date; deploymentConsent?: boolean }, +) { + const thread = await findReviewThreadFeedback(transaction, input.threadId) + if (!thread || thread.authorId !== input.resolverId) return + const evaluation = await getRepositoryEvaluationSetting(transaction, thread.repositoryId) + if (!evaluation?.enabled || !evaluation.evaluationGrantId) return + const consent = await getReviewCommentConsent( + transaction, + thread.repositoryId, + input.deploymentConsent ?? false, + ) + if (consent.turnedOff || (!consent.hubAdministrator && !consent.repositoryGrantId)) return + const later = await findNewestSuccessfulBuildAfter(transaction, { + prototypeId: thread.prototypeId, + after: thread.buildStartedAt, + }) + if (!later) return + await saveLearningReviewerVerification(transaction, { + repositoryId: thread.repositoryId, + prototypeId: thread.prototypeId, + commitSha: later.commitSha, + verifiedAt: input.verifiedAt, + }) + await recordLearningScoreRequest(transaction, { + repositoryId: thread.repositoryId, + commitSha: later.commitSha, + }) +} diff --git a/hub/server/domains/learning/resolve-learning-references/index.ts b/hub/server/domains/learning/resolve-learning-references/index.ts index cb730874e..2597924a1 100644 --- a/hub/server/domains/learning/resolve-learning-references/index.ts +++ b/hub/server/domains/learning/resolve-learning-references/index.ts @@ -14,6 +14,7 @@ export const referenceSchema = z source: z .object({ kind: z.string().optional(), + sessionId: z.string().min(1).optional(), hubOrigin: z.string().optional(), repositoryId: z.string().optional(), prototypeId: z.string().optional(), @@ -52,7 +53,15 @@ export async function resolveLearningReferences( commandOptions: { cliPath: string; nodePath: string; learningDatabaseUrl?: string } }, ) { - const eventIds = [...new Set(references.flatMap((reference) => reference.eventIds))] + // Session references carry their provenance already. Never read private chat + // payloads just to count the sessions named by a learning. + const eventIds = [ + ...new Set( + references.flatMap((reference) => + reference.source.kind === "agent_session" ? [] : reference.eventIds, + ), + ), + ] if (!input.evidenceSource || eventIds.length === 0) return references.map(() => []) const events: LearningObservationEvent[] = [] for (let offset = 0; offset < eventIds.length; offset += eventBatchSize) { diff --git a/hub/server/domains/learning/review-comment-learning-source/types.ts b/hub/server/domains/learning/review-comment-learning-source/types.ts index 3cd6e6824..95527c4e4 100644 --- a/hub/server/domains/learning/review-comment-learning-source/types.ts +++ b/hub/server/domains/learning/review-comment-learning-source/types.ts @@ -5,6 +5,7 @@ export interface LearningEvidenceReference { eventIds: string[] source: { kind?: string + sessionId?: string hubOrigin?: string repositoryId?: string prototypeId?: string diff --git a/hub/server/domains/learning/score-applied-learnings/index.test.ts b/hub/server/domains/learning/score-applied-learnings/index.test.ts new file mode 100644 index 000000000..44dae2c9d --- /dev/null +++ b/hub/server/domains/learning/score-applied-learnings/index.test.ts @@ -0,0 +1,364 @@ +import { readdir, readFile } from "node:fs/promises" +import { describe, expect, it, vi } from "vitest" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors" +import { scoreAppliedLearnings } from "." + +async function withLock(operation: (signal: AbortSignal) => Promise) { + return await operation(new AbortController().signal) +} + +describe("scoreAppliedLearnings()", () => { + it("scores with the commit's diff and the consented screenshots", async () => { + const digest = "c".repeat(64) + const finish = vi.fn(() => Promise.resolve()) + const readScreenshot = vi.fn(() => Promise.resolve(new Uint8Array([1, 2, 3]))) + let evidence: { diff: string; screenshots: string[] } | undefined + const runCommand = vi.fn(async (arguments_: string[]) => { + if (arguments_[0] === "grants") + return [{ grant: { sources: ["agent_session"] }, activePurposes: ["evaluation"] }] + if (arguments_[0] === "usage") { + return { + reports: [ + { + used: [ + { + id: "learning-1", + memoryId: "memory-1", + before: { sha256: `sha256:${"a".repeat(64)}` }, + after: { sha256: `sha256:${digest}`, consentGrantId: "active" }, + }, + ], + }, + ], + } + } + const diffFile = arguments_[arguments_.indexOf("--diff-file") + 1]! + const screenshots = arguments_[arguments_.indexOf("--screenshots") + 1]! + evidence = { + diff: await readFile(diffFile, "utf8"), + screenshots: await readdir(screenshots), + } + return { + score: { id: "score-1", memoryId: "memory-1" }, + usage: { requests: 1, nanoAiu: 2_000_000_000 }, + } + }) + + const result = await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest: () => Promise.resolve(), + finish, + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-25T09:00:00Z"), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve("diff --git a/app.tsx b/app.tsx"), + readScreenshot, + refuseCredential: () => Promise.resolve(), + requestUpdate: () => Promise.resolve(), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + verifications: () => Promise.resolve([]), + withLock, + }) + + expect(result).toBe("done") + expect(readScreenshot).toHaveBeenCalledExactlyOnceWith(digest, "active") + expect(evidence).toEqual({ + diff: "diff --git a/app.tsx b/app.tsx", + screenshots: [`${digest}.png`], + }) + expect(finish).toHaveBeenCalledWith("run-1", { + state: "SUCCEEDED", + scoreId: "score-1", + aiCredits: "2", + copilotRequests: 1, + finishedAt: new Date("2026-12-25T09:00:00Z"), + }) + }) + + it("pauses and records the refusal when Copilot rejects the credential", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const refuseCredential = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants") return Promise.resolve([]) + if (arguments_[0] === "usage") { + return Promise.resolve({ + reports: [ + { + used: [ + { id: "learning-1", memoryId: "memory-1" }, + { id: "learning-2", memoryId: "memory-2" }, + ], + }, + ], + }) + } + return Promise.reject(new LearningCommandError("unauthorized", "Copilot said no.")) + }) + + const result = await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + refuseCredential, + requestUpdate: () => Promise.resolve(), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + verifications: () => Promise.resolve([]), + withLock, + }) + + expect(result).toBe("paused") + expect(refuseCredential).toHaveBeenCalledOnce() + expect(runCommand).toHaveBeenCalledTimes(3) + expect(finish).not.toHaveBeenCalled() + expect(deleteRequest).not.toHaveBeenCalled() + }) + + it("records what a failed score spent and finishes the request", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants") return Promise.resolve([]) + if (arguments_[0] === "usage") { + return Promise.resolve({ + reports: [{ used: [{ id: "learning-1", memoryId: "memory-learning-1" }] }], + }) + } + return Promise.reject( + new LearningCommandError("unavailable", "Copilot returned an incomplete answer.", { + result: { usage: { requests: 2, nanoAiu: 1_500_000_000 } }, + }), + ) + }) + + const result = await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date("2026-12-25T09:00:00Z"), + prepare: () => Promise.resolve(["--store", "hub"]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + refuseCredential: () => Promise.resolve(), + requestUpdate: () => Promise.resolve(), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + verifications: () => Promise.resolve([]), + withLock, + }) + + expect(result).toBe("done") + expect(runCommand).toHaveBeenCalledWith( + ["score", "learning-1", "--operation-id", "op-1", "--store", "hub"], + expect.objectContaining({ githubToken: "token" }), + ) + expect(finish).toHaveBeenCalledWith("run-1", { + state: "FAILED", + failureCode: "unavailable", + aiCredits: "1.5", + copilotRequests: 2, + finishedAt: new Date("2026-12-25T09:00:00Z"), + }) + expect(deleteRequest).toHaveBeenCalledOnce() + }) + + it("pauses without scoring once the monthly budget is spent", async () => { + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn(() => Promise.resolve({})) + + const result = await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish: () => Promise.resolve(), + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + refuseCredential: () => Promise.resolve(), + requestUpdate: () => Promise.resolve(), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(false), + verifications: () => Promise.resolve([]), + withLock, + }) + + expect(result).toBe("paused") + expect(runCommand).not.toHaveBeenCalled() + expect(deleteRequest).not.toHaveBeenCalled() + }) + + it("leaves an interrupted score running so the next pass retries it", async () => { + const finish = vi.fn(() => Promise.resolve()) + const deleteRequest = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants") return Promise.resolve([]) + if (arguments_[0] === "usage") { + return Promise.resolve({ + reports: [{ used: [{ id: "learning-1", memoryId: "memory-learning-1" }] }], + }) + } + return Promise.reject(new LearningCommandError("cancelled", "The worker stopped.")) + }) + + await expect( + scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest, + finish, + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + refuseCredential: () => Promise.resolve(), + requestUpdate: () => Promise.resolve(), + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + verifications: () => Promise.resolve([]), + withLock, + }), + ).rejects.toMatchObject({ code: "cancelled" }) + expect(finish).not.toHaveBeenCalled() + expect(deleteRequest).not.toHaveBeenCalled() + }) + + it("scores a learning once more only with its own prototype's verification", async () => { + const requestUpdate = vi.fn(() => Promise.resolve()) + const start = vi.fn((usedLearningId: string, trigger: string) => + Promise.resolve({ id: `run-${trigger}`, operationId: `op-${trigger}`, state: "RUNNING" }), + ) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants") return Promise.resolve([]) + if (arguments_[0] === "usage") { + return Promise.resolve({ + reports: [ + { + prototypeId: "prototype-2", + used: [{ id: "learning-1", memoryId: "memory-learning-1" }], + }, + { + prototypeId: "prototype-1", + used: [{ id: "learning-2", memoryId: "memory-learning-2" }], + }, + ], + }) + } + return Promise.resolve({ + score: { id: "score-1", memoryId: `memory-${arguments_[1]}` }, + usage: { requests: 1, nanoAiu: 0 }, + }) + }) + + await scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest: () => Promise.resolve(), + finish: () => Promise.resolve(), + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + refuseCredential: () => Promise.resolve(), + requestUpdate, + runCommand, + start, + withinBudget: () => Promise.resolve(true), + verifications: () => + Promise.resolve([ + { prototypeId: "prototype-1", verifiedAt: new Date("2026-12-03T10:00:00.250Z") }, + ]), + withLock, + }) + + expect(start.mock.calls).toEqual([ + ["learning-1", "USAGE"], + ["learning-2", "USAGE"], + ["learning-2", "REVIEWER_VERIFICATION"], + ]) + expect(runCommand).toHaveBeenLastCalledWith( + [ + "score", + "learning-2", + "--operation-id", + "op-REVIEWER_VERIFICATION", + "--reviewer-verified-at", + "2026-12-03T10:00:00.250Z", + ], + expect.anything(), + ) + // Each new score asks the daily job to check its learning's wording. + expect(requestUpdate.mock.calls).toEqual([ + ["memory-learning-1"], + ["memory-learning-2"], + ["memory-learning-2"], + ]) + }) + + it("keeps the run open when the score names a different learning than the one used", async () => { + const finish = vi.fn(() => Promise.resolve()) + const requestUpdate = vi.fn(() => Promise.resolve()) + const runCommand = vi.fn((arguments_: string[]) => { + if (arguments_[0] === "grants") return Promise.resolve([]) + if (arguments_[0] === "usage") { + return Promise.resolve({ + reports: [{ used: [{ id: "learning-1", memoryId: "memory-learning-1" }] }], + }) + } + return Promise.resolve({ + score: { id: "score-1", memoryId: "memory-other" }, + usage: { requests: 1, nanoAiu: 0 }, + }) + }) + + await expect( + scoreAppliedLearnings({ + commitSha: "a".repeat(40), + credential: () => Promise.resolve({ githubToken: "token" }), + deleteRequest: () => Promise.resolve(), + finish, + hasPendingUserRun: () => Promise.resolve(false), + isEnabled: () => Promise.resolve(true), + now: () => new Date(), + prepare: () => Promise.resolve([]), + readDiff: () => Promise.resolve(null), + readScreenshot: () => Promise.resolve(null), + refuseCredential: () => Promise.resolve(), + requestUpdate, + runCommand, + start: () => Promise.resolve({ id: "run-1", operationId: "op-1", state: "RUNNING" }), + withinBudget: () => Promise.resolve(true), + verifications: () => Promise.resolve([]), + withLock, + }), + ).rejects.toThrow("different learning") + expect(requestUpdate).not.toHaveBeenCalled() + expect(finish).not.toHaveBeenCalled() + }) +}) diff --git a/hub/server/domains/learning/score-applied-learnings/index.ts b/hub/server/domains/learning/score-applied-learnings/index.ts new file mode 100644 index 000000000..3373a1f15 --- /dev/null +++ b/hub/server/domains/learning/score-applied-learnings/index.ts @@ -0,0 +1,232 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { resolve } from "node:path" +import { z } from "zod" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { formatAiCredits } from "../../../utils/format-ai-credits/index.ts" +import { allowsSessionEvaluation } from "../allows-session-evaluation/index.ts" + +const screenshotSchema = z + .object({ + consentGrantId: z.string().optional(), + sha256: z.string().regex(/^sha256:[0-9a-f]{64}$/), + }) + .loose() +const usageSchema = z + .object({ + reports: z.array( + z + .object({ + prototypeId: z.string().optional(), + used: z.array( + z + .object({ + // The ID is passed to the package as an argument, so it must never + // read as an option. + id: z + .string() + .min(1) + .max(255) + .refine((id) => !id.startsWith("-")), + memoryId: z.string().min(1).max(255), + before: screenshotSchema.optional(), + after: screenshotSchema.optional(), + }) + .loose(), + ), + }) + .loose(), + ), + }) + .loose() +const spentSchema = z + .object({ + usage: z + .object({ + requests: z.number().int().nonnegative(), + nanoAiu: z.number().int().nonnegative(), + }) + .loose(), + }) + .loose() +const refusedCodes = ["unauthorized", "installation_revoked", "permission_denied"] +const scoredSchema = spentSchema.extend({ + score: z.object({ id: z.string().min(1).max(255), memoryId: z.string().min(1).max(255) }).loose(), +}) + +/** + * Scores each learning agents said they applied in one built commit, one Copilot call at a + * time, while the shared monthly budget lasts. Each attempt is recorded with what it cost, + * even when it fails, so spending is never undercounted. Returns "paused" when Copilot or + * the budget is unavailable, so the request is kept and tried again later, and "deferred" + * when a person is waiting on a learning run, which goes first. When a reviewer verified + * the commit, each learning is scored once more with that verification, and the first + * score is kept. A report that names a prototype gets only that prototype's verification, + * since two prototypes can share a commit. Each new score flags its learning so the daily + * job checks whether its wording should change. + */ +export async function scoreAppliedLearnings(dependencies: { + commitSha: string + credential(): Promise<{ githubToken?: string } | null> + deleteRequest(): Promise + finish( + runId: string, + input: { aiCredits: string; copilotRequests: number; finishedAt: Date } & ( + { state: "SUCCEEDED"; scoreId: string } | { state: "FAILED"; failureCode: string } + ), + ): Promise + hasPendingUserRun(): Promise + isEnabled(): Promise + now(): Date + prepare(): Promise + readDiff(): Promise + readScreenshot(sha256: string, grantId: string): Promise + refuseCredential(): Promise + requestUpdate(memoryId: string): Promise + runCommand( + arguments_: string[], + options: { githubToken?: string; signal: AbortSignal; timeoutMs?: number }, + ): Promise + start( + usedLearningId: string, + trigger: "USAGE" | "REVIEWER_VERIFICATION", + ): Promise<{ id: string; operationId: string; state: string }> + verifications(): Promise<{ prototypeId: string; verifiedAt: Date }[]> + withinBudget(): Promise + withLock(operation: (signal: AbortSignal) => Promise): Promise +}): Promise<"done" | "deferred" | "paused"> { + // Turning evaluations off means nothing more is scored, so the request is dropped. + if (!(await dependencies.isEnabled())) { + await dependencies.deleteRequest() + return "done" + } + if (!(await dependencies.withinBudget())) return "paused" + const store = await dependencies.prepare() + const verifications = await dependencies.verifications() + const { reports } = usageSchema.parse( + await dependencies.withLock((signal) => + dependencies.runCommand(["usage", "--commit", dependencies.commitSha, ...store], { + signal, + }), + ), + ) + const temporary = await mkdtemp(resolve(tmpdir(), "replica-learning-score-")) + try { + let diffFile: string | null | undefined + const attempts = reports.flatMap((report) => { + const verified = verifications.findLast( + (verification) => + report.prototypeId === undefined || verification.prototypeId === report.prototypeId, + ) + return report.used.flatMap((used) => [ + { used, trigger: "USAGE" as const, verified: undefined }, + ...(verified ? [{ used, trigger: "REVIEWER_VERIFICATION" as const, verified }] : []), + ]) + }) + for (const [index, { used, trigger, verified }] of attempts.entries()) { + const outcome = await dependencies.withLock(async (signal) => { + // Checked under the lock before each paid call, so turning evaluations off or + // removing the repository stops scoring, and two jobs or an update check can't + // both spend the last of the budget. + if (await dependencies.hasPendingUserRun()) return "deferred" + if (!(await dependencies.isEnabled())) return "disabled" + if (!(await dependencies.withinBudget())) return "paused" + // A reviewer can withdraw source consent while earlier uses are being scored. + const verifiedAt = verified + ? (await dependencies.verifications()).find((v) => v.prototypeId === verified.prototypeId) + ?.verifiedAt + : undefined + if (verified && !verifiedAt) return "skipped" + const run = await dependencies.start(used.id, trigger) + if (run.state !== "RUNNING") return "skipped" + + // A repository evaluation grant does not authorize sending session code. The + // package rechecks this same consent at send time, even if it changes here. + const canSendDiff = allowsSessionEvaluation( + await dependencies.runCommand(["grants", "list", ...store], { signal }), + ) + if (canSendDiff && diffFile === undefined) { + const diff = await dependencies.readDiff() + diffFile = diff === null ? null : resolve(temporary, "commit.diff") + if (diffFile) await writeFile(diffFile, diff!, { mode: 0o600 }) + } + // A hosted store keeps no screenshot bytes, so Hub hands over the ones whose + // consent still holds as files named by their digest. + const screenshots = resolve(temporary, `screenshots-${index}`) + let hasScreenshots = false + for (const shot of [used.before, used.after]) { + if (!shot?.consentGrantId) continue + // Hub stores the digest without its "sha256:" label. + const digest = shot.sha256.slice(7) + const bytes = await dependencies.readScreenshot(digest, shot.consentGrantId) + if (!bytes) continue + await mkdir(screenshots, { recursive: true, mode: 0o700 }) + await writeFile(resolve(screenshots, `${digest}.png`), bytes, { mode: 0o600 }) + hasScreenshots = true + } + try { + // Installation tokens expire within an hour, so each score asks for a fresh one. + const credential = await dependencies.credential() + if (!credential) return "paused" + const scored = scoredSchema.parse( + await dependencies.runCommand( + [ + "score", + used.id, + "--operation-id", + run.operationId, + ...(canSendDiff && diffFile ? ["--diff-file", diffFile] : []), + ...(hasScreenshots ? ["--screenshots", screenshots] : []), + // The package wants microsecond timestamps. + ...(verifiedAt ? ["--reviewer-verified-at", verifiedAt.toISOString()] : []), + ...store, + ], + { ...credential, signal, timeoutMs: 10 * 60 * 1000 }, + ), + ) + // The score must be for the learning that was used, so a wrong ID can't send + // another learning's text to Copilot. Failing leaves the run to be retried. + if (scored.score.memoryId !== used.memoryId) + throw new Error("The score names a different learning than the one used.") + // Flagged before the run closes, since a closed run is never scored again. + await dependencies.requestUpdate(used.memoryId) + await dependencies.finish(run.id, { + state: "SUCCEEDED", + scoreId: scored.score.id, + aiCredits: formatAiCredits(scored.usage.nanoAiu), + copilotRequests: scored.usage.requests, + finishedAt: dependencies.now(), + }) + return "scored" + } catch (error) { + // An interrupted score stays running, so the next pass retries it with the same + // operation ID and the store doesn't charge twice for a score it already saved. + if (!(error instanceof LearningCommandError) || error.code === "cancelled") throw error + // Copilot being down or refusing the credential says nothing about the learning, + // so the score stays running and the rest of the commit waits for Copilot. + const spent = spentSchema.safeParse(error.result) + const paid = + spent.success && (spent.data.usage.requests > 0 || spent.data.usage.nanoAiu > 0) + const refused = refusedCodes.includes(error.code) + if (refused) await dependencies.refuseCredential() + if (!paid && (refused || error.code === "unavailable")) return "paused" + await dependencies.finish(run.id, { + state: "FAILED", + failureCode: error.code.slice(0, 60), + aiCredits: spent.success ? formatAiCredits(spent.data.usage.nanoAiu) : "0", + copilotRequests: spent.success ? spent.data.usage.requests : 0, + finishedAt: dependencies.now(), + }) + return "scored" + } + }) + if (outcome === "deferred" || outcome === "paused") return outcome + if (outcome === "disabled") break + } + } finally { + await rm(temporary, { recursive: true, force: true }) + } + await dependencies.deleteRequest() + return "done" +} diff --git a/hub/server/domains/learning/summarize-learning-evidence/index.ts b/hub/server/domains/learning/summarize-learning-evidence/index.ts new file mode 100644 index 000000000..320164cbf --- /dev/null +++ b/hub/server/domains/learning/summarize-learning-evidence/index.ts @@ -0,0 +1,20 @@ +import type { LearningEvidenceReference } from "../review-comment-learning-source/types.ts" +import type { LearningEvidence } from "../types.ts" + +/** Counts distinct sessions without exposing session IDs or treating each note as a chat. */ +export function summarizeLearningEvidence( + references: LearningEvidenceReference[], + resolved: LearningEvidence[][], + solo: boolean, +) { + const sessions = new Set() + let unavailable = 0 + for (const [index, reference] of references.entries()) { + if (solo && reference.source.kind === "agent_session" && reference.source.sessionId) { + sessions.add(reference.source.sessionId) + } else if (!resolved[index]?.length) { + unavailable++ + } + } + return { sessions: sessions.size, unavailable } +} diff --git a/hub/server/domains/learning/types.ts b/hub/server/domains/learning/types.ts index f6bb39b1c..ba04bdb15 100644 --- a/hub/server/domains/learning/types.ts +++ b/hub/server/domains/learning/types.ts @@ -10,6 +10,7 @@ export interface LearningEvidence { } export interface LearningSuggestion { + sessions?: { supporting: number; opposing: number } id: string title: string | null content: string @@ -63,6 +64,61 @@ export type LearningDecision = | { decision: "retire"; reason: string } | { decision: "edit"; digest: string; title?: string; content?: string; reason: string } | { decision: "reinstate"; digest: string; reason: string } + | { + decision: "apply_update" + proposalId: string + title?: string + content?: string + reason: string + } + | { decision: "dismiss_update"; proposalId: string; reason: string } + +/** How one use of a learning was scored, with the Build it judged. */ +export type LearningOutcome = Omit< + ReportedLearningOutcome, + "commitSha" | "prototypeId" | "before" | "after" +> & { + build: { prototypeId: string; prototypeName: string; number: number } + before?: { sha256: string; route: string } + after?: { sha256: string; route: string } +} + +/** How one use of a learning was scored, as the package recorded it. */ +export interface ReportedLearningOutcome { + id: string + /** Whether a reviewer confirmed the work before it was scored. */ + source: "automated" | "reviewer_confirmed" + commitSha: string + prototypeId: string | null + /** 4 is best. 1 and 2 come with an issue. */ + efficiency: number + followed: "followed" | "not_followed" | "unclear" + reasoning: string + issue: string | null + scoredAt: string + before?: ReportedScreenshot + after?: ReportedScreenshot +} + +/** Suggested new wording for an accepted learning, waiting for an administrator. */ +export interface LearningUpdateSuggestion { + id: string + issue: string + title: string | null + content: string + reasoning: string + /** Where the issue showed: the scores as reported, or the Builds people can open. */ + support: Support[] +} + +/** Wording agents were given before the current version, with how it was scored. */ +export interface EarlierLearningGuidance { + version: number + title: string | null + content: string + outcomes: Outcome[] +} + export interface LearningActivityDay { date: string runState: "succeeded" | "failed" @@ -72,3 +128,20 @@ export interface LearningActivityDay { commentsTagged: number suggestions: number } + +/** 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 +} + +export type ReportedScreenshot = { sha256: string; route: string; consentGrantId?: string } diff --git a/hub/server/domains/review-comments/create-review-comment-service/index.ts b/hub/server/domains/review-comments/create-review-comment-service/index.ts index 13e55eb29..7bfa7de21 100644 --- a/hub/server/domains/review-comments/create-review-comment-service/index.ts +++ b/hub/server/domains/review-comments/create-review-comment-service/index.ts @@ -3,6 +3,7 @@ import { recordReviewAnalyticsActivity } from "../../analytics/record-event/inde import { classifyPrismaTransactionError } from "../../../integrations/prisma/classify-transaction-error/index.ts" import { createReviewCommentRepository } from "../../../repositories/review-comments/create-review-comment-repository/index.ts" import type { ReviewPersistenceFailure } from "../../../repositories/review-comments/types.ts" +import { recordReviewerVerification } from "../../learning/record-reviewer-verification/index.ts" import { runWithBoundedRetries } from "../../identity/run-with-bounded-retries/index.ts" import { applyReviewActivity } from "../apply-review-activity/index.ts" import { reviewMentionLogins } from "../create-review-mention-directory/index.ts" @@ -69,6 +70,7 @@ export function createReviewCommentService( repositoryId: string, ) => Promise = () => Promise.resolve(true), options: { + deploymentReviewConsent?: boolean onDeleted?: (input: { repositoryId: string commentId: number @@ -101,6 +103,14 @@ export function createReviewCommentService( threadId, }) } + if (kind === "resolved") { + await recordReviewerVerification(transaction, { + deploymentConsent: options.deploymentReviewConsent, + threadId, + resolverId: input.actor.userId, + verifiedAt: new Date(), + }) + } }, } } diff --git a/hub/server/index.ts b/hub/server/index.ts index a982d4c46..00a369855 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -206,7 +206,10 @@ try { authenticationEnvironment, authentication.currentSession, logger, - { scopeGitHubMembers: authenticationConfiguration.githubConfigured }, + { + scopeGitHubMembers: authenticationConfiguration.githubConfigured, + ...(storage ? { artifactStorage: storage } : {}), + }, ) learnings = learningDependencies const agentApplicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN @@ -215,6 +218,7 @@ try { applicationOrigin: agentApplicationOrigin, databaseUrl, learning: learningConfiguration, + ...(storage ? { artifactStorage: storage } : {}), } } if (decisionRuntimeConfiguration) { @@ -286,6 +290,7 @@ try { githubReviewDirectory: repositoryCredentials ? createReviewDirectory(repositoryCredentials) : undefined, + deploymentReviewConsent: learningConfiguration?.reviewCommentConsent, onReviewCommentDeleted: (input) => learningDependencies.redactComment(input), previewBaseOrigin: previewConfigured ? authenticationEnvironment.HUB_PREVIEW_ORIGIN diff --git a/hub/server/integrations/github/create-github-actions-client/index.test.ts b/hub/server/integrations/github/create-github-actions-client/index.test.ts index 41e97a50c..89bcf467b 100644 --- a/hub/server/integrations/github/create-github-actions-client/index.test.ts +++ b/hub/server/integrations/github/create-github-actions-client/index.test.ts @@ -586,6 +586,24 @@ describe("createGitHubActionsClient", () => { await expect(client.getCommitAuthor("a".repeat(40))).rejects.toThrow(GitHubProviderRequestError) }) + it("reads a commit's diff, and nothing when it is too large to read whole", async () => { + const sha = "a".repeat(40) + const diff = "diff --git a/app.tsx b/app.tsx\n" + const fetch = respond((url, init) => { + expect(url.pathname).toBe(`/repositories/56/commits/${sha}`) + expect(init.headers).toMatchObject({ Accept: "application/vnd.github.diff" }) + return new Response(diff) + }) + const oversized = respond( + () => new Response("x", { headers: { "content-length": String(3_000_000) } }), + ) + + await expect(createGitHubActionsClient(input, { fetch }).getCommitDiff(sha)).resolves.toBe(diff) + await expect( + createGitHubActionsClient(input, { fetch: oversized }).getCommitDiff(sha), + ).resolves.toBeNull() + }) + it("downloads from the redirect without forwarding the token", async () => { const fetch = respond((url) => url.hostname === "api.github.com" diff --git a/hub/server/integrations/github/create-github-actions-client/index.ts b/hub/server/integrations/github/create-github-actions-client/index.ts index fce6b986e..d12f8d451 100644 --- a/hub/server/integrations/github/create-github-actions-client/index.ts +++ b/hub/server/integrations/github/create-github-actions-client/index.ts @@ -159,6 +159,7 @@ export function createGitHubActionsClient( ...init, headers: { Accept: "application/vnd.github+json", + ...(init.headers as Record | undefined), Authorization: `Bearer ${authorization}`, "User-Agent": "Replica-Hub", "X-GitHub-Api-Version": "2022-11-28", @@ -315,6 +316,24 @@ export function createGitHubActionsClient( : null }, + /** + * Reads one commit's changes as a unified diff, for an evaluator judging the work. A diff + * too large to read whole returns null, since a partial one could mislead. + */ + async getCommitDiff(commitSha: string) { + if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(commitSha)) { + throw new GitHubProviderRequestError({ cause: new Error("Invalid commit SHA.") }) + } + const response = await send( + `${repositoryPath}/commits/${commitSha}`, + await installationToken(), + { headers: { Accept: "application/vnd.github.diff" } }, + ) + if (!response.ok) throw new GitHubCommitLookupError(response.status) + const bytes = await readBounded(response, 2_097_152) + return bytes === undefined ? null : bytes.toString("utf8") + }, + /** Lists branch heads without assuming a truncated response is a complete snapshot. */ async listBranchHeads(): Promise<{ branchName: string; commitSha: string }[]> { const heads: { branchName: string; commitSha: string }[] = [] 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/find-consented-agent-screenshots/index.ts b/hub/server/repositories/agent-screenshots/find-consented-agent-screenshots/index.ts new file mode 100644 index 000000000..88455990b --- /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: { enabled: true, screenshotGrantId: true }, + }) + const grantId = setting?.screenshotGrantId + if (!setting?.enabled || !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/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..63c978dc5 --- /dev/null +++ b/hub/server/repositories/agent-screenshots/list-agent-screenshot-grants/index.ts @@ -0,0 +1,21 @@ +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: { + enabled: true, + 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..85b961bc1 --- /dev/null +++ b/hub/server/repositories/evaluation-settings/get-repository-evaluation-setting/index.ts @@ -0,0 +1,15 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function getRepositoryEvaluationSetting( + database: Pick, + 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..9837c5376 --- /dev/null +++ b/hub/server/repositories/evaluation-settings/initialize-evaluation-setting/index.ts @@ -0,0 +1,8 @@ +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) { + const 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..34dcf2a29 --- /dev/null +++ b/hub/server/repositories/evaluation-settings/save-repository-evaluation-setting/index.ts @@ -0,0 +1,21 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function saveRepositoryEvaluationSetting( + database: Prisma.TransactionClient, + repositoryId: string, + data: + | { retiringScreenshotGrantId: null } + | { enabled: boolean; evaluationGrantId: string | null } + | { + screenshotGrantId: string | null + retiringScreenshotGrantId: 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..b54f58ded --- /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, +) { + const key = evaluationSettingKey + return database.evaluationSetting.upsert({ + where: { key }, + create: { key, monthlyBudgetCredits, revision: 1 }, + update: { monthlyBudgetCredits, revision: { increment: 1 } }, + }) +} diff --git a/hub/server/repositories/learning-activity-days/list-learning-activity-days/index.ts b/hub/server/repositories/learning-activity-days/list-learning-activity-days/index.ts new file mode 100644 index 000000000..974889a8d --- /dev/null +++ b/hub/server/repositories/learning-activity-days/list-learning-activity-days/index.ts @@ -0,0 +1,22 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Return counts that repository members may read after individual runs expire. */ +export async function listLearningActivityDays( + database: Pick, + repositoryId: string, + from: Date, + through: Date, +) { + const days = await database.learningActivityDay.findMany({ + where: { repositoryId, date: { gte: from, lte: through } }, + select: { + date: true, + runs: true, + commentsAnalyzed: true, + commentsTagged: true, + suggestions: true, + }, + orderBy: { date: "asc" }, + }) + return days.map(({ date, ...counts }) => ({ date: date.toISOString().slice(0, 10), ...counts })) +} diff --git a/hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.db.test.ts b/hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.db.test.ts new file mode 100644 index 000000000..43e69e756 --- /dev/null +++ b/hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.db.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { listLearningActivityWithLastRuns } from "." + +describe("listLearningActivityWithLastRuns()", () => { + it("shows only the last finished run for a complete repository day", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/design", defaultBranch: "main" }, + }) + const other = await prisma.repository.create({ + data: { nameWithOwner: "other/design", defaultBranch: "main" }, + }) + const user = await prisma.user.create({ + data: { profile: { create: { provider: "github", login: "mona" } } }, + }) + const date = new Date("2026-12-31") + const counts = { runs: 2, commentsAnalyzed: 4, commentsTagged: 3, suggestions: 1 } + await prisma.learningActivityDay.create({ + data: { repositoryId: repository.id, date, ...counts }, + }) + const earlier = { + repositoryId: repository.id, + state: "SUCCEEDED" as const, + scheduled: true, + startedAt: new Date("2026-12-31T12:00:00Z"), + finishedAt: new Date("2026-12-31T12:30:00Z"), + } + const startedAt = new Date("2027-01-01T04:30:00+05:00") + const latest = await prisma.learningRun.create({ + data: { + repositoryId: repository.id, + requestedById: user.id, + state: "FAILED", + failureCode: "enqueue_failed", + failureSummary: "Private enqueue details.", + createdAt: startedAt, + finishedAt: new Date("2027-01-01T00:01:00Z"), + }, + }) + await prisma.learningRun.createMany({ + data: [ + earlier, + { ...earlier, repositoryId: other.id, startedAt }, + { repositoryId: repository.id, state: "RUNNING", startedAt }, + ], + }) + + function activity() { + return prisma.$transaction(async (transaction) => { + await transaction.$executeRaw`SET LOCAL TIME ZONE 'Asia/Tokyo'` + return listLearningActivityWithLastRuns(transaction, repository.id, date, date) + }) + } + await expect(activity()).resolves.toEqual([ + { + date: "2026-12-31", + ...counts, + lastRun: { + state: "failed", + startedAt: startedAt.toISOString(), + startedBy: { type: "user", login: "mona" }, + }, + }, + ]) + + await prisma.learningRun.delete({ where: { id: latest.id } }) + await expect(activity()).resolves.toEqual([{ date: "2026-12-31", ...counts }]) + }) +}) diff --git a/hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.ts b/hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.ts new file mode 100644 index 000000000..354e18d10 --- /dev/null +++ b/hub/server/repositories/learning-activity-days/list-learning-activity-with-last-runs/index.ts @@ -0,0 +1,67 @@ +import { Prisma } from "../../../generated/prisma/client.ts" + +interface ActivityRow { + date: Date + runs: number + commentsAnalyzed: number + commentsTagged: number + suggestions: number + state: "SUCCEEDED" | "FAILED" | null + startedAt: Date | null + scheduled: boolean | null + login: string | null +} + +/** + * Read totals and their latest finished run in one snapshot. If pruning removed + * part of a day, an older retained run cannot prove who last started a run. + */ +export async function listLearningActivityWithLastRuns( + database: Pick, + repositoryId: string, + from: Date, + through: Date, +) { + const firstDay = from.toISOString().slice(0, 10) + const lastDay = through.toISOString().slice(0, 10) + const rows = await database.$queryRaw(Prisma.sql` + WITH finished AS ( + SELECT (COALESCE(started_at, created_at) AT TIME ZONE 'UTC')::date AS day, + COALESCE(started_at, created_at) AS started, number, state, scheduled, requested_by_id + FROM learning_runs + WHERE repository_id = ${repositoryId}::uuid AND state IN ('SUCCEEDED', 'FAILED') + ), latest AS ( + SELECT DISTINCT ON (day) day, started, state, scheduled, requested_by_id, + COUNT(*) OVER (PARTITION BY day) AS retained + FROM finished + WHERE day BETWEEN ${firstDay}::date AND ${lastDay}::date + ORDER BY day, started DESC, number DESC + ) + SELECT d.date, d.runs, d.comments_analyzed AS "commentsAnalyzed", + d.comments_tagged AS "commentsTagged", d.suggestions, latest.state, + latest.started AT TIME ZONE 'UTC' AS "startedAt", latest.scheduled, p.login + FROM learning_activity_days d + LEFT JOIN latest ON latest.day = d.date AND latest.retained = d.runs + LEFT JOIN user_profiles p ON p.user_id = latest.requested_by_id + WHERE d.repository_id = ${repositoryId}::uuid + AND d.date BETWEEN ${firstDay}::date AND ${lastDay}::date + ORDER BY d.date + `) + return rows.map(({ date, state, startedAt, scheduled, login, ...counts }) => ({ + date: date.toISOString().slice(0, 10), + ...counts, + ...(state && startedAt + ? { + lastRun: { + state: state === "FAILED" ? ("failed" as const) : ("succeeded" as const), + startedAt: startedAt.toISOString(), + startedBy: scheduled + ? ({ type: "daily" } as const) + : login + ? ({ type: "user", login } as const) + : ({ type: "unknown" } as const), + }, + } + : {}), + })) +} diff --git a/hub/server/repositories/learning-activity-days/record-learning-activity-day/index.ts b/hub/server/repositories/learning-activity-days/record-learning-activity-day/index.ts new file mode 100644 index 000000000..1845a0f81 --- /dev/null +++ b/hub/server/repositories/learning-activity-days/record-learning-activity-day/index.ts @@ -0,0 +1,22 @@ +import { Prisma } from "../../../generated/prisma/client.ts" + +/** Compute the UTC day in PostgreSQL so the connection's timezone cannot shift it. */ +export function recordLearningActivityDay( + database: Pick, + runId: string, +) { + return database.$executeRaw(Prisma.sql` + INSERT INTO learning_activity_days AS day + (id, repository_id, date, runs, comments_analyzed, comments_tagged, suggestions) + SELECT gen_random_uuid(), repository_id, + (COALESCE(started_at, created_at) AT TIME ZONE 'UTC')::date, 1, + comments_considered, comments_labeled, suggestions + FROM learning_runs WHERE id = ${runId}::uuid + ON CONFLICT (repository_id, date) DO UPDATE SET + runs = day.runs + 1, + comments_analyzed = day.comments_analyzed + EXCLUDED.comments_analyzed, + comments_tagged = day.comments_tagged + EXCLUDED.comments_tagged, + suggestions = day.suggestions + EXCLUDED.suggestions, + updated_at = CURRENT_TIMESTAMP + `) +} diff --git a/hub/server/repositories/learning-decision-operations/create-learning-decision-operation/index.ts b/hub/server/repositories/learning-decision-operations/create-learning-decision-operation/index.ts index 02c9b9cdb..169901239 100644 --- a/hub/server/repositories/learning-decision-operations/create-learning-decision-operation/index.ts +++ b/hub/server/repositories/learning-decision-operations/create-learning-decision-operation/index.ts @@ -9,7 +9,9 @@ export function createLearningDecisionOperation( soloStoreKey: string | null actorMembershipId: string learningId: string - decision: "accept" | "reject" | "retire" | "edit" | "reinstate" + proposalId?: string + decision: + "apply_update" | "dismiss_update" | "accept" | "reject" | "retire" | "edit" | "reinstate" }, ) { return database.learningDecisionOperation.create({ data: input }) diff --git a/hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts b/hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts new file mode 100644 index 000000000..617ac2cbb --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/finish-learning-evaluation-run/index.ts @@ -0,0 +1,16 @@ +import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts" + +export function finishLearningEvaluationRun( + database: Pick, + runId: string, + input: { + aiCredits: Prisma.Decimal | string + copilotRequests: number + finishedAt: Date + } & ({ state: "SUCCEEDED"; scoreId: string } | { state: "FAILED"; failureCode: string }), +) { + return database.learningEvaluationRun.updateMany({ + where: { id: runId, state: "RUNNING" }, + data: input, + }) +} diff --git a/hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts b/hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts new file mode 100644 index 000000000..7ae0d4f38 --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/start-learning-evaluation-run/index.ts @@ -0,0 +1,20 @@ +import { randomUUID } from "node:crypto" + +import type { PrismaClient } from "../../../generated/prisma/client.ts" +import type { LearningScoreTrigger } from "../../../generated/prisma/enums.ts" + +/** + * Starts scoring one used learning, or returns its earlier attempt. An attempt that never + * finished keeps its operation ID, so retrying it can't store a second score. A reviewer's + * verification is its own trigger, so it earns one more score without repeating the first. + */ +export function startLearningEvaluationRun( + database: Pick, + input: { repositoryId: string; usedLearningId: string; trigger: LearningScoreTrigger }, +) { + return database.learningEvaluationRun.upsert({ + where: { repositoryId_usedLearningId_trigger: input }, + create: { ...input, operationId: randomUUID() }, + update: {}, + }) +} diff --git a/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts new file mode 100644 index 000000000..302dbf49a --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.db.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { sumLearningEvaluationCredits } from "." + +describe("sumLearningEvaluationCredits()", () => { + it("counts update suggestions against the same monthly budget as scoring", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/learning", defaultBranch: "main" }, + }) + const since = new Date("2026-12-01T00:00:00Z") + await prisma.learningEvaluationRun.create({ + data: { + repositoryId: repository.id, + usedLearningId: "used-1", + operationId: "00000000-0000-4000-8000-000000000001", + aiCredits: "1.25", + finishedAt: new Date("2026-12-02T00:00:00Z"), + }, + }) + await prisma.learningUpdateRun.createMany({ + data: [ + { + repositoryId: repository.id, + memoryId: "memory-1", + aiCredits: "0.5", + finishedAt: new Date("2026-12-03T00:00:00Z"), + }, + { + repositoryId: repository.id, + memoryId: "memory-1", + aiCredits: "9", + finishedAt: new Date("2026-11-30T00:00:00Z"), + }, + ], + }) + + expect((await sumLearningEvaluationCredits(prisma, since))?.toString()).toBe("1.75") + }) +}) diff --git a/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts new file mode 100644 index 000000000..5f8b11a25 --- /dev/null +++ b/hub/server/repositories/learning-evaluation-runs/sum-learning-evaluation-credits/index.ts @@ -0,0 +1,24 @@ +import { Prisma, type PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Adds up the AI credits every repository's scoring and update suggestions have spent + * since a moment, since both draw on the same monthly budget. Spending is counted when an + * attempt finishes, since one that resumes later is charged then. + */ +export async function sumLearningEvaluationCredits( + database: Pick, + since: Date, +) { + const [scores, updates] = await Promise.all([ + database.learningEvaluationRun.aggregate({ + where: { finishedAt: { gte: since } }, + _sum: { aiCredits: true }, + }), + database.learningUpdateRun.aggregate({ + where: { finishedAt: { gte: since } }, + _sum: { aiCredits: true }, + }), + ]) + if (!scores._sum.aiCredits && !updates._sum.aiCredits) return null + return new Prisma.Decimal(scores._sum.aiCredits ?? 0).plus(updates._sum.aiCredits ?? 0) +} diff --git a/hub/server/repositories/learning-reviewer-verifications/list-learning-reviewer-verifications/index.ts b/hub/server/repositories/learning-reviewer-verifications/list-learning-reviewer-verifications/index.ts new file mode 100644 index 000000000..c1aa377a2 --- /dev/null +++ b/hub/server/repositories/learning-reviewer-verifications/list-learning-reviewer-verifications/index.ts @@ -0,0 +1,12 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function listLearningReviewerVerifications( + database: Pick, + input: { repositoryId: string; commitSha: string }, +) { + return database.learningReviewerVerification.findMany({ + where: input, + orderBy: [{ verifiedAt: "asc" }, { id: "asc" }], + select: { prototypeId: true, verifiedAt: true }, + }) +} diff --git a/hub/server/repositories/learning-reviewer-verifications/save-learning-reviewer-verification/index.ts b/hub/server/repositories/learning-reviewer-verifications/save-learning-reviewer-verification/index.ts new file mode 100644 index 000000000..f62ae4527 --- /dev/null +++ b/hub/server/repositories/learning-reviewer-verifications/save-learning-reviewer-verification/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Keeps when a reviewer confirmed one prototype's commit. It lives apart from the score + * request, so usage reported later for the same commit still gets the confirmation. + */ +export function saveLearningReviewerVerification( + transaction: Pick, + input: { repositoryId: string; prototypeId: string; commitSha: string; verifiedAt: Date }, +) { + return transaction.learningReviewerVerification.upsert({ + where: { + prototypeId_commitSha: { prototypeId: input.prototypeId, commitSha: input.commitSha }, + }, + create: input, + update: { verifiedAt: input.verifiedAt }, + }) +} diff --git a/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.db.test.ts b/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.db.test.ts new file mode 100644 index 000000000..30097ceb6 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.db.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { deleteExpiredLearningScoreRequests } from "." + +describe("deleteExpiredLearningScoreRequests()", () => { + it("keeps old requests whose commit built, since they may be waiting for budget", async () => { + const built = "a".repeat(40) + const unbuilt = "b".repeat(40) + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/scored", defaultBranch: "main" }, + }) + const prototype = await prisma.prototype.create({ + data: { repositoryId: repository.id, branchName: "empty-state", name: "Empty state" }, + }) + await prisma.build.create({ + data: { + prototypeId: prototype.id, + number: 1, + state: "successful", + commitSha: built, + startedAt: new Date("2026-11-01T00:00:00Z"), + finishedAt: new Date("2026-11-01T00:01:00Z"), + }, + }) + const createdAt = new Date("2026-11-01T00:00:00Z") + await prisma.learningScoreRequest.createMany({ + data: [ + { repositoryId: repository.id, commitSha: built, createdAt }, + { repositoryId: repository.id, commitSha: unbuilt, createdAt }, + ], + }) + + await deleteExpiredLearningScoreRequests(prisma, new Date("2026-12-01T00:00:00Z")) + + const remaining = await prisma.learningScoreRequest.findMany({ select: { commitSha: true } }) + expect(remaining).toEqual([{ commitSha: built }]) + }) +}) diff --git a/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts b/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts new file mode 100644 index 000000000..4f26f38a4 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/delete-expired-learning-score-requests/index.ts @@ -0,0 +1,44 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Drops score requests older than the cutoff whose commit never got a successful Build. + * Built requests stay, since they may only be waiting for budget or Copilot to return. + */ +export async function deleteExpiredLearningScoreRequests( + database: Pick, + cutoff: Date, +) { + let cursor: string | undefined + while (true) { + const requests = await database.learningScoreRequest.findMany({ + where: { createdAt: { lt: cutoff } }, + orderBy: { id: "asc" }, + take: 100, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + select: { id: true, repositoryId: true, commitSha: true }, + }) + if (requests.length === 0) return + cursor = requests.at(-1)!.id + const builds = await database.build.findMany({ + where: { + state: "successful", + commitSha: { in: requests.map((request) => request.commitSha) }, + prototype: { repositoryId: { in: requests.map((request) => request.repositoryId) } }, + }, + select: { commitSha: true, prototype: { select: { repositoryId: true } } }, + }) + const built = new Set( + builds.map((build) => `${build.prototype.repositoryId}:${build.commitSha}`), + ) + await database.learningScoreRequest.deleteMany({ + where: { + id: { + in: requests + .filter((request) => !built.has(`${request.repositoryId}:${request.commitSha}`)) + .map((request) => request.id), + }, + }, + }) + if (requests.length < 100) return + } +} diff --git a/hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts b/hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts new file mode 100644 index 000000000..0a774ff8c --- /dev/null +++ b/hub/server/repositories/learning-score-requests/delete-learning-score-request/index.ts @@ -0,0 +1,18 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Drops a score request once scoring has read it. A report that arrives meanwhile raises + * the revision and keeps the request, so its learnings are scored on the next pass. + */ +export function deleteLearningScoreRequest( + database: Pick, + input: { repositoryId: string; commitSha: string; revision: number }, +) { + return database.learningScoreRequest.deleteMany({ + where: { + repositoryId: input.repositoryId, + commitSha: input.commitSha, + revision: input.revision, + }, + }) +} diff --git a/hub/server/repositories/learning-score-requests/find-learning-score-request/index.ts b/hub/server/repositories/learning-score-requests/find-learning-score-request/index.ts new file mode 100644 index 000000000..838bf2b76 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/find-learning-score-request/index.ts @@ -0,0 +1,12 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** Reads a commit's score request, including the revision that later reports raise. */ +export function findLearningScoreRequest( + database: Pick, + input: { repositoryId: string; commitSha: string }, +) { + return database.learningScoreRequest.findUnique({ + where: { repositoryId_commitSha: input }, + select: { revision: true }, + }) +} diff --git a/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts new file mode 100644 index 000000000..b999d8bc0 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.db.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { listReadyLearningScoreRequests } from "." + +describe("listReadyLearningScoreRequests()", () => { + it("finds built commits past a page of commits that never built", async () => { + const built = "a".repeat(40) + const unbuilt = "b".repeat(40) + const repository = await prisma.repository.create({ + data: { + nameWithOwner: "team/scored", + defaultBranch: "main", + evaluationSetting: { create: { enabled: true, evaluationGrantId: "evaluation_1" } }, + }, + }) + const other = await prisma.repository.create({ + data: { + nameWithOwner: "team/other", + defaultBranch: "main", + evaluationSetting: { create: { enabled: true, evaluationGrantId: "evaluation_1" } }, + }, + }) + const prototype = await prisma.prototype.create({ + data: { repositoryId: repository.id, branchName: "empty-state", name: "Empty state" }, + }) + await prisma.build.create({ + data: { + prototypeId: prototype.id, + number: 1, + state: "successful", + commitSha: built, + startedAt: new Date("2026-12-01T00:00:00Z"), + finishedAt: new Date("2026-12-01T00:01:00Z"), + }, + }) + await prisma.learningScoreRequest.createMany({ + // IDs fix the reading order, so the unbuilt requests fill the first pages. + data: [ + { + id: "00000000-0000-4000-8000-000000000001", + repositoryId: repository.id, + commitSha: unbuilt, + }, + { id: "00000000-0000-4000-8000-000000000002", repositoryId: other.id, commitSha: built }, + { + id: "00000000-0000-4000-8000-000000000003", + repositoryId: repository.id, + commitSha: built, + }, + ], + }) + + await expect(listReadyLearningScoreRequests(prisma, 1)).resolves.toEqual([ + { repositoryId: repository.id, commitSha: built }, + ]) + }) +}) diff --git a/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts new file mode 100644 index 000000000..1f71421c2 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/list-ready-learning-score-requests/index.ts @@ -0,0 +1,50 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Lists commits an agent reported learning usage for that are ready to score: their + * repository is still connected and can be evaluated, and the commit has a successful + * Build there. The + * Build can land before or after the report, so either order ends up here. Requests are + * read in pages, so a pile of commits that never build can't hide ones that did. + */ +export async function listReadyLearningScoreRequests( + database: Pick, + limit = 100, +) { + const ready: Array<{ repositoryId: string; commitSha: string }> = [] + let cursor: string | undefined + while (ready.length < limit) { + const requests = await database.learningScoreRequest.findMany({ + where: { + repository: { + removedAt: null, + evaluationSetting: { enabled: true, evaluationGrantId: { not: null } }, + }, + }, + orderBy: { id: "asc" }, + take: limit, + ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), + select: { id: true, repositoryId: true, commitSha: true }, + }) + if (requests.length === 0) break + cursor = requests.at(-1)!.id + const builds = await database.build.findMany({ + where: { + state: "successful", + commitSha: { in: requests.map((request) => request.commitSha) }, + prototype: { repositoryId: { in: requests.map((request) => request.repositoryId) } }, + }, + select: { commitSha: true, prototype: { select: { repositoryId: true } } }, + }) + const built = new Set( + builds.map((build) => `${build.prototype.repositoryId}:${build.commitSha}`), + ) + for (const request of requests) { + if (built.has(`${request.repositoryId}:${request.commitSha}`)) { + ready.push({ repositoryId: request.repositoryId, commitSha: request.commitSha }) + } + } + if (requests.length < limit) break + } + return ready.slice(0, limit) +} diff --git a/hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts b/hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts new file mode 100644 index 000000000..c791b6093 --- /dev/null +++ b/hub/server/repositories/learning-score-requests/record-learning-score-request/index.ts @@ -0,0 +1,17 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Remembers that an agent reported learning usage in a commit. A repeat report raises the + * revision, so a scoring job already running keeps the request for another pass. The + * database counts revisions, so clocks on different hosts can't reorder reports. + */ +export function recordLearningScoreRequest( + database: Pick, + input: { repositoryId: string; commitSha: string }, +) { + return database.learningScoreRequest.upsert({ + where: { repositoryId_commitSha: input }, + create: input, + update: { revision: { increment: 1 } }, + }) +} diff --git a/hub/server/repositories/learning-shares/list-learning-shares/index.ts b/hub/server/repositories/learning-shares/list-learning-shares/index.ts new file mode 100644 index 000000000..23e6959ef --- /dev/null +++ b/hub/server/repositories/learning-shares/list-learning-shares/index.ts @@ -0,0 +1,29 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Every active share from a repository Hub still lists, oldest first, with the source + * repository's name and the sharer's login for display. + */ +export function listLearningShares( + database: Pick, + candidates?: Array<{ repositoryId: string; learningId: string; digest: string }>, +) { + return database.learningShare.findMany({ + where: { + withdrawnAt: null, + repository: { removedAt: null, localPath: null }, + ...(candidates ? { OR: candidates } : {}), + }, + orderBy: [{ sharedAt: "asc" }, { id: "asc" }], + select: { + repositoryId: true, + learningId: true, + digest: true, + sharedAt: true, + repository: { select: { nameWithOwner: true } }, + sharedByMembership: { + select: { user: { select: { profile: { select: { login: true } } } } }, + }, + }, + }) +} diff --git a/hub/server/repositories/learning-shares/save-learning-share/index.ts b/hub/server/repositories/learning-shares/save-learning-share/index.ts new file mode 100644 index 000000000..9c0476958 --- /dev/null +++ b/hub/server/repositories/learning-shares/save-learning-share/index.ts @@ -0,0 +1,31 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Shares a learning with every repository. Sharing one that was withdrawn shares it again + * under the new sharer, so one row always describes the current share. + */ +export function saveLearningShare( + database: Pick, + input: { + repositoryId: string + learningId: string + digest: string + membershipId: string + at: Date + }, +) { + const shared = { + digest: input.digest, + sharedByMembershipId: input.membershipId, + sharedAt: input.at, + withdrawnAt: null, + withdrawnByMembershipId: null, + } + return database.learningShare.upsert({ + where: { + repositoryId_learningId: { repositoryId: input.repositoryId, learningId: input.learningId }, + }, + create: { repositoryId: input.repositoryId, learningId: input.learningId, ...shared }, + update: shared, + }) +} diff --git a/hub/server/repositories/learning-shares/withdraw-learning-share/index.ts b/hub/server/repositories/learning-shares/withdraw-learning-share/index.ts new file mode 100644 index 000000000..595df558d --- /dev/null +++ b/hub/server/repositories/learning-shares/withdraw-learning-share/index.ts @@ -0,0 +1,14 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Stops sharing a learning. The row stays so its history shows who shared and withdrew it. + */ +export function withdrawLearningShare( + database: Pick, + input: { repositoryId: string; learningId: string; membershipId: string; at: Date }, +) { + return database.learningShare.updateMany({ + where: { repositoryId: input.repositoryId, learningId: input.learningId, withdrawnAt: null }, + data: { withdrawnAt: input.at, withdrawnByMembershipId: input.membershipId }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts new file mode 100644 index 000000000..39030e60e --- /dev/null +++ b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.db.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { recordLearningUpdateRequest } from "../record-learning-update-request" +import { deleteLearningUpdateRequest } from "." + +describe("deleteLearningUpdateRequest", () => { + it("keeps a learning queued when a new score arrives while it is being checked", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/learning", defaultBranch: "main" }, + }) + const request = { repositoryId: repository.id, memoryId: "memory-1" } + const seen = await recordLearningUpdateRequest(prisma, request) + const latest = await recordLearningUpdateRequest(prisma, request) + + await deleteLearningUpdateRequest(prisma, seen) + const kept = await prisma.learningUpdateRequest.count() + await deleteLearningUpdateRequest(prisma, latest) + + expect([kept, await prisma.learningUpdateRequest.count()]).toEqual([1, 0]) + }) +}) diff --git a/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts new file mode 100644 index 000000000..312d1d067 --- /dev/null +++ b/hub/server/repositories/learning-update-requests/delete-learning-update-request/index.ts @@ -0,0 +1,14 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Drops an update request once its check is done. A score that lands during the check + * raises the revision, so the request stays and the learning is checked again. + */ +export function deleteLearningUpdateRequest( + database: Pick, + input: { id: string; revision: number }, +) { + return database.learningUpdateRequest.deleteMany({ + where: { id: input.id, revision: input.revision }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts b/hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts new file mode 100644 index 000000000..52791ae1e --- /dev/null +++ b/hub/server/repositories/learning-update-requests/find-learning-update-request/index.ts @@ -0,0 +1,11 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function findLearningUpdateRequest( + database: Pick, + id: string, +) { + return database.learningUpdateRequest.findUnique({ + where: { id }, + select: { id: true, repositoryId: true, memoryId: true, revision: true }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts b/hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts new file mode 100644 index 000000000..758f7abdf --- /dev/null +++ b/hub/server/repositories/learning-update-requests/list-learning-update-requests/index.ts @@ -0,0 +1,9 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** Lists learnings with new scores, oldest first, so none waits behind newer ones. */ +export function listLearningUpdateRequests(database: Pick) { + return database.learningUpdateRequest.findMany({ + orderBy: [{ createdAt: "asc" }, { id: "asc" }], + select: { id: true }, + }) +} diff --git a/hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts b/hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts new file mode 100644 index 000000000..59bec9e0e --- /dev/null +++ b/hub/server/repositories/learning-update-requests/record-learning-update-request/index.ts @@ -0,0 +1,16 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Remembers that a learning has a new score, so the daily job checks it for a suggested + * update. A repeat raises the revision, so a check already running keeps the request. + */ +export function recordLearningUpdateRequest( + database: Pick, + input: { repositoryId: string; memoryId: string }, +) { + return database.learningUpdateRequest.upsert({ + where: { repositoryId_memoryId: input }, + create: input, + update: { revision: { increment: 1 } }, + }) +} diff --git a/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts new file mode 100644 index 000000000..8a11c2af1 --- /dev/null +++ b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.db.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { closeAbandonedLearningUpdateRuns } from "." + +describe("closeAbandonedLearningUpdateRuns", () => { + it("closes unfinished checks as interrupted and leaves finished ones alone", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/learning", defaultBranch: "main" }, + }) + const stale = await prisma.learningUpdateRun.create({ + data: { repositoryId: repository.id, memoryId: "memory-1" }, + }) + const finished = await prisma.learningUpdateRun.create({ + data: { + repositoryId: repository.id, + memoryId: "memory-2", + state: "SUCCEEDED", + result: "no_change", + }, + }) + const finishedAt = new Date("2026-12-27T03:00:00Z") + + await closeAbandonedLearningUpdateRuns(prisma, finishedAt) + + const runs = await prisma.learningUpdateRun.findMany({ + select: { id: true, state: true, failureCode: true, finishedAt: true }, + }) + expect(runs).toEqual( + expect.arrayContaining([ + { id: stale.id, state: "FAILED", failureCode: "interrupted", finishedAt }, + { id: finished.id, state: "SUCCEEDED", failureCode: null, finishedAt: null }, + ]), + ) + }) +}) diff --git a/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts new file mode 100644 index 000000000..e2154a72d --- /dev/null +++ b/hub/server/repositories/learning-update-runs/close-abandoned-learning-update-runs/index.ts @@ -0,0 +1,15 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** + * Closes update checks left running by a stopped worker. The package can't resume a + * check, so they are recorded as interrupted. + */ +export function closeAbandonedLearningUpdateRuns( + database: Pick, + finishedAt: Date, +) { + return database.learningUpdateRun.updateMany({ + where: { state: "RUNNING" }, + data: { state: "FAILED", failureCode: "interrupted", finishedAt }, + }) +} diff --git a/hub/server/repositories/learning-update-runs/find-latest-learning-update-result/index.ts b/hub/server/repositories/learning-update-runs/find-latest-learning-update-result/index.ts new file mode 100644 index 000000000..4ebe2c474 --- /dev/null +++ b/hub/server/repositories/learning-update-runs/find-latest-learning-update-result/index.ts @@ -0,0 +1,14 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +/** What the newest finished check of one learning found, such as too little evidence. */ +export async function findLatestLearningUpdateResult( + database: Pick, + input: { repositoryId: string; memoryId: string }, +) { + const run = await database.learningUpdateRun.findFirst({ + where: { ...input, state: "SUCCEEDED" }, + orderBy: [{ createdAt: "desc" }, { id: "desc" }], + select: { result: true }, + }) + return run?.result ?? null +} diff --git a/hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts b/hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts new file mode 100644 index 000000000..d0ccbc573 --- /dev/null +++ b/hub/server/repositories/learning-update-runs/finish-learning-update-run/index.ts @@ -0,0 +1,16 @@ +import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts" + +export function finishLearningUpdateRun( + database: Pick, + runId: string, + input: { + aiCredits: Prisma.Decimal | string + copilotRequests: number + finishedAt: Date + } & ({ state: "SUCCEEDED"; result: string } | { state: "FAILED"; failureCode: string }), +) { + return database.learningUpdateRun.updateMany({ + where: { id: runId, state: "RUNNING" }, + data: input, + }) +} diff --git a/hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts b/hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts new file mode 100644 index 000000000..b3ecdc9d3 --- /dev/null +++ b/hub/server/repositories/learning-update-runs/start-learning-update-run/index.ts @@ -0,0 +1,11 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" + +export function startLearningUpdateRun( + database: Pick, + input: { repositoryId: string; memoryId: string }, +) { + return database.learningUpdateRun.create({ + data: { repositoryId: input.repositoryId, memoryId: input.memoryId }, + select: { id: true }, + }) +} diff --git a/hub/server/repositories/prototype-index/list-successful-commit-builds/index.ts b/hub/server/repositories/prototype-index/list-successful-commit-builds/index.ts new file mode 100644 index 000000000..d211529c9 --- /dev/null +++ b/hub/server/repositories/prototype-index/list-successful-commit-builds/index.ts @@ -0,0 +1,47 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" +import { reviewablePrototypeWhere } from "../reviewable-prototype-where/index.ts" + +/** + * Lists a repository's successful Builds of the given commits, newest first, so a score + * recorded against a commit can point people at the Build it judged. Only prototypes + * people can open count, so the link never leads to a hidden page. + */ +export async function listSuccessfulCommitBuilds( + database: PrismaClient, + input: { repository: { id: string; defaultBranch: string }; commitShas: string[] }, +) { + if (input.commitShas.length === 0) return [] + const builds = await database.build.findMany({ + where: { + state: "successful", + commitSha: { in: input.commitShas }, + prototype: reviewablePrototypeWhere(input.repository), + }, + select: { + commitSha: true, + number: true, + createdAt: true, + workflowCreatedAt: true, + prototype: { select: { id: true, name: true, branchName: true } }, + }, + }) + // Build numbers count up separately for each prototype, so only time orders them across + // prototypes. This matches the order prototype pages use. + builds.sort((first, second) => { + const firstCreatedAt = (first.workflowCreatedAt ?? first.createdAt).getTime() + const secondCreatedAt = (second.workflowCreatedAt ?? second.createdAt).getTime() + return secondCreatedAt - firstCreatedAt || second.number - first.number + }) + return builds.flatMap(({ commitSha, number, prototype }) => + commitSha + ? [ + { + commitSha, + number, + prototypeId: prototype.id, + prototypeName: prototype.name ?? prototype.branchName, + }, + ] + : [], + ) +} diff --git a/hub/server/repositories/prototypes/find-newest-successful-build-after/index.ts b/hub/server/repositories/prototypes/find-newest-successful-build-after/index.ts new file mode 100644 index 000000000..27c171856 --- /dev/null +++ b/hub/server/repositories/prototypes/find-newest-successful-build-after/index.ts @@ -0,0 +1,31 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * The prototype's newest successful Build with a commit that started after the given time. + * Build numbers follow the order Hub found the runs, which can differ from when they ran, + * so this compares the workflow's creation time and falls back to the Build's own. + */ +export async function findNewestSuccessfulBuildAfter( + transaction: Pick, + input: { prototypeId: string; after: Date }, +) { + const builds = await transaction.build.findMany({ + where: { + prototypeId: input.prototypeId, + state: "successful", + commitSha: { not: null }, + OR: [ + { workflowCreatedAt: { gt: input.after } }, + { workflowCreatedAt: null, createdAt: { gt: input.after } }, + ], + }, + select: { id: true, commitSha: true, workflowCreatedAt: true, createdAt: true }, + }) + function started(build: (typeof builds)[number]) { + return (build.workflowCreatedAt ?? build.createdAt).getTime() + } + const [newest] = builds.sort( + (left, right) => started(right) - started(left) || right.id.localeCompare(left.id), + ) + return newest?.commitSha ? { commitSha: newest.commitSha } : null +} diff --git a/hub/server/repositories/review-comments/find-review-thread-feedback/index.ts b/hub/server/repositories/review-comments/find-review-thread-feedback/index.ts new file mode 100644 index 000000000..d5e446f39 --- /dev/null +++ b/hub/server/repositories/review-comments/find-review-thread-feedback/index.ts @@ -0,0 +1,24 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** The thread's prototype, who gave its first comment, and when its Build started. */ +export async function findReviewThreadFeedback( + transaction: Pick, + threadId: string, +) { + const thread = await transaction.reviewThread.findUnique({ + where: { id: threadId }, + select: { + repositoryId: true, + prototypeId: true, + build: { select: { workflowCreatedAt: true, createdAt: true } }, + comments: { where: { rootId: null }, select: { authorId: true }, take: 1 }, + }, + }) + if (!thread) return null + return { + repositoryId: thread.repositoryId, + prototypeId: thread.prototypeId, + authorId: thread.comments[0]?.authorId ?? null, + buildStartedAt: thread.build.workflowCreatedAt ?? thread.build.createdAt, + } +} 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 2926aab4b..5b35f8f03 100644 --- a/hub/server/repositories/security-audits/create-security-audit/types.ts +++ b/hub/server/repositories/security-audits/create-security-audit/types.ts @@ -228,7 +228,8 @@ export interface CopilotConnectionAudit extends SecurityAuditEvent { export interface LearningDecisionAudit extends SecurityAuditEvent { type: "learning_decision" actorMembershipId: string - decision: "accept" | "reject" | "retire" | "edit" | "reinstate" + decision: + "accept" | "reject" | "retire" | "edit" | "reinstate" | "apply_update" | "dismiss_update" learningId: string operationId: string outcome: "requested" | "succeeded" | "failed" @@ -236,6 +237,14 @@ export interface LearningDecisionAudit extends SecurityAuditEvent { repositoryId: string } +export interface LearningShareAudit extends SecurityAuditEvent { + type: "learning_share" + actorMembershipId: string + learningId: string + repositoryId: string + shared: boolean +} + export interface LearningRunAudit extends SecurityAuditEvent { type: "learning_run" actorMembershipId: string @@ -248,7 +257,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_settings" + operation: + | "learning_share" + | "learning_overview" + | "learning_run" + | "learning_decision" + | "learning_settings" reason: "authority_missing" repositoryId: string } @@ -316,6 +330,7 @@ export type CreateSecurityAuditEvent = | AuthenticationProviderLifecycleAudit | AuthenticationProvidersReconcileFailedAudit | SessionRevocationAdvancedAudit + | LearningShareAudit | LearningDecisionAudit | LearningRunAudit | RepositoryAdministrationDeniedAudit diff --git a/hub/server/repositories/security-audits/get-security-audit-data/index.ts b/hub/server/repositories/security-audits/get-security-audit-data/index.ts index a5c351503..918cf97b3 100644 --- a/hub/server/repositories/security-audits/get-security-audit-data/index.ts +++ b/hub/server/repositories/security-audits/get-security-audit-data/index.ts @@ -339,6 +339,18 @@ export function getSecurityAuditData( ...(event.reason ? { reason: event.reason } : {}), }, } + case "learning_share": + return { + id: event.id, + action: event.shared ? "learning.share" : "learning.unshare", + outcome: SecurityAuditOutcome.SUCCESS, + targetType: "learning", + targetId: event.learningId, + context: { + actorMembershipId: event.actorMembershipId, + repositoryId: event.repositoryId, + }, + } case "learning_run": return { id: event.id, 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 3e778cf91..af90af42f 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 @@ -289,7 +289,25 @@ const eventSchema = z.discriminatedUnion("type", [ z .object({ actorMembershipId: z.uuid(), - decision: z.enum(["accept", "reject", "retire", "edit", "reinstate"]), + id: z.uuid(), + learningId: z.string().min(1).max(255), + repositoryId: z.uuid(), + shared: z.boolean(), + type: z.literal("learning_share"), + }) + .strict(), + z + .object({ + actorMembershipId: z.uuid(), + decision: z.enum([ + "accept", + "reject", + "retire", + "edit", + "reinstate", + "apply_update", + "dismiss_update", + ]), id: z.uuid(), learningId: z.string().min(1).max(255), operationId: z.uuid(), @@ -315,6 +333,7 @@ const eventSchema = z.discriminatedUnion("type", [ actorMembershipId: z.uuid(), id: z.uuid(), operation: z.enum([ + "learning_share", "learning_overview", "learning_run", "learning_decision", diff --git a/hub/server/repositories/security-audits/parse-security-audit-event/types.ts b/hub/server/repositories/security-audits/parse-security-audit-event/types.ts index 5356d7c6c..3a0f261d6 100644 --- a/hub/server/repositories/security-audits/parse-security-audit-event/types.ts +++ b/hub/server/repositories/security-audits/parse-security-audit-event/types.ts @@ -28,6 +28,7 @@ import type { AllHubSessionsEndedAudit, SessionCreatedAudit, SessionEndedAudit, + LearningShareAudit, LearningDecisionAudit, LearningRunAudit, RepositoryAdministrationDeniedAudit, @@ -73,6 +74,7 @@ export type ParsedSecurityAuditEvent = providerKeys: ProviderKey[] }) | SessionRevocationAdvancedAudit + | LearningShareAudit | LearningDecisionAudit | LearningRunAudit | RepositoryAdministrationDeniedAudit diff --git a/hub/server/routes/agent-connections/index.db.test.ts b/hub/server/routes/agent-connections/index.db.test.ts index 182c06674..fd95069fb 100644 --- a/hub/server/routes/agent-connections/index.db.test.ts +++ b/hub/server/routes/agent-connections/index.db.test.ts @@ -41,6 +41,7 @@ it("connects an agent with a protected Hub session and ends access on sign-out", githubRepositoryId, }, }) + const logLines: string[] = [] server.on( "request", createApp({ @@ -57,7 +58,7 @@ it("connects an agent with a protected Hub session and ends access on sign-out", staticDirectories: [], }, }, - logger: createLogger({ level: "silent" }), + logger: createLogger({ destination: { write: (line) => logLines.push(line) } }), }), ) const mcpUrl = `${requestOrigin}/mcp/repositories/${repository.id}` @@ -205,6 +206,24 @@ it("connects an agent with a protected Hub session and ends access on sign-out", expect((await callMcp(firstTokens.access_token)).status).toBe(401) expect((await refreshWith(registered.client_id, firstTokens.refresh_token)).status).toBe(400) + const malformed = await fetch(mcpUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${tokens.access_token}`, + }, + body: '{"note":"private-malformed-agent-image"', + }) + expect(malformed.status).toBe(400) + await malformed.arrayBuffer() + await vi.waitFor(() => + expect( + logLines.some((line) => line.includes('"statusCode":400') && line.includes("/mcp/")), + ).toBe(true), + ) + expect(logLines.join("\n")).not.toContain("private-malformed-agent-image") + expect(logLines.join("\n")).not.toContain(tokens.access_token) + // Local sign-in cannot read GitHub repositories, so the token works but access stops // at the repository check. expect((await callMcp(tokens.access_token)).status).toBe(403) diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 9d8500331..84bcc391d 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -1,3 +1,7 @@ +import { saveAgentScreenshot } from "../../domains/agent-connections/save-agent-screenshot/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 { recordLearningScoreRequest } from "../../repositories/learning-score-requests/record-learning-score-request/index.ts" import express from "express" import type { Request, RequestHandler, Response } from "express" import type { Logger } from "pino" @@ -40,7 +44,7 @@ export function agentConnectionRoutes( getRepositoryPermission?: GetCanvasRepositoryPermission, logger?: Logger, ) { - const { applicationOrigin, databaseUrl, learning } = dependencies + const { applicationOrigin, databaseUrl, learning, artifactStorage } = dependencies const router = express.Router() const browserMutation = requireOrigin(applicationOrigin) @@ -178,6 +182,7 @@ export function agentConnectionRoutes( router.post( mcpPath, requireAgentToken(applicationOrigin, service), + express.json({ limit: "32mb", strict: true }), handler(async (request, response) => { const id = String(request.params.repositoryId) const { prisma, authority } = await load() @@ -211,12 +216,33 @@ export function agentConnectionRoutes( recordPickAndPolishNotesReceived(prisma, repository.id, receiptIds), }, repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, + async requestScore(commitSha) { + await recordLearningScoreRequest(prisma, { repositoryId: repository.id, commitSha }) + }, serialize: (operation) => withLearningExecutionLock({ databaseUrl, protectSessionAuthority: true, run: operation, }), + ...(artifactStorage + ? { + screenshots: { + grantId: async () => { + const setting = await getRepositoryEvaluationSetting(prisma, repository.id) + return setting?.enabled ? setting.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/applied/get/index.ts b/hub/server/routes/api/learnings/applied/get/index.ts new file mode 100644 index 000000000..b7f0bbd6c --- /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 000000000..dcbe68707 --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/applied-learnings.db.test.ts @@ -0,0 +1,96 @@ +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([]) + await prisma.prototype.create({ + data: { + id: address.prototypeId, + repositoryId: repository.id, + branchName: "prototype/checkout", + name: "Checkout", + registeredAt: new Date(), + builds: { create: { number: 1, state: "successful", commitSha: address.commitSha } }, + }, + }) + 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 new file mode 100644 index 000000000..03e46cb57 --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/evaluation-settings.db.test.ts @@ -0,0 +1,219 @@ +import pino from "pino" +import { describe, expect, it, vi } from "vitest" + +import { changeEvaluationConsent } from "../../../../domains/learning/change-evaluation-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-evaluation-consent", () => ({ + changeEvaluationConsent: 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("grants evaluation consent while evaluations are on and withdraws it, with screenshots, when they 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, + }, + }) + // Records what Hub showed at the moment each store grant was withdrawn. + let grantAtWithdrawal: string | null | undefined + let evaluationAtWithdrawal: unknown + vi.mocked(changeEvaluationConsent).mockImplementation(async ({ allowed, source }) => { + if (allowed) return source === "agent_screenshots" ? "grant_1" : "evaluation_1" + const setting = await prisma.repositoryEvaluationSetting.findUnique({ + where: { repositoryId: repository.id }, + }) + if (source === "agent_screenshots") grantAtWithdrawal = setting?.screenshotGrantId + else { + evaluationAtWithdrawal = { + enabled: setting?.enabled, + evaluationGrantId: setting?.evaluationGrantId, + } + } + return 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, + } + + const source = await prisma.repositoryLearningSetting.create({ + data: { + repositoryId: repository.id, + noteGrantId: "existing-note", + reviewCommentGrantId: "existing-review", + reviewCommentsTurnedOff: true, + }, + }) + 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 }, + }) + vi.mocked(changeEvaluationConsent).mockRejectedValueOnce(new Error("Withdrawal interrupted")) + await expect(learnings.changeEvaluationSettings({ ...change, enabled: false })).rejects.toThrow( + "Withdrawal interrupted", + ) + await expect(learnings.getEvaluationSettings(repository.id)).resolves.toMatchObject({ + enabled: false, + screenshots: { allowed: false }, + notes: { allowed: true }, + reviewComments: { allowed: false }, + }) + await expect( + prisma.repositoryEvaluationSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }), + ).resolves.toMatchObject({ screenshotGrantId: null, retiringScreenshotGrantId: "grant_1" }) + await learnings.changeEvaluationSettings({ ...change, enabled: false }) + await expect( + prisma.repositoryLearningSetting.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }), + ).resolves.toEqual(source) + + expect(await learnings.getEvaluationSettings(repository.id)).toMatchObject({ + enabled: false, + screenshots: { allowed: false }, + }) + expect(vi.mocked(changeEvaluationConsent).mock.lastCall?.[0]).toMatchObject({ + allowed: false, + grantId: "grant_1", + }) + expect(grantAtWithdrawal).toBeNull() + expect(vi.mocked(changeEvaluationConsent)).toHaveBeenCalledWith( + expect.objectContaining({ + allowed: false, + grantId: "evaluation_1", + source: "hub_review_comments", + }), + ) + expect(evaluationAtWithdrawal).toEqual({ enabled: false, evaluationGrantId: "evaluation_1" }) + await expect( + prisma.repositoryEvaluationSetting.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toMatchObject({ evaluationGrantId: null }) + 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 c5fed7c46..cdd14746b 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 @@ -1,3 +1,26 @@ +import { readShareableLearnings } from "../../../../domains/learning/read-shareable-learnings/index.ts" +import { findLatestLearningUpdateResult } from "../../../../repositories/learning-update-runs/find-latest-learning-update-result/index.ts" +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 { 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 type { JobDefinition } from "../../../../integrations/bullmq/types.ts" +import { changeEvaluationConsent } from "../../../../domains/learning/change-evaluation-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 { sumLearningEvaluationCredits } from "../../../../repositories/learning-evaluation-runs/sum-learning-evaluation-credits/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 { lockAdministratorHubSession } from "../../../../repositories/hub-sessions/lock-administrator-hub-session/index.ts" +import { startOfUtcMonth } from "../../../../utils/start-of-utc-month/index.ts" +import { listSuccessfulCommitBuilds } from "../../../../repositories/prototype-index/list-successful-commit-builds/index.ts" +import { + consentedScreenshot, + consentedScreenshotPair, +} from "../../../../domains/learning/consented-screenshot-pair/index.ts" import { randomUUID } from "node:crypto" import type { Logger } from "pino" @@ -12,6 +35,7 @@ import { getLearningOverview } from "../../../../domains/learning/get-learning-o import { getLearningRepositoryScope } from "../../../../domains/learning/get-learning-repository-scope/index.ts" import { findSoloLearningStore } from "../../../../domains/learning/find-solo-learning-store/index.ts" import { listLocalLearningActivity } from "../../../../domains/learning/list-local-learning-activity/index.ts" +import { recordFinishedLearningRun } from "../../../../domains/learning/record-finished-learning-run/index.ts" import { learningRunJob } from "../../../../domains/learning/jobs/learning-run.ts" import { redactReviewCommentJob } from "../../../../domains/learning/jobs/redact-review-comment.ts" import type { ReviewCommentLearningSource } from "../../../../domains/learning/review-comment-learning-source/types.ts" @@ -25,10 +49,13 @@ import { classifyPrismaTransactionError } from "../../../../integrations/prisma/ import { getCopilotConnectionState } from "../../../../repositories/copilot-connection-states/get-copilot-connection-state/index.ts" import { getCopilotConnection } from "../../../../repositories/copilot-connections/get-copilot-connection/index.ts" import { getRepositoryLearningSetting } from "../../../../repositories/learning-settings/get-repository-learning-setting/index.ts" +import { getReviewCommentConsent } from "../../../../repositories/learning-settings/get-review-comment-consent/index.ts" import { saveRepositoryLearningSetting } from "../../../../repositories/learning-settings/save-repository-learning-setting/index.ts" import { createLearningRun } from "../../../../repositories/learning-runs/create-learning-run/index.ts" import { finishLearningRun } from "../../../../repositories/learning-runs/finish-learning-run/index.ts" import { listLearningRuns } from "../../../../repositories/learning-runs/list-learning-runs/index.ts" +import { listLearningActivityDays } from "../../../../repositories/learning-activity-days/list-learning-activity-days/index.ts" +import { listLearningActivityWithLastRuns } from "../../../../repositories/learning-activity-days/list-learning-activity-with-last-runs/index.ts" import { createLearningDecisionOperation } from "../../../../repositories/learning-decision-operations/create-learning-decision-operation/index.ts" import { deleteLearningDecisionOperation } from "../../../../repositories/learning-decision-operations/delete-learning-decision-operation/index.ts" import { isEffectiveAdministrator } from "../../../../repositories/memberships/is-effective-administrator/index.ts" @@ -44,11 +71,18 @@ import { runWithBoundedRetries } from "../../../../domains/identity/run-with-bou import type { CurrentSessionDependencies } from "../../auth/types.ts" import type { LearningsRouteDependencies } from "../types.ts" +const sharedSourceConcurrency = 4 +const sharedSourceTimeoutMs = 10_000 + 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 @@ -164,6 +198,237 @@ export async function createLearningsRouteDependencies( return result } + function isHostedRepository( + database: Pick, + repositoryId: string, + ) { + return database.repository.findFirst({ + where: { + id: repositoryId, + removedAt: null, + localPath: null, + githubRepositoryId: { not: null }, + }, + select: { id: true }, + }) + } + + /** + * Reads the learnings other repositories share, straight from each source store, so a + * learning that was retired or stopped reaching agents there stops being shared too. A + * source Hub cannot read is skipped rather than hiding this repository's own learnings. + */ + async function readSharedLearnings(shares: Awaited>) { + const sources = new Map() + for (const share of shares) { + sources.set(share.repositoryId, [...(sources.get(share.repositoryId) ?? []), share]) + } + async function readSource([sourceId, sourceShares]: [string, typeof shares]) { + try { + const records = await readShareableLearnings({ + ...configuration, + learningIds: sourceShares.map((share) => share.learningId), + repositoryId: sourceId, + repositoryScope: await getLearningRepositoryScope(prisma, sourceId), + timeoutMs: sharedSourceTimeoutMs, + }) + return records.flatMap((record) => { + const share = sourceShares.find( + (item) => item.learningId === record.id && item.digest === record.digest, + ) + return share ? [{ record, repositoryId: sourceId, digest: share.digest }] : [] + }) + } catch (error) { + // Any failure stays with its source, so one broken store cannot take down the + // Learnings page of every repository it shares with. + logger.warn( + { + learningFailureCode: error instanceof LearningCommandError ? error.code : "unexpected", + repositoryId: sourceId, + }, + "Shared learnings could not be read", + ) + return [] + } + } + // A few sources at a time, each with a short deadline, so stalled stores cannot hold + // the page for minutes or start one process per repository at once. + const entries = [...sources] + const shared = [] + for (let start = 0; start < entries.length; start += sharedSourceConcurrency) { + const batch = entries.slice(start, start + sharedSourceConcurrency) + shared.push(...(await Promise.all(batch.map(readSource))).flat()) + } + // A source can stop sharing while its store is read. Check the publication + // decision after those reads, not just when choosing which stores to open. + if (!shared.length) return [] + const active = await listLearningShares( + prisma, + shared.map(({ record, repositoryId, digest }) => ({ + repositoryId, + learningId: record.id, + digest, + })), + ) + const wording = new Map( + shared.map(({ record, repositoryId, digest }) => [ + `${repositoryId}:${record.id}:${digest}`, + record, + ]), + ) + return active.flatMap((share) => { + const record = wording.get(`${share.repositoryId}:${share.learningId}:${share.digest}`) + return record + ? [ + { + id: record.id, + title: record.title, + content: record.content, + status: "recalled" as const, + source: share.repository.nameWithOwner, + sharedBy: share.sharedByMembership?.user.profile?.login ?? null, + sharedAt: share.sharedAt.toISOString(), + }, + ] + : [] + }) + } + + async function readHistory({ + repositoryId, + learningId, + }: { + repositoryId: string + learningId: string + }) { + return readInScope(repositoryId, async (location) => { + const { reviewableUpdate, ...history } = await getLearningHistory({ + ...configuration, + ...location, + evidenceSource: source, + learningId, + repositoryId, + }) + const repository = await prisma.repository.findUnique({ + where: { id: repositoryId }, + select: { id: true, defaultBranch: true }, + }) + const scored = [ + ...history.outcomes, + ...history.earlierGuidance.flatMap((guidance) => guidance.outcomes), + ...history.updates.flatMap((update) => update.support), + ] + const builds = repository + ? await listSuccessfulCommitBuilds(prisma, { + repository, + commitShas: [...new Set(scored.map((outcome) => outcome.commitSha))], + }) + : [] + const lastCheck = + reviewableUpdate && !location.soloDirectory && !history.updates.length + ? await findLatestLearningUpdateResult(prisma, { repositoryId, memoryId: learningId }) + : null + const consented = await findConsented(repositoryId, scored) + function buildOf({ + commitSha, + prototypeId, + }: Pick<(typeof scored)[number], "commitSha" | "prototypeId">) { + return builds.find( + (candidate) => + candidate.commitSha === commitSha && + (prototypeId === null || candidate.prototypeId === prototypeId), + ) + } + // The scorer's words may describe a screenshot that consent no longer covers. + function withheld({ before, after }: Pick<(typeof scored)[number], "before" | "after">) { + return Boolean( + (before && !consentedScreenshot(consented, before)) || + (after && !consentedScreenshot(consented, after)), + ) + } + // A score with no Build left to show is hidden rather than shown without context. + function shown(outcomes: typeof scored) { + return outcomes.flatMap((reported) => { + const { commitSha, prototypeId, before, after, ...outcome } = reported + const build = buildOf({ commitSha, prototypeId }) + if (!build) return [] + return [ + { + ...outcome, + ...(withheld(reported) ? { reasoning: "", issue: null } : {}), + build: { + prototypeId: build.prototypeId, + prototypeName: build.prototypeName, + number: build.number, + }, + ...consentedScreenshotPair(consented, { before, after }), + }, + ] + }) + } + // Suggested wording is written from its supporting scores, so it may repeat what a + // hidden Build or a withdrawn screenshot showed. + const updates = history.updates.flatMap((update) => + update.support.every((outcome) => buildOf(outcome) && !withheld(outcome)) + ? [{ ...update, support: shown(update.support).map(({ build }) => build) }] + : [], + ) + return { + ...history, + updateNeedsMoreEvidence: lastCheck === "insufficient_evidence", + outcomes: shown(history.outcomes), + earlierGuidance: history.earlierGuidance.map((guidance) => ({ + ...guidance, + outcomes: shown(guidance.outcomes), + })), + updates, + } + }) + } + + async function findConsented( + repositoryId: string, + items: Array<{ before?: { sha256: string }; after?: { sha256: string } }>, + ) { + const digests = items.flatMap(({ before, after }) => + [before, after].flatMap((screenshot) => (screenshot ? [screenshot.sha256] : [])), + ) + if (!digests.length || !options.artifactStorage) return null + return findConsentedAgentScreenshots(prisma, { repositoryId, sha256s: digests }) + } + + async function enqueueOnDemand( + definition: JobDefinition, + payload: Payload, + jobId: string, + ) { + const queue = createJobQueue({ name: "on-demand", databaseUrl: requiredDatabaseUrl, logger }) + try { + await enqueueJob(queue, definition, payload, { jobId }) + } finally { + await queue.close() + } + } + + /** + * 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(repositoryId: string, grantId: string) { + try { + await enqueueOnDemand( + deleteAgentScreenshotsJob, + { repositoryId, grantId }, + `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", + ) + } + } + async function getLearningSettings(repositoryId: string) { const setting = await getRepositoryLearningSetting(prisma, repositoryId) return { @@ -287,7 +552,7 @@ export async function createLearningsRouteDependencies( }) }, findRepository, - getOverview: async ({ repositoryId, viewer }) => { + getOverview: async ({ repositoryId, viewer, includeShareEligibility }) => { let solo = false try { return await readInScope(repositoryId, async (location) => { @@ -299,7 +564,49 @@ export async function createLearningsRouteDependencies( repositoryId, viewer, }) - return { ...overview, solo, localLearningSetupNeeded: false } + const canShareAcrossHub = !solo && !!(await isHostedRepository(prisma, repositoryId)) + const shares = canShareAcrossHub ? await listLearningShares(prisma) : [] + const shared = await readSharedLearnings( + shares.filter((item) => item.repositoryId !== repositoryId), + ) + const own = new Map( + shares + .filter((item) => item.repositoryId === repositoryId) + .map((item) => [item.learningId, item.digest]), + ) + const ids = overview.learnings + .filter( + (item) => + canShareAcrossHub && + (includeShareEligibility || own.has(item.id)) && + item.content !== null && + (item.status === "recalled" || item.status === "budget-excluded"), + ) + .map((item) => item.id) + const eligible = ids.length + ? await readShareableLearnings({ + ...configuration, + repositoryId, + repositoryScope: location.repositoryScope, + learningIds: ids, + }) + : [] + const publishable = new Map(eligible.map((record) => [record.id, record.digest])) + return { + ...overview, + canShareAcrossHub, + shared, + learnings: overview.learnings.map((item) => ({ + ...item, + shareable: !!item.digest && publishable.get(item.id) === item.digest, + shared: !!item.digest && own.get(item.id) === item.digest, + })), + // The old digest can no longer publish this learning, but its source + // administrators can still withdraw the saved publication decision. + rejected: overview.rejected.map((item) => ({ ...item, shared: own.has(item.id) })), + solo, + localLearningSetupNeeded: false, + } }) } catch (error) { if (!(error instanceof LearningCommandError)) throw error @@ -337,25 +644,340 @@ export async function createLearningsRouteDependencies( } } }, - getHistory: async ({ repositoryId, learningId }) => { - return readInScope(repositoryId, (location) => - getLearningHistory({ + share: async (input) => { + const { actorMembershipId, learningId, repositoryId, sessionDigest } = input + const result = await withLearningExecutionLock({ + databaseUrl: requiredDatabaseUrl, + protectSessionAuthority: true, + run: async (signal) => { + const location = await findStoreLocation(prisma, repositoryId) + if (location.soloDirectory || !(await isHostedRepository(prisma, repositoryId))) + throw new LearningsError( + 409, + "learning_not_shareable", + "Local learnings cannot be shared across Hub.", + ) + if (input.shared) { + const records = await readShareableLearnings({ + ...configuration, + repositoryId, + repositoryScope: location.repositoryScope, + learningIds: [learningId], + signal, + }) + if (!records.some((item) => item.id === learningId && item.digest === input.digest)) + throw new LearningsError( + 409, + "stale_review", + "Only the current, accepted wording agents receive can be shared.", + ) + } + return runRepositoryAuthorityTransaction(async (transaction) => { + signal.throwIfAborted() + if ( + !(await lockRepositoryAdministratorSession(transaction, { + membershipId: actorMembershipId, + repositoryId, + sessionDigest, + })) || + !(await isEffectiveAdministrator(transaction, actorMembershipId)) + ) + return false + if ( + !(await isHostedRepository(transaction, repositoryId)) || + (await getLearningRepositoryScope(transaction, repositoryId)) !== + location.repositoryScope + ) + throw new LearningCommandError( + "repository_scope_unavailable", + "The repository learning scope changed. Try again.", + ) + const change = { + repositoryId, + learningId, + membershipId: actorMembershipId, + at: new Date(), + } + if (input.shared) + await saveLearningShare(transaction, { ...change, digest: input.digest }) + else await withdrawLearningShare(transaction, change) + await createSecurityAudit(transaction, { + id: randomUUID(), + type: "learning_share", + actorMembershipId, + learningId, + repositoryId, + shared: input.shared, + }) + return true + }) + }, + }) + if (!result) { + await createSecurityAudit(prisma, { + id: randomUUID(), + type: "repository_administration_denied", + operation: "learning_share", + actorMembershipId, + repositoryId, + reason: "authority_missing", + }) + throw new LearningsError( + 403, + "repository_administrator_required", + "Hub and repository administrator access is required.", + ) + } + return { notice: input.shared ? "Shared across Hub." : "Stopped sharing across Hub." } + }, + getHistory: readHistory, + getLearningSettings, + changeLearningSettings, + getAppliedLearnings: async ({ repositoryId, prototypeId, commitSha }) => { + const repository = await prisma.repository.findUnique({ + where: { id: repositoryId }, + select: { id: true, defaultBranch: true }, + }) + if (!repository) return [] + const builds = await listSuccessfulCommitBuilds(prisma, { + repository, + commitShas: [commitSha], + }) + if (!builds.some((build) => build.prototypeId === prototypeId)) return [] + const applied = await readInScope(repositoryId, (location) => + getAppliedLearnings({ ...configuration, ...location, - evidenceSource: source, - learningId, + commitSha, + prototypeId, repositoryId, }), ) + const consented = await findConsented(repositoryId, applied) + return applied.map(({ before, after, ...learning }) => ({ + ...learning, + ...consentedScreenshotPair(consented, { before, after }), + })) + }, + 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 }) => { + const setting = await getRepositoryEvaluationSetting(prisma, repositoryId) + return Boolean(setting?.enabled && setting.screenshotGrantId === grantId) + }, + getEvaluationSettings: async (repositoryId) => { + await getLearningRepositoryScope(prisma, repositoryId) + const budget = await initializeEvaluationSetting(prisma) + const setting = await getRepositoryEvaluationSetting(prisma, repositoryId) + const used = await sumLearningEvaluationCredits(prisma, startOfUtcMonth(new Date())) + return { + // toFixed keeps tiny budgets in plain digits instead of forms like 1e-9. + monthlyBudgetCredits: budget.monthlyBudgetCredits.toFixed(), + usedCredits: used?.toFixed() ?? "0", + enabled: setting?.enabled ?? false, + screenshots: { + allowed: Boolean(setting?.enabled && setting.screenshotGrantId), + changedBy: setting?.screenshotsChangedByMembership?.user.profile?.login ?? null, + changedAt: setting?.screenshotsChangedAt?.toISOString() ?? null, + }, + ...(await getLearningSettings(repositoryId)), + } + }, + changeEvaluationSettings: async ({ actorMembershipId, sessionDigest, ...input }) => { + async function deny(): Promise { + await createSecurityAudit(prisma, { + id: randomUUID(), + type: "repository_administration_denied", + actorMembershipId, + operation: "learning_settings", + repositoryId: input.repositoryId, + reason: "authority_missing", + }) + 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: requiredDatabaseUrl, + 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.", + ) + } + const evaluationGrantId = setting?.evaluationGrantId ?? null + function changeConsent( + source: "hub_review_comments" | "agent_screenshots", + allowed: boolean, + current: string | null, + ) { + return changeEvaluationConsent({ + ...configuration, + actor: input.actor, + allowed, + grantId: current, + repositoryId: input.repositoryId, + repositoryScope, + signal, + source, + }) + } + function saveEnabled(next: string | null) { + return withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { + enabled, + evaluationGrantId: next, + }), + ) + } + function saveGrant( + screenshotGrantId: string | null, + retiringScreenshotGrantId: string | null, + ) { + return withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { + screenshotGrantId, + retiringScreenshotGrantId, + screenshotsChangedAt: new Date(), + screenshotsChangedByMembershipId: actorMembershipId, + }), + ) + } + // Hide a withdrawn grant immediately and remember it until the store agrees. + // A retry must finish this withdrawal before creating a replacement grant. + let retiring = setting?.retiringScreenshotGrantId ?? null + if (!enabled && setting?.enabled && !(await saveEnabled(evaluationGrantId))) + return deny() + if (!allowed && grantId) { + retiring = grantId + if (!(await saveGrant(null, retiring))) return deny() + } + if (enabled && (!setting?.enabled || !evaluationGrantId)) { + const next = await changeConsent("hub_review_comments", true, null) + if (!(await saveEnabled(next))) return deny() + } else if (!enabled && evaluationGrantId) { + await changeConsent("hub_review_comments", false, evaluationGrantId) + if (!(await saveEnabled(null))) return deny() + } + if (retiring) { + await changeConsent("agent_screenshots", false, retiring) + const saved = await withAuthority((transaction) => + saveRepositoryEvaluationSetting(transaction, input.repositoryId, { + retiringScreenshotGrantId: null, + }), + ) + if (!saved) return deny() + await queueScreenshotDeletion(input.repositoryId, retiring) + } + if (allowed && !grantId) { + const next = await changeConsent("agent_screenshots", true, null) + if (!(await saveGrant(next, null))) return deny() + } + }, + }) + } 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: "Learning 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." } }, - getLearningSettings, - changeLearningSettings, getCopilot, - listRuns: (repositoryId) => listLearningRuns(prisma, repositoryId, new Date()), - listActivity: (repositoryId, from) => + listRuns: async (repositoryId) => { + const [summary, consent] = await Promise.all([ + listLearningRuns(prisma, repositoryId, new Date()), + configuration.automaticRuns + ? getReviewCommentConsent(prisma, repositoryId, configuration.reviewCommentConsent) + : null, + ]) + return { + ...summary, + needsReviewConsent: + !!consent && + !consent.turnedOff && + !consent.hubAdministrator && + !consent.repositoryGrantId, + } + }, + listHostedActivity: (repositoryId, from, through, includeLastRun) => + includeLastRun + ? listLearningActivityWithLastRuns(prisma, repositoryId, from, through) + : listLearningActivityDays(prisma, repositoryId, from, through), + listLocalActivity: (repositoryId, from, through) => readInScope(repositoryId, (location) => location.soloDirectory - ? listLocalLearningActivity(location.soloDirectory, from) + ? listLocalLearningActivity(location.soloDirectory, from, through) : Promise.resolve([]), ), requestRun: async ({ actorMembershipId, repositoryId, requestedById, sessionDigest }) => { @@ -363,7 +985,7 @@ export async function createLearningsRouteDependencies( throw new LearningsError( 409, "learning_run_unavailable", - "Solo looks for learnings after each agent session.", + "In local learning mode, your agent looks for learnings after each session.", ) } if ( @@ -489,12 +1111,14 @@ export async function createLearningsRouteDependencies( ) } catch (error) { if (created || promoted) { - await finishLearningRun(prisma, run.id, { - state: "FAILED", - failureCode: "enqueue_failed", - failureSummary: "Hub could not queue this learning run.", - finishedAt: new Date(), - }) + await recordFinishedLearningRun(prisma, run.id, (transaction) => + finishLearningRun(transaction, run.id, { + state: "FAILED", + failureCode: "enqueue_failed", + failureSummary: "Hub could not queue this learning run.", + finishedAt: new Date(), + }), + ) await createSecurityAudit(prisma, { id: randomUUID(), type: "learning_run", @@ -591,6 +1215,9 @@ export async function createLearningsRouteDependencies( id: operationId, actorMembershipId, decision: input.decision.decision, + ...("proposalId" in input.decision + ? { proposalId: input.decision.proposalId } + : {}), learningId: input.learningId, repositoryId: input.repositoryId, repositoryScope: location.repositoryScope, @@ -624,6 +1251,16 @@ export async function createLearningsRouteDependencies( ) } operationCreated = true + const decision = input.decision + if ( + (decision.decision === "apply_update" || decision.decision === "dismiss_update") && + !(await readHistory(input)).updates.some(({ id }) => id === decision.proposalId) + ) { + throw new LearningCommandError( + "stale_review", + "That suggested update is no longer available for review.", + ) + } return executeLearningDecision({ ...configuration, ...input, diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-outcomes.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-outcomes.db.test.ts new file mode 100644 index 000000000..e53add39b --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-outcomes.db.test.ts @@ -0,0 +1,191 @@ +import pino from "pino" +import { describe, expect, it, vi } from "vitest" + +import { getLearningHistory } from "../../../../domains/learning/get-learning-history" +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-learning-history", () => ({ + getLearningHistory: vi.fn(), +})) + +describe("learning outcomes", () => { + it("links each score to a Build people can open and hides scores without one", async () => { + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 17n, nameWithOwner: "octo/source" }, + }) + const checkout = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "checkout", + name: "Checkout", + registeredAt: new Date("2026-11-01T00:00:00Z"), + }, + }) + const signup = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "signup", + name: "Signup", + registeredAt: new Date("2026-11-01T00:00:00Z"), + }, + }) + const main = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "main", + name: "Main", + registeredAt: new Date("2026-11-01T00:00:00Z"), + }, + }) + const shared = "a".repeat(40) + // Checkout's Build is the newest despite its lower number, judged by workflow time. + for (const [prototype, number, times] of [ + [ + checkout, + 3, + { + createdAt: new Date("2026-12-01T00:00:00Z"), + workflowCreatedAt: new Date("2026-12-01T02:00:00Z"), + }, + ], + [signup, 7, { createdAt: new Date("2026-12-01T01:00:00Z") }], + [main, 9, { createdAt: new Date("2026-12-01T03:00:00Z") }], + ] as const) { + await prisma.build.create({ + data: { + ...times, + prototypeId: prototype.id, + number, + state: "successful", + commitSha: shared, + startedAt: new Date("2026-12-01T00:00:00Z"), + finishedAt: new Date("2026-12-01T00:01:00Z"), + }, + }) + } + const score = { + source: "automated" as const, + efficiency: 3, + followed: "followed" as const, + reasoning: "The form kept its labels.", + issue: null, + scoredAt: "2026-12-02T00:00:00.000Z", + } + vi.mocked(getLearningHistory).mockResolvedValue({ + reviewableUpdate: true, + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + earlierGuidance: [], + updates: [], + outcomes: [ + { ...score, id: "score_checkout", commitSha: shared, prototypeId: checkout.id }, + { ...score, id: "score_signup", commitSha: shared, prototypeId: signup.id }, + { ...score, id: "score_any_prototype", commitSha: shared, prototypeId: null }, + { ...score, id: "score_unbuilt", commitSha: "b".repeat(40), prototypeId: null }, + ], + }) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + + const history = await learnings.getHistory({ repositoryId: repository.id, learningId: "mem_1" }) + + expect(history.outcomes.map((outcome) => [outcome.id, outcome.build])).toEqual([ + ["score_checkout", { prototypeId: checkout.id, prototypeName: "Checkout", number: 3 }], + ["score_signup", { prototypeId: signup.id, prototypeName: "Signup", number: 7 }], + ["score_any_prototype", { prototypeId: checkout.id, prototypeName: "Checkout", number: 3 }], + ]) + }) + + it("hides the scorer's words, and suggestions drawn from them, when a screenshot is no longer shown", async () => { + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 18n, nameWithOwner: "octo/consent" }, + }) + const prototype = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "checkout", + name: "Checkout", + registeredAt: new Date("2026-11-01T00:00:00Z"), + }, + }) + const commitSha = "c".repeat(40) + await prisma.build.create({ + data: { + prototypeId: prototype.id, + number: 1, + state: "successful", + commitSha, + startedAt: new Date("2026-12-01T00:00:00Z"), + finishedAt: new Date("2026-12-01T00:01:00Z"), + }, + }) + const withScreenshot = { + id: "score_with_screenshot", + source: "automated" as const, + commitSha, + prototypeId: prototype.id, + efficiency: 2, + followed: "followed" as const, + reasoning: "The screenshot shows the card number.", + issue: "The card number is visible.", + scoredAt: "2026-12-02T00:00:00.000Z", + after: { sha256: "d".repeat(64), route: "/checkout", consentGrantId: "grant_old" }, + } + const fromDiff = { + ...withScreenshot, + id: "score_from_diff", + reasoning: "The diff removed the label.", + issue: "The label is gone.", + after: undefined, + } + const suggestion = { + issue: "Labels go missing.", + title: null, + content: "Keep a visible label on every field.", + reasoning: "Builds kept dropping labels.", + } + vi.mocked(getLearningHistory).mockResolvedValue({ + reviewableUpdate: true, + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + earlierGuidance: [], + updates: [ + { ...suggestion, id: "upd_from_screenshot", support: [withScreenshot, fromDiff] }, + { ...suggestion, id: "upd_from_diff", support: [fromDiff] }, + ], + outcomes: [withScreenshot], + }) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + + const history = await learnings.getHistory({ repositoryId: repository.id, learningId: "mem_1" }) + + expect(history.outcomes).toEqual([ + expect.objectContaining({ id: "score_with_screenshot", reasoning: "", issue: null }), + ]) + expect(history.outcomes[0]).not.toHaveProperty("after") + expect(history.updates).toEqual([ + expect.objectContaining({ + id: "upd_from_diff", + support: [{ prototypeId: prototype.id, prototypeName: "Checkout", number: 1 }], + }), + ]) + }) +}) diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-shares.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-shares.db.test.ts new file mode 100644 index 000000000..715585c12 --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-shares.db.test.ts @@ -0,0 +1,249 @@ +import pino from "pino" +import { describe, expect, it, vi } from "vitest" + +import { getLearningOverview } from "../../../../domains/learning/get-learning-overview" +import { readShareableLearnings } from "../../../../domains/learning/read-shareable-learnings" +import { prisma } from "../../../../integrations/prisma" +import { getDatabaseUrl } from "../../../../../test/database/get-database-url" +import { createLearningsRouteDependencies } from "." + +vi.mock("../../../../domains/learning/get-learning-overview", () => ({ + getLearningOverview: vi.fn(), +})) +vi.mock("../../../../domains/learning/read-shareable-learnings", () => ({ + readShareableLearnings: vi.fn(), +})) + +describe("learning shares", () => { + it("gives other repositories a shared learning until it is withdrawn", 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 source = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 17n, nameWithOwner: "octo/source" }, + }) + const receiver = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 18n, nameWithOwner: "octo/receiver" }, + }) + await prisma.repositoryAccessGrant.create({ + data: { + accessLevel: "ADMIN", + membershipId: membership.id, + observedAt: new Date(), + repositoryId: source.id, + }, + }) + const digest = `sha256:${"a".repeat(64)}` + const record = { + id: "mem_shared", + digest, + title: null, + content: "Use one primary button per page.", + } + vi.mocked(readShareableLearnings).mockResolvedValue([record]) + vi.mocked(getLearningOverview).mockResolvedValue({ + loadError: null, + identityReviewCount: 0, + suggestions: [], + learnings: [], + rejected: [], + administratorFollowUp: null, + recall: { text: "", count: 0 }, + }) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + const share = { + actorMembershipId: membership.id, + learningId: "mem_shared", + repositoryId: source.id, + sessionDigest, + } + + expect(await learnings.share({ ...share, shared: true, digest })).toEqual({ + notice: "Shared across Hub.", + }) + function received() { + return learnings.getOverview({ repositoryId: receiver.id, viewer: "human:mona" }) + } + expect((await received()).shared).toEqual([ + expect.objectContaining({ id: record.id, content: record.content, source: "octo/source" }), + ]) + vi.mocked(readShareableLearnings).mockResolvedValueOnce([ + { ...record, digest: `sha256:${"b".repeat(64)}`, content: "Not shared." }, + ]) + expect((await received()).shared).toEqual([]) + vi.mocked(getLearningOverview).mockResolvedValueOnce({ + loadError: null, + administratorFollowUp: null, + identityReviewCount: 0, + suggestions: [], + learnings: [], + rejected: [ + { + id: record.id, + state: "retired", + digest: null, + content: null, + title: null, + replaces: [], + reason: null, + decidedAt: null, + decidedBy: null, + }, + ], + recall: { text: "", count: 0 }, + }) + const retired = await learnings.getOverview({ repositoryId: source.id, viewer: "human:mona" }) + expect(retired.rejected).toMatchObject([ + { id: record.id, state: "retired", shared: true, content: null }, + ]) + await prisma.repository.update({ + where: { id: receiver.id }, + data: { localPath: "/local/checkout" }, + }) + expect((await received()).shared).toEqual([]) + await expect( + learnings.share({ ...share, repositoryId: receiver.id, shared: true, digest }), + ).rejects.toMatchObject({ status: 409, code: "learning_not_shareable" }) + await prisma.repository.update({ where: { id: receiver.id }, data: { localPath: null } }) + vi.mocked(readShareableLearnings).mockImplementationOnce(async () => { + await learnings.share({ ...share, shared: false }) + return [record] + }) + expect((await received()).shared).toEqual([]) + expect( + await prisma.learningShare.findUniqueOrThrow({ + where: { repositoryId_learningId: { repositoryId: source.id, learningId: "mem_shared" } }, + }), + ).toMatchObject({ sharedByMembershipId: membership.id, withdrawnByMembershipId: membership.id }) + const audits = await prisma.securityAudit.findMany({ + where: { targetType: "learning", targetId: "mem_shared" }, + orderBy: { createdAt: "asc" }, + }) + expect(audits.map((audit) => audit.action)).toEqual(["learning.share", "learning.unshare"]) + }) + + it("saves no share for a learning agents do not get or an administrator who lost access", 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 source = await prisma.repository.create({ + data: { defaultBranch: "main", githubRepositoryId: 17n, nameWithOwner: "octo/source" }, + }) + const grant = await prisma.repositoryAccessGrant.create({ + data: { + accessLevel: "ADMIN", + membershipId: membership.id, + observedAt: new Date(), + repositoryId: source.id, + }, + }) + const learnings = await createLearningsRouteDependencies( + { HUB_APPLICATION_ORIGIN: "https://hub.example.test", DATABASE_URL: getDatabaseUrl() }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + const share = { + actorMembershipId: membership.id, + learningId: "mem_shared", + repositoryId: source.id, + sessionDigest, + shared: true as const, + digest: `sha256:${"a".repeat(64)}`, + } + + vi.mocked(readShareableLearnings).mockResolvedValueOnce([]) + await expect(learnings.share(share)).rejects.toMatchObject({ + code: "stale_review", + status: 409, + }) + vi.mocked(readShareableLearnings).mockResolvedValueOnce([ + { id: "mem_shared", digest: share.digest, title: null, content: "Reviewed wording." }, + ]) + await prisma.repositoryAccessGrant.update({ + data: { accessLevel: "READ" }, + where: { id: grant.id }, + }) + await expect(learnings.share(share)).rejects.toMatchObject({ + code: "repository_administrator_required", + status: 403, + }) + + expect(await prisma.learningShare.count()).toBe(0) + const audits = await prisma.securityAudit.findMany({ where: { targetId: source.id } }) + expect(audits.map((audit) => audit.action)).toEqual([ + "repository.administration.learning_share.denied", + ]) + }) +}) diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts index 84ce2ba25..99c094611 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/repository-authority.db.test.ts @@ -29,6 +29,31 @@ vi.mock("../../../../domains/learning/find-solo-learning-store", () => ({ })) describe("learning overview repository visibility", () => { + it("stops prompting for first-run consent when the repository opts out or already has a grant", async () => { + const repository = await prisma.repository.create({ + data: { defaultBranch: "main", nameWithOwner: "team/design", githubRepositoryId: 17n }, + }) + const learnings = await createLearningsRouteDependencies( + { + HUB_APPLICATION_ORIGIN: "https://hub.example.test", + DATABASE_URL: getDatabaseUrl(), + REPLICA_LEARNING_AUTOMATIC_RUNS: "true", + }, + { restore: vi.fn() }, + pino({ level: "silent" }), + ) + expect((await learnings.listRuns(repository.id)).needsReviewConsent).toBe(true) + await prisma.repositoryLearningSetting.create({ + data: { repositoryId: repository.id, reviewCommentsTurnedOff: true }, + }) + expect((await learnings.listRuns(repository.id)).needsReviewConsent).toBe(false) + await prisma.repositoryLearningSetting.update({ + where: { repositoryId: repository.id }, + data: { reviewCommentsTurnedOff: false, reviewCommentGrantId: "grant_review" }, + }) + expect((await learnings.listRuns(repository.id)).needsReviewConsent).toBe(false) + }) + it("lets a Hub administrator read an identified repository without decision authority", async () => { const user = await prisma.user.create({ data: {} }) const membership = await prisma.membership.create({ data: { userId: user.id } }) @@ -40,6 +65,20 @@ describe("learning overview repository visibility", () => { }, }) const repositoryMember = await prisma.user.create({ data: {} }) + const otherRepository = await prisma.repository.create({ + data: { defaultBranch: "main", nameWithOwner: "other/private" }, + }) + const year = new Date().getUTCFullYear() + const currentDay = `${year}-01-01` + const counts = { runs: 2, commentsAnalyzed: 8, commentsTagged: 3, suggestions: 1 } + await prisma.learningActivityDay.createMany({ + data: [ + { repositoryId: repository.id, date: new Date(currentDay), ...counts }, + { repositoryId: otherRepository.id, date: new Date(currentDay), ...counts }, + { repositoryId: repository.id, date: new Date(`${year - 1}-12-31`), ...counts }, + { repositoryId: repository.id, date: new Date(`${year + 1}-01-01`), ...counts }, + ], + }) const repositoryMembership = await prisma.membership.create({ data: { userId: repositoryMember.id }, }) @@ -98,7 +137,8 @@ describe("learning overview repository visibility", () => { const body = await response.text() expect(response.status).toBe(200) - expect(JSON.parse(body)).toMatchObject({ + const state: unknown = JSON.parse(body) + expect(state).toMatchObject({ accessDenied: false, repository: { id: repository.id }, capabilities: { administerHub: true, administerRepository: false }, @@ -108,6 +148,7 @@ describe("learning overview repository visibility", () => { recall: { text: "private learning data", count: 1 }, }) expect(overview).toHaveBeenCalledOnce() + expect(state).toHaveProperty("activity", [{ date: currentDay, ...counts }]) } finally { await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())), diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/solo-setup.db.test.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/solo-setup.db.test.ts index dc92cff4d..45f6a681a 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/solo-setup.db.test.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/solo-setup.db.test.ts @@ -51,7 +51,7 @@ describe("local learning setup", () => { ) const unresolved = await overview() expect(unresolved.localLearningSetupNeeded).toBe(false) - expect(unresolved.loadError).toMatch(/start solo/i) + expect(unresolved.loadError).toMatch(/start local learning mode/i) await writeFile(config, "{") const unusable = await overview() expect(unusable.localLearningSetupNeeded).toBe(false) diff --git a/hub/server/routes/api/learnings/decision/post/index.ts b/hub/server/routes/api/learnings/decision/post/index.ts index 0589858d6..d2fcff6e8 100644 --- a/hub/server/routes/api/learnings/decision/post/index.ts +++ b/hub/server/routes/api/learnings/decision/post/index.ts @@ -14,6 +14,7 @@ const guidance = z .trim() .min(1) .refine((value) => Array.from(value).length <= 4000) +const proposalId = z.string().regex(/^[a-z][a-z0-9]{1,15}_[A-Za-z0-9_-]{8,128}$/) const decisionSchema = z.discriminatedUnion("decision", [ z .object({ @@ -52,6 +53,22 @@ const decisionSchema = z.discriminatedUnion("decision", [ reason: z.string().trim().min(1).max(500), }) .strict(), + z + .object({ + decision: z.literal("apply_update"), + proposalId, + title: z.string().trim().min(1).max(120).optional(), + content: guidance.optional(), + reason: z.string().trim().min(1).max(500), + }) + .strict(), + z + .object({ + decision: z.literal("dismiss_update"), + proposalId, + reason: z.string().trim().min(1).max(500), + }) + .strict(), ]) export function post(dependencies: LearningsRouteDependencies): RequestHandler { return async (request, response, next) => { 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..2f85df13d --- /dev/null +++ b/hub/server/routes/api/learnings/evaluations/get/index.ts @@ -0,0 +1,83 @@ +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 + } + if ( + initial.role !== "ADMINISTRATOR" && + !(await dependencies.authorizeRepositoryAdministration({ + membershipId: initial.membershipId, + repositoryId: repository.id, + })) + ) { + await dependencies.auditRepositoryAdministrationDenial({ + actorMembershipId: initial.membershipId, + repositoryId: repository.id, + operation: "learning_settings", + }) + response.status(403).json({ + code: "repository_administrator_required", + error: "Repository administrator access is required.", + }) + 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, + ...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..11c17d4cf --- /dev/null +++ b/hub/server/routes/api/learnings/evaluations/patch/index.ts @@ -0,0 +1,113 @@ +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() + .refine((value) => Object.keys(value).length > 0) +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_settings", + repositoryId, + }) + return { status: 403, body: denied } + } + return null +} + +/** Rechecks repository and session authority around each evaluation change. */ +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 + } + const updated = await dependencies.changeEvaluationSettings({ + repositoryId: repositoryId.data, + actor: `human:${current.login}`, + actorMembershipId: current.membershipId, + sessionDigest, + ...change.data, + }) + const latest = await readLearningSession(request, dependencies) + if (!latest || latest.membershipId !== current.membershipId) { + response.status(403).json(denied) + return + } + const latestAccess = await checkAccess(dependencies, latest, repositoryId.data) + if (latestAccess) { + response.status(latestAccess.status).json(latestAccess.body) + return + } + response.json(updated) + } catch (error) { + if (!respondLearningError(response, error)) next(error) + } + } +} diff --git a/hub/server/routes/api/learnings/get/index.ts b/hub/server/routes/api/learnings/get/index.ts index 0147aab5a..07fdecd60 100644 --- a/hub/server/routes/api/learnings/get/index.ts +++ b/hub/server/routes/api/learnings/get/index.ts @@ -37,21 +37,22 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { }) const today = new Date().toISOString().slice(0, 10) + const from = new Date(`${today.slice(0, 4)}-01-01`) + const through = new Date(today) const [overview, copilot, runSummary] = await Promise.all([ dependencies.getOverview({ repositoryId: repository.id, viewer: `human:${initial.login}`, + includeShareEligibility: administrator && initial.role === "ADMINISTRATOR", }), dependencies.getCopilot(), administrator ? dependencies.listRuns(repository.id) : null, ]) - const activity = - overview.solo && !overview.localLearningSetupNeeded && !overview.loadError - ? await dependencies.listActivity( - repository.id, - new Date(`${today.slice(0, 4)}-01-01T00:00:00.000Z`), - ) - : [] + const activity = !overview.solo + ? await dependencies.listHostedActivity(repository.id, from, through, administrator) + : overview.localLearningSetupNeeded || overview.loadError + ? [] + : await dependencies.listLocalActivity(repository.id, from, through) 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." }) @@ -75,7 +76,7 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { copilot.state === "connected" && (runSummary.active === null || (runSummary.active.scheduled && runSummary.active.state === "QUEUED")) - const { administratorFollowUp, ...publicOverview } = overview + const { administratorFollowUp, canShareAcrossHub, ...publicOverview } = overview response.json({ accessDenied: false, repository, @@ -84,6 +85,11 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { administerRepository: stillAdministrator, }, permissions: { + share: + !!canShareAcrossHub && + hubLearning && + current.role === "ADMINISTRATOR" && + stillAdministrator, viewEvidence: true, decide: stillAdministrator, requestRun: hubLearning && stillAdministrator && dependencies.requestRun !== undefined, @@ -92,13 +98,18 @@ export function get(dependencies: LearningsRouteDependencies): RequestHandler { automaticRunsEnabled: dependencies.automaticRunsEnabled, usageCredits: hubLearning && stillAdministrator ? runSummary.usageCredits : null, runAvailable, + firstRunNeeded: runAvailable && runSummary.needsReviewConsent === true, ...publicOverview, loadError: [publicOverview.loadError, stillAdministrator && administratorFollowUp] .filter(Boolean) .join(" ") || null, runs: hubLearning && stillAdministrator ? runSummary.runs : [], - activity: overview.solo ? activity : [], + activity: activity.map((day) => { + if (!("runs" in day)) return day + const { lastRun, ...counts } = day + return stillAdministrator && lastRun ? { ...counts, lastRun } : counts + }), today, }) } catch (error) { diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index e2493c4cc..3d196588e 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -1,3 +1,7 @@ +import { get as getEvaluations } from "./evaluations/get/index.ts" +import { patch as patchEvaluations } from "./evaluations/patch/index.ts" +import { get as getAppliedLearnings } from "./applied/get/index.ts" +import { get as getScreenshot } from "./screenshots/get/index.ts" import { once } from "node:events" import { createServer } from "node:http" import type { AddressInfo } from "node:net" @@ -9,6 +13,7 @@ import { hashAuthenticationValue } from "../../../domains/authentication/hash-au import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { LearningExecutionBusyError } from "../../../integrations/postgres/with-learning-execution-lock/errors.ts" import { LearningsError } from "./errors.ts" +import { post as postShare } from "./share/post/index.ts" import { post as postDecision } from "./decision/post/index.ts" import { get as getLearnings } from "./get/index.ts" import { get as getLearningHistory } from "./history/get/index.ts" @@ -51,6 +56,7 @@ function dependencies( learnings: [], recall: { text: "", count: 0 }, }), + share: vi.fn(), getHistory: vi.fn().mockResolvedValue({ decisions: [], evidence: [], @@ -58,6 +64,19 @@ function dependencies( contradictions: [], otherContradictionsCount: 0, }), + getAppliedLearnings: vi.fn().mockResolvedValue([]), + readScreenshot: vi.fn().mockResolvedValue(null), + isScreenshotGrantActive: vi.fn().mockResolvedValue(true), + getEvaluationSettings: vi.fn().mockResolvedValue({ + monthlyBudgetCredits: "0", + usedCredits: "0", + enabled: false, + screenshots: { allowed: false, changedBy: null, changedAt: null }, + notes: { allowed: false, changedBy: null, changedAt: null }, + reviewComments: { allowed: true, changedBy: null, changedAt: null }, + }), + changeEvaluationSettings: vi.fn().mockResolvedValue({ notice: "Learning settings saved." }), + changeEvaluationBudget: vi.fn().mockResolvedValue({ notice: "Budget saved." }), getLearningSettings: vi.fn().mockResolvedValue({ notes: { allowed: false, changedBy: null, changedAt: null }, reviewComments: { allowed: true, changedBy: null, changedAt: null }, @@ -68,7 +87,8 @@ function dependencies( }), getCopilot: vi.fn().mockResolvedValue({ state: "connected", connectedBy: "mona" }), listRuns: vi.fn().mockResolvedValue({ runs: [], usageCredits: "0", active: null }), - listActivity: vi.fn().mockResolvedValue([]), + listLocalActivity: vi.fn().mockResolvedValue([]), + listHostedActivity: vi.fn().mockResolvedValue([]), decide: vi.fn().mockResolvedValue({ notice: "Learning accepted." }), redactComment: vi.fn().mockResolvedValue(undefined), serializeReviewCommentDeletion: (operation) => operation(), @@ -334,7 +354,7 @@ describe("learning routes", () => { usageCredits: "1.25", active: null, }) - const listActivity = vi.fn().mockResolvedValue(activity) + const listLocalActivity = vi.fn().mockResolvedValue(activity) const deps = dependencies({ getOverview: vi.fn().mockResolvedValue({ loadError: null, @@ -346,7 +366,7 @@ describe("learning routes", () => { recall: { text: "", count: 0 }, }), listRuns, - listActivity, + listLocalActivity, requestRun: vi.fn(), }) @@ -362,7 +382,7 @@ describe("learning routes", () => { expect(response.status).toBe(200) expect(await response.json()).toMatchObject({ solo: true, - permissions: { viewEvidence: true, decide: true, requestRun: false }, + permissions: { viewEvidence: true, decide: true, requestRun: false, share: false }, usageCredits: null, runAvailable: false, runs: [], @@ -370,15 +390,30 @@ describe("learning routes", () => { today: new Date().toISOString().slice(0, 10), }) expect(listRuns).toHaveBeenCalledOnce() - expect(listActivity).toHaveBeenCalledWith( + expect(listLocalActivity).toHaveBeenCalledWith( repositoryId, new Date(`${new Date().getUTCFullYear()}-01-01T00:00:00.000Z`), + new Date(new Date().toISOString().slice(0, 10)), ) }, ) }) it("maps the repository administrator overview for a Hub member", async () => { + const activity = [ + { + date: "2026-10-03", + runs: 1, + commentsAnalyzed: 4, + commentsTagged: 2, + suggestions: 1, + lastRun: { + state: "succeeded", + startedAt: "2026-10-03T14:00:00Z", + startedBy: { type: "user", login: "mona" }, + }, + }, + ] const loadError = "Rebuild learning mem_111111111111111111111111. Follow up on export exp_222222222222222222222222 at private/exports/team.json." const evidence = { @@ -432,6 +467,7 @@ describe("learning routes", () => { usageCredits: "0.021", active: null, }), + listHostedActivity: vi.fn().mockResolvedValue(activity), }) await withRoute( @@ -451,13 +487,14 @@ describe("learning routes", () => { administerHub: false, administerRepository: true, }, - permissions: { viewEvidence: true, decide: true, requestRun: false }, + permissions: { viewEvidence: true, decide: true, requestRun: false, share: false }, copilot: { state: "connected", connectedBy: "mona" }, automaticRunsEnabled: true, - activity: [], + activity, today: new Date().toISOString().slice(0, 10), usageCredits: "0.021", runAvailable: false, + firstRunNeeded: false, loadError, identityReviewCount: 1, suggestions: [suggestion], @@ -507,6 +544,18 @@ describe("learning routes", () => { }) it("drops administrator data when repository authority is lost while loading", async () => { + const counts = { + date: "2026-10-03", + runs: 2, + commentsAnalyzed: 4, + commentsTagged: 2, + suggestions: 1, + } + const lastRun = { + state: "failed", + startedAt: "2026-10-03T19:00:00Z", + startedBy: { type: "user", login: "private" }, + } const listRuns = vi.fn().mockResolvedValue({ runs: [{ id: 17 }], usageCredits: "12.5", @@ -518,6 +567,7 @@ describe("learning routes", () => { .mockResolvedValueOnce(true) .mockResolvedValueOnce(false), listRuns, + listHostedActivity: vi.fn().mockResolvedValue([{ ...counts, lastRun }]), }) await withRoute( @@ -539,6 +589,7 @@ describe("learning routes", () => { runs: [], }) expect(listRuns).toHaveBeenCalledOnce() + expect(body).toHaveProperty("activity", [counts]) }, ) }) @@ -899,6 +950,66 @@ describe("learning routes", () => { ) }) + it("shares a learning only for someone who administers both Hub and its repository", async () => { + const digest = `sha256:${"a".repeat(64)}` + const share = vi.fn().mockResolvedValue({ notice: "Shared across Hub." }) + const auditRepositoryAdministrationDenial = vi.fn().mockResolvedValue(undefined) + const administrator = { ...session, role: "ADMINISTRATOR" as const } + const authorizeRepositoryAdministration = vi + .fn() + .mockResolvedValueOnce(false) + .mockResolvedValue(true) + const deps = dependencies({ + currentSession: { + restore: vi + .fn() + .mockResolvedValueOnce(session) + .mockResolvedValueOnce(administrator) + .mockResolvedValue(administrator), + }, + authorizeRepositoryAdministration, + auditRepositoryAdministrationDenial, + share, + }) + + await withRoute( + "post", + "/api/repositories/:repositoryId/learnings/:learningId/share", + postShare(deps), + async (baseUrl) => { + function request() { + return fetch(`${baseUrl}/api/repositories/${repositoryId}/learnings/mem_1/share`, { + method: "POST", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ shared: true, digest }), + }) + } + + const member = await request() + expect(member.status).toBe(403) + const hubAdministratorOnly = await request() + expect(hubAdministratorOnly.status).toBe(403) + expect(auditRepositoryAdministrationDenial).toHaveBeenCalledWith({ + actorMembershipId: session.membershipId, + operation: "learning_share", + repositoryId, + }) + expect(share).not.toHaveBeenCalled() + + const both = await request() + expect(both.status).toBe(200) + expect(share).toHaveBeenCalledWith({ + repositoryId, + learningId: "mem_1", + actorMembershipId: session.membershipId, + shared: true, + digest, + sessionDigest: hashAuthenticationValue("current-session"), + }) + }, + ) + }) + it("surfaces a stale digest as a conflict", async () => { const decide = vi .fn() @@ -997,4 +1108,306 @@ 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("rejects source consent fields on the evaluation endpoint before changing either setting", async () => { + const changeLearningSettings = vi.fn() + const changeEvaluationSettings = vi.fn() + const deps = dependencies({ changeLearningSettings, changeEvaluationSettings }) + await withRoute( + "patch", + "/api/repositories/:repositoryId/learnings/evaluations", + patchEvaluations(deps), + async (base) => { + for (const change of [ + { enabled: true, notes: true }, + { screenshots: true, reviewComments: true }, + ]) { + const response = await fetch( + `${base}/api/repositories/${repositoryId}/learnings/evaluations`, + { + method: "PATCH", + headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify(change), + }, + ) + expect(response.status).toBe(422) + } + expect(changeLearningSettings).not.toHaveBeenCalled() + expect(changeEvaluationSettings).not.toHaveBeenCalled() + }, + ) + }) + + it("withholds the settings once repository authority is lost during the read", async () => { + const deps = dependencies({ + authorizeRepositoryAdministration: vi + .fn() + .mockResolvedValueOnce(true) + .mockResolvedValue(false), + }) + await withRoute( + "get", + "/api/repositories/:repositoryId/learnings/evaluations", + getEvaluations(deps), + async (base) => { + const response = await fetch( + `${base}/api/repositories/${repositoryId}/learnings/evaluations`, + { headers }, + ) + expect(response.status).toBe(403) + expect(await response.text()).not.toContain("monthlyBudgetCredits") + }, + ) + }) + + 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_settings", + 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/screenshots/get/index.ts b/hub/server/routes/api/learnings/screenshots/get/index.ts new file mode 100644 index 000000000..eae15a9c4 --- /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/share/post/index.ts b/hub/server/routes/api/learnings/share/post/index.ts new file mode 100644 index 000000000..58873d59e --- /dev/null +++ b/hub/server/routes/api/learnings/share/post/index.ts @@ -0,0 +1,111 @@ +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 { learningIdSchema } from "../../../../../domains/learning/learning-id/index.ts" +import type { ProductViewer } from "../../../product/types.ts" +import type { LearningsRouteDependencies } from "../../types.ts" + +const shareSchema = z.discriminatedUnion("shared", [ + z.object({ shared: z.literal(true), digest: z.string().regex(/^sha256:[0-9a-f]{64}$/) }).strict(), + z.object({ shared: z.literal(false) }).strict(), +]) +const denied = { + code: "repository_administrator_required", + error: "Hub and repository administrator access is required.", +} + +/** Why a signed-in Hub administrator may not change this repository's shares, 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_share", + repositoryId, + }) + return { status: 403, body: denied } + } + return null +} + +/** + * Shares a learning with every repository in Hub, or stops sharing it. A Hub role alone + * does not speak for one repository's guidance, so the person must also administer the + * repository the learning came from. Access is read twice so a change mid-request counts. + */ +export function post(dependencies: LearningsRouteDependencies): RequestHandler { + return async (request, response, next) => { + try { + const repositoryId = z.uuid().safeParse(request.params.repositoryId) + const learningId = learningIdSchema.safeParse(request.params.learningId) + if (!repositoryId.success || !learningId.success) { + response.status(400).json({ + code: "invalid_learning_address", + error: "Enter a valid learning address.", + }) + return + } + const share = shareSchema.safeParse(request.body) + if (!share.success) { + response.status(422).json({ + code: "invalid_learning_share", + error: "Choose whether to share the learning and try again.", + }) + return + } + const initial = await readLearningSession(request, dependencies) + if (!initial || initial.role !== "ADMINISTRATOR") { + 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 || + current.role !== "ADMINISTRATOR" + ) { + 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.share({ + repositoryId: repositoryId.data, + learningId: learningId.data, + actorMembershipId: current.membershipId, + ...share.data, + sessionDigest, + }), + ) + } 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 1cd8a1b07..95e7aed48 100644 --- a/hub/server/routes/api/learnings/types.ts +++ b/hub/server/routes/api/learnings/types.ts @@ -1,7 +1,11 @@ import type { CurrentSessionDependencies } from "../auth/types.ts" import type { ProductViewer } from "../product/types.ts" import type { + EarlierLearningGuidance, + LearningOutcome, + LearningUpdateSuggestion, AcceptedLearning, + AppliedLearning, LearningActivityDay, LearningDecision, LearningDecisionRecord, @@ -38,6 +42,29 @@ export interface LearningRun { usage: { credits: string; requests: number } | null } +export interface EvaluationSettings { + monthlyBudgetCredits: string + /** What scoring has spent this calendar month in UTC, across every repository. */ + usedCredits: string + enabled: boolean + screenshots: { allowed: boolean; changedBy: string | null; changedAt: string | null } + notes: { allowed: boolean; changedBy: string | null; changedAt: string | null } + reviewComments: { allowed: boolean; changedBy: string | null; changedAt: string | null } +} + +interface HostedActivityDay { + date: string + runs: number + commentsAnalyzed: number + commentsTagged: number + suggestions: number + lastRun?: { + state: "succeeded" | "failed" + startedAt: string + startedBy: LearningRun["startedBy"] + } +} + export interface LearningsRouteDependencies { applicationOrigin: string automaticRunsEnabled: boolean @@ -56,11 +83,21 @@ export interface LearningsRouteDependencies { }): Promise auditRepositoryAdministrationDenial(input: { actorMembershipId: string - operation: "learning_overview" | "learning_run" | "learning_decision" | "learning_settings" + operation: + | "learning_share" + | "learning_overview" + | "learning_run" + | "learning_decision" + | "learning_settings" repositoryId: string }): Promise - getOverview(input: { repositoryId: string; viewer: string }): Promise<{ + getOverview(input: { + repositoryId: string + viewer: string + includeShareEligibility?: boolean + }): Promise<{ administratorFollowUp?: string | null + canShareAcrossHub?: boolean loadError: string | null solo: boolean localLearningSetupNeeded: boolean @@ -68,15 +105,54 @@ export interface LearningsRouteDependencies { suggestions: LearningSuggestion[] learnings: AcceptedLearning[] rejected: RejectedLearning[] + shared?: Array<{ + id: string + title: string | null + content: string | null + source: string + sharedBy: string | null + sharedAt: string + status: "recalled" | "budget-excluded" + }> recall: { text: string; count: number } }> getHistory(input: { repositoryId: string; learningId: string }): Promise<{ + outcomes: LearningOutcome[] + sessions?: { supporting: number; opposing: number } + updateNeedsMoreEvidence: boolean + earlierGuidance: EarlierLearningGuidance[] + updates: LearningUpdateSuggestion[] decisions: LearningDecisionRecord[] evidence: LearningEvidence[] otherEvidenceCount: number contradictions: LearningEvidence[] otherContradictionsCount: 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 + 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 }> getLearningSettings(repositoryId: string): Promise<{ notes: { allowed: boolean; changedBy: string | null; changedAt: string | null } reviewComments: { allowed: boolean; changedBy: string | null; changedAt: string | null } @@ -98,17 +174,32 @@ export interface LearningsRouteDependencies { | { state: "refused"; refusedAt: string | null } > listRuns(repositoryId: string): Promise<{ + needsReviewConsent: boolean runs: LearningRun[] usageCredits: string active: { scheduled: boolean; state: "QUEUED" | "RUNNING" } | null }> - listActivity(repositoryId: string, from: Date): Promise + listLocalActivity(repositoryId: string, from: Date, through: Date): Promise + listHostedActivity( + repositoryId: string, + from: Date, + through: Date, + includeLastRun: boolean, + ): Promise requestRun?: (input: { actorMembershipId: string repositoryId: string requestedById: string sessionDigest: string }) => Promise<{ notice: string }> + share( + input: { + repositoryId: string + learningId: string + actorMembershipId: string + sessionDigest: string + } & ({ shared: true; digest: string } | { shared: false }), + ): Promise<{ notice: string }> decide(input: { repositoryId: string learningId: string diff --git a/hub/server/routes/api/product-index/index.db.test.ts b/hub/server/routes/api/product-index/index.db.test.ts index c21494e15..b7b2fc481 100644 --- a/hub/server/routes/api/product-index/index.db.test.ts +++ b/hub/server/routes/api/product-index/index.db.test.ts @@ -1290,6 +1290,7 @@ describe("real product index", () => { }) vi.spyOn(learnings, "getCopilot").mockResolvedValue({ state: "not-connected" }) vi.spyOn(learnings, "listRuns").mockResolvedValue({ + needsReviewConsent: false, runs: [], usageCredits: "0", active: null, diff --git a/hub/server/routes/api/product/create-product-route-dependencies/index.ts b/hub/server/routes/api/product/create-product-route-dependencies/index.ts index 0c82fa5a1..5328bbb45 100644 --- a/hub/server/routes/api/product/create-product-route-dependencies/index.ts +++ b/hub/server/routes/api/product/create-product-route-dependencies/index.ts @@ -81,6 +81,7 @@ interface CreateProductRouteDependenciesOptions { userId: string, repositoryId: string, ) => Promise + deploymentReviewConsent?: boolean onReviewCommentDeleted?: (input: { repositoryId: string commentId: number @@ -105,6 +106,7 @@ export function createProductRouteDependencies({ scopeGitHubMembers = false, githubReviewDirectory, authorizeReviewMutation, + deploymentReviewConsent, onReviewCommentDeleted, previewBaseOrigin, privatePreviewHubOrigin, @@ -396,6 +398,7 @@ export function createProductRouteDependencies({ } : undefined, reviewComments: createReviewCommentService(prisma, authorizeReview, { + deploymentReviewConsent, onDeleted: onReviewCommentDeleted, withDeleteLock: withReviewCommentDeleteLock, resolveMentions: (input, logins) => mentions.resolve(input, logins), 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 f30670594..9c9addff7 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 @@ -25,6 +25,7 @@ const providerSchema = z.unknown().transform((value, context) => { }) const operationSchema = z.enum(["designate", "revoke"]) const repositoryAdministrationOperationSchema = z.enum([ + "learning_share", "learning_overview", "learning_run", "learning_decision", @@ -102,6 +103,7 @@ function actorFor(record: SecurityAuditListRecord) { case "learning.run.failed": case "repository.administration.learning_overview.denied": case "repository.administration.learning_run.denied": + case "repository.administration.learning_share.denied": case "repository.administration.learning_decision.denied": case "decision.training.requested": case "decision.training.cancelled": @@ -432,6 +434,7 @@ 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", ]) const scheduled = getJobProcessors("scheduled").map(({ name }) => name) expect(scheduled).toContain("learning.recover-runs") - expect(scheduled).toEqual(expect.arrayContaining(["learning.run", "learning.schedule-runs"])) + expect(scheduled).toEqual( + expect.arrayContaining([ + "learning.run", + "learning.schedule-runs", + "learning.score-applied-learnings", + ]), + ) expect(jobSchedules).toContainEqual( expect.objectContaining({ id: "learning-run-recovery", diff --git a/hub/server/workers/configuration.ts b/hub/server/workers/configuration.ts index aa3528277..4905887f8 100644 --- a/hub/server/workers/configuration.ts +++ b/hub/server/workers/configuration.ts @@ -14,6 +14,7 @@ import { } from "../domains/decision-model/jobs/reconcile-runtime-deletions.ts" import { createLearningJobProcessors } from "../domains/learning/create-learning-job-processors/index.ts" import { scheduledMaintenancePriority } from "../domains/learning/jobs/priorities.ts" +import { proposeLearningUpdatesJob } from "../domains/learning/jobs/propose-learning-updates.ts" import { recoverLearningRunsJob } from "../domains/learning/jobs/recover-learning-runs.ts" import { scheduleLearningRunsJob } from "../domains/learning/jobs/schedule-learning-runs.ts" import { getLocalBuildJobDefinition } from "../domains/local-builds/get-local-build-job-definition/index.ts" @@ -75,6 +76,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() @@ -88,6 +90,9 @@ const jobProcessors: Record = { decision.reconcileDeletions, learning.recover, learning.schedule, + learning.score, + learning.proposeUpdates, + learning.proposeUpdate, createJobProcessor(githubInstallationReconciliation, reconcileGitHubInstallation), createJobProcessor(githubBuildImportRetry, retryGitHubBuildsAwaitingImport), createJobProcessor(githubWorkflowRunDiscovery, discoverGitHubWorkflowRunsJob), @@ -146,6 +151,12 @@ export const jobSchedules: { payload: {}, repeat: { pattern: "0 2 * * *", tz: "UTC" }, }, + { + id: "learning-update-daily", + definition: proposeLearningUpdatesJob, + payload: {}, + repeat: { pattern: "0 3 * * *", tz: "UTC" }, + }, { id: "github-installation-reconciliation", definition: githubInstallationReconciliation, diff --git a/hub/server/workers/github-recovery.test.ts b/hub/server/workers/github-recovery.test.ts index 679de006f..4faa6618f 100644 --- a/hub/server/workers/github-recovery.test.ts +++ b/hub/server/workers/github-recovery.test.ts @@ -60,6 +60,7 @@ describe("GitHub recovery workers", () => { listBranchHeads: vi.fn(() => Promise.resolve([])), isAncestor: vi.fn(() => Promise.resolve(false)), getWorkflowRun: vi.fn(() => Promise.resolve(null)), + getCommitDiff: vi.fn(() => Promise.resolve(null)), getCommitAuthor: vi.fn(() => Promise.resolve(null)), listWorkflowRuns: vi.fn(() => Promise.resolve([])), listRunArtifacts: vi.fn(() => Promise.resolve([])), diff --git a/hub/test/database/learning-activity-days-migration/index.db.test.ts b/hub/test/database/learning-activity-days-migration/index.db.test.ts new file mode 100644 index 000000000..2864e04a4 --- /dev/null +++ b/hub/test/database/learning-activity-days-migration/index.db.test.ts @@ -0,0 +1,78 @@ +import { randomBytes, randomUUID } from "node:crypto" +import { readFile, readdir } from "node:fs/promises" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import pg from "pg" +import { describe, expect, it } from "vitest" + +const baseMigration = "20261224120000_repository_learning_settings" + +describe("learning activity days migration", () => { + it("groups earlier finished runs by UTC day, including runs without review comments", async () => { + const url = new URL(process.env.TEST_DATABASE_URL!) + const admin = new pg.Client({ connectionString: url.toString() }) + const name = `replica_activity_days_upgrade_${randomBytes(8).toString("hex")}` + await admin.connect() + try { + await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) + url.pathname = name + const database = new pg.Client({ connectionString: url.toString() }) + try { + await database.connect() + const root = fileURLToPath(new URL("../../../schema/migrations/", import.meta.url)) + const base = (await readdir(root, { withFileTypes: true })) + .filter((entry) => entry.isDirectory() && entry.name <= baseMigration) + .map(({ name }) => name) + .sort() + expect(base.at(-1)).toBe(baseMigration) + for (const migration of base) { + const sql = await readFile(join(root, migration, "migration.sql"), "utf8") + if (migration === "20261104190000_entra_oidc_authentication") { + const lines = sql.split("\n") + await database.query(lines.slice(0, 2).join("\n")) + await database.query(lines.slice(2).join("\n")) + } else await database.query(sql) + } + await database.query("SET TIME ZONE 'Asia/Tokyo'") + const repositoryId = randomUUID() + await database.query( + "INSERT INTO repositories (id, name_with_owner, default_branch) VALUES ($1,'team/design','main')", + [repositoryId], + ) + await database.query( + `INSERT INTO learning_runs ( + id, repository_id, state, review_comments_due, comments_considered, comments_labeled, + suggestions, started_at, created_at, finished_at, failure_code, failure_summary + ) VALUES + (gen_random_uuid(), $1, 'SUCCEEDED', true, 4, 2, 1, '2026-12-01T23:30:00Z', + '2026-12-01T23:00:00Z', '2026-12-02T00:10:00Z', NULL, NULL), + (gen_random_uuid(), $1, 'SUCCEEDED', false, 0, 0, 2, '2026-12-01T09:00:00Z', + '2026-12-01T09:00:00Z', '2026-12-01T09:10:00Z', NULL, NULL), + (gen_random_uuid(), $1, 'FAILED', true, 0, 0, 0, NULL, + '2026-12-01T23:50:00Z', '2026-12-02T00:10:00Z', 'enqueue_failed', 'Not queued.'), + (gen_random_uuid(), $1, 'RUNNING', true, 9, 9, 9, '2026-12-01T12:00:00Z', + '2026-12-01T12:00:00Z', NULL, NULL, NULL)`, + [repositoryId], + ) + + await database.query( + await readFile(join(root, "20261224130000_learning_activity_days/migration.sql"), "utf8"), + ) + + const { rows } = await database.query( + `SELECT date::text, runs, comments_analyzed, comments_tagged, suggestions + FROM learning_activity_days WHERE repository_id = $1`, + [repositoryId], + ) + expect(rows).toEqual([ + { date: "2026-12-01", runs: 3, comments_analyzed: 4, comments_tagged: 2, suggestions: 3 }, + ]) + } finally { + await database.end() + await admin.query(`DROP DATABASE ${pg.escapeIdentifier(name)} WITH (FORCE)`) + } + } finally { + await admin.end() + } + }, 120_000) +}) From 3c6c947dcb1410ddc347986de77b02da97f056a7 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 18:21:27 -0800 Subject: [PATCH 22/32] fix(hub): restore the approved Learnings review experience Bring back the sticky repository bar, activity grid, guidance history, and Build and settings flows from the accepted design. Drive Storybook from the live pages and retain the consent and access boundaries added by the stack. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../hub/learnings-contracts/index.test.ts | 24 +- .../hub/learnings-contracts/index.ts | 209 +++- .../hub/learnings-contracts/types.ts | 107 +- .../requests/get-applied-learnings/index.ts | 16 + .../routes/fixtures/empty-learnings/index.ts | 1 + .../routes/fixtures/preview-handlers/index.ts | 3 + .../hub/routes/learning-agents/index.tsx | 2 +- .../hub/routes/learning-evaluations/index.tsx | 10 + .../routes/learning-settings-flow.test.tsx | 89 +- .../hub/routes/learning-settings/index.tsx | 61 +- .../hub/routes/learnings-flow.test.tsx | 333 +++++- .../application/hub/routes/product-routes.ts | 1 + .../hub/routes/prototype/index.tsx | 33 + .../hub/routes/real-build-history.test.tsx | 5 +- .../hub/routes/route-naming.test.tsx | 3 + .../hub/routes/settings-learnings/index.tsx | 37 +- .../screens/product-form-boundary/styles.css | 1 + .../hub/screens/prototype-screen/index.tsx | 10 +- .../learnings-library/index.test.ts | 35 + .../view-models/learnings-library/index.ts | 229 +++- .../prototype-show-data/index.test.ts | 58 + .../view-models/prototype-show-data/index.ts | 54 + .../view-models/repository-workspace/index.ts | 2 +- .../settings-learnings/index.test.ts | 79 +- .../view-models/settings-learnings/index.ts | 29 +- .../learning-activity-grid/index.test.tsx | 8 +- .../features/learning-activity-grid/index.tsx | 46 +- .../features/learning-activity-grid/types.ts | 15 +- .../features/learnings-library/index.tsx | 1005 ++++++++++++----- .../features/learnings-library/styles.css | 150 ++- .../features/learnings-library/types.ts | 48 + .../styles.css | 12 + .../prototype-workspace-header/index.tsx | 15 +- .../prototype-workspace-header/types.ts | 2 + .../features/prototype-workspace/index.tsx | 3 + .../agent-connections-page/index.test.tsx | 18 + .../pages/agent-connections-page/index.tsx | 25 +- .../pages/agent-connections-page/stories.tsx | 6 +- .../pages/agent-connections-page/types.ts | 2 +- .../automated-evaluations/index.tsx | 169 +++ .../automated-evaluations/styles.css | 83 ++ .../pages/learning-settings-page/index.tsx | 11 +- .../pages/learning-settings-page/stories.tsx | 19 +- .../pages/learning-settings-page/types.ts | 12 +- .../pages/learnings-page/detail/stories.tsx | 150 ++- .../pages/learnings-page/index.test.tsx | 66 +- hub/client/pages/learnings-page/index.tsx | 100 +- hub/client/pages/learnings-page/stories.tsx | 70 +- hub/client/pages/learnings-page/styles.css | 6 +- hub/client/pages/learnings-page/types.ts | 6 +- .../pages/prototypes-show-page/index.test.tsx | 74 ++ .../pages/prototypes-show-page/index.tsx | 58 +- .../pages/prototypes-show-page/stories.tsx | 56 + .../pages/prototypes-show-page/styles.css | 24 + .../pages/prototypes-show-page/types.ts | 18 + hub/client/storybook/fixtures/learnings.ts | 83 +- hub/client/utils/diff-words/index.test.ts | 33 + hub/client/utils/diff-words/index.ts | 91 ++ hub/client/utils/diff-words/types.ts | 4 + hub/docs/README.md | 2 +- hub/docs/development.md | 2 +- hub/docs/learning-foundation.md | 48 +- 62 files changed, 3424 insertions(+), 547 deletions(-) create mode 100644 hub/client/application/hub/requests/get-applied-learnings/index.ts create mode 100644 hub/client/application/hub/routes/learning-evaluations/index.tsx create mode 100644 hub/client/pages/learning-settings-page/automated-evaluations/index.tsx create mode 100644 hub/client/pages/learning-settings-page/automated-evaluations/styles.css create mode 100644 hub/client/utils/diff-words/index.test.ts create mode 100644 hub/client/utils/diff-words/index.ts create mode 100644 hub/client/utils/diff-words/types.ts diff --git a/hub/client/application/hub/learnings-contracts/index.test.ts b/hub/client/application/hub/learnings-contracts/index.test.ts index f75c0de30..456f07877 100644 --- a/hub/client/application/hub/learnings-contracts/index.test.ts +++ b/hub/client/application/hub/learnings-contracts/index.test.ts @@ -30,10 +30,24 @@ describe("Learnings contracts", () => { automaticRunsEnabled: false, solo: false, localLearningSetupNeeded: false, - activity: [], + activity: [ + { + date: "2026-11-10", + runs: 2, + commentsAnalyzed: 4, + commentsTagged: 2, + suggestions: 1, + lastRun: { + state: "failed", + startedAt: "2026-11-10T12:00:00.000Z", + startedBy: { type: "user", login: "mona" }, + }, + }, + ], today: "2026-11-10", usageCredits: "0.0735", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 1, suggestions: [ @@ -120,6 +134,12 @@ describe("Learnings contracts", () => { } expect(learningsResponseSchema.parse(response)).toEqual(response) + expect( + learningsResponseSchema.safeParse({ + ...response, + capabilities: { administerHub: true, administerRepository: false }, + }).success, + ).toBe(false) const soloActivity = { ...response, @@ -142,6 +162,7 @@ describe("Learnings contracts", () => { } expect(learningsResponseSchema.parse(soloActivity)).toEqual(soloActivity) + expect(learningsResponseSchema.safeParse({ ...soloActivity, solo: false }).success).toBe(false) }) it.each([false, true])( @@ -221,6 +242,7 @@ describe("Learnings contracts", () => { usageCredits: "0", runAvailable: false, loadError: null, + firstRunNeeded: false, identityReviewCount: 0, suggestions: [ { diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index 0ba9db9f8..738c636c1 100644 --- a/hub/client/application/hub/learnings-contracts/index.ts +++ b/hub/client/application/hub/learnings-contracts/index.ts @@ -1,3 +1,4 @@ +import type { AppliedLearningsResponse, EvaluationSettingsResponse } from "./types" import { z } from "zod" import { recordIdentifierSchema, repositorySchema } from "@application/hub/contracts" @@ -13,11 +14,13 @@ import type { LearningHistoryResponse, LearningMutationResponse, LearningRunResponse, + LearningShareInput, LearningSettingsInput, LearningSettingsResponse, LearningSuggestionResponse, LearningsResponse, RejectedLearningResponse, + SharedLearningResponse, } from "./types" const identifier = z.number().int().positive() @@ -49,12 +52,15 @@ const replaces = z.array( z.object({ id: learningIdentifier, content: z.string().nullable() }).strict(), ) +const sessions = z.object({ supporting: count, opposing: count }).strict().optional() + export const learningSuggestionResponseSchema = z .object({ id: learningIdentifier, title: title.nullable(), content: guidance, reviewDigest: digest, + sessions, support: z.object({ reviewers: count, prototypes: count }).strict().nullable(), replaces, evidence: z.array(learningEvidenceResponseSchema), @@ -72,17 +78,32 @@ export const acceptedLearningResponseSchema = z digest: digest.nullable(), acceptedBy: z.string().nullable(), acceptedAt: timestamp.nullable(), + shared: z.boolean().optional(), edited: z.boolean(), + shareable: z.boolean().optional(), status: z.enum(["recalled", "not-recalled", "budget-excluded", "damaged", "identity-review"]), }) .strict() satisfies z.ZodType +export const sharedLearningResponseSchema = z + .object({ + id: learningIdentifier, + title: title.nullable(), + content: z.string().nullable(), + source: z.string().min(1), + sharedBy: z.string().nullable(), + sharedAt: timestamp, + status: z.enum(["recalled", "budget-excluded"]), + }) + .strict() satisfies z.ZodType + export const rejectedLearningResponseSchema = z .object({ id: learningIdentifier, title: title.nullable(), content: z.string().nullable(), digest: digest.nullable(), + shared: z.boolean().optional(), state: z.enum(["rejected", "retired"]), replaces, decidedBy: z.string().nullable(), @@ -91,6 +112,35 @@ export const rejectedLearningResponseSchema = z }) .strict() satisfies z.ZodType +const historyScreenshotSchema = z + .object({ sha256: z.string().regex(/^[0-9a-f]{64}$/), route: z.string() }) + .strict() + +const buildSchema = z + .object({ + prototypeId: recordIdentifierSchema, + prototypeName: z.string().min(1), + number: identifier, + }) + .strict() + +const learningOutcomeResponseSchema = z + .object({ + id: z.string().min(1), + source: z.enum(["automated", "reviewer_confirmed"]), + efficiency: z.number().int().min(1).max(4), + followed: z.enum(["followed", "not_followed", "unclear"]), + reasoning: z.string(), + issue: z.string().nullable(), + scoredAt: timestamp, + build: buildSchema, + before: historyScreenshotSchema.optional(), + after: historyScreenshotSchema.optional(), + }) + .strict() + +const proposalId = z.string().regex(/^[a-z][a-z0-9]{1,15}_[A-Za-z0-9_-]{8,128}$/) + export const learningHistoryResponseSchema = z .object({ decisions: z.array( @@ -109,6 +159,31 @@ export const learningHistoryResponseSchema = z otherEvidenceCount: count, contradictions: z.array(learningEvidenceResponseSchema), otherContradictionsCount: count, + updateNeedsMoreEvidence: z.boolean().optional(), + sessions, + outcomes: z.array(learningOutcomeResponseSchema), + earlierGuidance: z.array( + z + .object({ + version: identifier, + title: z.string().nullable(), + content: z.string(), + outcomes: z.array(learningOutcomeResponseSchema), + }) + .strict(), + ), + updates: z.array( + z + .object({ + id: proposalId, + issue: z.string(), + title: z.string().nullable(), + content: z.string(), + reasoning: z.string(), + support: z.array(buildSchema), + }) + .strict(), + ), }) .strict() satisfies z.ZodType @@ -126,32 +201,48 @@ const learningRunResultSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("failed"), summary: z.string().min(1) }).strict(), ]) +const runStarter = z.discriminatedUnion("type", [ + z.strictObject({ type: z.literal("daily") }), + z.strictObject({ type: z.literal("user"), login: z.string().min(1) }), + z.strictObject({ type: z.literal("unknown") }), +]) + export const learningRunResponseSchema = z .object({ id: identifier, startedAt: timestamp, - startedBy: z.discriminatedUnion("type", [ - z.object({ type: z.literal("daily") }).strict(), - z.object({ type: z.literal("user"), login: z.string().min(1) }).strict(), - z.object({ type: z.literal("unknown") }).strict(), - ]), + startedBy: runStarter, state: z.enum(["queued", "running", "succeeded", "failed"]), result: learningRunResultSchema.nullable(), usage: z.object({ credits, requests: identifier }).strict().nullable(), }) .strict() satisfies z.ZodType -const learningActivityDayResponseSchema = z - .object({ - date: z.iso.date(), +const activityCounts = { + date: z.iso.date(), + commentsAnalyzed: count, + commentsTagged: count, + suggestions: count, +} +const learningActivityDayResponseSchema = z.union([ + z.strictObject({ + ...activityCounts, + runs: z.number().int().positive(), + lastRun: z + .strictObject({ + state: z.enum(["succeeded", "failed"]), + startedAt: timestamp, + startedBy: runStarter, + }) + .optional(), + }), + z.strictObject({ + ...activityCounts, runState: z.enum(["succeeded", "failed"]), startedAt: timestamp, - startedBy: z.object({ type: z.literal("agent") }).strict(), - commentsAnalyzed: count, - commentsTagged: count, - suggestions: count, - }) - .strict() + startedBy: z.strictObject({ type: z.literal("agent") }), + }), +]) export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ z @@ -181,6 +272,7 @@ export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ viewEvidence: z.boolean(), decide: z.boolean(), requestRun: z.boolean(), + share: z.boolean().optional(), }) .strict(), copilot: z.discriminatedUnion("state", [ @@ -205,15 +297,24 @@ export const learningsResponseSchema = z.discriminatedUnion("accessDenied", [ today: z.iso.date(), usageCredits: credits.nullable(), runAvailable: z.boolean(), + firstRunNeeded: z.boolean(), loadError: z.string().min(1).nullable(), identityReviewCount: count, suggestions: z.array(learningSuggestionResponseSchema), learnings: z.array(acceptedLearningResponseSchema), rejected: z.array(rejectedLearningResponseSchema), + shared: z.array(sharedLearningResponseSchema).optional(), recall: z.object({ text: z.string(), count }).strict(), runs: z.array(learningRunResponseSchema).max(10), }) - .strict(), + .strict() + .refine( + ({ solo, activity, capabilities }) => + activity.every((day) => + "runs" in day ? !solo && (!day.lastRun || capabilities.administerRepository) : solo, + ), + { message: "The activity details do not match this repository access.", path: ["activity"] }, + ), ]) satisfies z.ZodType export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ @@ -253,8 +354,29 @@ export const learningDecisionInputSchema = z.discriminatedUnion("decision", [ reason: z.string().trim().min(1).max(500), }) .strict(), + z + .object({ + decision: z.literal("apply_update"), + proposalId, + title: title.optional(), + content: guidance.optional(), + reason: z.string().trim().min(1).max(500), + }) + .strict(), + z + .object({ + decision: z.literal("dismiss_update"), + proposalId, + reason: z.string().trim().min(1).max(500), + }) + .strict(), ]) satisfies z.ZodType +export const learningShareInputSchema = z.discriminatedUnion("shared", [ + z.object({ shared: z.literal(true), digest }).strict(), + z.object({ shared: z.literal(false) }).strict(), +]) satisfies z.ZodType + export const learningMutationResponseSchema = z .object({ notice: z.string().min(1) }) .strict() satisfies z.ZodType @@ -282,3 +404,60 @@ export const learningSettingsInputSchema = z }) .strict() .refine((value) => Object.keys(value).length > 0) 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 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(), + notes: z + .object({ + allowed: z.boolean(), + changedBy: z.string().min(1).nullable(), + changedAt: timestamp.nullable(), + }) + .strict(), + reviewComments: 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 52ba093f1..3f4e813ed 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -12,6 +12,7 @@ export interface LearningEvidenceResponse { } export interface LearningSuggestionResponse { + sessions?: { supporting: number; opposing: number } id: string title: string | null content: string @@ -31,6 +32,8 @@ export interface AcceptedLearningResponse { digest: string | null acceptedBy: string | null acceptedAt: string | null + shareable?: boolean + shared?: boolean edited: boolean status: "recalled" | "not-recalled" | "budget-excluded" | "damaged" | "identity-review" } @@ -40,6 +43,7 @@ export interface RejectedLearningResponse { title: string | null content: string | null digest: string | null + shared?: boolean state: "rejected" | "retired" replaces: Array<{ id: string; content: string | null }> decidedBy: string | null @@ -47,7 +51,18 @@ export interface RejectedLearningResponse { reason: string | null } +export interface SharedLearningResponse { + id: string + title: string | null + content: string | null + source: string + sharedBy: string | null + sharedAt: string + status: "recalled" | "budget-excluded" +} + export interface LearningHistoryResponse { + sessions?: { supporting: number; opposing: number } decisions: Array<{ version: number state: "proposed" | "accepted" | "rejected" | "retired" @@ -60,6 +75,44 @@ export interface LearningHistoryResponse { otherEvidenceCount: number contradictions: LearningEvidenceResponse[] otherContradictionsCount: number + outcomes: LearningOutcomeResponse[] + /** Wording agents were given before the current version, newest first. */ + earlierGuidance: Array<{ + version: number + title: string | null + content: string + outcomes: LearningOutcomeResponse[] + }> + /** Suggested new wording waiting for an administrator. */ + updateNeedsMoreEvidence?: boolean + updates: LearningUpdateResponse[] +} + +/** Suggested new wording, drafted because scored uses kept showing the same issue. */ +export interface LearningUpdateResponse { + id: string + issue: string + title: string | null + content: string + reasoning: string + /** The Builds whose scores showed the issue. */ + support: LearningOutcomeResponse["build"][] +} + +/** How one use of a learning was scored, with the Build it judged. */ +export interface LearningOutcomeResponse { + id: string + /** Whether a reviewer confirmed the work before it was scored. */ + source: "automated" | "reviewer_confirmed" + /** 4 is best. 1 and 2 come with an issue. */ + efficiency: number + followed: "followed" | "not_followed" | "unclear" + reasoning: string + issue: string | null + scoredAt: string + build: { prototypeId: string; prototypeName: string; number: number } + before?: { sha256: string; route: string } + after?: { sha256: string; route: string } } export interface LearningRunResponse { @@ -81,15 +134,22 @@ export interface LearningRunResponse { usage: { credits: string; requests: number } | null } -export interface LearningActivityDayResponse { +export type LearningActivityDayResponse = { date: string - runState: "succeeded" | "failed" - startedAt: string - startedBy: { type: "agent" } commentsAnalyzed: number commentsTagged: number suggestions: number -} +} & ( + | { + runs: number + lastRun?: { + state: "succeeded" | "failed" + startedAt: string + startedBy: LearningRunResponse["startedBy"] + } + } + | { runState: "succeeded" | "failed"; startedAt: string; startedBy: { type: "agent" } } +) export type LearningsResponse = | { @@ -101,7 +161,7 @@ export type LearningsResponse = accessDenied: false repository: RepositoryRecord capabilities: { administerHub: boolean; administerRepository: boolean } - permissions: { viewEvidence: boolean; decide: boolean; requestRun: boolean } + permissions: { viewEvidence: boolean; decide: boolean; requestRun: boolean; share?: boolean } copilot: | { state: "connected"; connectedBy: string | null } | { state: "not-connected" } @@ -113,11 +173,13 @@ export type LearningsResponse = today: string usageCredits: string | null runAvailable: boolean + firstRunNeeded: boolean loadError: string | null identityReviewCount: number suggestions: LearningSuggestionResponse[] learnings: AcceptedLearningResponse[] rejected: RejectedLearningResponse[] + shared?: SharedLearningResponse[] recall: { text: string; count: number } runs: LearningRunResponse[] } @@ -128,6 +190,16 @@ export type LearningDecisionInput = | { decision: "retire"; reason: string } | { decision: "edit"; digest: string; title?: string; content?: string; reason: string } | { decision: "reinstate"; digest: string; reason: string } + | { + decision: "apply_update" + proposalId: string + title?: string + content?: string + reason: string + } + | { decision: "dismiss_update"; proposalId: string; reason: string } + +export type LearningShareInput = { shared: true; digest: string } | { shared: false } export interface LearningMutationResponse { notice: string @@ -149,3 +221,26 @@ export interface LearningSettingsInput { notes?: boolean reviewComments?: 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 EvaluationSettingsResponse { + repository: { id: string; nameWithOwner: string; defaultBranch: string } + monthlyBudgetCredits: string + usedCredits: string + enabled: boolean + screenshots: { allowed: boolean; changedBy: string | null; changedAt: string | null } + notes: { allowed: boolean; changedBy: string | null; changedAt: string | null } + reviewComments: { allowed: boolean; changedBy: string | null; changedAt: string | null } + permissions: { changeBudget: boolean; changeRepository: boolean } +} 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 000000000..412330f2a --- /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/empty-learnings/index.ts b/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts index 9c8ace521..bcbb67679 100644 --- a/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts +++ b/hub/client/application/hub/routes/fixtures/empty-learnings/index.ts @@ -16,6 +16,7 @@ export function emptyLearnings( today: new Date().toISOString().slice(0, 10), usageCredits: "0", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 0, suggestions: [], 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 8cd71bac2..2e8c179d5 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/learning-agents/index.tsx b/hub/client/application/hub/routes/learning-agents/index.tsx index e19333e1d..b13229b91 100644 --- a/hub/client/application/hub/routes/learning-agents/index.tsx +++ b/hub/client/application/hub/routes/learning-agents/index.tsx @@ -92,7 +92,7 @@ export default function LearningAgents({ loaderData, params }: Route.ComponentPr data={{ view: "connections", repositoryName: repository?.nameWithOwner ?? "this repository", - mcpUrl: loaderData.mcpUrl, + mcpUrl: repository && !repository.capabilities?.local ? loaderData.mcpUrl : null, signedInAs: workspace?.viewer.login ?? "", connections: loaderData.connections, notice: busy ? null : (fetcher.data?.notice ?? null), 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..c022c5b81 --- /dev/null +++ b/hub/client/application/hub/routes/learning-evaluations/index.tsx @@ -0,0 +1,10 @@ +import { redirect } from "react-router" +import type { LoaderFunctionArgs } from "react-router" + +import { readRecordIdentifier } from "@application/hub/read-record-identifier" + +/** Keep existing evaluation links pointing at the combined Learning settings. */ +export function clientLoader({ params }: LoaderFunctionArgs) { + const id = readRecordIdentifier(params.repositoryId, "repository") + return redirect(`/repositories/${id}/learnings/settings`) +} diff --git a/hub/client/application/hub/routes/learning-settings-flow.test.tsx b/hub/client/application/hub/routes/learning-settings-flow.test.tsx index 8471b8e6e..d2ee9024f 100644 --- a/hub/client/application/hub/routes/learning-settings-flow.test.tsx +++ b/hub/client/application/hub/routes/learning-settings-flow.test.tsx @@ -11,9 +11,18 @@ import { renderHubFlow } from "./fixtures/render-hub-flow" const repository = { id: "2001", nameWithOwner: "github/prototype", defaultBranch: "main" } const settings = `/repositories/${repository.id}/learnings/settings` -function response(notes: boolean, reviewComments: boolean) { +function response(notes: boolean, reviewComments: boolean, reading = false) { return Response.json({ repository, + ...(reading + ? { + enabled: false, + monthlyBudgetCredits: "100", + usedCredits: "4", + screenshots: { allowed: false, changedBy: null, changedAt: null }, + permissions: { changeRepository: true, changeBudget: true }, + } + : {}), notes: { allowed: notes, changedBy: null, changedAt: null }, reviewComments: { allowed: reviewComments, changedBy: null, changedAt: null }, }) @@ -26,7 +35,9 @@ describe("Learning settings", () => { const changes: unknown[] = [] const api = stubHubFetch( ...authenticatedWorkspace([repository]), - http.get(`/api${settings}`, () => response(notesAllowed, commentsAllowed)), + http.get(`/api/repositories/${repository.id}/learnings/evaluations`, () => + response(notesAllowed, commentsAllowed, true), + ), http.patch(`/api${settings}`, async ({ request }) => { const change = (await request.json()) as LearningSettingsInput changes.push(change) @@ -50,12 +61,84 @@ describe("Learning settings", () => { expect(comments).not.toBeChecked() }) + it("saves a Hub budget without allowing that administrator to change repository consent", async () => { + const changes: unknown[] = [] + let budget = "100" + const api = stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(`/api/repositories/${repository.id}/learnings/evaluations`, async () => + Response.json({ + ...(await response(false, true, true).json()), + monthlyBudgetCredits: budget, + permissions: { changeRepository: false, changeBudget: true }, + }), + ), + http.patch("/api/learnings/evaluation-budget", async ({ request }) => { + const change = (await request.json()) as { monthlyBudgetCredits: string } + changes.push(change) + budget = change.monthlyBudgetCredits + return Response.json({ notice: "Budget saved." }) + }), + ) + const router = await renderHubFlow(api, `/repositories/${repository.id}/learnings/evaluations`) + expect(screen.getAllByRole("switch").every((control) => control.hasAttribute("disabled"))).toBe( + true, + ) + fireEvent.change(screen.getByLabelText("Shared Hub budget", { selector: "input" }), { + target: { value: "0.000000001" }, + }) + await router.settle(() => fireEvent.click(screen.getByRole("button", { name: "Save" }))) + expect(changes).toEqual([{ monthlyBudgetCredits: "0.000000001" }]) + expect(screen.getByText("Budget saved.")).toBeInTheDocument() + }) + + it("lets a repository administrator enable evaluations before allowing screenshots", async () => { + let enabled = false + let screenshots = false + const endpoint = `/api/repositories/${repository.id}/learnings/evaluations` + const changes: unknown[] = [] + const router = await renderHubFlow( + stubHubFetch( + ...authenticatedWorkspace([repository]), + http.get(endpoint, async () => + Response.json({ + ...(await response(false, false, true).json()), + enabled, + screenshots: { allowed: screenshots, changedBy: null, changedAt: null }, + permissions: { changeRepository: true, changeBudget: false }, + }), + ), + http.patch(endpoint, async ({ request }) => { + const change = (await request.json()) as { enabled?: boolean; screenshots?: boolean } + changes.push(change) + enabled = change.enabled ?? enabled + screenshots = enabled && (change.screenshots ?? screenshots) + return Response.json({ notice: "Learning settings saved." }) + }), + ), + settings, + ) + const evaluate = screen.getByRole("switch", { name: `Evaluate ${repository.nameWithOwner}` }) + const images = screen.getByRole("switch", { name: "Allow screenshots" }) + expect(screen.queryByRole("textbox", { name: "Shared Hub budget" })).not.toBeInTheDocument() + expect(images).toBeDisabled() + await router.settle(() => fireEvent.click(evaluate)) + await router.settle(() => fireEvent.click(images)) + expect(images).toBeChecked() + await router.settle(() => fireEvent.click(evaluate)) + expect(images).toBeDisabled() + expect(images).not.toBeChecked() + expect(changes).toEqual([{ enabled: true }, { screenshots: true }, { enabled: false }]) + }) + it("blocks both switches during a save and restores the saved choices after failure", async () => { const pending = deferred() onTestFinished(() => pending.resolve()) const api = stubHubFetch( ...authenticatedWorkspace([repository]), - http.get(`/api${settings}`, () => response(false, true)), + http.get(`/api/repositories/${repository.id}/learnings/evaluations`, () => + response(false, true, true), + ), http.patch(`/api${settings}`, async () => { await pending.promise return Response.json({ error: "Hub could not save this setting." }, { status: 503 }) diff --git a/hub/client/application/hub/routes/learning-settings/index.tsx b/hub/client/application/hub/routes/learning-settings/index.tsx index f8e4d379a..bab03e03a 100644 --- a/hub/client/application/hub/routes/learning-settings/index.tsx +++ b/hub/client/application/hub/routes/learning-settings/index.tsx @@ -3,6 +3,8 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router" import { recordIdentifierSchema, workspaceResponseSchema } from "@application/hub/contracts" import { + evaluationSettingsResponseSchema, + learningMutationResponseSchema, learningSettingsInputSchema, learningSettingsResponseSchema, } from "@application/hub/learnings-contracts" @@ -29,8 +31,8 @@ export async function clientLoader({ request, params }: LoaderFunctionArgs) { const id = repositoryId(params) const response = await requestProductJson( request, - `/api/repositories/${id}/learnings/settings`, - learningSettingsResponseSchema, + `/api/repositories/${id}/learnings/evaluations`, + evaluationSettingsResponseSchema, ) if (response.repository.id !== id) { throw new Response("This repository is not available.", { status: 404 }) @@ -46,20 +48,35 @@ export async function clientAction({ request, params }: ActionFunctionArgs) { const form = await request.formData() const setting = form.get("setting") const allowed = form.get("allowed") - const input: LearningSettingsInput = - setting === "notes" && (allowed === "true" || allowed === "false") - ? { notes: allowed === "true" } - : setting === "reviewComments" && (allowed === "true" || allowed === "false") - ? { reviewComments: allowed === "true" } - : {} - const parsed = learningSettingsInputSchema.safeParse(input) - if (!parsed.success) { - return data( - { saved: false, error: "Choose a Learning setting and try again." }, - { status: 422 }, - ) - } try { + if (setting === "monthlyBudgetCredits" || setting === "enabled" || setting === "screenshots") { + const budget = setting === "monthlyBudgetCredits" + if (typeof allowed !== "string" || (!budget && allowed !== "true" && allowed !== "false")) { + return data({ saved: false, error: "Choose a valid evaluation setting." }, { status: 422 }) + } + const result = await requestProductJson( + request, + budget + ? "/api/learnings/evaluation-budget" + : `/api/repositories/${id}/learnings/evaluations`, + learningMutationResponseSchema, + { method: "PATCH", body: { [setting]: budget ? allowed.trim() : allowed === "true" } }, + ) + return data({ saved: true, notice: result.notice }) + } + const input: LearningSettingsInput = + setting === "notes" && (allowed === "true" || allowed === "false") + ? { notes: allowed === "true" } + : setting === "reviewComments" && (allowed === "true" || allowed === "false") + ? { reviewComments: allowed === "true" } + : {} + const parsed = learningSettingsInputSchema.safeParse(input) + if (!parsed.success) { + return data( + { saved: false, error: "Choose a Learning setting and try again." }, + { status: 422 }, + ) + } await requestProductJson( request, `/api/repositories/${id}/learnings/settings`, @@ -71,7 +88,7 @@ export async function clientAction({ request, params }: ActionFunctionArgs) { if (error instanceof Response) { return data({ saved: false, error: await error.text() }, { status: error.status }) } - if (error instanceof ApiRequestError && [403, 404, 409, 502, 503].includes(error.status)) { + if (error instanceof ApiRequestError && [403, 404, 409, 422, 502, 503].includes(error.status)) { return data({ saved: false, error: error.message }, { status: error.status }) } return productActionError(error) @@ -105,6 +122,11 @@ export default function LearningSettings({ ...pageWorkspace, repositoryName: loaderData.repository.nameWithOwner, learningsPath: `/repositories/${loaderData.repository.id}/learnings`, + enabled: loaderData.enabled, + screenshots: loaderData.screenshots, + monthlyBudgetCredits: loaderData.monthlyBudgetCredits, + usedCredits: loaderData.usedCredits, + permissions: loaderData.permissions, notes: loaderData.notes, reviewComments: loaderData.reviewComments, } @@ -117,11 +139,8 @@ export default function LearningSettings({ error={!busy && fetcher.data?.saved === false ? (fetcher.data.error ?? null) : null} notice={!busy && fetcher.data?.saved ? (fetcher.data.notice ?? null) : null} onChange={(change: LearningSettingsChange) => { - const submission = - "notes" in change - ? { setting: "notes", allowed: String(change.notes) } - : { setting: "reviewComments", allowed: String(change.reviewComments) } - void fetcher.submit(submission, { method: "post" }) + const [setting, value] = Object.entries(change)[0]! + void fetcher.submit({ setting, allowed: String(value) }, { method: "post" }) }} /> diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index a8f31d671..2c3ec619b 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -36,6 +36,7 @@ function learningsResponse() { today: "2026-11-10", usageCredits: "0.0945", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 1, suggestions: [ @@ -87,6 +88,7 @@ function learningsResponse() { acceptedAt: "2026-11-08T20:00:00.000Z", edited: true, status: "recalled" as const, + shareable: true, }, { id: "mem_damaged", @@ -135,6 +137,9 @@ function learningsResponse() { function emptyHistory() { return http.get("/api/repositories/2001/learnings/:learningId/history", () => Response.json({ + outcomes: [], + earlierGuidance: [], + updates: [], decisions: [], evidence: [], otherEvidenceCount: 0, @@ -192,6 +197,9 @@ describe("Learnings frontend integration", () => { http.get(`/api/repositories/2001/learnings`, () => Response.json(learningsResponse())), http.get("/api/repositories/2001/learnings/mem_accepted/history", () => Response.json({ + outcomes: [], + earlierGuidance: [], + updates: [], decisions: [ { version: 1, @@ -399,6 +407,213 @@ describe("Learnings frontend integration", () => { expect(screen.getByRole("button", { name: "Edit learning" })).toBeVisible() }) + it("applies edited wording from a suggested update and shows it in the history", async () => { + const original = learningsResponse() + const learning = { + ...original.learnings[0]!, + title: "One primary button", + content: "Use one primary button per form.", + } + const build = { prototypeId: "1", prototypeName: "Checkout", number: 4 } + const score = { + id: "score_12345678", + source: "automated", + efficiency: 2, + followed: "followed", + reasoning: "The button was placed inconsistently.", + issue: "The guidance does not say where the button goes.", + scoredAt: "2026-11-09T20:00:00.000Z", + build, + } + const update = { + id: "update_1234567890abcdef", + issue: score.issue, + title: "Place the primary button", + content: "Put one primary button at the bottom of each form.", + reasoning: "Naming the position removes the guess.", + support: [build, build], + } + const decision = vi.fn() + let applied = false + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...original, + learnings: [ + applied + ? { + ...learning, + title: "Place the main button", + content: "Put the primary button below each form.", + digest: `sha256:${"b".repeat(64)}`, + acceptedBy: "octocat", + acceptedAt: "2026-11-10T12:00:00.000Z", + } + : learning, + ], + }), + ), + http.get("/api/repositories/2001/learnings/mem_accepted/history", () => + Response.json({ + decisions: [ + { + version: 2, + state: "accepted", + change: "accepted", + by: "octocat", + at: "2026-11-08T20:00:00.000Z", + reason: null, + }, + ...(applied + ? [ + { + version: 3, + state: "accepted", + change: "edited", + by: "octocat", + at: "2026-11-10T12:00:00.000Z", + reason: "Make the placement clear.", + }, + ] + : []), + ], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + outcomes: applied ? [] : [score], + earlierGuidance: applied + ? [{ version: 2, title: learning.title, content: learning.content, outcomes: [score] }] + : [], + updates: applied ? [] : [update], + updateNeedsMoreEvidence: false, + }), + ), + http.post("/api/repositories/2001/learnings/mem_accepted/decision", async ({ request }) => { + decision(await request.json()) + applied = true + return Response.json({ notice: "Learning updated." }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const suggestion = await screen.findByRole("region", { name: "Suggested update" }) + + expect(suggestion.querySelector("del")).toBeInTheDocument() + expect(suggestion.querySelector("ins")).toBeInTheDocument() + expect(within(suggestion).getAllByRole("link", { name: "Checkout, Build 4" })).toHaveLength(1) + expect(within(suggestion).getByRole("link", { name: "Checkout, Build 4" })).toHaveAttribute( + "href", + "/repositories/2001/prototypes/1?build=4", + ) + + const form = await submitDialog( + "Apply update", + { + Title: "Place the main button", + Guidance: "Put the primary button below each form.", + "Why apply it?": "Make the placement clear.", + }, + "Apply update", + ) + await router.settle(() => fireEvent.submit(form)) + + expect(decision).toHaveBeenCalledExactlyOnceWith({ + decision: "apply_update", + proposalId: update.id, + title: "Place the main button", + content: "Put the primary button below each form.", + reason: "Make the placement clear.", + }) + expect(screen.getByRole("heading", { name: "Place the main button" })).toBeVisible() + expect(screen.getByText("Put the primary button below each form.")).toBeVisible() + expect(screen.getByRole("region", { name: "Decision history" })).toHaveTextContent( + "Edited by @octocat", + ) + expect(screen.getByRole("region", { name: "Decision history" })).toHaveTextContent( + "Make the placement clear.", + ) + expect(screen.getByRole("region", { name: "Earlier guidance" })).toHaveTextContent( + learning.content, + ) + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + }) + + it("keeps a failed dismissal for retry and removes it without changing the learning", async () => { + const original = learningsResponse() + const learning = original.learnings[0]! + const update = { + id: "update_1234567890abcdef", + issue: "The guidance does not say where the button goes.", + title: null, + content: "Put one primary button at the bottom of each form.", + reasoning: "Naming the position removes the guess.", + support: [{ prototypeId: "1", prototypeName: "Checkout", number: 4 }], + } + const bodies: unknown[] = [] + let dismissed = false + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => Response.json(original)), + http.get("/api/repositories/2001/learnings/mem_accepted/history", () => + Response.json({ + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + outcomes: [], + earlierGuidance: [], + updates: dismissed ? [] : [update], + updateNeedsMoreEvidence: false, + }), + ), + http.post("/api/repositories/2001/learnings/mem_accepted/decision", async ({ request }) => { + bodies.push(await request.json()) + if (bodies.length === 1) { + return Response.json({ error: "Decisions are temporarily unavailable." }, { status: 503 }) + } + dismissed = true + return Response.json({ notice: "Suggested update dismissed." }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const form = await submitDialog( + "Dismiss", + { "Why dismiss it?": "The position depends on the form." }, + "Dismiss", + ) + await router.settle(() => fireEvent.submit(form)) + + const dialog = screen.getByRole("dialog", { name: "Dismiss suggested update" }) + expect(within(dialog).getByRole("alert")).toHaveTextContent( + "Decisions are temporarily unavailable.", + ) + expect(within(dialog).getByRole("textbox", { name: "Why dismiss it?" })).toHaveValue( + "The position depends on the form.", + ) + const retry = within(dialog).getByRole("button", { name: "Dismiss" }).closest("form") + if (!retry) throw new Error("The dismissal control must belong to a form.") + await router.settle(() => fireEvent.submit(retry)) + + expect(bodies).toEqual([ + { + decision: "dismiss_update", + proposalId: update.id, + reason: "The position depends on the form.", + }, + { + decision: "dismiss_update", + proposalId: update.id, + reason: "The position depends on the form.", + }, + ]) + expect(screen.getByText(learning.content!, { selector: "p" })).toBeVisible() + expect(screen.queryByRole("region", { name: "Suggested update" })).not.toBeInTheDocument() + expect(screen.queryByRole("dialog")).not.toBeInTheDocument() + }) + it("shows a changed suggestion's current wording after a stale-digest response", async () => { const server = stubHubFetch(...learningsWorkspace()) const original = learningsResponse() @@ -560,6 +775,116 @@ describe("Learnings frontend integration", () => { expect(bodies).toEqual([{ decision: "reinstate", digest, reason: "External links only." }]) }) + it("asks to share a learning and shows why Hub could not save it", async () => { + const server = stubHubFetch(...learningsWorkspace()) + const bodies: unknown[] = [] + server.use( + http.get(`/api/repositories/2001/learnings`, () => + Response.json({ + ...learningsResponse(), + permissions: { viewEvidence: true, decide: true, requestRun: true, share: true }, + }), + ), + emptyHistory(), + http.post(`/api/repositories/2001/learnings/mem_accepted/share`, async ({ request }) => { + bodies.push(await request.json()) + return Response.json({ error: "Sharing is temporarily unavailable." }, { status: 503 }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings?learning=mem_accepted") + const toggle = await screen.findByRole("switch", { name: "Share across Hub" }) + await router.settle(() => fireEvent.click(toggle)) + + expect(await screen.findByText("Sharing is temporarily unavailable.")).toBeVisible() + expect(bodies).toEqual([{ shared: true, digest }]) + }) + + it("withdraws a saved share without reinstating or revealing a retired learning", async () => { + let shared = true + const bodies: unknown[] = [] + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...learningsResponse(), + permissions: { viewEvidence: true, decide: true, requestRun: true, share: true }, + rejected: [ + { + id: "mem_old", + state: "retired", + shared, + content: null, + title: null, + digest: null, + replaces: [], + reason: null, + decidedBy: null, + decidedAt: null, + }, + ], + }), + ), + emptyHistory(), + http.post("/api/repositories/2001/learnings/mem_old/share", async ({ request }) => { + bodies.push(await request.json()) + shared = false + return Response.json({ notice: "Stopped sharing across Hub." }) + }), + ) + const router = await renderHubFlow( + server, + "/repositories/2001/learnings?status=rejected&learning=mem_old", + ) + const remove = await screen.findByRole("button", { name: "Remove saved share" }) + expect(screen.queryByRole("button", { name: "Accept learning" })).not.toBeInTheDocument() + await router.settle(() => fireEvent.click(remove)) + expect(bodies).toEqual([{ shared: false }]) + expect(screen.queryByRole("button", { name: "Remove saved share" })).not.toBeInTheDocument() + expect( + screen.getByText("This learning's wording is not available for review.", { selector: "p" }), + ).toBeVisible() + }) + + it("shows a learning another repository shared as read-only", async () => { + const historyRequests = vi.fn() + const server = stubHubFetch( + ...learningsWorkspace(), + http.get("/api/repositories/2001/learnings", () => + Response.json({ + ...learningsResponse(), + shared: [ + { + id: "mem_shared", + title: "Keep labels visible", + content: "Show a label above every field.", + source: "github/design-guidelines", + sharedBy: "mona", + sharedAt: "2026-11-07T20:00:00.000Z", + status: "recalled", + }, + ], + }), + ), + http.get("/api/repositories/2001/learnings/:learningId/history", historyRequests), + ) + await renderHubFlow( + server, + "/repositories/2001/learnings?learning=shared%3Agithub%2Fdesign-guidelines%3Amem_shared", + ) + + expect( + await screen.findByText( + "Shared from github/design-guidelines · Read-only in this repository.", + ), + ).toBeVisible() + expect( + screen.getByText("Agents in this repository don't get shared learnings yet."), + ).toBeVisible() + expect(screen.queryByRole("button", { name: "Edit learning" })).not.toBeInTheDocument() + expect(screen.queryByRole("switch", { name: "Share across Hub" })).not.toBeInTheDocument() + expect(historyRequests).not.toHaveBeenCalled() + }) + it("shows a Hub administrator without repository authority a read-only library", async () => { const server = stubHubFetch( ...learningsWorkspace(), @@ -577,7 +902,10 @@ describe("Learnings frontend integration", () => { await renderHubFlow(server, "/repositories/2001/learnings") expect(await screen.findByRole("heading", { name: "Browse learnings" })).toBeVisible() - expect(screen.queryByRole("heading", { name: "Recent runs" })).not.toBeInTheDocument() + expect(screen.getByRole("group", { name: "Daily learning activity for 2026" })).toBeVisible() + expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() + expect(screen.queryByText(/Recent runs/)).not.toBeInTheDocument() + expect(screen.queryByText(/Copilot usage/)).not.toBeInTheDocument() expect(screen.queryByRole("button", { name: "Accept" })).not.toBeInTheDocument() }) @@ -601,7 +929,7 @@ describe("Learnings frontend integration", () => { expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() }) - it("keeps Copilot connection management outside repository Learnings", async () => { + it("warns a repository administrator who cannot connect Copilot without offering that action", async () => { const server = stubHubFetch(...learningsWorkspace()) const response = learningsResponse() server.use( @@ -622,6 +950,7 @@ describe("Learnings frontend integration", () => { screen.getByRole("link", { name: "Show a visible label above every form field." }), ).toBeVisible() expect(screen.queryByRole("button", { name: "Find learnings now" })).not.toBeInTheDocument() + expect(screen.queryByRole("link", { name: /connect copilot/i })).not.toBeInTheDocument() expect(screen.queryByRole("button", { name: /connect copilot/i })).not.toBeInTheDocument() }) diff --git a/hub/client/application/hub/routes/product-routes.ts b/hub/client/application/hub/routes/product-routes.ts index 48bd8d7a0..e1ecaf826 100644 --- a/hub/client/application/hub/routes/product-routes.ts +++ b/hub/client/application/hub/routes/product-routes.ts @@ -13,6 +13,7 @@ export const repositoryProductRoutes: RouteConfigEntry[] = [ route("learnings", "routes/settings-learnings/index.tsx"), route("learnings/agents", "routes/learning-agents/index.tsx"), route("learnings/settings", "routes/learning-settings/index.tsx"), + route("learnings/evaluations", "routes/learning-evaluations/index.tsx"), ] export const workspaceProductRoutes: RouteConfigEntry[] = [ diff --git a/hub/client/application/hub/routes/prototype/index.tsx b/hub/client/application/hub/routes/prototype/index.tsx index ee33992d4..90be850f7 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 || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(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/routes/real-build-history.test.tsx b/hub/client/application/hub/routes/real-build-history.test.tsx index a847d3a84..1261228be 100644 --- a/hub/client/application/hub/routes/real-build-history.test.tsx +++ b/hub/client/application/hub/routes/real-build-history.test.tsx @@ -125,7 +125,10 @@ describe("real Build history", () => { { build: "3" }, ]) expect(screen.queryByRole("link", { name: "Analytics" })).not.toBeInTheDocument() - expect(screen.queryByRole("link", { name: "Learnings" })).not.toBeInTheDocument() + expect(screen.getByRole("link", { name: "Learnings" })).toHaveAttribute( + "href", + `/repositories/${repositoryId}/learnings`, + ) expect(document.querySelector('form[action="/api/auth/session/sign-out"]')).not.toBeNull() expect(document.querySelector('form[action="/session"]')).toBeNull() const history = screen.getByRole("list", { name: "History" }) diff --git a/hub/client/application/hub/routes/route-naming.test.tsx b/hub/client/application/hub/routes/route-naming.test.tsx index 3c7e9b39c..17b8bbd5c 100644 --- a/hub/client/application/hub/routes/route-naming.test.tsx +++ b/hub/client/application/hub/routes/route-naming.test.tsx @@ -147,6 +147,9 @@ describe("Hub primary route names", () => { http.get(`/api${path}/:learningId/history`, () => Response.json({ decisions: [], + outcomes: [], + earlierGuidance: [], + updates: [], evidence: [], otherEvidenceCount: 0, contradictions: [], diff --git a/hub/client/application/hub/routes/settings-learnings/index.tsx b/hub/client/application/hub/routes/settings-learnings/index.tsx index 057f17f59..9c18bdd52 100644 --- a/hub/client/application/hub/routes/settings-learnings/index.tsx +++ b/hub/client/application/hub/routes/settings-learnings/index.tsx @@ -12,6 +12,7 @@ import { learningDecisionInputSchema, learningHistoryResponseSchema, learningMutationResponseSchema, + learningShareInputSchema, learningsResponseSchema, } from "@application/hub/learnings-contracts" import type { ProductActionResult } from "@application/hub/product-contracts/types" @@ -141,7 +142,7 @@ function submitDecision( form: FormData, ) { const prefix = `${route}/` - const suffix = "/decision" + const suffix = source.pathname.endsWith("/share") ? "/share" : "/decision" if (!source.pathname.startsWith(prefix) || !source.pathname.endsWith(suffix)) { throw new Response("This learning action is not connected.", { status: 400 }) } @@ -155,6 +156,20 @@ function submitDecision( throw new Response("Invalid learning identifier.", { status: 400 }) } const path = `/api/repositories/${repositoryId}/learnings/${encodeURIComponent(learningId)}` + if (suffix === "/share") { + const shared = form.get("shared") + const parsed = learningShareInputSchema.safeParse({ + shared: shared === "true" ? true : shared === "false" ? false : shared, + ...(shared === "true" ? { digest: form.get("digest") } : {}), + }) + if (!parsed.success) { + throw new Response("Choose whether to share this learning.", { status: 422 }) + } + return requestProductJson(request, `${path}/share`, learningMutationResponseSchema, { + method: "POST", + body: parsed.data, + }) + } const decision = form.get("decision") const title = form.get("title") const input = @@ -179,7 +194,17 @@ function submitDecision( } : decision === "reinstate" ? { decision, digest: form.get("digest"), reason: form.get("reason") } - : { decision } + : decision === "apply_update" + ? { + decision, + proposalId: form.get("proposalId"), + ...(typeof title === "string" && title.trim() ? { title } : {}), + content: form.get("content"), + reason: form.get("reason"), + } + : decision === "dismiss_update" + ? { decision, proposalId: form.get("proposalId"), reason: form.get("reason") } + : { decision } const parsed = learningDecisionInputSchema.safeParse(input) if (!parsed.success) { throw new Response(parsed.error.issues.map(({ message }) => message).join(" "), { status: 422 }) @@ -220,6 +245,8 @@ function SettingsLearningsContent({ const revalidatedResult = useRef(undefined) const busy = fetcher.state !== "idle" || revalidator.state !== "idle" const result = busy ? undefined : fetcher.data + const page = settingsLearnings(workspace, loaderData, location, loaderData.history) + const detail = !page.accessDenied && page.library.selected !== null useEffect(() => { if (!result?.revalidate || revalidatedResult.current === result) return revalidatedResult.current = result @@ -228,15 +255,13 @@ function SettingsLearningsContent({ return ( { void fetcher.submit(input, { method: "post" }) }} > - + ) } diff --git a/hub/client/application/hub/screens/product-form-boundary/styles.css b/hub/client/application/hub/screens/product-form-boundary/styles.css index c9542bbe5..aae75890b 100644 --- a/hub/client/application/hub/screens/product-form-boundary/styles.css +++ b/hub/client/application/hub/screens/product-form-boundary/styles.css @@ -29,6 +29,7 @@ .hub-product-flow__workspace { position: relative; min-block-size: 0; + overflow: auto; flex: 1; contain: layout; } diff --git a/hub/client/application/hub/screens/prototype-screen/index.tsx b/hub/client/application/hub/screens/prototype-screen/index.tsx index 979d86ddd..df0ffbf57 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/learnings-library/index.test.ts b/hub/client/application/hub/view-models/learnings-library/index.test.ts index 7f5349602..cb9e472d9 100644 --- a/hub/client/application/hub/view-models/learnings-library/index.test.ts +++ b/hub/client/application/hub/view-models/learnings-library/index.test.ts @@ -80,6 +80,9 @@ describe("learningsLibrary()", () => { state, { pathname, search: "?status=rejected&learning=mem_retired" }, { + updates: [], + outcomes: [], + earlierGuidance: [], decisions: [ { version: 1, @@ -157,4 +160,36 @@ describe("learningsLibrary()", () => { const result = learningsLibrary(state, { pathname, search: "?learning=mem_excluded" }, null) expect(result.selected?.facts).toContain("Agents do not currently get this learning.") }) + it("counts the agent sessions a local suggestion came from instead of reviewers", () => { + const state = emptyLearnings() + state.solo = true + state.suggestions = [ + { + id: "mem_local", + title: "Visible field labels", + content: "Show a visible label above every form field.", + reviewDigest: digest, + support: { reviewers: 1, prototypes: 0 }, + replaces: [], + evidence: [], + sessions: { supporting: 2, opposing: 1 }, + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + }, + ] + + const result = learningsLibrary( + state, + { pathname, search: "?status=suggested&learning=mem_local" }, + null, + ) + + expect(result.selected?.facts).toEqual([ + "Found in 2 agent sessions", + "Questioned in 1 agent session", + ]) + expect(result.selected?.otherEvidence).toBeNull() + expect(result.selected?.otherContradictions).toBeNull() + }) }) diff --git a/hub/client/application/hub/view-models/learnings-library/index.ts b/hub/client/application/hub/view-models/learnings-library/index.ts index 41decbe32..ced57895f 100644 --- a/hub/client/application/hub/view-models/learnings-library/index.ts +++ b/hub/client/application/hub/view-models/learnings-library/index.ts @@ -2,12 +2,14 @@ import type { LearningDetail, LearningEvidence, LearningStatus, + LearningOutcome, LearningsLibraryData, LibraryLearning, } from "@features/learnings-library/types" import type { LearningEvidenceResponse, LearningHistoryResponse, + LearningOutcomeResponse, LearningsResponse, } from "@application/hub/learnings-contracts/types" @@ -69,8 +71,47 @@ function evidence(items: LearningEvidenceResponse[], repositoryId: string): Lear })) } +function buildLink(build: LearningOutcomeResponse["build"], repositoryId: string) { + return { + label: `${build.prototypeName}, Build ${build.number}`, + path: `/repositories/${repositoryId}/prototypes/${build.prototypeId}?build=${build.number}`, + } +} + +/** + * Reads each score as a plain result. A score only says something about the guidance + * when the agent followed it, and 3 or 4 means the work went well. + */ +function outcomes(items: LearningOutcomeResponse[], repositoryId: string): LearningOutcome[] { + function screenshot(value?: { sha256: string }) { + return value ? `/api/repositories/${repositoryId}/learnings/screenshots/${value.sha256}` : null + } + return items.toReversed().map((item) => { + const build = buildLink(item.build, repositoryId) + return { + id: item.id, + result: + item.followed !== "followed" + ? "inconclusive" + : item.efficiency >= 3 + ? "supports" + : "concern", + reviewerConfirmed: item.source === "reviewer_confirmed", + summary: item.issue ?? item.reasoning, + buildLabel: build.label, + buildPath: build.path, + evaluatedAt: item.scoredAt, + beforeScreenshotUrl: screenshot(item.before), + afterScreenshotUrl: screenshot(item.after), + } + }) +} + function detailEvidence( - source: Omit | null, + source: Pick< + LearningHistoryResponse, + "evidence" | "otherEvidenceCount" | "contradictions" | "otherContradictionsCount" + > | null, repositoryId: string, ) { return { @@ -109,38 +150,43 @@ export function learningsLibrary( history: LearningHistoryResponse | null, ): LearningsLibraryData { const params = new URLSearchParams(location.search) - const records: LearningRecord[] = [ - ...state.suggestions.map((entry) => ({ + function record( + entry: { id: string; title: string | null }, + status: LearningStatus, + guidance: string, + updatedAt: string | null, + source: LearningRecord["source"] = null, + ): LearningRecord { + return { id: entry.id, - status: "suggested" as const, - title: titleFrom(entry.title, entry.content), - guidance: entry.content, - updatedAt: null, - })), - ...state.learnings.map((entry) => { - const guidance = entry.content ?? unavailableGuidance(entry.status) - return { - id: entry.id, - status: "active" as const, - title: titleFrom(entry.title, guidance), - guidance, - updatedAt: entry.acceptedAt, - } - }), - ...state.rejected.map((entry) => { - const guidance = entry.content ?? unavailableGuidance(null) - return { - id: entry.id, - status: "rejected" as const, - title: titleFrom(entry.title, guidance), - guidance, - updatedAt: entry.decidedAt, - } - }), + status, + title: titleFrom(entry.title, guidance), + guidance, + updatedAt, + source, + } + } + const records = [ + ...state.suggestions.map((entry) => record(entry, "suggested", entry.content, null)), + ...state.learnings.map((entry) => + record(entry, "active", entry.content ?? unavailableGuidance(entry.status), entry.acceptedAt), + ), + ...(state.solo ? [] : (state.shared ?? [])).map((entry) => + record( + { ...entry, id: `shared:${entry.source}:${entry.id}` }, + "active", + entry.content ?? unavailableGuidance(null), + entry.sharedAt, + entry.source, + ), + ), + ...state.rejected.map((entry) => + record(entry, "rejected", entry.content ?? unavailableGuidance(null), entry.decidedAt), + ), ] const counts = { suggested: state.suggestions.length, - active: state.learnings.length, + active: state.learnings.length + (state.solo ? 0 : (state.shared?.length ?? 0)), rejected: state.rejected.length, } // Suggestions need a decision, so they lead until there are none. @@ -197,7 +243,30 @@ function detail( const path = `/repositories/${repositoryId}/learnings/${encodeURIComponent(record.id)}/decision` const canDecide = state.permissions.decide const suggestion = state.suggestions.find((item) => item.id === record.id) + const sessions = (suggestion ?? history)?.sessions + const sessionFacts = + sessions && state.solo + ? [ + ...(sessions.supporting + ? [`Found in ${count(sessions.supporting, "agent session")}`] + : []), + ...(sessions.opposing + ? [`Questioned in ${count(sessions.opposing, "agent session")}`] + : []), + ] + : [] const shared = { + source: record.source, + share: null, + updates: [], + updateNeedsMoreEvidence: false, + outcomes: null, + earlierGuidance: (history?.earlierGuidance ?? []).map((entry) => ({ + version: entry.version, + title: entry.title, + guidance: entry.content, + outcomes: outcomes(entry.outcomes, repositoryId), + })), id: record.id, status: record.status, title: record.title, @@ -213,17 +282,34 @@ function detail( reason: entry.reason, })), } + if (record.source) { + const received = state.shared?.find((item) => `shared:${item.source}:${item.id}` === record.id) + return { + ...shared, + facts: [ + ...(received + ? [ + `Shared${received.sharedBy ? ` by @${received.sharedBy}` : ""} on ${longDate(received.sharedAt)}`, + ] + : []), + "Agents in this repository don't get shared learnings yet.", + ], + decision: null, + } + } if (record.status === "suggested" && suggestion) { return { ...shared, - facts: suggestion.support - ? [ - `Raised by ${count(suggestion.support.reviewers, "reviewer")} on ${count( - suggestion.support.prototypes, - "prototype", - )}`, - ] - : [], + facts: state.solo + ? sessionFacts + : suggestion.support + ? [ + `Raised by ${count(suggestion.support.reviewers, "reviewer")} on ${count( + suggestion.support.prototypes, + "prototype", + )}`, + ] + : [], replaces: replacements(suggestion.replaces), decision: canDecide ? { path, digest: suggestion.reviewDigest, title: "", content: "" } @@ -232,17 +318,64 @@ function detail( } const accepted = state.learnings.find((item) => item.id === record.id) if (record.status === "active" && accepted) { + const receipt = history?.decisions.at(-1) + const verb = + receipt?.change === "edited" + ? "Edited" + : receipt?.change === "reinstated" + ? "Reinstated" + : "Accepted" return { ...shared, + outcomes: accepted.content !== null ? outcomes(history?.outcomes ?? [], repositoryId) : null, + updates: (accepted.content !== null ? (history?.updates ?? []) : []).map((update) => ({ + id: update.id, + issue: update.issue, + title: update.title, + content: update.content, + reasoning: update.reasoning, + // Both scores of one Build can support a suggestion, so each Build is linked once. + support: [ + ...new Map( + update.support.map((build) => { + const link = buildLink(build, repositoryId) + return [link.path, link] + }), + ).values(), + ], + })), + updateNeedsMoreEvidence: history?.updateNeedsMoreEvidence ?? false, + share: + !state.solo && + state.permissions.share && + (accepted.shared || + (accepted.shareable && + accepted.content !== null && + accepted.digest && + ["recalled", "budget-excluded"].includes(accepted.status))) + ? { + path: path.replace(/decision$/, "share"), + shared: accepted.shared ?? false, + digest: accepted.digest, + } + : null, facts: [ ...(accepted.acceptedBy && accepted.acceptedAt ? [ - `Accepted by @${accepted.acceptedBy} on ${longDate(accepted.acceptedAt)}${ - accepted.edited ? ", with edits" : "" + `${verb} by @${accepted.acceptedBy} on ${longDate(accepted.acceptedAt)}${ + verb === "Accepted" && accepted.edited ? ", with edits" : "" }`, ] : []), recallFact(accepted.status), + ...sessionFacts, + ...(accepted.shared + ? [ + accepted.shareable + ? "Shared across Hub" + : "Sharing is paused because this version is no longer eligible.", + ] + : []), ], decision: canDecide && accepted.digest && accepted.content !== null @@ -257,12 +390,24 @@ function detail( } const rejected = state.rejected.find((item) => item.id === record.id) const verb = rejected?.state === "retired" ? "Retired" : "Rejected" + const savedShare = !state.solo && rejected?.shared return { ...shared, - facts: - rejected?.decidedBy && rejected.decidedAt + share: + savedShare && state.permissions.share + ? { path: path.replace(/decision$/, "share"), shared: true } + : null, + facts: [ + ...(rejected?.decidedBy && rejected.decidedAt ? [`${verb} by @${rejected.decidedBy} on ${longDate(rejected.decidedAt)}`] - : [], + : []), + ...sessionFacts, + ...(savedShare + ? [ + "Other repositories cannot see this learning. A share from an earlier version is still saved.", + ] + : []), + ], reason: rejected?.reason ? { heading: `Why it was ${verb.toLowerCase()}`, text: rejected.reason } : null, 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 af14b80cc..caff703ef 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 @@ -143,3 +143,61 @@ it("plays a private Build inline only when it has no legacy review viewer", () = copyPrivatePreviewLinkLabel: "Copy private Hub link", }) }) + +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: null, + 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 f95428bd8..30f4beb98 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 = @@ -117,6 +119,16 @@ export function prototypeShowData( selectedBuild && !previewBuild ? `Build ${selectedBuild.number} · ${buildStateLabel(selectedBuild.state)}` : "Choose build", + ...(selectedBuild?.state === "successful" && appliedLearnings.length > 0 + ? { + agentReportedUseLabel: "Applied learnings", + agentReportedUse: agentReportedUse( + data.repository.id, + selectedBuild.number, + appliedLearnings, + ), + } + : {}), selectedBuild: previewBuild?.previewUrl ? { number: previewBuild.number, @@ -126,3 +138,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/client/application/hub/view-models/repository-workspace/index.ts b/hub/client/application/hub/view-models/repository-workspace/index.ts index 19d2fe4da..c25b484ec 100644 --- a/hub/client/application/hub/view-models/repository-workspace/index.ts +++ b/hub/client/application/hub/view-models/repository-workspace/index.ts @@ -15,7 +15,7 @@ export function repositoryWorkspace(workspace: WorkspaceResponse, repository: Re analyticsLabel: "Analytics", analyticsPath: canManageAnalytics ? `/repositories/${repository.id}/analytics` : null, learningsLabel: "Learnings", - learningsPath: null, + learningsPath: `/repositories/${repository.id}/learnings`, newPrototypeLabel: "Create", newPrototypePath: browseTemplates ? `/repositories/${repository.id}/new` : null, prototypesLabel: "Prototypes", diff --git a/hub/client/application/hub/view-models/settings-learnings/index.test.ts b/hub/client/application/hub/view-models/settings-learnings/index.test.ts index 25db90f39..86a7a4859 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.test.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.test.ts @@ -58,10 +58,25 @@ describe("settingsLearnings()", () => { automaticRunsEnabled: false, solo: false, localLearningSetupNeeded: false, - activity: [], + activity: [ + { date: "2026-11-09", runs: 2, commentsAnalyzed: 3, commentsTagged: 1, suggestions: 1 }, + { + date: "2026-11-10", + runs: 3, + commentsAnalyzed: 6, + commentsTagged: 2, + suggestions: 1, + lastRun: { + state: "failed", + startedAt: "2026-11-10T12:00:00Z", + startedBy: { type: "user", login: "mona" }, + }, + }, + ], today: "2026-11-10", usageCredits: "0", runAvailable: true, + firstRunNeeded: false, loadError: null, identityReviewCount: 0, suggestions: [], @@ -76,6 +91,19 @@ describe("settingsLearnings()", () => { expect(result.accessDenied).toBe(false) if (result.accessDenied) throw new Error("Expected repository learning access.") expect(result.run?.path).toBe("/repositories/2001/learnings/runs") + expect(result.activity).toEqual([ + { ...state.activity[0], runState: "aggregate", startedAt: null, startedBy: null }, + { + date: "2026-11-10", + runs: 3, + commentsAnalyzed: 6, + commentsTagged: 2, + suggestions: 1, + runState: "failed", + startedAt: "2026-11-10T12:00:00Z", + startedBy: "@mona", + }, + ]) expect(result.administrationLinks).toEqual([]) }) @@ -117,17 +145,54 @@ describe("settingsLearnings()", () => { expect(result).not.toHaveProperty("run") }) - it("keeps an explicit run available when Hub has daily runs", () => { - const state = mockState(false) - + it("links a Hub administrator to Copilot setup without granting a repository run", () => { const result = settingsLearnings( + workspace, + { + ...emptyLearnings(true), + capabilities: { administerHub: true, administerRepository: false }, + permissions: { viewEvidence: true, decide: false, requestRun: false }, + copilot: { state: "not-connected" }, + runAvailable: false, + usageCredits: null, + }, + location, + null, + ) + + expect(result).toMatchObject({ copilotPath: "/settings/copilot", run: null }) + }) + + it("offers a run regardless of daily runs but asks for consent only when needed", () => { + const state = mockState(false) + const daily = { ...state.learnings, automaticRunsEnabled: true } + const withoutHistory = settingsLearnings(state.workspace, daily, location, null) + const needsConsent = settingsLearnings( state.workspace, - { ...state.learnings, automaticRunsEnabled: true }, + { + ...daily, + firstRunNeeded: true, + runs: [ + { + id: 1, + startedBy: { type: "daily" }, + startedAt: "2026-11-09T12:00:00Z", + state: "failed", + result: { type: "failed", summary: "Review consent is missing." }, + usage: null, + }, + ], + }, location, null, ) - if (result.accessDenied) throw new Error("Expected repository learning access.") - expect(result.run?.path).toBe("/repositories/2001/learnings/runs") + expect(withoutHistory).toMatchObject({ + run: { path: "/repositories/2001/learnings/runs" }, + firstRunNotice: null, + }) + if (needsConsent.accessDenied) throw new Error("Expected repository learning access.") + expect(needsConsent.run?.path).toBe("/repositories/2001/learnings/runs") + expect(needsConsent.firstRunNotice).toMatch(/allow Hub to learn from .*review comments/i) }) }) 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 96640fc65..b6af084c1 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -48,17 +48,34 @@ export function settingsLearnings( : "" }, so Hub stopped looking for learnings until the token is replaced or checked again on the Copilot page. You can still decide on suggestions, and agents still get accepted learnings.` : null - const activity: LearningActivityDay[] = state.activity.map(({ startedBy, ...day }) => ({ - ...day, - startedBy: startedBy.type === "agent" ? "your agent" : null, - })) + const activity: LearningActivityDay[] = state.activity.map((day) => { + if (!("runs" in day)) return { ...day, startedBy: "your agent" } + const { lastRun, ...counts } = day + if (!lastRun) return { ...counts, runState: "aggregate", startedAt: null, startedBy: null } + return { + ...counts, + runState: lastRun.state, + startedAt: lastRun.startedAt, + startedBy: + lastRun.startedBy.type === "daily" + ? "the daily schedule" + : lastRun.startedBy.type === "user" + ? `@${lastRun.startedBy.login}` + : null, + } + }) return { ...shared, accessDenied: false, copilotWarning, + copilotPath: copilotWarning && state.capabilities.administerHub ? "/settings/copilot" : null, + firstRunNotice: + state.firstRunNeeded && state.permissions.requestRun && !state.solo + ? "Choose Find learnings now to allow Hub to learn from this repository's review comments. You can review what this enables before confirming." + : null, soloNotice: state.solo && !state.localLearningSetupNeeded - ? "These learnings come from Solo in this checkout. Solo looks for new ones after each agent session, and agents here get the ones you accept." + ? "This checkout uses local learning mode. Your agent looks for new learnings after each session, and agents here get the ones you accept." : null, localLearningSetupCommand: state.localLearningSetupNeeded ? "node /packages/learning/bin/replica-learning.mjs setup" @@ -70,7 +87,7 @@ export function settingsLearnings( ? null : `/repositories/${repositoryId}/learnings/agents`, settingsPath: - !state.solo && state.capabilities.administerRepository + !state.solo && (state.capabilities.administerRepository || state.capabilities.administerHub) ? `/repositories/${repositoryId}/learnings/settings` : null, // Keep an explicit run available so repository admins can establish first-run consent. diff --git a/hub/client/features/learning-activity-grid/index.test.tsx b/hub/client/features/learning-activity-grid/index.test.tsx index 6f6354ff7..ab6967fad 100644 --- a/hub/client/features/learning-activity-grid/index.test.tsx +++ b/hub/client/features/learning-activity-grid/index.test.tsx @@ -13,6 +13,7 @@ describe("LearningActivityGrid()", () => { activity={[ { date: "2026-11-18", + runs: 2, runState: "failed", startedAt: "2026-11-18T16:30:00Z", startedBy: "@mona", @@ -22,6 +23,7 @@ describe("LearningActivityGrid()", () => { }, { date: "2026-11-19", + runs: 1, runState: "succeeded", startedAt: "2026-11-19T16:30:00Z", startedBy: "the daily schedule", @@ -36,13 +38,15 @@ describe("LearningActivityGrid()", () => { const calendar = screen.getByRole("group", { name: "Daily learning activity for 2026" }) expect(within(calendar).getAllByRole("button")).toHaveLength(324) - expect(screen.getByText(/Run completed · Started by the daily schedule/)).toBeVisible() + expect( + screen.getByText(/1 learning run · Last run completed · Started by the daily schedule/), + ).toBeVisible() expect(screen.getByText("Suggestions", { selector: "dt" }).parentElement).toHaveTextContent("2") const latest = within(calendar).getByRole("button", { name: /^November 19, 2026,/ }) fireEvent.keyDown(latest, { key: "ArrowUp" }) expect(document.activeElement).toHaveAccessibleName(/^November 18, 2026,.*run failed$/) - expect(screen.getByText(/Run failed · Started by @mona/)).toBeVisible() + expect(screen.getByText(/2 learning runs · Last run failed · Started by @mona/)).toBeVisible() const today = within(calendar).getByRole("button", { name: /^November 20, 2026,/ }) fireEvent.click(today) diff --git a/hub/client/features/learning-activity-grid/index.tsx b/hub/client/features/learning-activity-grid/index.tsx index 27913a7d8..eab5f3522 100644 --- a/hub/client/features/learning-activity-grid/index.tsx +++ b/hub/client/features/learning-activity-grid/index.tsx @@ -31,6 +31,27 @@ function countLabel(value: number, singular: string) { type CalendarCell = { date: string; day: LearningActivityDay | null } +function runSummary(day: LearningActivityDay) { + if (day.runState === "none") return "No learning run" + if (day.runState === "aggregate") return countLabel(day.runs, "learning run") + const status = day.runState === "failed" ? "failed" : "completed" + const parts = [ + day.runs ? `${countLabel(day.runs, "learning run")} · Last run ${status}` : `Run ${status}`, + ] + if (day.startedBy) parts.push(`Started by ${day.startedBy}`) + if (day.startedAt) { + parts.push( + new Intl.DateTimeFormat("en-US", { + hour: "numeric", + minute: "2-digit", + timeZone: "UTC", + timeZoneName: "short", + }).format(new Date(day.startedAt)), + ) + } + return parts.join(" · ") +} + function quietDay(date: string): LearningActivityDay { return { date, @@ -212,11 +233,11 @@ function CalendarYear({ activity, today }: { activity: LearningActivityDay[]; to const value = day[metric] const level = value === 0 ? 0 : Math.min(4, Math.ceil((value / maximum) * 4)) const runLabel = - day.runState === "none" - ? "no run" - : day.runState === "failed" - ? "run failed" - : "run succeeded" + day.runState === "aggregate" + ? countLabel(day.runs, "run") + : day.runState === "none" + ? "no run" + : `${day.runs ? `${countLabel(day.runs, "run")}; last ` : ""}run ${day.runState}` const accessibleLabel = `${dayLabel(day.date)}, ${metricLabel}: ${value}; ${countLabel(day.commentsAnalyzed, "comment")} analyzed, ${countLabel(day.commentsTagged, "comment")} categorized, ${countLabel(day.suggestions, "suggestion")}, ${runLabel}` return ( + + + + ) : learning.status === "active" ? ( + <> + - - + + ) : ( + - - ) : learning.status === "active" ? ( - <> - + ) : ( + +

+ Share across Hub + shareForm.current?.requestSubmit()} + size="small" + /> + {/* The tooltip is visual, so screen readers get the hint here. */} + {shareHint} +
+ + )} + + ) : null} + + + {learning.updates.map((update) => ( + +
+ + Issue: {update.issue} + +
+
+
Title
+
+ {diffText(learning.title, update.title ?? learning.title)} +
+
+
+
Guidance
+
+ + {diffText(learning.guidance, update.content)} + +
+
+
+
+
+ + Why: {update.reasoning} + + {update.support.length ? ( +
+ Seen in + {update.support.map((build) => ( + + {build.label} + + ))} +
+ ) : null} +
+ {decision ? ( +
+ - - - ) : ( - - )} +
+ ) : null} +
+ ))} + + {learning.reason ? ( +
+ + + {learning.reason.heading} + + {learning.reason.text}
) : null} - - - {learning.reason ? ( -
- - - {learning.reason.heading} - - {learning.reason.text} -
- ) : null} - {learning.replaces.length ? ( - -
    - {learning.replaces.map((target) => ( -
  • - - {target.content} - -
  • - ))} -
-
- ) : null} + {learning.replaces.length ? ( + +
    + {learning.replaces.map((target) => ( +
  • + + {target.content} + +
  • + ))} +
+
+ ) : null} - {learning.history.length ? ( - -
    - {learning.history.map((entry, index) => ( -
  • - - {entry.label} - {entry.by ? ` by @${entry.by}` : null} - {entry.at ? ( - <> - {" · "} - - - ) : null} - - {entry.reason ?

    {entry.reason}

    : null} -
  • - ))} -
-
- ) : null} + {learning.evidence.length || learning.otherEvidence ? ( + + + + ) : null} - {learning.evidence.length || learning.otherEvidence ? ( - - - - ) : null} + {learning.contradictions.length || learning.otherContradictions ? ( + + + + ) : null} - {learning.contradictions.length || learning.otherContradictions ? ( - - - - ) : null} + {learning.outcomes ? ( + + + {learning.updateNeedsMoreEvidence ? ( + + Not enough Builds show the same issue to suggest new wording yet. + + ) : null} + + ) : null} - {decision && dialog ? ( - setDialog(null)} - > -

- {dialog === "edit" - ? "This updates the stored guidance. The decision history keeps your reason." - : dialog === "reinstate" - ? "This moves the learning back to Active. The decision history keeps your reason." - : "Agents do not get rejected learnings. You can accept it later."} -

- - {dialog === "edit" ? ( - <> - - Title - - - - Guidance -