feat(frontend): edit projects and show semantic match evidence

This commit is contained in:
shira committed 2026-10-11 14:03:31 +03:00
1 parent 5a731c25b7
commit bc00d6901f
52 files changed
+2992 -111

No files matched your search

+4
View File
@@ -15,6 +15,7 @@ export type {
MatchConfirmedComponentsModel,
MatchGroup,
MatchSearchModel,
MatchSemanticEvidenceModel,
MatchSearchSourceModel,
MatchUnconfirmedCardModel,
} from "./model/adapter";
@@ -37,8 +38,11 @@ export {
evidenceRows,
formatScore,
otherUnknowns,
semanticBlock,
type ComponentRow,
type EvidenceRow,
type SemanticBlock,
type SemanticRow,
} from "./model/explanation";
export {
gradeCodes,
@@ -203,6 +203,82 @@ describe("match response adapter", () => {
expect(matchSearchFromTransport(roundTrip)).toEqual(model);
});
it("round-trips the semantic evidence of an entry in the server order", () => {
const response = matchResponseFixture();
const [candidate] = response.groups.main;
if (!candidate) throw new Error("Fixture main card is missing.");
const evidence = [
{
requirement_kind: "task" as const,
requirement_text: "Разработать сервис сверки платежей",
item_kind: "project" as const,
project_title: "Платежный шлюз",
repository_verified: true,
similarity: "high" as const,
},
{
requirement_kind: "required_skill" as const,
requirement_text: "PostgreSQL",
item_kind: "stack" as const,
project_title: null,
repository_verified: false,
similarity: "medium" as const,
},
];
const withEvidence = {
...response,
groups: { ...response.groups, main: [{ ...candidate, semantic_evidence: evidence }] },
};
const model = matchSearchFromTransport(withEvidence);
expect(model.cards[0]?.semanticEvidence).toEqual([
{
requirementKind: "task",
requirementText: "Разработать сервис сверки платежей",
itemKind: "project",
projectTitle: "Платежный шлюз",
repositoryVerified: true,
similarity: "high",
},
{
requirementKind: "required_skill",
requirementText: "PostgreSQL",
itemKind: "stack",
projectTitle: null,
repositoryVerified: false,
similarity: "medium",
},
]);
expect(matchSearchToTransport(model)).toEqual(withEvidence);
});
it("rejects evidence that carries a repository address or an owner", () => {
const response = matchResponseFixture();
const [candidate] = response.groups.main;
if (!candidate) throw new Error("Fixture main card is missing.");
const item = {
requirement_kind: "task",
requirement_text: "Разработать сервис сверки платежей",
item_kind: "project",
project_title: "Платежный шлюз",
repository_verified: true,
similarity: "high",
};
for (const extra of [
{ repository_url: "https://github.com/example-org/payments-ledger" },
{ repository_owner: "example-org" },
]) {
expectInvalidResponse({
...response,
groups: {
...response.groups,
main: [{ ...candidate, semantic_evidence: [{ ...item, ...extra }] }],
},
});
}
});
it("keeps the truncation flag, which carries no count", () => {
const response = { ...matchResponseFixture(), truncated: true };
const model = matchSearchFromTransport(response);
+49 -4
View File
@@ -43,10 +43,26 @@ type MatchPublicContext = {
};
type MatchEvidence = ConfirmedCandidate["evidence_summary"][number];
type MatchSemanticEvidenceTransport = ConfirmedCandidate["semantic_evidence"][number];
type MatchUnknownFlag = ConfirmedCandidate["unknown_flags"][number];
type ConfirmedComponents = ConfirmedCandidate["components"];
type UnconfirmedComponents = UnconfirmedCandidate["components"];
/**
* Why a requirement of the need matched a published card item. The server
* computes it from stored vectors; it carries only public card values, so it
* has no repository address and no owner.
*/
export type MatchSemanticEvidenceModel = {
readonly requirementKind: MatchSemanticEvidenceTransport["requirement_kind"];
readonly requirementText: string;
readonly itemKind: MatchSemanticEvidenceTransport["item_kind"];
/** Published project title for a project item, otherwise null. */
readonly projectTitle: string | null;
readonly repositoryVerified: boolean;
readonly similarity: MatchSemanticEvidenceTransport["similarity"];
};
export type MatchConfirmedComponentsModel = Omit<ConfirmedComponents, "rank_score"> & {
readonly rankScore: ConfirmedComponents["rank_score"];
};
@@ -61,6 +77,8 @@ export type MatchConfirmedCardModel = {
readonly strength: ConfirmedCandidate["strength"];
readonly publicContext: MatchPublicContext;
readonly evidenceSummary: readonly MatchEvidence[];
/** In the order the server sent: strongest similarity first. */
readonly semanticEvidence: readonly MatchSemanticEvidenceModel[];
readonly components: MatchConfirmedComponentsModel;
readonly unknownFlags: readonly MatchUnknownFlag[];
};
@@ -75,6 +93,7 @@ export type MatchUnconfirmedCardModel = {
readonly strength: null;
readonly publicContext: MatchPublicContext;
readonly evidenceSummary: readonly MatchEvidence[];
readonly semanticEvidence: readonly MatchSemanticEvidenceModel[];
readonly components: UnconfirmedComponents;
readonly unknownFlags: readonly MatchUnknownFlag[];
};
@@ -215,6 +234,32 @@ function publicContextToTransport(
};
}
function semanticEvidenceFromTransport(
items: readonly MatchSemanticEvidenceTransport[],
): MatchSemanticEvidenceModel[] {
return items.map((item) => ({
requirementKind: item.requirement_kind,
requirementText: item.requirement_text,
itemKind: item.item_kind,
projectTitle: item.project_title,
repositoryVerified: item.repository_verified,
similarity: item.similarity,
}));
}
function semanticEvidenceToTransport(
items: readonly MatchSemanticEvidenceModel[],
): MatchSemanticEvidenceTransport[] {
return items.map((item) => ({
requirement_kind: item.requirementKind,
requirement_text: item.requirementText,
item_kind: item.itemKind,
project_title: item.projectTitle,
repository_verified: item.repositoryVerified,
similarity: item.similarity,
}));
}
function confirmedFromTransport(
group: "main" | "near",
candidate: ConfirmedCandidate,
@@ -230,6 +275,7 @@ function confirmedFromTransport(
strength: candidate.strength,
publicContext: publicContextFromTransport(candidate.public_context),
evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })),
semanticEvidence: semanticEvidenceFromTransport(candidate.semantic_evidence),
components: { ...components, rankScore },
unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })),
};
@@ -246,6 +292,7 @@ function unconfirmedFromTransport(candidate: UnconfirmedCandidate): MatchUnconfi
strength: null,
publicContext: publicContextFromTransport(candidate.public_context),
evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })),
semanticEvidence: semanticEvidenceFromTransport(candidate.semantic_evidence),
components: { fit: candidate.components.fit, coverage: candidate.components.coverage },
unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })),
};
@@ -275,8 +322,7 @@ function confirmedToTransport(candidate: MatchConfirmedCardModel): ConfirmedCand
strength: candidate.strength,
public_context: publicContextToTransport(candidate.publicContext),
evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })),
// The card model does not carry the semantic explanation yet.
semantic_evidence: [],
semantic_evidence: semanticEvidenceToTransport(candidate.semanticEvidence),
components: { ...components, rank_score: rankScore },
unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })),
};
@@ -292,8 +338,7 @@ function unconfirmedToTransport(candidate: MatchUnconfirmedCardModel): Unconfirm
strength: null,
public_context: publicContextToTransport(candidate.publicContext),
evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })),
// The card model does not carry the semantic explanation yet.
semantic_evidence: [],
semantic_evidence: semanticEvidenceToTransport(candidate.semanticEvidence),
components: { fit: candidate.components.fit, coverage: candidate.components.coverage },
unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })),
};
@@ -27,6 +27,15 @@ export type CardDetails = {
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
/** Published projects in the candidate's order; null when the card has none to show. */
projects:
| readonly {
title: string;
description: string | null;
stack: readonly string[];
repositoryVerified: boolean;
}[]
| null;
};
/**
@@ -54,6 +63,13 @@ export function presentCard(card: AnonymousCardContent): CardDetails {
salaryCompatibility: card.salary_compatibility
? salaryCompatibilityLabels[card.salary_compatibility]
: null,
projects:
card.projects?.map((project) => ({
title: project.title,
description: project.description,
stack: [...project.stack],
repositoryVerified: project.repository_verified,
})) ?? null,
};
}
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
import { componentRows, evidenceRows, formatScore, otherUnknowns } from "./explanation";
import {
componentRows,
evidenceRows,
formatScore,
otherUnknowns,
semanticBlock,
} from "./explanation";
import { matchModelFixture } from "./match.fixtures";
function cardAt(index: number) {
@@ -79,3 +85,59 @@ describe("match explanation", () => {
]);
});
});
describe("semantic evidence block", () => {
it("lists the rows in the order the server sent, with kind, label, and band", () => {
const block = semanticBlock(cardAt(1));
expect(block?.kind).toBe("evidence");
if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
expect(
block.rows.map((row) => [
row.requirementLabel,
row.itemKindLabel,
row.itemLabel,
row.similarityLabel,
]),
).toEqual([
["Задача", "Проект", "Платежный шлюз", "Высокое сходство"],
["Обязательный навык", "Стек", "Технологии карточки", "Среднее сходство"],
["Желательный навык", "Проект", "Внутренняя витрина", "Среднее сходство"],
["Задача", "Роль", "Специализации и грейды карточки", "Среднее сходство"],
]);
});
it("marks only a verified project as backed by a public repository", () => {
const block = semanticBlock(cardAt(1));
if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
expect(block.rows.map((row) => row.repositoryVerified)).toEqual([true, false, false, false]);
});
it("never marks a stack or roles item, even if a verified flag came with it", () => {
const card = cardAt(1);
const forged = {
...card,
semanticEvidence: card.semanticEvidence.map((item) => ({
...item,
repositoryVerified: true,
})),
};
const block = semanticBlock(forged);
if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
expect(block.rows.map((row) => row.repositoryVerified)).toEqual([true, false, true, false]);
});
it("keeps the unavailable wording when the semantic component is unknown for lack of ML", () => {
expect(semanticBlock(cardAt(0))).toEqual({
kind: "unavailable",
text: "смысловой анализ недоступен",
});
});
it("shows no block when there is nothing to say", () => {
// An unconfirmed entry without evidence and without a semantics flag.
expect(semanticBlock(cardAt(3))).toBeNull();
});
});
@@ -3,6 +3,10 @@ import type { MatchCardModel } from "./adapter";
import {
evidenceCodeLabels,
evidenceStateLabels,
semanticItemKindLabels,
semanticItemPlainLabels,
semanticRequirementLabels,
semanticSimilarityLabels,
unknownComponentLabels,
unknownReasonLabels,
} from "./labels";
@@ -157,3 +161,52 @@ export function evidenceRows(card: MatchCardModel): EvidenceRow[] {
stateLabel: evidenceStateLabels[item.state],
}));
}
export type SemanticRow = {
key: string;
requirementLabel: string;
requirementText: string;
itemKindLabel: string;
/** The title of a published project, or a plain label of the stack or the roles. */
itemLabel: string;
/** True only for a project whose linked repository the server found public. */
repositoryVerified: boolean;
similarity: "high" | "medium";
similarityLabel: string;
};
export type SemanticBlock =
{ kind: "evidence"; rows: SemanticRow[] } | { kind: "unavailable"; text: string };
/**
* The "matches by meaning" block of one entry. The rows keep the order and
* the limit that the server sent. With no rows the block appears only when
* the server names the semantic component unknown because ML was down, with
* the same words as the explanation; an empty list from a bank search or from
* a need without a match shows no block at all.
*/
export function semanticBlock(card: MatchCardModel): SemanticBlock | null {
if (card.semanticEvidence.length > 0) {
return {
kind: "evidence",
rows: card.semanticEvidence.map((item, index) => ({
key: `${index}:${item.requirementKind}:${item.requirementText}`,
requirementLabel: semanticRequirementLabels[item.requirementKind],
requirementText: item.requirementText,
itemKindLabel: semanticItemKindLabels[item.itemKind],
itemLabel:
item.itemKind === "project"
? (item.projectTitle ?? semanticItemKindLabels.project)
: semanticItemPlainLabels[item.itemKind],
repositoryVerified: item.itemKind === "project" && item.repositoryVerified,
similarity: item.similarity,
similarityLabel: semanticSimilarityLabels[item.similarity],
})),
};
}
const flag = flagFor(card, "semantics");
if (flag?.reason === "ml_unavailable") {
return { kind: "unavailable", text: describeUnknownReason(flag) };
}
return null;
}
@@ -5,6 +5,7 @@ import type {
MatchEvidenceCode,
MatchEvidenceState,
MatchSearchStackTag,
MatchSemanticItemKind,
MatchStrength,
MatchUnknownComponent,
MatchUnknownReason,
@@ -154,3 +155,29 @@ export const unknownReasonLabels: Readonly<Record<MatchUnknownReason, string>> =
no_response_history: "нет истории ответов",
percentile_not_computed: "перцентиль пока не рассчитывается",
};
export const semanticRequirementLabels = {
required_skill: "Обязательный навык",
desired_skill: "Желательный навык",
task: "Задача",
} as const;
export const semanticItemKindLabels: Readonly<Record<MatchSemanticItemKind, string>> = {
project: "Проект",
stack: "Стек",
roles: "Роль",
};
/**
* Public labels of the card items that carry no title of their own: the
* stack and the roles are shown as the card shows them to the organization.
*/
export const semanticItemPlainLabels: Readonly<Record<"stack" | "roles", string>> = {
stack: "Технологии карточки",
roles: "Специализации и грейды карточки",
};
export const semanticSimilarityLabels = {
high: "Высокое сходство",
medium: "Среднее сходство",
} as const;
@@ -89,7 +89,40 @@ export function matchResponseFixture(
{ code: "confirmed_category", state: "supports" },
{ code: "required_skill_evidence", state: "partial" },
],
semantic_evidence: [],
semantic_evidence: [
{
requirement_kind: "task",
requirement_text: "Разработать сервис сверки платежей",
item_kind: "project",
project_title: "Платежный шлюз",
repository_verified: true,
similarity: "high",
},
{
requirement_kind: "required_skill",
requirement_text: "Проектирование схем PostgreSQL",
item_kind: "stack",
project_title: null,
repository_verified: false,
similarity: "medium",
},
{
requirement_kind: "desired_skill",
requirement_text: "Наставничество в команде",
item_kind: "project",
project_title: "Внутренняя витрина",
repository_verified: false,
similarity: "medium",
},
{
requirement_kind: "task",
requirement_text: "Поддерживать сервисы доставки",
item_kind: "roles",
project_title: null,
repository_verified: false,
similarity: "medium",
},
],
components: {
fit: 0.4,
coverage: 0.18,
@@ -0,0 +1,70 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { AnonymousCardContent } from "../../../shared/api/schemas";
import { matchCardQueryKeys } from "../api/card";
import { CandidateCardDetails } from "./candidate-card-details";
const accountId = "11111111-1111-4111-8111-111111111111";
const organizationId = "22222222-2222-4222-8222-222222222222";
const handle = "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
const card: AnonymousCardContent = {
pseudonym: handle,
categories: null,
stack: ["go"],
self_assessment: null,
experience_band: "3_6",
work_formats: null,
salary_compatibility: null,
projects: [
{
title: "Платежный шлюз",
description: "Проводки и сверки.\nВыплаты по расписанию.",
stack: ["Go", "PostgreSQL"],
repository_verified: true,
},
{ title: "Каталог", description: null, stack: [], repository_verified: false },
],
};
function render(content: AnonymousCardContent): string {
const client = new QueryClient();
client.setQueryData(matchCardQueryKeys.card(accountId, organizationId, handle), content);
return renderToString(
<QueryClientProvider client={client}>
<CandidateCardDetails
id="card-panel"
accountId={accountId}
organizationId={organizationId}
candidateHandle={handle}
open
/>
</QueryClientProvider>,
).replaceAll("<!-- -->", "");
}
describe("candidate card details", () => {
it("lists the published projects with tags and a badge for a verified repository", () => {
const html = render(card);
expect(html).toContain(">Проекты</h6>");
expect(html).toContain("Платежный шлюз");
expect(html).toContain("Выплаты по расписанию.");
expect(html).toContain(">PostgreSQL<");
expect(html.match(/Подтвержден публичным репозиторием/g)).toHaveLength(1);
expect(html).toContain("Каталог");
});
it("shows no address or link of a repository", () => {
const html = render(card);
expect(html).not.toContain("github");
expect(html).not.toMatch(/href="https?:/);
});
it("shows no projects block while the card carries none", () => {
expect(render({ ...card, projects: null })).not.toContain(">Проекты</h6>");
expect(render({ ...card, projects: [] })).not.toContain(">Проекты</h6>");
});
});
@@ -4,6 +4,7 @@ import {
ForbiddenState,
isAccessDenied,
LoadingState,
PublishedProjects,
StatusView,
TrustLevel,
} from "../../../shared/ui";
@@ -155,6 +156,12 @@ export function CandidateCardDetails({
<dt>Зарплатные ожидания</dt>
<dd>{details.salaryCompatibility ?? "Нет значения в карточке"}</dd>
</dl>
{details.projects && details.projects.length > 0 ? (
<section aria-label="Проекты кандидата">
<h6 className={styles.subtitle}>Проекты</h6>
<PublishedProjects projects={details.projects} />
</section>
) : null}
{hasCategories ? (
<section aria-label="Подтверждающие факты оценки">
<h6 className={styles.subtitle}>Подтверждающие факты оценки</h6>
@@ -223,3 +223,72 @@
flex: 1 1 100%;
}
}
/* "Matches by meaning": a requirement of the need, an arrow, the card item
* that matched it, and the similarity band as a tag. The words carry the
* meaning; the arrow only repeats the direction. */
.semantic {
display: grid;
gap: var(--space-2);
min-width: 0;
padding-block-start: var(--space-2);
border-block-start: var(--line-thin) solid var(--color-divider);
}
.semantic-title {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.semantic-list {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.semantic-list li {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--space-1) var(--space-3);
min-width: 0;
}
.semantic-side {
display: flex;
flex-wrap: wrap;
gap: 0 var(--space-2);
align-items: baseline;
min-width: 0;
}
.semantic-side .caption {
flex: none;
}
.semantic-text {
min-width: 0;
color: var(--color-text);
overflow-wrap: anywhere;
}
.semantic-arrow {
color: var(--color-text-secondary);
}
.semantic-badge,
.semantic-band {
display: inline-flex;
}
@media (width >= 48rem) {
.semantic-list li {
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto;
align-items: baseline;
}
}
+43 -1
View File
@@ -2,7 +2,7 @@ import type { ReactNode } from "react";
import type { MatchSearchStackTag } from "../../../shared/api/schemas";
import { Card, Mono, Tag, TrustLevel, VisuallyHidden } from "../../../shared/ui";
import type { MatchCardModel } from "../model/adapter";
import { evidenceRows, type EvidenceRow } from "../model/explanation";
import { evidenceRows, semanticBlock, type EvidenceRow } from "../model/explanation";
import {
experienceBandLabels,
gradeLabels,
@@ -61,6 +61,7 @@ export function MatchCardView({
const confirmed = card.confirmationStatus === "confirmed";
const context = card.publicContext;
const sources = evidenceRows(card);
const semantic = semanticBlock(card);
const shortSpecialization = specializationShortLabels[card.specialization];
const compatibility = context.salaryCompatibility;
@@ -180,6 +181,47 @@ export function MatchCardView({
) : (
<p className={styles.unknown}>Сервер не вернул пояснений по источникам.</p>
)}
{semantic ? (
<div className={styles.semantic}>
<h6 id={`${headingId}-semantic`} className={styles["semantic-title"]}>
Совпадения по смыслу
</h6>
{semantic.kind === "evidence" ? (
<ul className={styles["semantic-list"]} aria-labelledby={`${headingId}-semantic`}>
{semantic.rows.map((row) => (
<li key={row.key} data-similarity={row.similarity}>
<span className={styles["semantic-side"]}>
<span className={styles.caption}>{row.requirementLabel}</span>
<span className={styles["semantic-text"]}>{row.requirementText}</span>
</span>
<span className={styles["semantic-arrow"]} aria-hidden="true">
→
</span>
<VisuallyHidden>совпало с:</VisuallyHidden>
<span className={styles["semantic-side"]}>
<span className={styles.caption}>{row.itemKindLabel}</span>
<span className={styles["semantic-text"]}>{row.itemLabel}</span>
{row.repositoryVerified ? (
<span className={styles["semantic-badge"]}>
<Tag tone="success" dot>
Публичный репозиторий
</Tag>
</span>
) : null}
</span>
<span className={styles["semantic-band"]}>
<Tag tone={row.similarity === "high" ? "accent" : "neutral"}>
{row.similarityLabel}
</Tag>
</span>
</li>
))}
</ul>
) : (
<p className={styles.unknown}>Совпадения по смыслу: {semantic.text}.</p>
)}
</div>
) : null}
</Card>
</div>
{actions ? <div className={styles.actions}>{actions}</div> : null}