diff --git a/hub/client/application/hub/learnings-contracts/index.ts b/hub/client/application/hub/learnings-contracts/index.ts index f2d1708c1..2648befad 100644 --- a/hub/client/application/hub/learnings-contracts/index.ts +++ b/hub/client/application/hub/learnings-contracts/index.ts @@ -143,6 +143,27 @@ export const learningHistoryResponseSchema = z otherEvidenceCount: count, contradictions: z.array(learningEvidenceResponseSchema), otherContradictionsCount: count, + outcomes: z.array( + z + .object({ + id: z.string().min(1), + 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: z + .object({ + prototypeId: recordIdentifierSchema, + prototypeName: z.string().min(1), + number: identifier, + }) + .strict(), + before: appliedScreenshotSchema.optional(), + after: appliedScreenshotSchema.optional(), + }) + .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 65bfd2bf9..dded4ce8d 100644 --- a/hub/client/application/hub/learnings-contracts/types.ts +++ b/hub/client/application/hub/learnings-contracts/types.ts @@ -84,6 +84,21 @@ export interface LearningHistoryResponse { otherEvidenceCount: number contradictions: LearningEvidenceResponse[] otherContradictionsCount: number + outcomes: LearningOutcomeResponse[] +} + +/** How one use of a learning was scored, with the Build it judged. */ +export interface LearningOutcomeResponse { + id: string + /** 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 } } /** A day's learning runs, kept for a year after the runs themselves are deleted. */ 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 67299bcad..5ba96e538 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 @@ -106,6 +106,7 @@ describe("learningsLibrary()", () => { otherEvidenceCount: 2, contradictions: [], otherContradictionsCount: 0, + outcomes: [], }, ) @@ -221,6 +222,7 @@ describe("learningsLibrary()", () => { }, ], otherContradictionsCount: 1, + outcomes: [], }, ) @@ -230,4 +232,75 @@ describe("learningsLibrary()", () => { "1 more opposing comment that Hub cannot show here", ) }) + + it("reads each score as a result, newest first", () => { + const state = emptyLearnings() + state.learnings = [ + { + id: "mem_active", + title: "Keep labels visible", + content: "Show a label above every field.", + digest, + acceptedBy: "hubot", + acceptedAt: "2026-10-09T15:00:00Z", + edited: false, + lastDecision: "accepted", + status: "recalled", + shared: false, + }, + ] + const score = { + reasoning: "The form kept its labels.", + issue: null, + build: { prototypeId: "17", prototypeName: "Checkout", number: 3 }, + } + + const result = learningsLibrary( + state, + { pathname, search: "?status=active&learning=mem_active" }, + { + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + outcomes: [ + { + ...score, + id: "score_not_followed", + efficiency: 4, + followed: "not_followed", + scoredAt: "2026-10-10T00:00:00Z", + }, + { + ...score, + id: "score_concern", + efficiency: 2, + followed: "followed", + issue: "The rule did not say where the label goes.", + scoredAt: "2026-10-11T00:00:00Z", + }, + { + ...score, + id: "score_supports", + efficiency: 3, + followed: "followed", + scoredAt: "2026-10-12T00:00:00Z", + after: { sha256: "b".repeat(64), route: "/checkout" }, + }, + ], + }, + ) + + expect(result.selected?.outcomes?.map((outcome) => [outcome.result, outcome.summary])).toEqual([ + ["supports", "The form kept its labels."], + ["concern", "The rule did not say where the label goes."], + ["inconclusive", "The form kept its labels."], + ]) + expect(result.selected?.outcomes?.[0]).toMatchObject({ + buildPath: "/repositories/2001/prototypes/17?build=3", + beforeScreenshotUrl: null, + afterScreenshotUrl: `/api/repositories/2001/learnings/screenshots/${"b".repeat(64)}`, + }) + }) }) 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 252e88793..4c0eb0a5b 100644 --- a/hub/client/application/hub/view-models/learnings-library/index.ts +++ b/hub/client/application/hub/view-models/learnings-library/index.ts @@ -1,6 +1,7 @@ import type { LearningDetail, LearningEvidence, + LearningOutcome, LearningStatus, LearningsLibraryData, LibraryLearning, @@ -8,6 +9,7 @@ import type { import type { LearningEvidenceResponse, LearningHistoryResponse, + LearningOutcomeResponse, LearningsResponse, } from "@application/hub/learnings-contracts/types" @@ -74,6 +76,27 @@ function evidence(items: LearningEvidenceResponse[], repositoryId: string): Lear })) } +/** + * Reads a 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) => ({ + id: item.id, + result: + item.followed !== "followed" ? "inconclusive" : item.efficiency >= 3 ? "supports" : "concern", + summary: item.issue ?? item.reasoning, + buildLabel: `${item.build.prototypeName}, Build ${item.build.number}`, + buildPath: `/repositories/${repositoryId}/prototypes/${item.build.prototypeId}?build=${item.build.number}`, + evaluatedAt: item.scoredAt, + beforeScreenshotUrl: screenshot(item.before), + afterScreenshotUrl: screenshot(item.after), + })) +} + function parseStatus(value: string | null): LearningStatus | null { return value === "suggested" || value === "active" || value === "rejected" ? value : null } @@ -227,6 +250,8 @@ function detail( by: entry.by?.includes(":") ? null : entry.by, reason: entry.reason, })), + // Only guidance agents get now can have later Builds to judge. + outcomes: record.status === "active" ? outcomes(history?.outcomes ?? [], repositoryId) : null, source: record.source, share: null, } diff --git a/hub/client/features/learnings-library/index.tsx b/hub/client/features/learnings-library/index.tsx index 9e5fe59b0..9e679fc8e 100644 --- a/hub/client/features/learnings-library/index.tsx +++ b/hub/client/features/learnings-library/index.tsx @@ -1,7 +1,9 @@ import { useEffect, useRef, useState, type ReactNode } from "react" import { + AlertIcon, ArrowLeftIcon, CheckCircleIcon, + CircleIcon, LightBulbIcon, SearchIcon, XCircleIcon, @@ -32,6 +34,7 @@ import { ReviewRelativeTime } from "@features/review-relative-time" import type { LearningDetail, LearningEvidence, + LearningOutcome, LearningStatus, LearningsLibraryData, } from "./types" @@ -65,6 +68,19 @@ const emptyMessages: Record = { rejected: "Learnings you reject or stop using stay here so you can accept them again.", } +const outcomeLabels: Record = { + supports: "Supports the guidance", + concern: "Possible concern", + inconclusive: "Inconclusive", +} + +// A result icon sets outcomes apart from review comments, which lead with an avatar. +const outcomeIcons: Record = { + supports: CheckCircleIcon, + concern: AlertIcon, + inconclusive: CircleIcon, +} + /** Renders a learning's state icon; Brand labels need an element, not a component. */ function StatusIcon({ status, className }: { status: LearningStatus; className?: string }) { const Glyph = statusIcons[status] @@ -415,6 +431,15 @@ function LearningDetailView({ ) : null} + {learning.outcomes ? ( + + + + ) : null} + {decision && dialog ? ( + Not evaluated yet. + + ) + } + return ( +
    + {outcomes.map((outcome) => { + const ResultIcon = outcomeIcons[outcome.result] + return ( +
  • +
    + + + {outcomeLabels[outcome.result]} + + + Automated assessment + + {outcome.buildLabel} + + +
    + {outcome.summary ? ( + + {outcome.summary} + + ) : null} + {outcome.beforeScreenshotUrl || outcome.afterScreenshotUrl ? ( +
    + {outcome.beforeScreenshotUrl ? ( + + Before screenshot + + ) : null} + {outcome.afterScreenshotUrl ? ( + + After screenshot + + ) : null} +
    + ) : null} +
  • + ) + })} +
+ ) +} + function EvidenceList({ evidence, other }: { evidence: LearningEvidence[]; other: string | null }) { return ( <> diff --git a/hub/client/features/learnings-library/styles.css b/hub/client/features/learnings-library/styles.css index 59736c6be..f35e68f05 100644 --- a/hub/client/features/learnings-library/styles.css +++ b/hub/client/features/learnings-library/styles.css @@ -335,6 +335,21 @@ color: var(--hub-fg-link); } +.learning-library__outcome-result { + display: inline-flex; + align-items: center; + gap: 0.25rem; + color: var(--hub-fg-default); +} + +.learning-library__outcome-result--supports svg { + color: var(--hub-fg-success); +} + +.learning-library__outcome-result--concern svg { + color: var(--hub-attention); +} + @container (max-width: 40rem) { .learning-library__toolbar { align-items: stretch; diff --git a/hub/client/features/learnings-library/types.ts b/hub/client/features/learnings-library/types.ts index ec9ec7a17..2ecaad322 100644 --- a/hub/client/features/learnings-library/types.ts +++ b/hub/client/features/learnings-library/types.ts @@ -36,6 +36,18 @@ export interface LearningHistoryEntry { } /** Everything the detail view shows for the selected learning. */ +/** How one later Build did with a learning's guidance. */ +export interface LearningOutcome { + id: string + result: "supports" | "concern" | "inconclusive" + summary: string + buildLabel: string + buildPath: string + evaluatedAt: string + beforeScreenshotUrl: string | null + afterScreenshotUrl: string | null +} + export interface LearningDetail { id: string status: LearningStatus @@ -50,6 +62,8 @@ export interface LearningDetail { contradictions: LearningEvidence[] otherContradictions: string | null history: LearningHistoryEntry[] + /** How later Builds did with the current wording. Null when agents don't get it. */ + outcomes: LearningOutcome[] | null /** * Present only when the viewer can decide and the stored version is intact. The * title and content are the stored wording, which the edit form starts from. diff --git a/hub/client/pages/learnings-page/stories.tsx b/hub/client/pages/learnings-page/stories.tsx index 93677d8bd..5f197559c 100644 --- a/hub/client/pages/learnings-page/stories.tsx +++ b/hub/client/pages/learnings-page/stories.tsx @@ -188,6 +188,7 @@ const suggestionDetail: LearningDetail = { contradictions: [], otherContradictions: null, history: [{ label: "Suggested", at: "2026-10-09T04:07:00Z", by: null, reason: null }], + outcomes: null, decision: { path: decisionPath(suggestionId), digest: `sha256:${"a".repeat(64)}`, @@ -220,6 +221,38 @@ const activeDetail: LearningDetail = { reason: "Name the action so the rule is easier to apply.", }, ], + outcomes: [ + { + id: "score-3", + result: "supports", + summary: "The form kept a single primary button named for its action.", + buildLabel: "Checkout, Build 12", + buildPath: "/repositories/2001/prototypes/17?build=12", + evaluatedAt: "2026-10-09T10:00:00Z", + beforeScreenshotUrl: `/api/repositories/2001/learnings/screenshots/${"d".repeat(64)}`, + afterScreenshotUrl: `/api/repositories/2001/learnings/screenshots/${"e".repeat(64)}`, + }, + { + id: "score-2", + result: "concern", + summary: "The rule did not say which button wins when a form has two equal actions.", + buildLabel: "Signup, Build 4", + buildPath: "/repositories/2001/prototypes/18?build=4", + evaluatedAt: "2026-10-08T10:00:00Z", + beforeScreenshotUrl: null, + afterScreenshotUrl: null, + }, + { + id: "score-1", + result: "inconclusive", + summary: "The change did not touch a form, so the guidance did not apply.", + buildLabel: "Checkout, Build 11", + buildPath: "/repositories/2001/prototypes/17?build=11", + evaluatedAt: "2026-10-07T10:00:00Z", + beforeScreenshotUrl: null, + afterScreenshotUrl: null, + }, + ], decision: { path: decisionPath(activeId), digest: `sha256:${"b".repeat(64)}`, @@ -254,6 +287,7 @@ const rejectedDetail: LearningDetail = { reason: "Only external links should open a new tab. This rule would break the back button.", }, ], + outcomes: null, decision: { path: decisionPath(rejectedId), digest: `sha256:${"c".repeat(64)}`, @@ -923,6 +957,10 @@ export const ActiveDetail: Story = { args: { data: { ...data, library: showing(activeDetail) } }, } +export const NotEvaluatedYet: Story = { + args: { data: { ...data, library: showing({ ...activeDetail, outcomes: [] }) } }, +} + export const EditingLearning: Story = { args: { data: { ...data, library: showing(activeDetail) } }, play: async ({ canvas, userEvent }) => { diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index c6348b571..90ce965a3 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -59,7 +59,7 @@ Repository decisions, runs, and redactions use the PostgreSQL advisory-lock prim ## Library page -The Learnings page lists a repository's learnings under Suggested, Active, and Rejected, with a search box and 25 learnings per page. Rejected also holds retired learnings. Selecting a learning opens its guidance, review comments, and decision history in place of the list. Repository administrators accept, edit, reject, and accept again from that view; members see the same view without those actions. +The Learnings page lists a repository's learnings under Suggested, Active, and Rejected, with a search box and 25 learnings per page. Rejected also holds retired learnings. Selecting a learning opens its guidance, review comments, decision history, and [observed outcomes](#observed-outcomes) in place of the list. Repository administrators accept, edit, reject, and accept again from that view; members see the same view without those actions. Above the list, a year grid shows each day's learning runs in the current UTC year, like GitHub's contribution graph. People can shade the squares by comments analyzed, comments categorized, or suggestions, and select a day to see its counts, whether its last run failed, and who started it. For example, a day with two runs reads "Run failed · Started by @mona" when Mona's later run failed. Every member sees the grid. @@ -168,6 +168,16 @@ When an agent's `report_usage` call names a commit, Hub remembers it. A later re - When the budget runs out or Copilot is unavailable, the request waits. The recovery pass tries it again each minute and starts scoring once the budget is raised or the next month begins. Requests that never find a successful Build are dropped after 30 days. - Scoring holds the learning execution lock for each command, so agent calls may briefly get a busy reply while a score runs. +### 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." + +- 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. +- 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` 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 f37067975..e45cbf9d5 100644 --- a/hub/server/domains/learning/get-learning-history/index.test.ts +++ b/hub/server/domains/learning/get-learning-history/index.test.ts @@ -21,7 +21,7 @@ describe("getLearningHistory()", () => { }) it("lists each decision once, including edits, reinstatements, and damaged versions", async () => { - vi.mocked(runLearningCommand).mockResolvedValue({ + vi.mocked(runLearningCommand).mockResolvedValueOnce({ withheld: false, record: { evidence: [] }, versions: [ @@ -69,6 +69,7 @@ describe("getLearningHistory()", () => { { withheld: true }, ], }) + vi.mocked(runLearningCommand).mockResolvedValueOnce({ outcomes: [] }) const result = await getLearningHistory({ applicationRoot: "/app", @@ -112,6 +113,59 @@ describe("getLearningHistory()", () => { expect(runLearningCommand).not.toHaveBeenCalled() }) + it("shows only how the current wording was scored", async () => { + const digest = "c".repeat(64) + const outcome = { + id: "score_1", + commitSha: "a".repeat(40), + prototypeId: "proto_1", + efficiency: 2, + followed: "followed", + reasoning: "The form kept its labels.", + issue: "The rule did not say where the label goes.", + scoredAt: "2026-11-05T00:00:00.000Z", + } + vi.mocked(runLearningCommand) + .mockResolvedValueOnce({ + withheld: false, + record: {}, + versions: [ + { version: 1, state: "accepted", contentDigest: "first wording" }, + { version: 2, state: "accepted", contentDigest: "second wording" }, + { version: 3, state: "retired", contentDigest: "second wording" }, + { version: 4, state: "accepted", contentDigest: "second wording" }, + ], + }) + .mockResolvedValueOnce({ + outcomes: [ + { ...outcome, id: "score_old", version: 1 }, + { + ...outcome, + version: 2, + after: { sha256: `sha256:${digest}`, route: "/checkout", consentGrantId: "grant-1" }, + }, + ], + }) + + 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).toEqual([ + { + ...outcome, + after: { sha256: digest, route: "/checkout", consentGrantId: "grant-1" }, + }, + ]) + }) + it("separates supporting and opposing comments and counts the ones it cannot show", async () => { const comment = { commentId: 1, @@ -137,6 +191,7 @@ describe("getLearningHistory()", () => { }, versions: [], }) + .mockResolvedValueOnce({ outcomes: [] }) .mockResolvedValueOnce({ events: [ { @@ -191,6 +246,7 @@ describe("getLearningHistory()", () => { }, versions: [], }) + .mockResolvedValueOnce({ outcomes: [] }) .mockResolvedValueOnce({ events: [] }) await getLearningHistory({ @@ -205,7 +261,7 @@ describe("getLearningHistory()", () => { staticDirectories: [], }) - const observationArguments = vi.mocked(runLearningCommand).mock.calls[1]?.[0] ?? [] + const observationArguments = vi.mocked(runLearningCommand).mock.calls[2]?.[0] ?? [] expect(observationArguments.filter((argument) => argument === "--event")).toHaveLength(1) expect(observationArguments).toContain("evt_1") expect(observationArguments).not.toContain("evt 2") diff --git a/hub/server/domains/learning/get-learning-history/index.ts b/hub/server/domains/learning/get-learning-history/index.ts index d7fc1c990..652294bcb 100644 --- a/hub/server/domains/learning/get-learning-history/index.ts +++ b/hub/server/domains/learning/get-learning-history/index.ts @@ -10,7 +10,7 @@ import type { LearningEvidenceReference, ReviewCommentLearningSource, } from "../review-comment-learning-source/types.ts" -import type { LearningDecisionRecord, LearningEvidence } from "../types.ts" +import type { LearningDecisionRecord, LearningEvidence, ReportedLearningOutcome } from "../types.ts" const decisionSchema = z .object({ @@ -45,6 +45,7 @@ const versionSchema = z version: z.number().int().positive().optional().catch(undefined), state: z.enum(["proposed", "accepted", "rejected", "retired"]).optional().catch(undefined), digest: z.string().optional().catch(undefined), + contentDigest: z.string().optional().catch(undefined), withheld: z.literal(true).optional(), updatedAt: z.string().optional(), proposal: z @@ -71,6 +72,34 @@ const showSchema = z versions: z.array(versionSchema).optional(), }) .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), + version: z.number().int().positive(), + commitSha: z.string().regex(/^[0-9a-f]{40}$/), + 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 observationsSchema = z .object({ events: z.array( @@ -189,6 +218,7 @@ export async function getLearningHistory(input: { otherEvidenceCount: number contradictions: LearningEvidence[] otherContradictionsCount: number + outcomes: ReportedLearningOutcome[] }> { // The ID is passed to the package as an argument, so it must never read as an option. if (input.learningId.startsWith("-")) { @@ -229,6 +259,17 @@ export async function getLearningHistory(input: { ), ) const history = decisions(shown.versions ?? []) + const outcomes = shown.withheld + ? [] + : currentOutcomes( + outcomesSchema.parse( + await runLearningCommand( + ["outcomes", input.learningId, ...commonArguments], + commandOptions, + ), + ).outcomes, + shown.versions ?? [], + ) const supporting = shown.withheld ? [] : (shown.record.evidence ?? []) const opposing = shown.withheld ? [] : (shown.record.contradictions ?? []) const references = [...supporting, ...opposing] @@ -239,6 +280,7 @@ export async function getLearningHistory(input: { otherEvidenceCount: missingEventCount(supporting, []), contradictions: [], otherContradictionsCount: missingEventCount(opposing, []), + outcomes, } } // The package reads at most 100 events at once, so a detail page shows the first 100. @@ -288,5 +330,41 @@ export async function getLearningHistory(input: { otherEvidenceCount: missingEventCount(supporting, evidence), contradictions, otherContradictionsCount: missingEventCount(opposing, contradictions), + outcomes, + } +} + +// Scores of older wording say nothing about the guidance agents get now. Retiring and +// reinstating add versions with the same wording, so match the wording, not the number. +function currentOutcomes( + outcomes: z.infer["outcomes"], + versions: z.infer[], +): ReportedLearningOutcome[] { + const wording = versions.at(-1)?.contentDigest + if (!wording) return [] + const current = new Set( + versions.filter((entry) => entry.contentDigest === wording).map((entry) => entry.version), + ) + return outcomes + .filter((outcome) => current.has(outcome.version)) + .map((outcome) => ({ + id: outcome.id, + 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/types.ts b/hub/server/domains/learning/types.ts index 3897ff345..2eca01fe8 100644 --- a/hub/server/domains/learning/types.ts +++ b/hub/server/domains/learning/types.ts @@ -95,4 +95,29 @@ export type ReportedAppliedLearning = Omit after?: ReportedScreenshot } +/** 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 + 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 +} + type ReportedScreenshot = { sha256: string; route: string; consentGrantId?: string } diff --git a/hub/server/repositories/prototypes/list-successful-commit-builds/index.ts b/hub/server/repositories/prototypes/list-successful-commit-builds/index.ts new file mode 100644 index 000000000..eedfa8f0f --- /dev/null +++ b/hub/server/repositories/prototypes/list-successful-commit-builds/index.ts @@ -0,0 +1,39 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" +import { reviewablePrototypeWhere } from "../../prototype-index/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), + }, + orderBy: { number: "desc" }, + select: { + commitSha: true, + number: true, + prototype: { select: { id: true, name: true, branchName: true } }, + }, + }) + return builds.flatMap(({ commitSha, number, prototype }) => + commitSha + ? [ + { + commitSha, + number, + prototypeId: prototype.id, + prototypeName: prototype.name ?? prototype.branchName, + }, + ] + : [], + ) +} 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 0ac5fedb8..fbd7d2739 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 @@ -44,6 +44,7 @@ import { saveLearningShare } from "../../../../repositories/learning-shares/save import { withdrawLearningShare } from "../../../../repositories/learning-shares/withdraw-learning-share/index.ts" import { lockAdministratorHubSession } from "../../../../repositories/hub-sessions/lock-administrator-hub-session/index.ts" import { isEffectiveAdministrator } from "../../../../repositories/memberships/is-effective-administrator/index.ts" +import { listSuccessfulCommitBuilds } from "../../../../repositories/prototypes/list-successful-commit-builds/index.ts" import { findActiveRepository } from "../../../../repositories/prototype-index/find-active-repository/index.ts" import { lockRepositoryAdministratorAuthority } from "../../../../repositories/repository-access/lock-repository-administrator-authority/index.ts" import { lockRepositoryAdministratorSession } from "../../../../repositories/repository-access/lock-repository-administrator-session/index.ts" @@ -171,6 +172,19 @@ export async function createLearningsRouteDependencies( * 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. */ + // Offer a screenshot only when it was taken under the consent that is on now, so the + // same image saved under a later grant can't revive one that was withdrawn. + async function consentedScreenshots( + 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 queueScreenshotDeletion(input: { databaseUrl: string grantId: string @@ -307,7 +321,48 @@ export async function createLearningsRouteDependencies( "The repository learning scope changed. Try again.", ) } - return history + const repository = await prisma.repository.findUnique({ + where: { id: repositoryId }, + select: { id: true, defaultBranch: true }, + }) + const builds = repository + ? await listSuccessfulCommitBuilds(prisma, { + repository, + commitShas: [...new Set(history.outcomes.map((outcome) => outcome.commitSha))], + }) + : [] + const consented = await consentedScreenshots(repositoryId, history.outcomes) + return { + ...history, + // A score with no Build left to show is hidden rather than shown without context. + outcomes: history.outcomes.flatMap( + ({ commitSha, prototypeId, before, after, ...outcome }) => { + const build = builds.find( + (candidate) => + candidate.commitSha === commitSha && + (prototypeId === null || candidate.prototypeId === prototypeId), + ) + if (!build) return [] + const shownBefore = consentedScreenshot(consented, before) + const shownAfter = consentedScreenshot(consented, after) + // The scorer's words may describe a screenshot that consent no longer covers. + const withheld = Boolean((before && !shownBefore) || (after && !shownAfter)) + return [ + { + ...outcome, + ...(withheld ? { reasoning: "", issue: null } : {}), + build: { + prototypeId: build.prototypeId, + prototypeName: build.prototypeName, + number: build.number, + }, + ...(shownBefore ? { before: shownBefore } : {}), + ...(shownAfter ? { after: shownAfter } : {}), + }, + ] + }, + ), + } }, getAppliedLearnings: async ({ repositoryId, prototypeId, commitSha }) => { const repositoryScope = await getLearningRepositoryScope(prisma, repositoryId) @@ -324,24 +379,10 @@ export async function createLearningsRouteDependencies( "The repository learning scope changed. Try again.", ) } - // Offer a screenshot only when it was taken under the consent that is on now, so - // the same image saved under a later grant can't revive one that was withdrawn. - const digests = applied.flatMap(({ before, after }) => - [before, after].flatMap((screenshot) => (screenshot ? [screenshot.sha256] : [])), - ) - const consented = - digests.length && options.artifactStorage - ? await findConsentedAgentScreenshots(prisma, { repositoryId, sha256s: digests }) - : null - function shown(screenshot?: { sha256: string; route: string; consentGrantId?: string }) { - if (!screenshot || !consented) return undefined - if (screenshot.consentGrantId !== consented.grantId) return undefined - if (!consented.storageKeys.has(screenshot.sha256)) return undefined - return { sha256: screenshot.sha256, route: screenshot.route } - } + const consented = await consentedScreenshots(repositoryId, applied) return applied.map(({ before, after, ...learning }) => { - const shownBefore = shown(before) - const shownAfter = shown(after) + const shownBefore = consentedScreenshot(consented, before) + const shownAfter = consentedScreenshot(consented, after) return { ...learning, ...(shownBefore ? { before: shownBefore } : {}), @@ -936,3 +977,13 @@ export async function createLearningsRouteDependencies( }, } } + +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 } +} 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..f16c9efb0 --- /dev/null +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/learning-outcomes.db.test.ts @@ -0,0 +1,153 @@ +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) + for (const [prototype, number] of [ + [checkout, 3], + [signup, 7], + [main, 9], + ] as const) { + await prisma.build.create({ + data: { + 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 = { + 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({ + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + 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: signup.id, prototypeName: "Signup", number: 7 }], + ]) + }) + + it("hides the scorer's words when a screenshot it saw 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"), + }, + }) + vi.mocked(getLearningHistory).mockResolvedValue({ + decisions: [], + evidence: [], + otherEvidenceCount: 0, + contradictions: [], + otherContradictionsCount: 0, + outcomes: [ + { + id: "score_with_screenshot", + commitSha, + prototypeId: prototype.id, + efficiency: 2, + followed: "followed", + 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 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") + }) +}) diff --git a/hub/server/routes/api/learnings/types.ts b/hub/server/routes/api/learnings/types.ts index 43a59763d..a0ba332b0 100644 --- a/hub/server/routes/api/learnings/types.ts +++ b/hub/server/routes/api/learnings/types.ts @@ -6,6 +6,7 @@ import type { LearningDecision, LearningDecisionRecord, LearningEvidence, + LearningOutcome, LearningSuggestion, RejectedLearning, SharedLearning, @@ -17,6 +18,7 @@ export type { LearningDecision, LearningDecisionRecord, LearningEvidence, + LearningOutcome, LearningSuggestion, RejectedLearning, SharedLearning, @@ -98,6 +100,7 @@ export interface LearningsRouteDependencies { decisions: LearningDecisionRecord[] evidence: LearningEvidence[] otherEvidenceCount: number + outcomes: LearningOutcome[] }> getAppliedLearnings(input: { repositoryId: string diff --git a/packages/learning/README.md b/packages/learning/README.md index 4309c20a0..8f33f0c61 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -55,6 +55,7 @@ node /packages/learning/bin/replica-learning.mjs doctor | `report-usage ` | Records which recalled learnings an agent says it used for a commit. The report names its own `reportId`, so sending it again stores nothing new. Each used learning names the `deliveryId` recall gave it, and may add a before and an after screenshot as a PNG file beside the report. Only each screenshot's digest is recorded; in a local store the bytes are kept under `evidence/` in the learning data directory. A hosted store keeps no bytes and accepts screenshots only with `--grant `, an active grant for `evaluation` that lists the `agent_screenshots` source. A report is the agent's claim, never a verified result | | `usage --commit ` | Lists the usage reports for one full commit SHA. Each used learning names its ID, the version the agent received, its title and text, and the digest, capture details, and consent grant of any before and after screenshot. Title and text are empty once the learning's evidence no longer allows review. A host uses it to show what was applied in the Build made from that commit | | `score --operation-id ` | Asks Copilot how efficiently one used learning helped, from 1 to 4, and whether the agent followed it, then keeps the score. See [Score applied learnings](#score-applied-learnings) | +| `outcomes ` | Lists how agents' uses of one learning were scored, oldest first. Each outcome names the version the agent received, the commit it reported, the efficiency from 1 to 4, whether the agent followed the learning, the evaluator's reasoning, and any before and after screenshot. Scores of a version whose evidence no longer permits review are left out | | `delete --reason ` | Removes a learning for good: every version, the records of its deliveries and use, and their screenshots. A learning that is part of a replacement, or that a stored proposal would replace, cannot be deleted; retire it instead | | `expire-guidance [--days ]` | Removes guidance records older than `--days`, 365 by default, that no usage report names | | `delete-repository --confirm ` | Removes every record this repository's store holds, including its audit trail. Naming the repository again guards against deleting the wrong store. Copies outside the store, such as exports, are not touched | diff --git a/packages/learning/conformance/index.mjs b/packages/learning/conformance/index.mjs index 68aac0bfc..9b9f21da3 100644 --- a/packages/learning/conformance/index.mjs +++ b/packages/learning/conformance/index.mjs @@ -1615,6 +1615,14 @@ export function memoryProviderConformance({ name, createProvider }) { await store.addGrant(designer(), { ...grantInput(), purposes: ["evaluation"] }) const inputs = await store.evaluationInputs(agent(), { usedLearningId: used.id }) assert.equal(inputs.learning.text, delivery.text) + const outcomes = await store.outcomesFor(designer(), { memoryId: proposal.id }) + assert.deepEqual( + outcomes.map((outcome) => [outcome.version, outcome.commitSha, outcome.issue]), + [ + [inputs.learning.version, "a".repeat(40), "The rule did not say where the label goes."], + [inputs.learning.version, "a".repeat(40), undefined], + ], + ) assert.equal((await store.verify(designer())).ok, true) }) diff --git a/packages/learning/index.d.mts b/packages/learning/index.d.mts index 4c7543ae7..c740a51dd 100644 --- a/packages/learning/index.d.mts +++ b/packages/learning/index.d.mts @@ -1168,6 +1168,30 @@ export interface LearningStore { bytes: Uint8Array | null }> }> + /** + * How agents' uses of one learning were scored, oldest first. Scores of a version whose + * evidence no longer permits review are left out. + */ + outcomesFor( + context: LearningContext, + request: { memoryId: string }, + ): Promise< + Array<{ + id: string + usedLearningId: string + version: number + commitSha: string + prototypeId?: string + efficiency: 1 | 2 | 3 | 4 + followed: "followed" | "not_followed" | "unclear" + reasoning: string + issue?: string + inputs: Array<"screenshots" | "build_diff"> + scoredAt: string + before?: { sha256: string; route: string; consentGrantId?: string } + after?: { sha256: string; route: string; consentGrantId?: string } + }> + > /** The score already kept for one scoring attempt, or null when it has none. */ scoreFor( context: LearningContext, diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index fc156cda5..0e5734f35 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -124,6 +124,7 @@ Use commit, with optional before and after screenshots; --grant names the consent that allows them usage --commit List what agents reported using for one commit + outcomes List how agents' uses of one learning were scored score --operation-id [--diff-file ] [--screenshots ] Score how well one used learning helped, with @@ -333,6 +334,7 @@ export async function main( "recall", "report-usage", "usage", + "outcomes", "score", "delete", "expire-guidance", @@ -446,6 +448,8 @@ async function run(session) { return reportUsage(session) case "usage": return usage(session) + case "outcomes": + return outcomes(session) case "score": return score(session) case "delete": @@ -1493,6 +1497,23 @@ function totals(calls) { } } +async function outcomes(session) { + const memoryId = argument(session, 1, "memory ID") + const { store } = await open(session) + const items = await store.outcomesFor(context(session, actor(session)), { memoryId }) + session.out( + { outcomes: items }, + items.length + ? items + .map( + (item) => + `${item.scoredAt} v${item.version} ${item.commitSha.slice(0, 12)} efficiency ${item.efficiency}, ${item.followed.replace("_", " ")}`, + ) + .join("\n") + : "No scored uses of this learning yet.", + ) +} + /** * Swap each screenshot's file or base64 data for its bytes. The store checks these limits * too, but only after every file is in memory, so the count and total size are checked here diff --git a/packages/learning/src/store.mjs b/packages/learning/src/store.mjs index 8ddff47e8..0ad5e7ee0 100644 --- a/packages/learning/src/store.mjs +++ b/packages/learning/src/store.mjs @@ -3737,6 +3737,82 @@ class LearningStore { } } + /** + * How agents' uses of one learning were scored, oldest first, so a host can show what was + * observed. Each outcome names the version the agent received and the commit it reported. + * A score of a version whose evidence no longer permits review is left out. + */ + async outcomesFor(context, { memoryId } = {}) { + assertContext(context) + if (typeof memoryId !== "string" || !RECORD_ID.test(memoryId)) + throw new LearningError("invalid_input", "Name the learning with its memory ID.") + const scores = (await this.#read("scores", context)).filter( + (record) => record.memoryId === memoryId, + ) + if (!scores.length) return [] + const used = new Map( + ( + await this.#read("usedLearnings", context, { + ids: scores.map((record) => record.usedLearningId), + }) + ).map((record) => [record.id, record]), + ) + const reports = new Map( + ( + await this.#read("usageReports", context, { + ids: scores.map((record) => record.usageReportId), + }) + ).map((record) => [record.id, record]), + ) + const deliveries = new Map( + ( + await this.#read("deliveries", context, { + ids: [...used.values()].map((record) => record.deliveryId), + }) + ).map((record) => [record.id, record]), + ) + const shots = new Map( + (await this.#read("screenshots", context)) + .filter((record) => reports.has(record.usageReportId)) + .map((record) => [record.id, record]), + ) + const delivered = await this.#deliveredVersions(context, "review") + function screenshot(id) { + const record = shots.get(id) + if (!record) return undefined + const { sha256, route, consentGrantId } = record + return { sha256, route, ...(consentGrantId ? { consentGrantId } : {}) } + } + return scores + .sort((a, b) => a.scoredAt.localeCompare(b.scoredAt)) + .flatMap((score) => { + const record = used.get(score.usedLearningId) + const report = reports.get(score.usageReportId) + const delivery = record && deliveries.get(record.deliveryId) + const match = delivery && delivered(memoryId, delivery) + if (!report || !match?.allowed) return [] + const before = screenshot(record.beforeScreenshotId) + const after = screenshot(record.afterScreenshotId) + return [ + { + id: score.id, + usedLearningId: score.usedLearningId, + version: match.version.version, + commitSha: report.commitSha, + ...(report.prototypeId ? { prototypeId: report.prototypeId } : {}), + efficiency: score.efficiency, + followed: score.followed, + reasoning: score.reasoning, + ...(score.issue ? { issue: score.issue } : {}), + inputs: score.inputs, + scoredAt: score.scoredAt, + ...(before ? { before } : {}), + ...(after ? { after } : {}), + }, + ] + }) + } + /** * The score already kept for one scoring attempt, or null. A host checks this before asking * Copilot, so retrying a finished attempt spends nothing.