From 7076e9bd1e73947a2c40f1b51c4e6f7687af8311 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Fri, 27 Nov 2026 19:01:56 -0800 Subject: [PATCH 01/18] feat(hub): list local checkouts when the development API starts Checkouts under the prototype root now appear in a local Hub before their first Build, so their Learnings pages are reachable right away. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/docs/development.md | 4 +- .../index.db.test.ts | 52 ++++++++++++++++++ .../register-local-repositories/index.ts | 49 +++++++++++++++++ hub/server/index.ts | 10 ++++ .../local-builds/prepare-local-build/index.ts | 20 +++---- .../register-local-repository/index.ts | 54 +++++++++++++++++++ 6 files changed, 174 insertions(+), 15 deletions(-) create mode 100644 hub/server/domains/local-development/register-local-repositories/index.db.test.ts create mode 100644 hub/server/domains/local-development/register-local-repositories/index.ts create mode 100644 hub/server/repositories/local-repositories/register-local-repository/index.ts diff --git a/hub/docs/development.md b/hub/docs/development.md index 2202942bd..ce5860d7f 100644 --- a/hub/docs/development.md +++ b/hub/docs/development.md @@ -136,7 +136,9 @@ npm run local:builds:enqueue npm run local:worker ``` -Each scan considers committed heads for the default branch and every other local branch. Hub creates one stable local repository and branch prototype, records the observed head, and creates at most one Build for that exact commit. An unchanged successful or failed head is not rebuilt. A queued or interrupted running Build may resume. Discovery and Build failures are isolated so another repository can still finish. +`npm run dev:api` also lists every checkout under the prototype root as a local repository each time it starts, with the local developer as its administrator. It creates no prototypes or Builds, so a checkout's Learnings page works before its first Build. + +Each scan considers committed heads for the default branch and every other local branch. Hub creates one stable local repository and branch prototype, records the observed head, and creates at most one Build for that exact commit. The local developer becomes the repository's administrator, so repository settings and Learnings decisions work locally. An unchanged successful or failed head is not rebuilt. A queued or interrupted running Build may resume. Discovery and Build failures are isolated so another repository can still finish. From a discovered repository's gallery, choose **Edit prototype listings** to add a draft branch to Hub or change a listed prototype's details. Adding a branch makes it appear in the gallery without creating or changing a Build. The default branch, replicas, deleted branches, and the reserved installation branch do not appear in the list. For a GitHub-backed repository, Hub confirms current Write, Maintain, or Admin permission and checks that a branch still exists before adding it. diff --git a/hub/server/domains/local-development/register-local-repositories/index.db.test.ts b/hub/server/domains/local-development/register-local-repositories/index.db.test.ts new file mode 100644 index 000000000..5a95172e0 --- /dev/null +++ b/hub/server/domains/local-development/register-local-repositories/index.db.test.ts @@ -0,0 +1,52 @@ +import pino from "pino" +import { describe, expect, it, vi } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { registerLocalRepositories } from "." + +const logger = pino({ level: "silent" }) + +describe("registerLocalRepositories()", () => { + it("lists each local checkout for the local developer to administer without running Builds", async () => { + const developer = await prisma.user.create({ + data: { + externalIdentities: { + create: { provider: "local", issuer: "local", subject: "local-developer" }, + }, + }, + }) + const membership = await prisma.membership.create({ data: { userId: developer.id } }) + const discover = vi.fn().mockResolvedValue({ + failures: [], + repositories: [ + { + path: "/prototypes/learning-demo", + name: "learning-demo", + defaultBranch: "main", + branches: [], + }, + ], + }) + + await registerLocalRepositories({ + database: prisma, + prototypeRoot: "/prototypes", + logger, + discover, + }) + + const repository = await prisma.repository.findUniqueOrThrow({ + where: { localPath: "/prototypes/learning-demo" }, + select: { + nameWithOwner: true, + accessGrants: { select: { membershipId: true, accessLevel: true } }, + prototypes: { select: { id: true } }, + }, + }) + expect(repository).toEqual({ + nameWithOwner: "local/learning-demo", + accessGrants: [{ membershipId: membership.id, accessLevel: "ADMIN" }], + prototypes: [], + }) + }) +}) diff --git a/hub/server/domains/local-development/register-local-repositories/index.ts b/hub/server/domains/local-development/register-local-repositories/index.ts new file mode 100644 index 000000000..a3e134dab --- /dev/null +++ b/hub/server/domains/local-development/register-local-repositories/index.ts @@ -0,0 +1,49 @@ +import type { Logger } from "pino" + +import type { PrismaClient } from "../../../generated/prisma/client.ts" +import { discoverLocalRepositories } from "../../../integrations/git/discover-local-repositories/index.ts" +import type { LocalRepositoryDiscovery } from "../../../integrations/git/discover-local-repositories/types.ts" +import { findLocalDeveloper } from "../../../repositories/local-builds/find-local-developer/index.ts" +import { registerLocalRepository } from "../../../repositories/local-repositories/register-local-repository/index.ts" + +/** + * Lists every checkout under the local prototype root in Hub when the development API + * starts. People can then open Learnings for a checkout without running local Builds + * first. Builds stay opt-in because they can be slow. + */ +export async function registerLocalRepositories({ + database, + prototypeRoot, + logger, + discover = discoverLocalRepositories, +}: { + database: PrismaClient + prototypeRoot: string + logger: Logger + discover?: (root: string) => Promise +}) { + const localDeveloper = await findLocalDeveloper(database) + if (!localDeveloper) { + logger.info("Sign in as the local developer, then restart to list local checkouts") + return { registered: 0 } + } + const discovery = await discover(prototypeRoot) + for (const failure of discovery.failures) { + logger.warn( + { repositoryPath: failure.path, errorType: failure.errorType }, + "Local repository discovery failed", + ) + } + for (const repository of discovery.repositories) { + await database.$transaction((transaction) => + registerLocalRepository(transaction, { + repositoryPath: repository.path, + repositoryName: repository.name, + defaultBranch: repository.defaultBranch, + localUserId: localDeveloper.userId, + }), + ) + } + logger.info({ registered: discovery.repositories.length }, "Local checkouts listed in Hub") + return { registered: discovery.repositories.length } +} diff --git a/hub/server/index.ts b/hub/server/index.ts index c86bea253..5c12c0214 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -167,6 +167,16 @@ try { const { createAuthenticationRouteDependencies, disableAuthenticationProviders } = await import("./routes/api/auth/create-authentication-route-dependencies/index.ts") try { + if (localDevelopment.enabled) { + const { prisma } = await import("./integrations/prisma/index.ts") + const { registerLocalRepositories } = + await import("./domains/local-development/register-local-repositories/index.ts") + await registerLocalRepositories({ + database: prisma, + prototypeRoot: localDevelopment.root, + logger, + }) + } if (authenticationConfiguration.providerConfigured) { authentication = await createAuthenticationRouteDependencies(authenticationEnvironment) const previewConfigured = storage && authenticationEnvironment.HUB_PREVIEW_ORIGIN diff --git a/hub/server/repositories/local-builds/prepare-local-build/index.ts b/hub/server/repositories/local-builds/prepare-local-build/index.ts index 25d95099a..ed55b3c09 100644 --- a/hub/server/repositories/local-builds/prepare-local-build/index.ts +++ b/hub/server/repositories/local-builds/prepare-local-build/index.ts @@ -1,5 +1,6 @@ import { Prisma, type PrismaClient } from "../../../generated/prisma/client.ts" +import { registerLocalRepository } from "../../local-repositories/register-local-repository/index.ts" import type { PrepareLocalBuildInput, PreparedLocalBuild } from "./types.ts" export async function prepareLocalBuild( @@ -10,24 +11,15 @@ export async function prepareLocalBuild( activity: { repositoryId: string; prototypeId: string }, ) => Promise, ): Promise { - const nameWithOwner = `local/${input.repositoryName}`.slice(0, 255) for (let attempt = 0; ; attempt += 1) { try { return await database.$transaction( async (transaction) => { - const repository = await transaction.repository.upsert({ - where: { localPath: input.repositoryPath }, - create: { - nameWithOwner, - defaultBranch: input.defaultBranch, - localPath: input.repositoryPath, - }, - update: { - nameWithOwner, - defaultBranch: input.defaultBranch, - removedAt: null, - }, - select: { id: true }, + const repository = await registerLocalRepository(transaction, { + repositoryPath: input.repositoryPath, + repositoryName: input.repositoryName, + defaultBranch: input.defaultBranch, + localUserId: input.localUserId, }) let prototype = await transaction.prototype.findFirst({ where: { diff --git a/hub/server/repositories/local-repositories/register-local-repository/index.ts b/hub/server/repositories/local-repositories/register-local-repository/index.ts new file mode 100644 index 000000000..6a9c001c5 --- /dev/null +++ b/hub/server/repositories/local-repositories/register-local-repository/index.ts @@ -0,0 +1,54 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Records one checkout on this machine as a Hub repository. The local developer owns + * every checkout here, so they administer it too. Without that grant, local Hub can't + * accept learnings or show Analytics. + */ +export async function registerLocalRepository( + transaction: Prisma.TransactionClient, + input: { + repositoryPath: string + repositoryName: string + defaultBranch: string + localUserId: string + }, +) { + const nameWithOwner = `local/${input.repositoryName}`.slice(0, 255) + const repository = await transaction.repository.upsert({ + where: { localPath: input.repositoryPath }, + create: { + nameWithOwner, + defaultBranch: input.defaultBranch, + localPath: input.repositoryPath, + }, + update: { + nameWithOwner, + defaultBranch: input.defaultBranch, + removedAt: null, + }, + select: { id: true }, + }) + const membership = await transaction.membership.findUnique({ + where: { userId: input.localUserId }, + select: { id: true }, + }) + if (membership) { + await transaction.repositoryAccessGrant.upsert({ + where: { + membershipId_repositoryId: { + membershipId: membership.id, + repositoryId: repository.id, + }, + }, + create: { + membershipId: membership.id, + repositoryId: repository.id, + accessLevel: "ADMIN", + observedAt: new Date(), + }, + update: { accessLevel: "ADMIN" }, + }) + } + return repository +} From fb5dca81f52a9022f9341eb8f7516ce4a07fbc98 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 20:45:44 -0800 Subject: [PATCH 02/18] feat(hub): add the Learnings library list and detail views Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../learnings-library/index.test.ts | 120 +++++ .../view-models/learnings-library/index.ts | 273 ++++++++++ .../features/learnings-library/index.tsx | 493 ++++++++++++++++++ .../features/learnings-library/styles.css | 328 ++++++++++++ .../features/learnings-library/types.ts | 69 +++ 5 files changed, 1283 insertions(+) create mode 100644 hub/client/application/hub/view-models/learnings-library/index.test.ts create mode 100644 hub/client/application/hub/view-models/learnings-library/index.ts create mode 100644 hub/client/features/learnings-library/index.tsx create mode 100644 hub/client/features/learnings-library/styles.css create mode 100644 hub/client/features/learnings-library/types.ts 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 new file mode 100644 index 000000000..9baa6f541 --- /dev/null +++ b/hub/client/application/hub/view-models/learnings-library/index.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from "vitest" + +import { emptyLearnings } from "@application/hub/routes/fixtures/empty-learnings" + +import { learningsLibrary } from "." + +const pathname = "/repositories/2001/learnings" +const digest = `sha256:${"a".repeat(64)}` + +describe("learningsLibrary()", () => { + it("opens on active learnings once nothing waits for a decision", () => { + const state = emptyLearnings() + state.learnings = [ + { + id: "mem_active", + title: null, + content: "Use one primary button per form.\nLabel it with the action.", + digest, + acceptedBy: "mona", + acceptedAt: "2026-10-06T15:00:00Z", + edited: false, + status: "recalled", + }, + ] + + const result = learningsLibrary(state, { pathname, search: "" }, null) + + expect(result.status).toBe("active") + expect(result.learnings).toEqual([ + expect.objectContaining({ + title: "Use one primary button per form.", + detailPath: `${pathname}?status=active&learning=mem_active`, + }), + ]) + }) + + it("searches titles and guidance and keeps the page within range", () => { + const state = emptyLearnings() + state.learnings = Array.from({ length: 30 }, (_, index) => ({ + id: `mem_${index}`, + title: index === 29 ? "Keep labels visible" : `Learning ${index}`, + content: index === 28 ? "Labels stay above fields." : "Use one primary button.", + digest, + acceptedBy: "mona", + acceptedAt: "2026-10-06T15:00:00Z", + edited: false, + status: "recalled" as const, + })) + + const firstPage = learningsLibrary(state, { pathname, search: "?status=active" }, null) + const pastTheEnd = learningsLibrary(state, { pathname, search: "?status=active&page=9" }, null) + const searched = learningsLibrary(state, { pathname, search: "?status=active&q=LABEL" }, null) + + expect(firstPage.learnings).toHaveLength(25) + expect(firstPage.pageCount).toBe(2) + expect(pastTheEnd.page).toBe(2) + expect(pastTheEnd.learnings).toHaveLength(5) + expect(pastTheEnd.returnPath).toBe(`${pathname}?status=active&page=2`) + expect(searched.learnings.map((learning) => learning.id)).toEqual(["mem_28", "mem_29"]) + expect(searched.statusPaths.rejected).toBe(`${pathname}?status=rejected&q=LABEL`) + }) + + it("shows why a learning was retired, its history, and how to accept it again", () => { + const state = emptyLearnings() + state.rejected = [ + { + id: "mem_retired", + title: "Open links in a new tab", + content: "Open every link in a new tab.", + digest, + state: "retired", + decidedBy: "hubot", + decidedAt: "2026-10-08T11:00:00Z", + reason: "It breaks the back button.", + }, + ] + + const result = learningsLibrary( + state, + { pathname, search: "?status=rejected&learning=mem_retired" }, + { + decisions: [ + { + version: 1, + state: "proposed", + change: "proposed", + by: "agent:replica-learning", + at: "2026-10-07T04:07:00Z", + reason: null, + }, + { + version: 2, + state: "retired", + change: "retired", + by: "hubot", + at: "2026-10-08T11:00:00Z", + reason: "It breaks the back button.", + }, + ], + evidence: [], + otherEvidenceCount: 2, + }, + ) + + expect(result.selected).toMatchObject({ + facts: ["Retired by @hubot on October 8, 2026"], + reason: { heading: "Why it was retired", text: "It breaks the back button." }, + otherEvidence: "2 more comments that Hub cannot show here", + history: [ + { label: "Suggested", by: null }, + { label: "Retired", by: "hubot" }, + ], + decision: { + path: `${pathname}/mem_retired/decision`, + digest, + title: "Open links in a new tab", + }, + }) + }) +}) diff --git a/hub/client/application/hub/view-models/learnings-library/index.ts b/hub/client/application/hub/view-models/learnings-library/index.ts new file mode 100644 index 000000000..8c0b511c4 --- /dev/null +++ b/hub/client/application/hub/view-models/learnings-library/index.ts @@ -0,0 +1,273 @@ +import type { + LearningDetail, + LearningEvidence, + LearningStatus, + LearningsLibraryData, + LibraryLearning, +} from "@features/learnings-library/types" +import type { + LearningEvidenceResponse, + LearningHistoryResponse, + LearningsResponse, +} from "@application/hub/learnings-contracts/types" + +// Matches GitHub's pull request list so long lists page the way people expect. +const pageSize = 25 +const titleLength = 80 + +const changeLabels: Record = { + proposed: "Suggested", + accepted: "Accepted", + edited: "Edited", + reinstated: "Accepted again", + rejected: "Rejected", + retired: "Retired", +} + +type Overview = Extract +type LearningRecord = Omit + +function count(value: number, singular: string, plural = `${singular}s`) { + return `${value} ${value === 1 ? singular : plural}` +} + +function longDate(value: string) { + return new Intl.DateTimeFormat("en-US", { dateStyle: "long" }).format(new Date(value)) +} + +// Older learnings have no title, so the list leads with the start of their guidance. +function titleFrom(title: string | null, guidance: string) { + if (title) return title + const line = guidance.split("\n")[0]?.trim() ?? "" + return line.length > titleLength ? `${line.slice(0, titleLength - 1).trimEnd()}…` : line +} + +function unavailableGuidance(status: Overview["learnings"][number]["status"] | null) { + return status === "damaged" + ? "This learning's wording is unavailable because its stored record failed integrity checks." + : status === "identity-review" + ? "This version's wording is withheld until its reviewer identities are revalidated." + : "This learning's wording is not available for review." +} + +function recallFact(status: Overview["learnings"][number]["status"]) { + return status === "recalled" + ? "Agents get this learning." + : status === "budget-excluded" + ? "Eligible, but the preview's count or text limit leaves it out." + : status === "damaged" + ? "Agents do not get this learning because it failed integrity checks." + : status === "identity-review" + ? "Agents do not get this version until its reviewer identities are revalidated." + : "Eligible. An agent's task decides whether it fits." +} + +function evidence(items: LearningEvidenceResponse[], repositoryId: string): LearningEvidence[] { + return items.map(({ prototypeId, ...item }) => ({ + ...item, + prototypePath: `/repositories/${repositoryId}/prototypes/${prototypeId}`, + })) +} + +function parseStatus(value: string | null): LearningStatus | null { + return value === "suggested" || value === "active" || value === "rejected" ? value : null +} + +/** + * Turns the Learnings overview and the address bar into one page of the library. The + * status, search and page live in the address so the back button and shared links + * work without extra page state. + */ +export function learningsLibrary( + state: Overview, + location: { pathname: string; search: string }, + history: LearningHistoryResponse | null, +): LearningsLibraryData { + const params = new URLSearchParams(location.search) + const records: LearningRecord[] = [ + ...state.suggestions.map((entry) => ({ + 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, + } + }), + ] + const counts = { + suggested: state.suggestions.length, + active: state.learnings.length, + rejected: state.rejected.length, + } + // Suggestions need a decision, so they lead until there are none. + const status = parseStatus(params.get("status")) ?? (counts.suggested ? "suggested" : "active") + const query = (params.get("q") ?? "").trim() + const needle = query.toLocaleLowerCase() + const matching = records.filter( + (record) => + record.status === status && + (!needle || + record.title.toLocaleLowerCase().includes(needle) || + record.guidance.toLocaleLowerCase().includes(needle)), + ) + const pageCount = Math.max(1, Math.ceil(matching.length / pageSize)) + const requestedPage = Number.parseInt(params.get("page") ?? "1", 10) + const page = Number.isFinite(requestedPage) ? Math.min(Math.max(requestedPage, 1), pageCount) : 1 + + function listPath(target: LearningStatus, targetPage = 1, learningId?: string) { + const next = new URLSearchParams({ status: target }) + if (query) next.set("q", query) + if (targetPage > 1) next.set("page", String(targetPage)) + if (learningId) next.set("learning", learningId) + return `${location.pathname}?${next}` + } + + const selectedId = params.get("learning") + const selected = selectedId ? records.find((record) => record.id === selectedId) : undefined + return { + status, + counts, + statusPaths: { + suggested: listPath("suggested"), + active: listPath("active"), + rejected: listPath("rejected"), + }, + query, + listPath: listPath(status), + returnPath: listPath(status, page), + page, + pageCount, + learnings: matching + .slice((page - 1) * pageSize, page * pageSize) + .map((record) => ({ ...record, detailPath: listPath(status, page, record.id) })), + selected: selected ? detail(state, selected, history) : null, + } +} + +function detail( + state: Overview, + record: LearningRecord, + history: LearningHistoryResponse | null, +): LearningDetail { + const repositoryId = state.repository.id + const path = `/repositories/${repositoryId}/learnings/${encodeURIComponent(record.id)}/decision` + const canDecide = state.permissions.decide + const shared = { + id: record.id, + status: record.status, + title: record.title, + guidance: record.guidance, + reason: null, + replaces: [], + evidence: evidence(history?.evidence ?? [], repositoryId), + otherEvidence: + history && history.otherEvidenceCount > 0 + ? `${count(history.otherEvidenceCount, "more comment")} that Hub cannot show here` + : null, + contradictions: [], + otherContradictions: null, + history: (history?.decisions ?? []).map((entry) => ({ + label: changeLabels[entry.change], + at: entry.at, + // Agents propose suggestions under service identities rather than GitHub logins. + by: entry.by?.includes(":") ? null : entry.by, + reason: entry.reason, + })), + } + const suggestion = state.suggestions.find((item) => item.id === record.id) + if (record.status === "suggested" && suggestion) { + return { + ...shared, + facts: suggestion.support + ? [ + `Raised by ${count(suggestion.support.reviewers, "reviewer")} on ${count( + suggestion.support.prototypes, + "prototype", + )}`, + ] + : [], + replaces: suggestion.replaces.map((target) => ({ + id: target.id, + content: target.content ?? "This learning's wording is not available for review.", + })), + evidence: evidence(suggestion.evidence, repositoryId), + otherEvidence: + suggestion.otherEvidenceCount > 0 + ? `${count(suggestion.otherEvidenceCount, "more comment")} that Hub cannot show here` + : null, + contradictions: evidence(suggestion.contradictions, repositoryId), + otherContradictions: + suggestion.otherContradictionsCount > 0 + ? `${count(suggestion.otherContradictionsCount, "more opposing comment")} that Hub cannot show here` + : null, + decision: canDecide + ? { path, digest: suggestion.reviewDigest, title: "", content: "" } + : null, + } + } + const accepted = state.learnings.find((item) => item.id === record.id) + if (record.status === "active" && accepted) { + return { + ...shared, + facts: [ + ...(accepted.acceptedBy && accepted.acceptedAt + ? [ + `Accepted by @${accepted.acceptedBy} on ${longDate(accepted.acceptedAt)}${ + accepted.edited ? ", with edits" : "" + }`, + ] + : []), + recallFact(accepted.status), + ], + decision: + canDecide && accepted.digest && accepted.content !== null + ? { + path, + digest: accepted.digest, + title: accepted.title ?? "", + content: accepted.content, + } + : null, + } + } + const rejected = state.rejected.find((item) => item.id === record.id) + const verb = rejected?.state === "retired" ? "Retired" : "Rejected" + return { + ...shared, + facts: + rejected?.decidedBy && rejected.decidedAt + ? [`${verb} by @${rejected.decidedBy} on ${longDate(rejected.decidedAt)}`] + : [], + reason: rejected?.reason + ? { heading: `Why it was ${verb.toLowerCase()}`, text: rejected.reason } + : null, + decision: + canDecide && rejected?.digest + ? { + path, + digest: rejected.digest, + title: rejected.title ?? "", + content: rejected.content ?? "", + } + : null, + } +} diff --git a/hub/client/features/learnings-library/index.tsx b/hub/client/features/learnings-library/index.tsx new file mode 100644 index 000000000..698536bbd --- /dev/null +++ b/hub/client/features/learnings-library/index.tsx @@ -0,0 +1,493 @@ +import { useState, type ReactNode } from "react" +import { + ArrowLeftIcon, + CheckCircleIcon, + LightBulbIcon, + SearchIcon, + XCircleIcon, + type Icon, +} from "@primer/octicons-react" +import { + Button, + FormControl, + Heading, + Label, + Pagination, + Text, + TextInput, + Textarea, +} from "@primer/react-brand" + +import { HubCounter } from "@components/hub-counter" +import { HubEmptyState } from "@components/hub-empty-state" +import { HubUserAvatar } from "@components/hub-user-avatar" +import { CanvasDialog } from "@components/prototype-canvas-dialog" +import { ReviewRelativeTime } from "@features/review-relative-time" + +import type { + LearningDetail, + LearningEvidence, + LearningStatus, + LearningsLibraryData, +} from "./types" +import "./styles.css" + +const statuses = ["suggested", "active", "rejected"] as const + +const statusLabels: Record = { + suggested: "Suggested", + active: "Active", + rejected: "Rejected", +} + +// Mirrors GitHub's pull request states so people can read status at a glance. +const statusIcons: Record = { + suggested: LightBulbIcon, + active: CheckCircleIcon, + rejected: XCircleIcon, +} + +const statusLabelColors = { + suggested: "default", + active: "green", + rejected: "red", +} as const satisfies Record + +const emptyMessages: Record = { + suggested: "Hub suggests a learning when the same point comes up in at least two review threads.", + active: "Accept a suggestion to share it with agents.", + rejected: "Learnings you reject or stop using stay here so you can accept them again.", +} + +/** 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] + return +} + +/** + * Lists a repository's learnings by status and shows one in detail. Members browse; + * repository administrators also decide what agents get. + */ +export function LearningsLibrary({ + data, + authenticityToken, +}: { + data: LearningsLibraryData + authenticityToken: string +}) { + return data.selected ? ( + + ) : ( + + ) +} + +function LearningList({ data }: { data: LearningsLibraryData }) { + function pageHref(page: number) { + const url = new URL(data.listPath, window.location.origin) + if (page > 1) url.searchParams.set("page", String(page)) + return `${url.pathname}${url.search}` + } + const searchPath = new URL(data.listPath, window.location.origin).pathname + + return ( +
+ + Browse learnings + +
+ +
+ + + Search learnings + } + maxLength={200} + name="q" + placeholder="Search learnings" + type="search" + /> + +
+
+ {data.learnings.length ? ( +
+ + + + + + + + + {data.learnings.map((learning) => ( + + + + + ))} + +
LearningUpdated
+
+ +
+ + {learning.title} + +

{learning.guidance}

+
+
+
+ {learning.updatedAt ? : "—"} +
+
+ ) : ( + + )} + {data.pageCount > 1 ? ( + + ) : null} +
+ ) +} + +function LearningDetailView({ + learning, + backPath, + authenticityToken, +}: { + learning: LearningDetail + backPath: string + authenticityToken: string +}) { + const [dialog, setDialog] = useState<"reject" | "edit" | "retire" | "reinstate" | null>(null) + const decision = learning.decision + + return ( +
+ + + Back to learnings + +
+
+ + + {learning.title} + + + {learning.guidance} + + {learning.facts.length ? ( +
    + {learning.facts.map((fact) => ( +
  • {fact}
  • + ))} +
+ ) : null} +
+ {decision ? ( +
+ {learning.status === "suggested" ? ( + <> + + + + + + ) : learning.status === "active" ? ( + <> + + + + ) : ( + + )} +
+ ) : null} +
+ + {learning.reason ? ( +
+ + + {learning.reason.heading} + + {learning.reason.text} +
+ ) : 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.contradictions.length || learning.otherContradictions ? ( + + + + ) : null} + + {decision && dialog ? ( + setDialog(null)} + > +

+ {dialog === "edit" + ? "Agents get the new wording. The decision history keeps your reason." + : dialog === "reinstate" + ? "Agents get this learning again." + : "Agents do not get rejected learnings. You can accept it later."} +

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