:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(review-hog): use an existing team skill as a review skill (#85459)
Alex Lebedev440333527014
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5eb3ebc77d17..74a1a20977f7 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1900,6 +1900,18 @@ snapshots:hash: v1.k794b7964.50a5102fcd24dd52bb07a41a78e6685486895d9ed86923b857de67a2bf0cfa25.yhotsOneF2mgB_iFToEVdcMfHQf58lr7yldfNN-ZYbUcomponents-sharing--recording-sharing-licensed--light:hash: v1.k794b7964.887ed3d23b03515cab22e56f2258a1f1f7be9b7b69c1b5f3e17db17b6c05b4db.XWPlz4WofkRpUrTptzJ_y3K-quE1bDXIBkc2F5gq2wk+ components-skillpicker--default--dark:+ hash: v1.k794b7964.42e480d1854fa4e855c514aa6cb4e0adebde88d01cccd1b802b6a2acba0ccfd3.zWHBN45jGiaWgIUoC6ZoTFd9RLQ9LxAZ5x5szvvO2aE+ components-skillpicker--default--light:+ hash: v1.k794b7964.cbbe33adfd71b1c432b64dfd92a343c2d562c2e64910d07fff58ff5a4cd926e7.utWGHbQe8EqWV_0Kb54dtyiG1QM_W4-HgVcJ8m6Sys4+ components-skillpicker--empty--dark:+ hash: v1.k794b7964.4502f6dbefd7848a18c884a205d5da9ccd1cc1b5ee65717fbbbb8fb07a7202bf.-IXKQW55ul9arMOKU0fHgh1-ppUfSpvYTJLOKg5rwxM+ components-skillpicker--empty--light:+ hash: v1.k794b7964.834f1daaa1c90c821674ed0d47d6a8cfe3fe2d92b8c5ba68f2a600383ec439ab.QEFmzIl_TfqoJYnNbyst2sFrixFceJNgdiEDxg3o0v8+ components-skillpicker--loading--dark:+ hash: v1.k794b7964.a6c03e74d88d7915ee632eb41078032b6a0ed2b7d2076e3824843ee0504c5184.sPVYxnzC5p8USLUKFktTDgFn9IKoZAr3p8LQ9q2HT1Q+ components-skillpicker--loading--light:+ hash: v1.k794b7964.1f11b533447e94851d7036d383a6c200445f7da972d711558cc3f7dba15819ea.hwvMJBLynPWX3xaxY8wXIxncAKZm74pJ_0khYfYWbescomponents-slack-channel-picker--alphabetical--dark:hash: v1.k794b7964.c5f45d681dad559cdf8bed1c8e9d31c5dca4d0973e1fbf5d1515ab30c393b554.SYg7auYBsl2kTK9lzMylWzKKRJ9Bf3sT0lwtvlfXx24components-slack-channel-picker--alphabetical--light:diff --git a/frontend/src/lib/components/SkillPicker/SkillPicker.stories.tsx b/frontend/src/lib/components/SkillPicker/SkillPicker.stories.tsxnew file mode 100644index 000000000000..c3e1565d898e--- /dev/null+++ b/frontend/src/lib/components/SkillPicker/SkillPicker.stories.tsx@@ -0,0 +1,71 @@+import { Meta, StoryObj } from '@storybook/react'++import { SkillPicker } from './SkillPicker'++const meta: Meta<typeof SkillPicker> = {+ title: 'Components/SkillPicker',+ component: SkillPicker,+}+export default meta++type Story = StoryObj<typeof SkillPicker>++const GROUPS = [+ {+ key: 'teammates',+ label: 'Perspectives from your teammates',+ skills: [+ {+ name: 'review-hog-perspective-accessibility',+ description:+ 'Reviews changed UI code for keyboard navigation, focus handling, and screen reader support.',+ },+ ],+ },+ {+ key: 'store',+ label: 'All team skills',+ skills: [+ {+ name: 'api-design-guidelines',+ description: 'How this team designs REST endpoints: naming, pagination, error shapes.',+ },+ {+ name: 'writing-database-migrations',+ description: 'Safe migration practices for large tables.',+ },+ { name: 'undocumented-helper', description: '' },+ ],+ },+]++export const Default: Story = {+ args: {+ groups: GROUPS,+ selectLabel: 'Use this skill',+ onSelect: () => {},+ loadBody: () => Promise.resolve('# Example skill\n\nSome markdown body content.'),+ },+}++export const Loading: Story = {+ args: {+ groups: [],+ loading: true,+ onSelect: () => {},+ },+ parameters: {+ testOptions: {+ // This story renders skeletons forever by design; the default wait would time out.+ waitForLoadersToDisappear: false,+ },+ },+}++export const Empty: Story = {+ args: {+ groups: [{ key: 'store', label: 'All team skills', skills: [] }],+ emptyMessage: 'Your team has no other skills yet.',+ onSelect: () => {},+ },+}diff --git a/frontend/src/lib/components/SkillPicker/SkillPicker.tsx b/frontend/src/lib/components/SkillPicker/SkillPicker.tsxnew file mode 100644index 000000000000..692fc6b5d363--- /dev/null+++ b/frontend/src/lib/components/SkillPicker/SkillPicker.tsx@@ -0,0 +1,198 @@+import { useState } from 'react'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { Link } from 'lib/lemon-ui/Link'+import { Spinner } from 'lib/lemon-ui/Spinner'++export interface SkillPickerSkill {+ name: string+ description: string+}++export interface SkillPickerGroup {+ key: string+ label: string+ skills: SkillPickerSkill[]+}++export interface SkillPickerProps {+ /** Skills to offer, already filtered and grouped by the caller. A group with no matches is hidden. */+ groups: SkillPickerGroup[]+ /** True while the caller is still fetching the groups' skills. */+ loading?: boolean+ /** Shown when every group is empty before any search input. */+ emptyMessage?: string+ /** Label of each row's select button. */+ selectLabel?: string+ onSelect: (skill: SkillPickerSkill) => void+ /** Lazily fetches a skill's markdown body when its preview is expanded. Omit to hide previews. */+ loadBody?: (name: string) => Promise<string>+ 'data-attr'?: string+}++function matchesQuery(skill: SkillPickerSkill, query: string): boolean {+ return skill.name.toLowerCase().includes(query) || skill.description.toLowerCase().includes(query)+}++function SkillPickerRow({+ skill,+ selectLabel,+ onSelect,+ loadBody,+}: {+ skill: SkillPickerSkill+ selectLabel: string+ onSelect: (skill: SkillPickerSkill) => void+ loadBody?: (name: string) => Promise<string>+}): JSX.Element {+ const [expanded, setExpanded] = useState(false)+ const [body, setBody] = useState<string | null>(null)+ const [bodyLoading, setBodyLoading] = useState(false)+ const [bodyFailed, setBodyFailed] = useState(false)++ const fetchBody = async (): Promise<void> => {+ if (body !== null || !loadBody) {+ return+ }+ setBodyLoading(true)+ setBodyFailed(false)+ try {+ setBody(await loadBody(skill.name))+ } catch {+ setBodyFailed(true)+ } finally {+ setBodyLoading(false)+ }+ }++ const togglePreview = (): void => {+ if (expanded) {+ setExpanded(false)+ return+ }+ setExpanded(true)+ void fetchBody()+ }++ return (+ <div className="flex flex-col gap-2 rounded border border-primary p-3">+ <div className="flex items-start justify-between gap-4">+ <div className="flex min-w-0 flex-col gap-1">+ <span className="text-sm font-semibold break-all">{skill.name}</span>+ {skill.description ? (+ <p className="m-0 text-xs text-secondary">{skill.description}</p>+ ) : (+ <p className="m-0 text-xs italic text-tertiary">No description</p>+ )}+ {loadBody && (+ <div className="text-xs">+ <Link onClick={togglePreview} data-attr="skill-picker-toggle-preview">+ {expanded ? 'Hide preview' : 'Preview'}+ </Link>+ </div>+ )}+ </div>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => onSelect(skill)}+ data-attr="skill-picker-select"+ >+ {selectLabel}+ </LemonButton>+ </div>+ {expanded &&+ (bodyLoading ? (+ <div className="flex items-center gap-2 text-xs text-secondary">+ <Spinner /> Loading the skill body+ </div>+ ) : bodyFailed ? (+ <div className="text-xs text-danger">+ Couldn't load the skill body. <Link onClick={() => void fetchBody()}>Try again</Link>+ </div>+ ) : body !== null ? (+ <div className="max-h-60 overflow-y-auto rounded border border-primary bg-surface-primary p-3">+ <LemonMarkdown className="text-xs" disableImages>+ {body}+ </LemonMarkdown>+ </div>+ ) : null)}+ </div>+ )+}++/**+ * A searchable, grouped list of skills with per-row preview and select. Fully controlled: the+ * caller fetches and groups the skills, this component only renders and filters them, so it can+ * host any product's picking flow (its first consumer is ReviewHog's "Use an existing skill").+ */+export function SkillPicker({+ groups,+ loading = false,+ emptyMessage = 'No skills available',+ selectLabel = 'Select',+ onSelect,+ loadBody,+ 'data-attr': dataAttr,+}: SkillPickerProps): JSX.Element {+ const [search, setSearch] = useState('')+ const query = search.trim().toLowerCase()++ const filteredGroups = groups+ .map((group) => ({ ...group, skills: group.skills.filter((skill) => matchesQuery(skill, query)) }))+ .filter((group) => group.skills.length > 0)+ const nothingToOffer = groups.every((group) => group.skills.length === 0)++ return (+ <div className="flex flex-col gap-3" data-attr={dataAttr}>+ <LemonInput+ type="search"+ fullWidth+ placeholder="Search skills"+ value={search}+ onChange={setSearch}+ autoFocus+ data-attr="skill-picker-search"+ />+ {loading ? (+ <div className="flex flex-col gap-2">+ <LemonSkeleton className="h-16 w-full" />+ <LemonSkeleton className="h-16 w-full" />+ <LemonSkeleton className="h-16 w-full" />+ </div>+ ) : nothingToOffer ? (+ <p className="m-0 text-sm text-secondary">{emptyMessage}</p>+ ) : filteredGroups.length === 0 ? (+ <p className="m-0 text-sm text-secondary">No skills match your search.</p>+ ) : (+ <div className="flex max-h-120 flex-col gap-4 overflow-y-auto">+ {filteredGroups.map((group) => (+ <div key={group.key} className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <span className="text-xxs font-semibold uppercase tracking-wide text-tertiary">+ {group.label}+ </span>+ <LemonTag type="muted" size="small">+ {group.skills.length}+ </LemonTag>+ </div>+ {group.skills.map((skill) => (+ <SkillPickerRow+ key={skill.name}+ skill={skill}+ selectLabel={selectLabel}+ onSelect={onSelect}+ loadBody={loadBody}+ />+ ))}+ </div>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 7923c0e4d54e..b766136e7215 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -507,7 +507,10 @@ A separate **blind-spots** skill (`skills/review-hog-blind-spots-general/SKILL.mit is pull-delivered the same way. The perspective / validation / blind-spot skills are all team-owned andcustomizable — see [DECISIONS.md](./DECISIONS.md) (the customizable-perspectives / per-user-enablement sections).The invariant that keeps this safe: **the output schema is fixed (code), only the skill body (logic) is editable**,-so editing a skill can never change the output format the downstream pipeline depends on.+so editing a skill can never change the output format the downstream pipeline depends on. Customs arrive two+ways from the Code review scene: "Create your own" (an authoring agent task guided by the `review-hog-authoring`+skill) and "Use an existing skill" — an **adopted skill**, a verbatim copy of any team skill duplicated under the+kind's prefix and activated in one flow (copy-not-reference; see `adr/0002`).---diff --git a/products/review_hog/CONTEXT.md b/products/review_hog/CONTEXT.mdindex 461daa69cc2b..54991d397e45 100644--- a/products/review_hog/CONTEXT.md+++ b/products/review_hog/CONTEXT.md@@ -8,6 +8,7 @@ Vocabulary settled while working on the product. Pure vocabulary — no spec, no- **Pipeline payload** — the same finding/verdict fields as consumed by downstream LLM stages (validator, dedup, covered-findings). The quality-critical audience.- **Structural conciseness vs compression** — _structural_: the same information content reshaped into labeled bullets (claim / trigger / evidence / impact); _compression_: dropping information to save words. The no-quality-loss constraint rules out compression of pipeline payloads; it does not rule out restructuring.- **Verify, don't restate** — the rule for validator argumentation: it is the _verification delta_ (what was checked, what was found with file:line evidence, confirmed impact, priority rationale), never a restatement of the finding body's claim. Safe because the full body always travels with the argumentation — every consumer, human or LLM, receives both in the same comment or payload.+- **Adopted skill** — a review skill created by copying an existing team skill under a `review-hog-<kind>-` prefixed name (the "Use an existing skill" flow), as opposed to one authored by the "Create your own" agent task. A fork, not a reference: edits to the source skill do not reach the copy, and the adopting user is the copy's author (see ADR 0002).- **Report status (`active` / `idle` / `closed`)** — the report-level at-work flag: `active` while any run (a review turn or a resolution run) is working the report, `idle` at rest, `closed` retired. A publishing turn holds `active` through the GitHub publish, so `idle` always implies the published state is final. The UI reads a row as in-progress from `active` plus recent activity, so a crashed run ages out of view instead of reading as running forever.## Resolution stage (the "implement the fixes" flow)diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.mdindex 165d82114d23..7e5b4819934f 100644--- a/products/review_hog/DECISIONS.md+++ b/products/review_hog/DECISIONS.md@@ -198,6 +198,40 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)rate drops materially (toward ≤50%) on frozen-PR evals with the valid-finding set intact (item 5'scoverage matrix as the guard); kill if valid findings drop with the noise.+### ✅ BUILT 2026-08-19 — "Use an existing skill": adopt a team skill as a review skill by copy (grilled 2026-08-19; ADR `adr/0002`)++Users with an existing team skill had no path into ReviewHog short of running the "Create your own" authoring+agent — the ask was a picker beside those buttons that reuses what the team already has. Design settled by a+grilled Q&A (copy-vs-reference was the root call, recorded with its consequences in+[ADR 0002](./adr/0002-adopt-existing-skills-by-copy.md)): **adopt = duplicate the source under the kind's+prefix + activate, verbatim** (no agent adaptation; the picker's body preview does the judgment work, and the+fixed output schema means a foreign body can never break the pipeline format). Mechanics, all existing+endpoints — the skills product's `duplicate` (strips `seeded_by`, adopter becomes author, so author-only+visibility and the sync's seeded-rows-only reconcile hold untouched) then the kind's config PATCH+(perspectives `enabled`, single-active kinds `active`, swapping the current selection; the confirm step names+the swap). Two client calls over a new atomic endpoint on purpose: the one partial-failure mode (copied but+not switched on) is harmless — the card exists, a toast says to flip it.++- **Picker scope:** one searchable list, two groups — teammates' same-kind `review-hog-*` customs first+ (adoptable precisely because the config surface hides them: the fork makes them yours), then every other+ team skill (cross-kind review skills included — a validation bar adopted as resolution criteria is+ legitimate). Community store deliberately out of scope (phase 2, own trust surface).+- **Naming:** confirm step with the prefix fixed and an editable slug, prefilled from the source name (any+ review-hog kind prefix stripped so cross-kind adoption doesn't double-prefix), client-side mirror of the+ name rules for inline errors; the server stays authoritative on conflicts.+- **Component layering:** the generic piece (`SkillPicker` — controlled groups, client-side search, lazy body+ preview) lives in `frontend/src/lib/components/SkillPicker/` per the no-cross-product-component-imports+ rule (the grill's products/skills pick adjusted to the sanctioned shared layer); ReviewHog's+ `AdoptSkillModal` owns the groups, the confirm step, and the adopt orchestration in+ `reviewHogSettingsLogic`.+- **Skills-product fix along the way:** `duplicate_skill` now derives `category` from the new name exactly+ like the create paths (was deliberately empty), so adopted skills group under the Skills page's Code review+ tab like agent-authored ones — also fixes the manual duplicate-into-prefix path.+- Tests: jest — adopt orchestration per kind (duplicate name + activation body), copy-failure keeps the modal+ open with no activation fired, activation-failure still reloads the kind's cards, picker grouping, slug+ prefill/validation (pure); BE — duplicate category derivation parameterized (new-name prefix wins, source+ category never copied).+### ✅ BUILT 2026-08-12 — review body cut to a severity tally (the chunk summary is gone)The published body opened with a walk of the chunk tree: a `## <chunk type>` heading per chunk, an `Issues: N`diff --git a/products/review_hog/adr/0002-adopt-existing-skills-by-copy.md b/products/review_hog/adr/0002-adopt-existing-skills-by-copy.mdnew file mode 100644index 000000000000..603727e18856--- /dev/null+++ b/products/review_hog/adr/0002-adopt-existing-skills-by-copy.md@@ -0,0 +1,7 @@+# Adopting an existing skill copies it under the kind's prefix, not by reference++"Use an existing skill" (Code review scene, beside each "Create your own …") turns an existing team `LLMSkill` into a review perspective / blind-spot check / validation criteria / resolution criteria by **duplicating it under a `review-hog-<kind>-<slug>` name** (the skills product's duplicate endpoint) and activating the copy through the existing config APIs. Considered a live-reference model instead — a `kind` column on `ReviewSkillConfig` pointing at arbitrary skill names, so edits to the source keep flowing; rejected because the name prefix is a review skill's whole identity everywhere (loader resolution, config-API scoping, stats bucketing, the sync's prefix-scoped reconcile, the documented contract in the authoring skill), so reference semantics would rework identity across all of them for a marginal gain, and because a copy keeps the author-only visibility rule intact for free — the adopting user becomes the copy's author. Renaming the source into the prefix was ruled out outright: other consumers pull skills by name over MCP.++## Consequences++An adopted skill is a fork: later edits to the source do not reach the copy (the confirm step says so), and adopting the same source twice needs a second name. The copy carries no `seeded_by` marker, so the canonical sync never touches it. `duplicate_skill` now derives `category` from the new name exactly like the create paths, so adopted skills group under the Skills page's Code review tab like agent-authored ones.diff --git a/products/review_hog/frontend/AdoptSkillModal.tsx b/products/review_hog/frontend/AdoptSkillModal.tsxnew file mode 100644index 000000000000..9488435f6f34--- /dev/null+++ b/products/review_hog/frontend/AdoptSkillModal.tsx@@ -0,0 +1,131 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonInput } from '@posthog/lemon-ui'++import { SkillPicker } from 'lib/components/SkillPicker/SkillPicker'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonModal } from 'lib/lemon-ui/LemonModal'+import { teamLogic } from 'scenes/teamLogic'++import { llmSkillsResolveNameRetrieve } from 'products/skills/frontend/generated/api'++import { REVIEW_SKILL_KIND_LABELS, REVIEW_SKILL_PREFIX_BY_KIND, reviewHogSettingsLogic } from './reviewHogSettingsLogic'++/**+ * The "Use an existing skill" flow: search the team's skill store, pick a source skill, confirm+ * the copy's name, and the logic copies it under the kind's prefix and switches it on. Hosts the+ * generic SkillPicker for the search step and owns the ReviewHog-specific confirm step.+ */+export function AdoptSkillModal(): JSX.Element {+ const {+ adoptSkillKind,+ adoptSource,+ adoptSlug,+ adoptSlugError,+ adoptingSkill,+ adoptSkillGroups,+ adoptableSkillsLoading,+ blindSpots,+ validators,+ resolutionSkills,+ } = useValues(reviewHogSettingsLogic)+ const { closeAdoptSkillModal, chooseAdoptSource, backToAdoptSearch, setAdoptSlug, submitAdoptSkill } =+ useActions(reviewHogSettingsLogic)+ const { currentTeamId } = useValues(teamLogic)++ const kindLabel = adoptSkillKind ? REVIEW_SKILL_KIND_LABELS[adoptSkillKind] : ''+ // Single-active kinds swap the user's current selection on adopt; name what gets replaced.+ const replacedSkillName =+ adoptSkillKind === 'blind_spots'+ ? blindSpots?.find((s) => s.active)?.skill_name+ : adoptSkillKind === 'validator'+ ? validators?.find((s) => s.active)?.skill_name+ : adoptSkillKind === 'resolution'+ ? resolutionSkills?.find((s) => s.active)?.skill_name+ : undefined++ return (+ <LemonModal+ isOpen={adoptSkillKind !== null}+ onClose={closeAdoptSkillModal}+ // Block close while the copy/activation requests are in flight: closing mid-flight lets+ // the user reopen and adopt again, and the first request's tail then closes that modal+ // and fires a success toast naming the wrong source.+ closable={!adoptingSkill}+ title={`Use an existing skill as your ${kindLabel}`}+ description={+ adoptSource+ ? undefined+ : 'Pick a skill from your team. A copy of it becomes a review skill; the original stays untouched.'+ }+ width={720}+ data-attr="review-hog-adopt-skill-modal"+ footer={+ adoptSource ? (+ <>+ <div className="flex-1">+ <LemonButton type="secondary" onClick={backToAdoptSearch} disabled={adoptingSkill}>+ Back+ </LemonButton>+ </div>+ <LemonButton+ type="primary"+ onClick={submitAdoptSkill}+ loading={adoptingSkill}+ disabledReason={adoptSlugError ?? undefined}+ data-attr="review-hog-adopt-skill-submit"+ >+ Copy and switch on+ </LemonButton>+ </>+ ) : (+ <LemonButton type="secondary" onClick={closeAdoptSkillModal}>+ Close+ </LemonButton>+ )+ }+ >+ {adoptSource ? (+ <div className="flex flex-col gap-4">+ <p className="m-0 text-sm text-secondary">+ This copies <span className="font-semibold">{adoptSource.name}</span> into a new {kindLabel}{' '}+ skill and switches it on for your PR reviews. Edits to the original won't change the copy.+ </p>+ {replacedSkillName && (+ <LemonBanner type="info">+ It replaces <span className="font-semibold">{replacedSkillName}</span> as your active{' '}+ {kindLabel}.+ </LemonBanner>+ )}+ <LemonField.Pure label="Name of the copy" error={adoptSlugError}>+ <LemonInput+ prefix={+ <span className="whitespace-nowrap text-secondary">+ {adoptSkillKind ? REVIEW_SKILL_PREFIX_BY_KIND[adoptSkillKind] : ''}+ </span>+ }+ value={adoptSlug}+ onChange={setAdoptSlug}+ autoFocus+ data-attr="review-hog-adopt-skill-slug"+ />+ </LemonField.Pure>+ </div>+ ) : (+ <SkillPicker+ groups={adoptSkillGroups}+ loading={adoptableSkillsLoading}+ emptyMessage='Your team has no other skills to use yet. "Create your own" makes one with an agent.'+ selectLabel="Use this skill"+ onSelect={(skill) => chooseAdoptSource({ name: skill.name, description: skill.description })}+ // Resolve returns the whole body; the plain name endpoint caps it at 8000 chars,+ // which would preview an adopted skill short of what the copy actually runs.+ loadBody={async (name) =>+ (await llmSkillsResolveNameRetrieve(String(currentTeamId), name)).skill.body+ }+ data-attr="review-hog-adopt-skill-picker"+ />+ )}+ </LemonModal>+ )+}diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsxindex 6944e0c74de7..c61020d089f7 100644--- a/products/review_hog/frontend/CodeReviewScene.tsx+++ b/products/review_hog/frontend/CodeReviewScene.tsx@@ -61,6 +61,7 @@ import {ReviewTriggerRequestRunModeEnumApi,} from 'products/review_hog/frontend/generated/api.schemas'+import { AdoptSkillModal } from './AdoptSkillModal'import { PipelineDetailModal } from './PipelineDetailModal'import { REVIEWS_PAGE_SIZE, ReviewDrawerTab, ReviewSkillKind, reviewHogSettingsLogic } from './reviewHogSettingsLogic'@@ -1369,18 +1370,40 @@ function CreateYourOwnButton({ kind, label }: { kind: ReviewSkillKind; label: stconst { creatingSkillKind } = useValues(reviewHogSettingsLogic)const { startSkillAuthorTask } = useActions(reviewHogSettingsLogic)return (- <div>- <LemonButton- type="secondary"- icon={<IconPlus />}- onClick={() => startSkillAuthorTask(kind)}- loading={creatingSkillKind === kind}- disabledReason={- creatingSkillKind && creatingSkillKind !== kind ? 'Another authoring task is starting…' : undefined- }- >- {label}- </LemonButton>+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ onClick={() => startSkillAuthorTask(kind)}+ loading={creatingSkillKind === kind}+ disabledReason={+ creatingSkillKind && creatingSkillKind !== kind ? 'Another authoring task is starting…' : undefined+ }+ >+ {label}+ </LemonButton>+ )+}++function UseExistingSkillButton({ kind }: { kind: ReviewSkillKind }): JSX.Element {+ const { openAdoptSkillModal } = useActions(reviewHogSettingsLogic)+ return (+ <LemonButton+ type="secondary"+ icon={<IconSearch />}+ onClick={() => openAdoptSkillModal(kind)}+ data-attr={`review-hog-adopt-skill-${kind}`}+ >+ Use an existing skill+ </LemonButton>+ )+}++/** The two ways to add a review skill, side by side under each kind's cards. */+function AddSkillRow({ kind, createLabel }: { kind: ReviewSkillKind; createLabel: string }): JSX.Element {+ return (+ <div className="flex flex-wrap items-center gap-2">+ <CreateYourOwnButton kind={kind} label={createLabel} />+ <UseExistingSkillButton kind={kind} /></div>)}@@ -1577,7 +1600,7 @@ function PerspectivesSection(): JSX.Element {))}</div>)}- <CreateYourOwnButton kind="perspective" label="Create your own perspective" />+ <AddSkillRow kind="perspective" createLabel="Create your own perspective" /></section>)}@@ -1636,7 +1659,7 @@ function SingleActiveSection({))}</div>)}- <CreateYourOwnButton kind={kind} label={createLabel} />+ <AddSkillRow kind={kind} createLabel={createLabel} /></section>)}@@ -1779,6 +1802,7 @@ export function CodeReviewScene(): JSX.Element {<UrgencySection /><SkillDrawer />+ <AdoptSkillModal /><ReviewDetailDrawer /></div></SceneContent>diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.tsindex 6b11a3cce981..2e392c338f4c 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts@@ -11,7 +11,14 @@ import {ReviewTriggerRequestRunModeEnumApi,} from 'products/review_hog/frontend/generated/api.schemas'-import { MAX_REVIEWS_LIMIT, REVIEWS_PAGE_SIZE, reviewHogSettingsLogic } from './reviewHogSettingsLogic'+import {+ MAX_REVIEWS_LIMIT,+ REVIEW_SKILL_PREFIX_BY_KIND,+ REVIEWS_PAGE_SIZE,+ defaultAdoptSlug,+ reviewHogSettingsLogic,+ validateAdoptSlug,+} from './reviewHogSettingsLogic'/** A minimal review detail: only the fields the drawer selectors read. */function reviewDetail(id: string, runUrgencyThreshold: string | null): Record<string, any> {@@ -509,4 +516,229 @@ describe('reviewHogSettingsLogic', () => {document.dispatchEvent(new Event('visibilitychange'))}).toDispatchActions(['loadRecentReviews'])})++ test.each([+ // Cross-kind adoption must strip the source's own prefix, or the copy gets a double-prefixed name.+ ['review-hog-validation-strict', 'resolution' as const, 'strict'],+ ['api-design-guidelines', 'perspective' as const, 'api-design-guidelines'],+ // Truncation to the 64-char cap must not leave a trailing hyphen, which the server rejects.+ ['a'.repeat(40) + '-' + 'b'.repeat(23), 'perspective' as const, 'a'.repeat(40)],+ ])('prefills the adopt slug from %s for kind %s', (sourceName, kind, expected) => {+ expect(defaultAdoptSlug(sourceName, kind)).toBe(expected)+ })++ test.each([+ ['', 'Enter a name for the copy'],+ ['Has-Uppercase', 'Use lowercase letters, numbers, and single hyphens between words'],+ ['double--hyphen', 'Use lowercase letters, numbers, and single hyphens between words'],+ ['trailing-', 'Use lowercase letters, numbers, and single hyphens between words'],+ ['a'.repeat(60), 'The full name must be 64 characters or fewer'],+ ['taken', 'A skill with this name already exists'],+ ['fine-name', null],+ ])('validates the adopt slug %s', (slug, expectedError) => {+ const taken = new Set(['review-hog-perspective-taken'])+ expect(validateAdoptSlug(slug, 'perspective', taken)).toBe(expectedError)+ })++ it('groups adoptable skills into teammates-of-the-kind and the rest of the store', async () => {+ // Guards the picker's filters: the user's own cards must not reappear as adoptable, a+ // teammate's same-kind custom must surface (it is invisible in the cards by design), and+ // other-kind review skills stay offered as plain store skills.+ useMocks({+ get: {+ '/api/projects/:team_id/review_hog/perspectives/': () => [+ 200,+ [+ {+ skill_name: 'review-hog-perspective-logic-correctness',+ enabled: true,+ description: '',+ body: '',+ },+ ],+ ],+ '/api/projects/:team_id/llm_skills/': () => [+ 200,+ {+ count: 4,+ results: [+ { name: 'review-hog-perspective-security-focus', description: 'A teammate lens' },+ { name: 'review-hog-perspective-logic-correctness', description: 'Already a card' },+ { name: 'review-hog-validation-strict', description: 'Another kind' },+ { name: 'api-design-guidelines', description: 'Plain store skill' },+ ],+ },+ ],+ },+ })+ logic.mount()+ // Sequenced (perspectives settle before the modal opens) because the history pointer only+ // moves forward: racing the two fetches makes their success order nondeterministic.+ await expectLogic(logic).toDispatchActions(['loadPerspectivesSuccess'])+ logic.actions.openAdoptSkillModal('perspective')+ await expectLogic(logic).toDispatchActions(['loadAdoptableSkillsSuccess'])++ expect(logic.values.adoptSkillGroups).toEqual([+ {+ key: 'teammates',+ label: 'Perspectives from your teammates',+ skills: [{ name: 'review-hog-perspective-security-focus', description: 'A teammate lens' }],+ },+ {+ key: 'store',+ label: 'All team skills',+ skills: [+ { name: 'review-hog-validation-strict', description: 'Another kind' },+ { name: 'api-design-guidelines', description: 'Plain store skill' },+ ],+ },+ ])+ })++ test.each([+ ['perspective' as const, '/review_hog/perspectives/', { enabled: true }],+ ['validator' as const, '/review_hog/validators/', { active: true }],+ ])('adopting a skill as %s copies it under the prefix and switches it on', async (kind, patchPath, patchBody) => {+ // Guards the kind→endpoint mapping end to end: the duplicate must target the picked source+ // with the prefixed name, and the follow-up activation must hit the right kind's endpoint+ // with its cardinality's body (multi-toggle enabled vs single-active active).+ const duplicated: { source: string; body: Record<string, unknown> }[] = []+ const patched: { url: string; body: Record<string, unknown> }[] = []+ useMocks({+ get: {+ '/api/projects/:team_id/llm_skills/': () => [+ 200,+ { count: 1, results: [{ name: 'api-design-guidelines', description: '' }] },+ ],+ },+ post: {+ '/api/projects/:team_id/llm_skills/name/:skill_name/duplicate/': async ({ request, params }) => {+ duplicated.push({+ source: String(params.skill_name),+ body: (await request.json()) as Record<string, unknown>,+ })+ return [201, { name: 'created' }]+ },+ },+ patch: {+ '/api/projects/:team_id/review_hog/perspectives/:skill_name/': async ({ request }) => {+ patched.push({ url: request.url, body: (await request.json()) as Record<string, unknown> })+ return [200, {}]+ },+ '/api/projects/:team_id/review_hog/validators/:skill_name/': async ({ request }) => {+ patched.push({ url: request.url, body: (await request.json()) as Record<string, unknown> })+ return [200, {}]+ },+ },+ })+ logic.mount()+ logic.actions.openAdoptSkillModal(kind)+ await expectLogic(logic).toDispatchActions(['loadAdoptableSkillsSuccess'])+ logic.actions.chooseAdoptSource({ name: 'api-design-guidelines', description: '' })++ const expectedName = `${REVIEW_SKILL_PREFIX_BY_KIND[kind]}api-design-guidelines`+ await expectLogic(logic, () => logic.actions.submitAdoptSkill())+ .toDispatchActions(['submitAdoptSkillStarted', 'submitAdoptSkillFinished', 'closeAdoptSkillModal'])+ .toMatchValues({ adoptingSkill: false, adoptSkillKind: null })+ expect(duplicated).toEqual([{ source: 'api-design-guidelines', body: { new_name: expectedName } }])+ expect(patched).toHaveLength(1)+ expect(patched[0].url).toContain(`${patchPath}${expectedName}/`)+ expect(patched[0].body).toEqual(patchBody)+ })++ it('a failed copy keeps the adopt modal open for a fix', async () => {+ // A name conflict must be correctable in place — closing the modal would throw away the+ // picked source, and firing the activation PATCH would target a skill that never got created.+ let patchCalls = 0+ useMocks({+ get: {+ '/api/projects/:team_id/llm_skills/': () => [+ 200,+ { count: 1, results: [{ name: 'api-design-guidelines', description: '' }] },+ ],+ },+ post: {+ '/api/projects/:team_id/llm_skills/name/:skill_name/duplicate/': () => [+ 400,+ { attr: 'new_name', detail: 'A skill with this name already exists.' },+ ],+ },+ patch: {+ '/api/projects/:team_id/review_hog/perspectives/:skill_name/': () => {+ patchCalls+++ return [200, {}]+ },+ },+ })+ logic.mount()+ logic.actions.openAdoptSkillModal('perspective')+ await expectLogic(logic).toDispatchActions(['loadAdoptableSkillsSuccess'])+ logic.actions.chooseAdoptSource({ name: 'api-design-guidelines', description: '' })++ await expectLogic(logic, () => logic.actions.submitAdoptSkill())+ .toDispatchActions(['submitAdoptSkillStarted', 'submitAdoptSkillFinished'])+ .toNotHaveDispatchedActions(['closeAdoptSkillModal'])+ .toMatchValues({ adoptingSkill: false, adoptSkillKind: 'perspective' })+ expect(logic.values.adoptSource).toEqual({ name: 'api-design-guidelines', description: '' })+ expect(patchCalls).toBe(0)+ })++ it('a copy that cannot be switched on still surfaces its card', async () => {+ // The copy exists on the server even when activation fails, so the flow must reload the+ // kind's list (the card appears, off) and close, not strand the modal as if nothing happened.+ useMocks({+ get: {+ '/api/projects/:team_id/llm_skills/': () => [+ 200,+ { count: 1, results: [{ name: 'api-design-guidelines', description: '' }] },+ ],+ },+ post: {+ '/api/projects/:team_id/llm_skills/name/:skill_name/duplicate/': () => [201, { name: 'created' }],+ },+ patch: {+ '/api/projects/:team_id/review_hog/perspectives/:skill_name/': () => [500, {}],+ },+ })+ logic.mount()+ logic.actions.openAdoptSkillModal('perspective')+ await expectLogic(logic).toDispatchActions(['loadAdoptableSkillsSuccess'])+ logic.actions.chooseAdoptSource({ name: 'api-design-guidelines', description: '' })++ await expectLogic(logic, () => logic.actions.submitAdoptSkill()).toDispatchActions([+ 'submitAdoptSkillStarted',+ 'loadPerspectives',+ 'submitAdoptSkillFinished',+ 'closeAdoptSkillModal',+ ])+ })++ it('loads every skills page so skills beyond the first stay adoptable', async () => {+ // The picker's search, grouping, and name-collision checks assume the complete store — a+ // loader that stops at one page would silently hide older skills and miss name conflicts.+ useMocks({+ get: {+ '/api/projects/:team_id/llm_skills/': ({ request }) => {+ const offset = Number(new URL(request.url).searchParams.get('offset') ?? 0)+ const pages: Record<number, { name: string; description: string }[]> = {+ 0: [{ name: 'newest-skill', description: '' }],+ 1: [{ name: 'older-skill', description: '' }],+ }+ return [+ 200,+ {+ count: 2,+ results: pages[offset] ?? [],+ next: offset === 0 ? '/api/projects/997/llm_skills/?offset=1' : null,+ },+ ]+ },+ },+ })+ logic.mount()+ logic.actions.openAdoptSkillModal('perspective')++ await expectLogic(logic).toDispatchActions(['loadAdoptableSkillsSuccess'])+ expect(logic.values.adoptableSkills?.map((skill) => skill.name)).toEqual(['newest-skill', 'older-skill'])+ })})diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.tsindex bca1d460d9ca..e3c62a961401 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts@@ -5,6 +5,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import type { SkillPickerGroup } from 'lib/components/SkillPicker/SkillPicker'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -43,6 +44,8 @@ import {ReviewHogReviewsListScope,ReviewTriggerRequestRunModeEnumApi,} from 'products/review_hog/frontend/generated/api.schemas'+import { llmSkillsList, llmSkillsNameDuplicateCreate } from 'products/skills/frontend/generated/api'+import type { LLMSkillListApi } from 'products/skills/frontend/generated/api.schemas'export type ReviewSkillKind = 'perspective' | 'blind_spots' | 'validator' | 'resolution'@@ -100,6 +103,70 @@ export interface ViewedSkill {skillName: string}+// Mirrors the backend naming contract (skill_loader.py): the name prefix is a review skill's whole+// identity, so an adopted copy must be created under its kind's prefix to be discovered by runs.+export const REVIEW_SKILL_PREFIX_BY_KIND: Record<ReviewSkillKind, string> = {+ perspective: 'review-hog-perspective-',+ blind_spots: 'review-hog-blind-spots-',+ validator: 'review-hog-validation-',+ resolution: 'review-hog-resolution-',+}++export const REVIEW_SKILL_KIND_LABELS: Record<ReviewSkillKind, string> = {+ perspective: 'perspective',+ blind_spots: 'blind-spot check',+ validator: 'validation criteria',+ resolution: 'resolution criteria',+}++// Group headings for the adopt picker: teammates' ready-made skills of the kind first (invisible in+// the cards above, since customs are author-only there), then the rest of the team's skill store.+const ADOPT_TEAMMATE_GROUP_LABELS: Record<ReviewSkillKind, string> = {+ perspective: 'Perspectives from your teammates',+ blind_spots: 'Blind-spot checks from your teammates',+ validator: 'Validation criteria from your teammates',+ resolution: 'Resolution criteria from your teammates',+}++/** Mirrors the skills API name limit: the whole adopted name (prefix + slug) must fit. */+export const SKILL_NAME_MAX_LENGTH = 64++// Page size for loading the skill store; the loader follows the pagination to the end, so this+// only bounds how many requests a large store takes, never which skills the picker offers.+const ADOPTABLE_SKILLS_PAGE_SIZE = 300++/** The existing skill an adoption copies from. */+export interface AdoptSource {+ name: string+ description: string+}++/** Prefill slug for an adopted copy: the source name minus any review-hog kind prefix, cut to fit. */+export function defaultAdoptSlug(sourceName: string, kind: ReviewSkillKind): string {+ const knownPrefix = Object.values(REVIEW_SKILL_PREFIX_BY_KIND).find((prefix) => sourceName.startsWith(prefix))+ const bare = knownPrefix ? sourceName.slice(knownPrefix.length) : sourceName+ const maxSlugLength = SKILL_NAME_MAX_LENGTH - REVIEW_SKILL_PREFIX_BY_KIND[kind].length+ return bare.slice(0, maxSlugLength).replace(/-+$/, '')+}++/** Client-side mirror of the skills API name rules, so the confirm step can reject inline. */+export function validateAdoptSlug(slug: string, kind: ReviewSkillKind, takenNames: Set<string>): string | null {+ if (!slug) {+ return 'Enter a name for the copy'+ }+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) {+ return 'Use lowercase letters, numbers, and single hyphens between words'+ }+ const fullName = REVIEW_SKILL_PREFIX_BY_KIND[kind] + slug+ if (fullName.length > SKILL_NAME_MAX_LENGTH) {+ return `The full name must be ${SKILL_NAME_MAX_LENGTH} characters or fewer`+ }+ if (takenNames.has(fullName)) {+ return 'A skill with this name already exists'+ }+ return null+}+// Thin scout-style kickoff pointers (mirrors SCOUT_AUTHOR_PROMPT): the actual authoring guide —// pipeline context, naming contract, per-kind body shape, activation steps — lives in the// `review-hog-authoring` team skill (canonical source: products/review_hog/skills/), synced per@@ -162,6 +229,15 @@ function parsePrPath(url: string): string | null {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reviewHogSettingsLogicValues {+ adoptNewSkillName: string+ adoptSkillGroups: SkillPickerGroup[]+ adoptSkillKind: ReviewSkillKind | null+ adoptSlug: string+ adoptSlugError: string | null+ adoptSource: AdoptSource | null+ adoptableSkills: LLMSkillListApi[] | null+ adoptableSkillsLoading: boolean+ adoptingSkill: booleanawaitingTriggeredReview: booleanblindSpots: ReviewBlindSpotsConfigApi[] | nullblindSpotsLoading: boolean@@ -208,9 +284,18 @@ export interface reviewHogSettingsLogicActions {applyDefaultReviewsScope: (scope: ReviewHogReviewsListScope) => {scope: ReviewHogReviewsListScope}+ backToAdoptSearch: () => {+ value: true+ }blockSingleActiveDeactivation: (kindLabel: string) => {kindLabel: string}+ chooseAdoptSource: (source: AdoptSource) => {+ source: AdoptSource+ }+ closeAdoptSkillModal: () => {+ value: true+ }closePipelineDetail: () => {value: true}@@ -220,6 +305,21 @@ export interface reviewHogSettingsLogicActions {closeSkillDrawer: () => {value: true}+ loadAdoptableSkills: (_?: any) => any+ loadAdoptableSkillsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAdoptableSkillsSuccess: (+ adoptableSkills: LLMSkillListApi[],+ payload?: any+ ) => {+ adoptableSkills: LLMSkillListApi[]+ payload?: any+ }loadAll: () => {value: true}@@ -346,6 +446,9 @@ export interface reviewHogSettingsLogicActions {markInitialLoadFailed: () => {value: true}+ openAdoptSkillModal: (kind: ReviewSkillKind) => {+ kind: ReviewSkillKind+ }openPipelineDetail: () => {value: true}@@ -371,6 +474,9 @@ export interface reviewHogSettingsLogicActions {selectValidator: (skillName: string) => {skillName: string}+ setAdoptSlug: (slug: string) => {+ slug: string+ }setReviewDrawerTab: (tab: ReviewDrawerTab) => {tab: ReviewDrawerTab}@@ -405,6 +511,15 @@ export interface reviewHogSettingsLogicActions {stopTriggeredReviewWatch: () => {value: true}+ submitAdoptSkill: () => {+ value: true+ }+ submitAdoptSkillFinished: () => {+ value: true+ }+ submitAdoptSkillStarted: () => {+ value: true+ }submitTriggerReview: (runMode?: ReviewTriggerRequestRunModeEnumApi) => {runMode: ReviewTriggerRequestRunModeEnumApi}@@ -447,6 +562,24 @@ export interface reviewHogSettingsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reviewHogSettingsLogicMeta {__keaTypeGenInternalSelectorTypes: {+ adoptSkillGroups: (+ adoptableSkills: LLMSkillListApi[] | null,+ adoptSkillKind: ReviewSkillKind | null,+ perspectives: ReviewPerspectiveConfigApi[] | null,+ blindSpots: ReviewBlindSpotsConfigApi[] | null,+ validators: ReviewValidatorConfigApi[] | null,+ resolutionSkills: ReviewResolutionConfigApi[] | null+ ) => SkillPickerGroup[]+ adoptNewSkillName: (adoptSkillKind: ReviewSkillKind | null, adoptSlug: string) => string+ adoptSlugError: (+ adoptSlug: string,+ adoptSkillKind: ReviewSkillKind | null,+ adoptableSkills: LLMSkillListApi[] | null,+ perspectives: ReviewPerspectiveConfigApi[] | null,+ blindSpots: ReviewBlindSpotsConfigApi[] | null,+ validators: ReviewValidatorConfigApi[] | null,+ resolutionSkills: ReviewResolutionConfigApi[] | null+ ) => string | nullrecentReviews: (recentReviewsPage: ReviewRecentReviewsPageApi | null) => ReviewRecentReviewApi[] | nullmoreReviewsAvailable: (recentReviewsPage: ReviewRecentReviewsPageApi | null, reviewsLimit: number) => booleanreviewFindingsSplit: (@@ -507,6 +640,17 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([applyDefaultReviewsScope: (scope: ReviewHogReviewsListScope) => ({ scope }),startSkillAuthorTask: (kind: ReviewSkillKind) => ({ kind }),startSkillAuthorTaskFinished: true,+ // "Use an existing skill": pick a team skill, copy it under the kind's prefix, switch it on.+ openAdoptSkillModal: (kind: ReviewSkillKind) => ({ kind }),+ closeAdoptSkillModal: true,+ chooseAdoptSource: (source: AdoptSource) => ({ source }),+ backToAdoptSearch: true,+ setAdoptSlug: (slug: string) => ({ slug }),+ submitAdoptSkill: true,+ // Flipped by the listener (not the submit action itself) so a repeat dispatch mid-flight is+ // dropped before it POSTs, mirroring the trigger flow's guard.+ submitAdoptSkillStarted: true,+ submitAdoptSkillFinished: true,setTriggerPrUrl: (prUrl: string) => ({ prUrl }),// Starts a run on the pasted PR URL: a review (which resolves comments per the user's// setting), a review without resolving, or a resolve-only run — the split button's variants.@@ -563,6 +707,32 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([loadResolutionSkills: async () => await reviewHogResolutionList(currentProjectId()),},],+ // Every live team skill, for the adopt picker. Fetched fresh on each modal open so a skill+ // created since the last open (e.g. by an authoring task) is offered. The picker's search,+ // grouping, and name-collision checks all assume the complete store, so the loader follows+ // the pagination to the end instead of trusting one page to cover it.+ adoptableSkills: [+ null as LLMSkillListApi[] | null,+ {+ loadAdoptableSkills: async (_ = null, breakpoint) => {+ const skills: LLMSkillListApi[] = []+ let hasMore = true+ while (hasMore) {+ // `offset: skills.length` adapts to the page size the server actually+ // returned, so a server-side clamp below the requested limit skips nothing.+ const response = await llmSkillsList(currentProjectId(), {+ limit: ADOPTABLE_SKILLS_PAGE_SIZE,+ offset: skills.length,+ })+ breakpoint()+ skills.push(...response.results)+ // An empty page stops the loop too, so a buggy `next` can never spin it forever.+ hasMore = Boolean(response.next) && response.results.length > 0+ }+ return skills+ },+ },+ ],recentReviewsPage: [null as ReviewRecentReviewsPageApi | null,{@@ -794,6 +964,39 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([startSkillAuthorTaskFinished: () => null,},],+ // Which kind the adopt modal is open for; null means closed.+ adoptSkillKind: [+ null as ReviewSkillKind | null,+ {+ openAdoptSkillModal: (_, { kind }) => kind,+ closeAdoptSkillModal: () => null,+ },+ ],+ // The picked source skill; non-null switches the modal from the picker to the confirm step.+ adoptSource: [+ null as AdoptSource | null,+ {+ chooseAdoptSource: (_, { source }) => source,+ backToAdoptSearch: () => null,+ openAdoptSkillModal: () => null,+ closeAdoptSkillModal: () => null,+ },+ ],+ adoptSlug: [+ '',+ {+ setAdoptSlug: (_, { slug }) => slug,+ openAdoptSkillModal: () => '',+ backToAdoptSearch: () => '',+ },+ ],+ adoptingSkill: [+ false,+ {+ submitAdoptSkillStarted: () => true,+ submitAdoptSkillFinished: () => false,+ },+ ],triggerPrUrl: ['',{@@ -819,6 +1022,97 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([}),selectors({+ // The adopt picker's two groups: teammates' ready-made skills of the kind (store rows with+ // the kind's prefix that aren't already cards above, i.e. not canonicals or own customs),+ // then every other team skill. Cross-kind review-hog skills land in the second group on+ // purpose: adopting, say, a validation bar as resolution criteria is legitimate reuse.+ adoptSkillGroups: [+ (s) => [+ s.adoptableSkills,+ s.adoptSkillKind,+ s.perspectives,+ s.blindSpots,+ s.validators,+ s.resolutionSkills,+ ],+ (+ adoptableSkills: LLMSkillListApi[] | null,+ adoptSkillKind: ReviewSkillKind | null,+ perspectives: ReviewPerspectiveConfigApi[] | null,+ blindSpots: ReviewBlindSpotsConfigApi[] | null,+ validators: ReviewValidatorConfigApi[] | null,+ resolutionSkills: ReviewResolutionConfigApi[] | null+ ): SkillPickerGroup[] => {+ if (!adoptSkillKind || !adoptableSkills) {+ return []+ }+ const prefix = REVIEW_SKILL_PREFIX_BY_KIND[adoptSkillKind]+ const cardsByKind: Record<ReviewSkillKind, { skill_name: string }[] | null> = {+ perspective: perspectives,+ blind_spots: blindSpots,+ validator: validators,+ resolution: resolutionSkills,+ }+ const cardNames = new Set((cardsByKind[adoptSkillKind] ?? []).map((card) => card.skill_name))+ const toPickerSkill = (skill: LLMSkillListApi): { name: string; description: string } => ({+ name: skill.name,+ description: skill.description,+ })+ return [+ {+ key: 'teammates',+ label: ADOPT_TEAMMATE_GROUP_LABELS[adoptSkillKind],+ skills: adoptableSkills+ .filter((skill) => skill.name.startsWith(prefix) && !cardNames.has(skill.name))+ .map(toPickerSkill),+ },+ {+ key: 'store',+ label: 'All team skills',+ skills: adoptableSkills.filter((skill) => !skill.name.startsWith(prefix)).map(toPickerSkill),+ },+ ]+ },+ ],+ adoptNewSkillName: [+ (s) => [s.adoptSkillKind, s.adoptSlug],+ (adoptSkillKind: ReviewSkillKind | null, adoptSlug: string): string =>+ adoptSkillKind ? REVIEW_SKILL_PREFIX_BY_KIND[adoptSkillKind] + adoptSlug : '',+ ],+ adoptSlugError: [+ (s) => [+ s.adoptSlug,+ s.adoptSkillKind,+ s.adoptableSkills,+ s.perspectives,+ s.blindSpots,+ s.validators,+ s.resolutionSkills,+ ],+ (+ adoptSlug: string,+ adoptSkillKind: ReviewSkillKind | null,+ adoptableSkills: LLMSkillListApi[] | null,+ perspectives: ReviewPerspectiveConfigApi[] | null,+ blindSpots: ReviewBlindSpotsConfigApi[] | null,+ validators: ReviewValidatorConfigApi[] | null,+ resolutionSkills: ReviewResolutionConfigApi[] | null+ ): string | null => {+ if (!adoptSkillKind) {+ return null+ }+ // Best-effort collision set: the store page plus the user's own cards. The server+ // still rejects anything this misses.+ const takenNames = new Set<string>([+ ...(adoptableSkills?.map((skill) => skill.name) ?? []),+ ...(perspectives?.map((card) => card.skill_name) ?? []),+ ...(blindSpots?.map((card) => card.skill_name) ?? []),+ ...(validators?.map((card) => card.skill_name) ?? []),+ ...(resolutionSkills?.map((card) => card.skill_name) ?? []),+ ])+ return validateAdoptSlug(adoptSlug, adoptSkillKind, takenNames)+ },+ ],recentReviews: [(s) => [s.recentReviewsPage],(recentReviewsPage: ReviewRecentReviewsPageApi | null): ReviewRecentReviewApi[] | null =>@@ -1060,6 +1354,64 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([blockSingleActiveDeactivation: ({ kindLabel }) => {lemonToast.info(`One ${kindLabel} always runs — switch by selecting another one`)},+ openAdoptSkillModal: () => {+ actions.loadAdoptableSkills()+ },+ loadAdoptableSkillsFailure: () => {+ // Without this the picker would render its "no skills yet" empty state over a fetch+ // error. Closing keeps the states honest; reopening retries the load.+ lemonToast.error("Couldn't load your team's skills. Open the picker again to retry.")+ actions.closeAdoptSkillModal()+ },+ chooseAdoptSource: ({ source }) => {+ if (values.adoptSkillKind) {+ actions.setAdoptSlug(defaultAdoptSlug(source.name, values.adoptSkillKind))+ }+ },+ submitAdoptSkill: async () => {+ const kind = values.adoptSkillKind+ const source = values.adoptSource+ if (!kind || !source || values.adoptingSkill || values.adoptSlugError) {+ return+ }+ const newName = values.adoptNewSkillName+ actions.submitAdoptSkillStarted()+ try {+ await llmSkillsNameDuplicateCreate(currentProjectId(), source.name, { new_name: newName })+ } catch (error: any) {+ // Kept open so a name conflict can be fixed in place; the server's detail names it.+ lemonToast.error(error?.data?.detail || error?.detail || error?.message || "Couldn't copy the skill")+ actions.submitAdoptSkillFinished()+ return+ }+ try {+ if (kind === 'perspective') {+ await reviewHogPerspectivesPartialUpdate(currentProjectId(), newName, { enabled: true })+ } else if (kind === 'blind_spots') {+ await reviewHogBlindSpotsPartialUpdate(currentProjectId(), newName, { active: true })+ } else if (kind === 'validator') {+ await reviewHogValidatorsPartialUpdate(currentProjectId(), newName, { active: true })+ } else {+ await reviewHogResolutionPartialUpdate(currentProjectId(), newName, { active: true })+ }+ lemonToast.success('Skill copied. It now runs on your PR reviews.')+ } catch {+ // The copy exists even though switching it on failed: close to its new card and let+ // the user flip it on there.+ lemonToast.error("Copied the skill, but couldn't switch it on. Turn it on from its card.")+ }+ if (kind === 'perspective') {+ actions.loadPerspectives()+ } else if (kind === 'blind_spots') {+ actions.loadBlindSpots()+ } else if (kind === 'validator') {+ actions.loadValidators()+ } else {+ actions.loadResolutionSkills()+ }+ actions.submitAdoptSkillFinished()+ actions.closeAdoptSkillModal()+ },openReviewDetail: ({ review }) => {actions.loadReviewDetail(review.id)},diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex d3fcea603d6e..c59410631148 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -430,11 +430,13 @@ def duplicate_skill(if LLMSkill.objects.filter(team=team, name=new_name, deleted=False).exists():raise LLMSkillDuplicateNameConflictError()- # A duplicate is a brand-new, user-authored skill under a new name, so it does not inherit the- # source's provenance or classification: drop the harness seed marker, and leave `category`- # at its default empty (the copy isn't a registered scout — it would only become one if named- # `signals-scout-*` and picked up by scout registration). This keeps non-runnable rows out of- # the Scouts tab and avoids mislabeling a fork as canonical.+ # A duplicate is a brand-new, user-authored skill under a new name, so it inherits nothing+ # from the source's provenance or classification: the harness seed marker is dropped, and+ # `category` is derived from the new name exactly like the create paths do (empty unless the+ # new name carries a registered prefix). Deriving instead of copying keeps a fork of a scout+ # or canonical from carrying that grouping under an unrelated name, while a copy named into+ # a registered prefix (e.g. adopting a skill as a ReviewHog perspective) groups like any+ # other skill of that kind.duplicated_metadata = dict(source_latest.metadata or {})duplicated_metadata.pop("seeded_by", None)@@ -448,6 +450,7 @@ def duplicate_skill(compatibility=source_latest.compatibility,allowed_tools=source_latest.allowed_tools,metadata=duplicated_metadata,+ category=category_for_skill_name(new_name),version=1,is_latest=True,created_by=user,diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 2bf662694e57..dfe80cedd368 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -896,6 +896,28 @@ class TestLLMSkillAPI(APIBaseTest):copy_skill = LLMSkill.objects.get(name="the-copy", deleted=False)assert LLMSkillFile.objects.filter(skill=copy_skill).count() == 1+ @parameterized.expand(+ [+ ("plain-name-copy", "", ""),+ ("review-hog-perspective-my-lens", "", "review_hog"),+ ("plain-copy-of-scout", "scout", ""),+ ]+ )+ def test_duplicate_derives_category_from_new_name(+ self, new_name: str, source_category: str, expected_category: str+ ):+ self.create_skill(name="category-source", category=source_category)++ response = self.client.post(+ self._url("name/category-source/duplicate"),+ data={"new_name": new_name},+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["category"] == expected_category+ assert LLMSkill.objects.get(name=new_name, deleted=False).category == expected_category+def test_duplicate_to_existing_name_fails(self):self.create_skill(name="source")self.create_skill(name="taken")