feat(matching): rank with semantic embeddings and explain matches by evidence

This commit is contained in:
shira committed 2026-10-11 10:39:46 +03:00
1 parent facc1789b1
commit 24b64d698a
215 files changed
+16951 -327

No files matched your search

+38 -4
View File
@@ -444,9 +444,12 @@ type CandidateProfileInput struct {
// the exact periods and indices in Experience.
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
SoftSkills []ProfileClaimInput[string]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
// Projects replaces the stored projects; nil keeps them, so a client
// that does not know the section never deletes it.
Projects *[]ProfileClaimInput[ProfileProject]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
}
// CandidateProfileContent is the validated content of a profile: every claim
@@ -464,6 +467,7 @@ type CandidateProfileContent struct {
experience []ProfileClaim[ProfileExperience]
parallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
softSkills []ProfileClaim[string]
projects []ProfileClaim[ProfileProject]
location *ProfileClaim[string]
relocation *ProfileClaim[bool]
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
@@ -562,6 +566,12 @@ func (content CandidateProfileContent) SoftSkills() []ProfileClaim[string] {
return slices.Clone(content.softSkills)
}
// Projects returns a copy of the projects in the order the candidate gave
// them.
func (content CandidateProfileContent) Projects() []ProfileClaim[ProfileProject] {
return slices.Clone(content.projects)
}
// Equal reports whether both contents hold the same claims with the same
// provenance, which tells a change from a body that changes nothing.
func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool {
@@ -576,7 +586,8 @@ func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool
slices.EqualFunc(content.roles, other.roles, claimsEqual) &&
slices.EqualFunc(content.experience, other.experience, claimsEqual) &&
slices.Equal(content.parallelPeriodAcknowledgements, other.parallelPeriodAcknowledgements) &&
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual)
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual) &&
slices.EqualFunc(content.projects, other.projects, claimsEqual)
}
func (CandidateProfileContent) String() string { return redactedProfile }
@@ -790,6 +801,7 @@ type profileRules struct {
softSkills claimRules[string]
roles claimRules[ProfileRole]
experience claimRules[ProfileExperience]
projects claimRules[ProfileProject]
}
func newProfileRules(now time.Time) profileRules {
@@ -815,6 +827,7 @@ func newProfileRules(now time.Time) profileRules {
validate: roleRules, key: func(role ProfileRole) string { return string(role.Specialization) }, keyPointer: "/specialization",
},
experience: claimRules[ProfileExperience]{validate: experienceRules(now)},
projects: claimRules[ProfileProject]{validate: projectRules, key: projectKey, keyPointer: "/repository_url"},
}
}
@@ -1028,6 +1041,14 @@ func ResolveCandidateProfileContent(stored CandidateProfileContent, input Candid
content.softSkills, err = resolveItems(rules.softSkills, location, "/soft_skills", input.SoftSkills, stored.softSkills, maxProfileSoftSkills, at)
return err
},
func() (err error) {
if input.Projects == nil {
content.projects = slices.Clone(stored.projects)
return nil
}
content.projects, err = resolveItems(rules.projects, location, "/projects", *input.Projects, stored.projects, maxProfileProjects, at)
return err
},
func() (err error) {
content.location, err = resolveOptional(rules.location, location, "/terms/location", input.Location, stored.location, at)
return err
@@ -1188,6 +1209,7 @@ const (
profileKindLocation = "terms_location"
profileKindRelocation = "terms_relocation"
profileKindSalaryMinimum = "terms_salary_minimum"
profileKindProject = "project"
)
// StoredProfileClaim is a claim as the claims table holds it: the kind, the
@@ -1302,6 +1324,7 @@ func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, err
entries = appendList(entries, profileKindRole, content.roles, roleStoredValue)
entries = appendList(entries, profileKindExperience, content.experience, experienceStoredValue)
entries = appendList(entries, profileKindSoftSkill, content.softSkills, plainValue[string])
entries = appendList(entries, profileKindProject, content.projects, projectStoredValue)
rows := make([]StoredProfileClaim, 0, len(entries))
for _, entry := range entries {
@@ -1394,6 +1417,8 @@ func restoreCandidateProfileClaim(
return restoreItem(&content.roles, rules.roles, row, status, source)
case profileKindExperience:
return restoreItem(&content.experience, rules.experience, row, status, source)
case profileKindProject:
return restoreItem(&content.projects, rules.projects, row, status, source)
default:
return errors.New("kind is unknown")
}
@@ -1443,6 +1468,15 @@ func decodeStoredValue[V comparable](row StoredProfileClaim) (V, error) {
EmployerName: stringOrEmpty(stored.EmployerName), Specialization: SpecializationCode(stored.Specialization),
StartedOn: stored.StartedOn, EndedOn: stringOrEmpty(stored.EndedOn), Summary: stringOrEmpty(stored.Summary),
}
case *ProfileProject:
var stored storedProjectValue
if err := decodeStrictJSON(row.Value, &stored); err != nil {
return value, err
}
if stored.Stack == nil {
return value, errors.New("value has an unexpected shape")
}
*target = NewProfileProject(stored.Title, stringOrEmpty(stored.Description), stored.Stack, stringOrEmpty(stored.RepositoryURL))
case *ProfileSalaryMinimum:
var stored storedSalaryValue
if err := decodeStrictJSON(row.Value, &stored); err != nil {
@@ -90,7 +90,7 @@ func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireAc
}
switch input.Kind {
case CandidateCardAccessCardViewed:
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > 6 {
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > maxCardViewedFields {
return ErrInvalidCandidateCardAccess
}
seen := make(map[CardField]struct{}, len(input.ProjectionFields))
@@ -116,10 +116,14 @@ func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireAc
return nil
}
// maxCardViewedFields is the number of card groups that a view can return;
// the CHECK of candidate_card_access_events allows the same.
const maxCardViewedFields = 7
func candidateCardProjectionField(field CardField) bool {
switch field {
case CardFieldCategories, CardFieldStack, CardFieldExperience, CardFieldSelfAssessment,
CardFieldWorkFormats, CardFieldSalaryCompatibility:
CardFieldWorkFormats, CardFieldSalaryCompatibility, CardFieldProjects:
return true
case CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation:
return false
@@ -0,0 +1,235 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"regexp"
"strings"
"unicode/utf8"
)
// ErrInvalidGitHubRepository reports a repository address that is not a
// GitHub repository address of the accepted form.
var ErrInvalidGitHubRepository = errors.New("invalid GitHub repository address")
const (
maxProfileProjects = 10
maxProfileProjectTitleRunes = 100
maxProfileProjectDescription = 500
maxProfileProjectStackItems = 10
maxRepositoryURLRunes = 160
githubRepositoryPrefix = "https://github.com/"
// projectStackSeparator joins the tags of a project into one comparable
// string. A tag is one line, so a line break never occurs inside one.
projectStackSeparator = "\n"
)
var (
// GitHub owner names: letters, digits, and single hyphens, at most 39
// characters, not starting with a hyphen.
githubOwnerPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$`)
// GitHub repository names: letters, digits, '.', '_', and '-'.
githubNamePattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,100}$`)
)
// GitHubRepository is a validated public repository coordinate. Owner and
// Name keep the letter case the candidate typed; Key is the lower-case form
// that GitHub treats as the same repository.
type GitHubRepository struct {
owner string
name string
}
// ParseGitHubRepositoryURL accepts only https://github.com/<owner>/<name>
// with an optional trailing slash or .git suffix. Any other scheme, host,
// port, user information, query, fragment, or path is rejected, so the
// address can never point the server at another host.
func ParseGitHubRepositoryURL(raw string) (GitHubRepository, error) {
const location = "domain.ParseGitHubRepositoryURL"
fail := func(reason string) (GitHubRepository, error) {
return GitHubRepository{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidGitHubRepository)
}
if !utf8.ValidString(raw) || utf8.RuneCountInString(raw) > maxRepositoryURLRunes {
return fail("address is too long or not UTF-8")
}
if !strings.HasPrefix(raw, githubRepositoryPrefix) {
return fail("address must start with https://github.com/")
}
path := strings.TrimPrefix(raw, githubRepositoryPrefix)
path = strings.TrimSuffix(path, "/")
parts := strings.Split(path, "/")
if len(parts) != 2 {
return fail("address must name exactly an owner and a repository")
}
owner, name := parts[0], strings.TrimSuffix(parts[1], ".git")
switch {
case !githubOwnerPattern.MatchString(owner) || strings.Contains(owner, "--"):
return fail("owner is not a GitHub account name")
case !githubNamePattern.MatchString(name) || name == "." || name == "..":
return fail("repository is not a GitHub repository name")
}
return GitHubRepository{owner: owner, name: name}, nil
}
// Owner returns the account part of the address.
func (repository GitHubRepository) Owner() string { return repository.owner }
// Name returns the repository part of the address.
func (repository GitHubRepository) Name() string { return repository.name }
// URL returns the canonical address https://github.com/<owner>/<name>.
func (repository GitHubRepository) URL() string {
return githubRepositoryPrefix + repository.owner + "/" + repository.name
}
// Key is "<owner>/<name>" in lower case: the identity of the repository for
// deduplication and for its stored check.
func (repository GitHubRepository) Key() string {
return strings.ToLower(repository.owner + "/" + repository.name)
}
// IsZero reports a repository that was not parsed.
func (repository GitHubRepository) IsZero() bool { return repository.owner == "" }
// The coordinate names an account, so formatting redacts it like profile data.
func (GitHubRepository) String() string { return redactedProfile }
func (GitHubRepository) GoString() string { return redactedProfile }
func (GitHubRepository) LogValue() slog.Value {
return slog.StringValue(redactedProfile)
}
func (GitHubRepository) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
// ProfileProject is one project of the profile. Description and
// RepositoryURL are "" when not given. The stack is kept as one string so the
// value stays comparable; StackTags returns the tags. The project is personal
// data: formatting redacts it.
type ProfileProject struct {
Title string
Description string
RepositoryURL string
stack string
}
// NewProfileProject builds a project value from request parts. Validation
// happens when the profile resolves it.
func NewProfileProject(title, description string, stack []string, repositoryURL string) ProfileProject {
return ProfileProject{
Title: title, Description: description, RepositoryURL: repositoryURL,
stack: strings.Join(stack, projectStackSeparator),
}
}
// StackTags returns the stack tags in the order the candidate gave them.
func (project ProfileProject) StackTags() []string {
if project.stack == "" {
return nil
}
return strings.Split(project.stack, projectStackSeparator)
}
// Repository returns the parsed repository and whether the project links one.
func (project ProfileProject) Repository() (GitHubRepository, bool) {
if project.RepositoryURL == "" {
return GitHubRepository{}, false
}
repository, err := ParseGitHubRepositoryURL(project.RepositoryURL)
if err != nil {
return GitHubRepository{}, false
}
return repository, true
}
func (ProfileProject) String() string { return redactedProfile }
func (ProfileProject) GoString() string { return redactedProfile }
func (ProfileProject) LogValue() slog.Value {
return slog.StringValue(redactedProfile)
}
func (ProfileProject) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
// projectRules validates and normalizes one project. The repository address
// becomes canonical, so a trailing slash or a .git suffix never creates a
// second value for the same repository.
func projectRules(value ProfileProject) (ProfileProject, string, string) {
value.Description = strings.ReplaceAll(value.Description, "\r\n", "\n")
if problem := singleLineTextProblem(value.Title, maxProfileProjectTitleRunes); problem != "" {
return value, "/title", problem
}
if value.Description != "" {
if problem := multiLineTextProblem(value.Description, maxProfileProjectDescription); problem != "" {
return value, "/description", problem
}
}
tags := value.StackTags()
if len(tags) > maxProfileProjectStackItems {
return value, "/stack", fmt.Sprintf("must have at most %d items", maxProfileProjectStackItems)
}
seen := make(map[string]struct{}, len(tags))
for index, tag := range tags {
if problem := singleLineTextProblem(tag, maxProfileTagRunes); problem != "" {
return value, fmt.Sprintf("/stack/%d", index), problem
}
key := strings.ToLower(tag)
if _, repeated := seen[key]; repeated {
return value, fmt.Sprintf("/stack/%d", index), "must not repeat an earlier item"
}
seen[key] = struct{}{}
}
if value.RepositoryURL != "" {
repository, err := ParseGitHubRepositoryURL(value.RepositoryURL)
if err != nil {
return value, "/repository_url", "must be a GitHub repository address https://github.com/<owner>/<repository>"
}
value.RepositoryURL = repository.URL()
}
return value, "", ""
}
// projectKey identifies a project for the repeat rule: two projects may not
// link the same repository. A project without a repository never repeats.
func projectKey(value ProfileProject) string {
repository, ok := value.Repository()
if !ok {
return "\x00" + value.Title + "\x00" + value.Description + "\x00" + value.stack
}
return repository.Key()
}
// storedProjectValue is the JSON shape of a project claim that the CHECK of
// candidate_profile_claims requires.
type storedProjectValue struct {
Title string `json:"title"`
Description *string `json:"description"`
Stack []string `json:"stack"`
RepositoryURL *string `json:"repository_url"`
}
func projectStoredValue(project ProfileProject) any {
stack := project.StackTags()
if stack == nil {
stack = []string{}
}
return storedProjectValue{
Title: project.Title, Description: optionalString(project.Description), Stack: stack,
RepositoryURL: optionalString(project.RepositoryURL),
}
}
// ProjectRepositories returns the distinct repositories that the projects of
// the content link, in project order.
func (content CandidateProfileContent) ProjectRepositories() []GitHubRepository {
var repositories []GitHubRepository
seen := make(map[string]struct{})
for _, claim := range content.projects {
repository, ok := claim.value.Repository()
if !ok {
continue
}
if _, repeated := seen[repository.Key()]; repeated {
continue
}
seen[repository.Key()] = struct{}{}
repositories = append(repositories, repository)
}
return repositories
}
@@ -0,0 +1,169 @@
package domain
import (
"errors"
"fmt"
"strings"
"testing"
"time"
)
func TestParseGitHubRepositoryURLAcceptsOnlyCanonicalGitHubAddresses(t *testing.T) {
for _, test := range []struct {
raw, url, key string
}{
{"https://github.com/Example-Org/Payments.Ledger", "https://github.com/Example-Org/Payments.Ledger", "example-org/payments.ledger"},
{"https://github.com/example/repo/", "https://github.com/example/repo", "example/repo"},
{"https://github.com/example/repo.git", "https://github.com/example/repo", "example/repo"},
} {
repository, err := ParseGitHubRepositoryURL(test.raw)
if err != nil || repository.URL() != test.url || repository.Key() != test.key {
t.Errorf("ParseGitHubRepositoryURL(%q) = %q %q, %v", test.raw, repository.URL(), repository.Key(), err)
}
}
for _, raw := range []string{
"http://github.com/example/repo",
"https://gitlab.com/example/repo",
"https://github.com.evil.example/example/repo",
"https://user:secret@github.com/example/repo",
"https://github.com:443/example/repo",
"https://github.com/example",
"https://github.com/example/repo/tree/main",
"https://github.com/example/repo?tab=readme",
"https://github.com/example/repo#readme",
"https://github.com/-example/repo",
"https://github.com/exa--mple/repo",
"https://github.com/example/..",
"https://github.com/example/re po",
"https://github.com/../../evil",
"https://api.github.com/repos/example/repo",
"https://github.com/" + strings.Repeat("a", 40) + "/repo",
"https://GITHUB.com/example/repo",
} {
if _, err := ParseGitHubRepositoryURL(raw); !errors.Is(err, ErrInvalidGitHubRepository) {
t.Errorf("ParseGitHubRepositoryURL(%q) accepted an address outside the allowed form", raw)
}
}
}
func TestGitHubRepositoryRedactsItselfInLogs(t *testing.T) {
repository, err := ParseGitHubRepositoryURL("https://github.com/private-owner/repo")
if err != nil {
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
}
if text := fmt.Sprintf("%v %+v %#v %s", repository, repository, repository, repository); strings.Contains(text, "private-owner") {
t.Fatalf("formatting leaks the owner: %s", text)
}
}
func projectInput(title, description string, stack []string, repository string) ProfileClaimInput[ProfileProject] {
return ProfileClaimInput[ProfileProject]{Value: NewProfileProject(title, description, stack, repository), Status: ProfileClaimConfirmed}
}
func TestProfileProjectsAreValidatedNormalizedAndOptionalInARequest(t *testing.T) {
at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
projects := []ProfileClaimInput[ProfileProject]{
projectInput("Ledger", "Idempotent\r\ncallbacks", []string{"Go", "PostgreSQL"}, "https://github.com/example/ledger.git"),
projectInput("Notes", "", nil, ""),
}
content, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &projects}, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
stored := content.Projects()
if len(stored) != 2 || stored[0].Value().RepositoryURL != "https://github.com/example/ledger" ||
stored[0].Value().Description != "Idempotent\ncallbacks" || strings.Join(stored[0].Value().StackTags(), ",") != "Go,PostgreSQL" {
t.Fatalf("projects = %+v, want the normalized values", stored)
}
if repositories := content.ProjectRepositories(); len(repositories) != 1 || repositories[0].Key() != "example/ledger" {
t.Fatalf("ProjectRepositories() = %d, want the linked repository", len(repositories))
}
// A request without the section keeps the stored projects.
kept, err := ResolveCandidateProfileContent(content, CandidateProfileInput{}, at)
if err != nil || len(kept.Projects()) != 2 || !kept.Equal(content) {
t.Fatalf("a request without projects changed them: %v", err)
}
// An empty list removes them.
empty := []ProfileClaimInput[ProfileProject]{}
cleared, err := ResolveCandidateProfileContent(content, CandidateProfileInput{Projects: &empty}, at)
if err != nil || len(cleared.Projects()) != 0 {
t.Fatalf("an empty list kept the projects: %v", err)
}
// The stored rows restore to the same content.
rows, err := content.StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
restored, err := RestoreCandidateProfileContent(rows)
if err != nil || !restored.Equal(content) {
t.Fatalf("RestoreCandidateProfileContent() = %v, want the same projects", err)
}
for _, test := range []struct {
name string
projects []ProfileClaimInput[ProfileProject]
pointer string
}{
{"empty title", []ProfileClaimInput[ProfileProject]{projectInput("", "", nil, "")}, "/projects/0/title"},
{"long title", []ProfileClaimInput[ProfileProject]{projectInput(strings.Repeat("a", 101), "", nil, "")}, "/projects/0/title"},
{"another host", []ProfileClaimInput[ProfileProject]{projectInput("A", "", nil, "https://gitlab.com/a/b")}, "/projects/0/repository_url"},
{"repeated tag", []ProfileClaimInput[ProfileProject]{projectInput("A", "", []string{"Go", "go"}, "")}, "/projects/0/stack/1"},
{"repeated repository", []ProfileClaimInput[ProfileProject]{
projectInput("A", "", nil, "https://github.com/a/b"), projectInput("B", "", nil, "https://github.com/A/B/"),
}, "/projects/1/repository_url"},
{"too many", func() []ProfileClaimInput[ProfileProject] {
many := make([]ProfileClaimInput[ProfileProject], 0, maxProfileProjects+1)
for index := range maxProfileProjects + 1 {
many = append(many, projectInput(fmt.Sprintf("P%d", index), "", nil, ""))
}
return many
}(), "/projects"},
} {
_, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &test.projects}, at)
var field *CandidateProfileFieldError
if !errors.As(err, &field) || field.Pointer != test.pointer {
t.Errorf("%s: error = %v, want pointer %s", test.name, err, test.pointer)
}
}
}
func TestPublishedProjectsReachTheCardWithoutTheRepository(t *testing.T) {
at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
projects := []ProfileClaimInput[ProfileProject]{
projectInput("Ledger", "Callbacks", []string{"Go"}, "https://github.com/private-owner/ledger"),
}
content, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &projects}, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
profile := CandidateViewProfileFromContentWithRepositories(content, map[string]bool{"private-owner/ledger": true})
pseudonym := "cv1_" + strings.Repeat("A", 43)
for _, test := range []struct {
fields []CardField
want int
}{
{[]CardField{CardFieldStack}, 0},
{[]CardField{CardFieldStack, CardFieldProjects}, 1},
} {
fields, err := NewCardFieldSet(test.fields)
if err != nil {
t.Fatalf("NewCardFieldSet() error = %v", err)
}
view, err := NewAnonymousCandidateView(CandidateViewInput{Pseudonym: pseudonym, PublishedFields: fields, Profile: profile, AsOf: at})
if err != nil {
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
}
card := view.DTO()
if len(card.Projects) != test.want {
t.Fatalf("fields %v: projects = %d, want %d", test.fields, len(card.Projects), test.want)
}
if test.want == 1 && (!card.Projects[0].RepositoryVerified || card.Projects[0].Title != "Ledger") {
t.Fatalf("card project = %+v, want the verified title", card.Projects[0])
}
if text := fmt.Sprintf("%+v", card.Projects); strings.Contains(text, "private-owner") || strings.Contains(text, "github") {
t.Fatalf("card projects carry the repository: %s", text)
}
}
}
+73 -1
View File
@@ -191,6 +191,14 @@ type candidateViewRoleClaim struct {
status ProfileClaimStatus
}
// candidateViewProjectClaim is a project with the verification of its
// repository. The repository key never leaves the private projection input.
type candidateViewProjectClaim struct {
value ProfileProject
status ProfileClaimStatus
verified bool
}
type candidateViewExperienceClaim struct {
startedOn string
endedOn string
@@ -204,6 +212,7 @@ type CandidateViewProfile struct {
stack []candidateViewStackClaim
roles []candidateViewRoleClaim
experience []candidateViewExperienceClaim
projects []candidateViewProjectClaim
}
func (CandidateViewProfile) String() string { return "[candidate view profile]" }
@@ -213,9 +222,28 @@ func (CandidateViewProfile) LogValue() slog.Value {
}
// CandidateViewProfileFromContent removes private profile values that are
// not needed to build the anonymous organization-facing view.
// not needed to build the anonymous organization-facing view. No project is
// marked as backed by a verified repository.
func CandidateViewProfileFromContent(content CandidateProfileContent) CandidateViewProfile {
return CandidateViewProfileFromContentWithRepositories(content, nil)
}
// CandidateViewProfileFromContentWithRepositories also marks each project
// whose repository key is in verifiedRepositories, the keys whose latest
// check found a public repository.
func CandidateViewProfileFromContentWithRepositories(
content CandidateProfileContent, verifiedRepositories map[string]bool,
) CandidateViewProfile {
profile := CandidateViewProfile{}
for _, claim := range content.Projects() {
verified := false
if repository, ok := claim.Value().Repository(); ok {
verified = verifiedRepositories[repository.Key()]
}
profile.projects = append(profile.projects, candidateViewProjectClaim{
value: claim.Value(), status: claim.Status(), verified: verified,
})
}
for _, claim := range content.Stack() {
profile.stack = append(profile.stack, candidateViewStackClaim{value: claim.Value(), status: claim.Status()})
}
@@ -263,6 +291,15 @@ func (compatibility CandidateViewSalaryCompatibility) IsKnown() bool {
return compatibility == CandidateViewSalaryCompatible || compatibility == CandidateViewSalaryNotCompatible
}
// CandidateViewProject is one published project as the card shows it: no
// repository address, owner, or fetched repository text.
type CandidateViewProject struct {
Title string `json:"title"`
Description *string `json:"description"`
Stack []string `json:"stack"`
RepositoryVerified bool `json:"repository_verified"`
}
// AnonymousCandidateViewDTO is the complete closed organization-facing data
// transfer object. It contains no account ID, raw profile fields, or history.
type AnonymousCandidateViewDTO struct {
@@ -273,6 +310,9 @@ type AnonymousCandidateViewDTO struct {
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
// Projects are published free text; cohort generalization leaves them
// unchanged and they are not a cohort feature.
Projects []CandidateViewProject `json:"projects"`
}
func (AnonymousCandidateViewDTO) String() string { return "[anonymous candidate view]" }
@@ -348,6 +388,9 @@ func NewAnonymousCandidateView(input CandidateViewInput) (AnonymousCandidateView
value := *input.SalaryCompatibility
view.dto.SalaryCompatibility = &value
}
if input.PublishedFields.Contains(CardFieldProjects) {
view.dto.Projects = candidateViewProjects(input.Profile)
}
return view, nil
}
@@ -366,9 +409,38 @@ func cloneAnonymousCandidateViewDTO(dto AnonymousCandidateViewDTO) AnonymousCand
dto.ExperienceBand = clonePointer(dto.ExperienceBand)
dto.WorkFormats = slices.Clone(dto.WorkFormats)
dto.SalaryCompatibility = clonePointer(dto.SalaryCompatibility)
if dto.Projects != nil {
projects := make([]CandidateViewProject, len(dto.Projects))
for index, project := range dto.Projects {
project.Description = clonePointer(project.Description)
project.Stack = slices.Clone(project.Stack)
projects[index] = project
}
dto.Projects = projects
}
return dto
}
// candidateViewProjects lists the confirmed projects in profile order, so
// the position of a project in the card equals its position in the profile.
func candidateViewProjects(profile CandidateViewProfile) []CandidateViewProject {
var projects []CandidateViewProject
for _, claim := range profile.projects {
if claim.status != ProfileClaimConfirmed {
continue
}
stack := claim.value.StackTags()
if stack == nil {
stack = []string{}
}
projects = append(projects, CandidateViewProject{
Title: claim.value.Title, Description: optionalString(claim.value.Description),
Stack: stack, RepositoryVerified: claim.verified,
})
}
return projects
}
func validCandidateViewPseudonym(pseudonym string) bool {
if !strings.HasPrefix(pseudonym, candidateViewPseudonymPrefix) {
return false
@@ -74,6 +74,7 @@ func cloneCandidateViewProfile(profile CandidateViewProfile) CandidateViewProfil
return CandidateViewProfile{
stack: slices.Clone(profile.stack), roles: slices.Clone(profile.roles),
experience: slices.Clone(profile.experience),
projects: slices.Clone(profile.projects),
}
}
+11
View File
@@ -106,3 +106,14 @@ func DemoProductPolicyV4() ProductPolicy {
policy.Matching = &matching
return policy
}
// DemoProductPolicyV5 returns DemoProductPolicyV4 with the semantic matching
// section and the semantic Fit weights (DemoSemanticMatchingPolicy). V4 stays
// the PRD point with Sem weight 0.10. It is published explicitly with the
// policy-publish command; startup seeding publishes V1 only.
func DemoProductPolicyV5() ProductPolicy {
policy := DemoProductPolicyV4()
matching := DemoSemanticMatchingPolicy()
policy.Matching = &matching
return policy
}
@@ -185,6 +185,34 @@ type matchingPolicyDocument struct {
PercentileMinCohort *int32 `json:"percentile_min_cohort"`
MaxResultsPerGroup *int32 `json:"max_results_per_group"`
SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"`
// Semantics is optional: a document without it is a matching section
// that ranks with the neutral Sem.
Semantics *matchingSemanticsDocument `json:"semantics,omitempty"`
}
type matchingSemanticsDocument struct {
Members *[]matchingSemanticMemberDocument `json:"members"`
Calibration *[]matchingCalibrationPointDocument `json:"calibration"`
SkillMediumBP *BasisPoints `json:"skill_medium_bp"`
SkillHighBP *BasisPoints `json:"skill_high_bp"`
TaskMediumBP *BasisPoints `json:"task_medium_bp"`
TaskHighBP *BasisPoints `json:"task_high_bp"`
MaxEvidencePerEntry *int32 `json:"max_evidence_per_entry"`
Source *string `json:"source"`
}
type matchingSemanticMemberDocument struct {
ModelID *string `json:"model_id"`
ModelRevision *string `json:"model_revision"`
PromptVersion *string `json:"prompt_version"`
WeightBP *BasisPoints `json:"weight_bp"`
MeanBP *int32 `json:"mean_bp"`
StandardDeviationBP *int32 `json:"standard_deviation_bp"`
}
type matchingCalibrationPointDocument struct {
ScoreBP *int32 `json:"score_bp"`
ProbabilityBP *BasisPoints `json:"probability_bp"`
}
type matchingSkillGroupDocument struct {
@@ -359,6 +387,31 @@ func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument {
PercentileMinCohort: pointer(policy.PercentileMinCohort),
MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup),
SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)),
Semantics: encodeMatchingSemantics(policy.Semantics),
}
}
func encodeMatchingSemantics(policy *MatchingSemanticsPolicy) *matchingSemanticsDocument {
if policy == nil {
return nil
}
points := make([]matchingCalibrationPointDocument, 0, len(policy.Calibration))
for _, point := range policy.Calibration {
points = append(points, matchingCalibrationPointDocument{ScoreBP: pointer(point.Score), ProbabilityBP: pointer(point.Probability)})
}
members := make([]matchingSemanticMemberDocument, 0, len(policy.Members))
for _, member := range policy.Members {
members = append(members, matchingSemanticMemberDocument{
ModelID: pointer(member.Model.ID), ModelRevision: pointer(member.Model.Revision),
PromptVersion: pointer(member.Model.PromptVersion), WeightBP: pointer(member.Weight),
MeanBP: pointer(member.Mean), StandardDeviationBP: pointer(member.StandardDeviation),
})
}
return &matchingSemanticsDocument{
Members: pointer(members), Calibration: pointer(points),
SkillMediumBP: pointer(policy.SkillMedium), SkillHighBP: pointer(policy.SkillHigh),
TaskMediumBP: pointer(policy.TaskMedium), TaskHighBP: pointer(policy.TaskHigh),
MaxEvidencePerEntry: pointer(policy.MaxEvidencePerEntry), Source: pointer(policy.Source),
}
}
@@ -621,6 +674,43 @@ func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPoli
PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort),
MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup),
SkillTaxonomy: taxonomy,
Semantics: decodeOptionalMatchingSemantics(reader, document.Semantics),
}
}
func decodeOptionalMatchingSemantics(reader *documentReader, document *matchingSemanticsDocument) *MatchingSemanticsPolicy {
if document == nil {
return nil
}
points := make([]MatchingCalibrationPoint, 0)
for _, point := range require(reader, "matching.semantics.calibration", document.Calibration) {
points = append(points, MatchingCalibrationPoint{
Score: require(reader, "matching.semantics.calibration.score_bp", point.ScoreBP),
Probability: require(reader, "matching.semantics.calibration.probability_bp", point.ProbabilityBP),
})
}
members := make([]MatchingSemanticMember, 0)
for _, member := range require(reader, "matching.semantics.members", document.Members) {
members = append(members, MatchingSemanticMember{
Model: SemanticModel{
ID: require(reader, "matching.semantics.members.model_id", member.ModelID),
Revision: require(reader, "matching.semantics.members.model_revision", member.ModelRevision),
PromptVersion: require(reader, "matching.semantics.members.prompt_version", member.PromptVersion),
},
Weight: require(reader, "matching.semantics.members.weight_bp", member.WeightBP),
Mean: require(reader, "matching.semantics.members.mean_bp", member.MeanBP),
StandardDeviation: require(reader, "matching.semantics.members.standard_deviation_bp", member.StandardDeviationBP),
})
}
return &MatchingSemanticsPolicy{
Members: members,
Calibration: points,
SkillMedium: require(reader, "matching.semantics.skill_medium_bp", document.SkillMediumBP),
SkillHigh: require(reader, "matching.semantics.skill_high_bp", document.SkillHighBP),
TaskMedium: require(reader, "matching.semantics.task_medium_bp", document.TaskMediumBP),
TaskHigh: require(reader, "matching.semantics.task_high_bp", document.TaskHighBP),
MaxEvidencePerEntry: require(reader, "matching.semantics.max_evidence_per_entry", document.MaxEvidencePerEntry),
Source: require(reader, "matching.semantics.source", document.Source),
}
}
+31 -2
View File
@@ -70,6 +70,11 @@ type MatchingPolicy struct {
// that stays below the daily card-view allowance of the first tier.
MaxResultsPerGroup int32
// Semantics is the optional semantic section: the encoder of the stored
// vectors, the calibration of Sem, and the explanation thresholds. A
// version without it ranks with the neutral Sem, as before.
Semantics *MatchingSemanticsPolicy
// SkillTaxonomy lists, for each specialization, the technologies that fall
// inside it. Evidence for a specialization is broader evidence for each of
// them, and evidence for one of them is narrower evidence for the
@@ -90,6 +95,10 @@ func (policy MatchingPolicy) Clone() MatchingPolicy {
for index := range policy.SkillTaxonomy {
policy.SkillTaxonomy[index].Skills = slices.Clone(policy.SkillTaxonomy[index].Skills)
}
if policy.Semantics != nil {
semantics := policy.Semantics.Clone()
policy.Semantics = &semantics
}
return policy
}
@@ -164,6 +173,20 @@ func DemoMatchingPolicy() MatchingPolicy {
}
}
// DemoSemanticMatchingPolicy returns DemoMatchingPolicy with semantic
// similarity in Fit. The research shows that the PRD weight 0.10 hides
// almost all of the encoder's gain (TEST nDCG@10 of Fit 0.649 against 0.818
// for the encoder alone) and that 0.5 recovers it (0.838). Sem therefore
// weighs 0.5 and Cov and Dom keep their PRD ratio 5:1 in the rest
// (0.4167 and 0.0833), so the weights still add up to one.
func DemoSemanticMatchingPolicy() MatchingPolicy {
policy := DemoMatchingPolicy()
policy.FitCoverageWeight, policy.FitDomainWeight, policy.FitSemanticsWeight = 4167, 833, 5000
semantics := DemoMatchingSemanticsPolicy()
policy.Semantics = &semantics
return policy
}
// TrustCoefficient returns the coefficient of an evidence trust level. An
// unknown level has none.
func (policy MatchingPolicy) TrustCoefficient(trust EvidenceTrust) (BasisPoints, bool) {
@@ -214,11 +237,17 @@ func (policy MatchingPolicy) RelationCoefficient(relation EvidenceSkillRelation)
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy MatchingPolicy) Validate() error {
return firstError(
if err := firstError(
policy.validateShares(),
policy.validateWeights(),
policy.validateOrdering(),
)
); err != nil {
return err
}
if policy.Semantics != nil {
return policy.Semantics.Validate()
}
return nil
}
func (policy MatchingPolicy) validateShares() error {
@@ -0,0 +1,304 @@
package domain
import (
"fmt"
"math"
"slices"
"unicode/utf8"
)
// MatchingSemanticsPolicy is the versioned semantic part of matching: which
// encoders the stored vectors must come from, how their cosines of the two
// whole views become Sem, and which item similarities an explanation may show.
// Values come from the research run named in Source; they are not product
// measurements.
type MatchingSemanticsPolicy struct {
// Members are the encoders whose cosines form the semantic score: the
// weighted sum of each cosine standardized by the member's mean and
// standard deviation. The first member also provides the item vectors of
// the explanation. The default is one member, Giga-480M, with weight 1,
// mean 0, and standard deviation 1, so the score is its cosine; an
// ensemble (for example 0.4 Giga + 0.6 Qwen3-Embedding) adds a member and
// needs a calibration fitted on its fused score.
Members []MatchingSemanticMember
// Calibration maps the fused score of the need view and the card view to
// Sem by linear interpolation between points, clipped at both ends. The
// points are an isotonic fit, so both coordinates never decrease.
Calibration []MatchingCalibrationPoint
// The item thresholds are cosines in basis points: a requirement whose
// closest card item reaches Medium is shown as "medium", reaching High as
// "high". Skills and tasks have their own pairs.
SkillMedium BasisPoints
SkillHigh BasisPoints
TaskMedium BasisPoints
TaskHigh BasisPoints
// MaxEvidencePerEntry bounds the explanation items of one entry.
MaxEvidencePerEntry int32
// Source names the data and the fit behind the values.
Source string
}
// MatchingSemanticMember is one encoder of the semantic score. Mean and
// StandardDeviation describe its cosine of a need and a card in basis
// points; the member contributes Weight * (cosine - Mean) / StandardDeviation.
type MatchingSemanticMember struct {
Model SemanticModel
Weight BasisPoints
Mean int32
StandardDeviation int32
}
// ExplanationModel is the encoder whose item vectors explain an entry.
func (policy MatchingSemanticsPolicy) ExplanationModel() SemanticModel {
if len(policy.Members) == 0 {
return SemanticModel{}
}
return policy.Members[0].Model
}
// FusedScore combines the whole-view cosines of the members, in member order,
// into the score that the calibration reads. It returns false unless every
// member has a cosine: a partial ensemble would put the entry on another scale.
func (policy MatchingSemanticsPolicy) FusedScore(cosines []float64) (float64, bool) {
if len(policy.Members) == 0 || len(cosines) != len(policy.Members) {
return 0, false
}
var score float64
for index, cosine := range cosines {
member := policy.Members[index]
weight := float64(member.Weight) / float64(basisPointsPerUnit)
mean := float64(member.Mean) / float64(basisPointsPerUnit)
deviation := float64(member.StandardDeviation) / float64(basisPointsPerUnit)
// The explicit conversion rounds the product, so no platform fuses it
// with the sum and every server computes the same score.
score += float64(weight * ((cosine - mean) / deviation))
}
return score, true
}
// MatchingCalibrationPoint is one point of the calibration curve: a fused
// score in basis points (-1..1 for a single cosine) and the probability that
// the pair is relevant.
type MatchingCalibrationPoint struct {
Score int32
Probability BasisPoints
}
const (
minCalibrationPoints = 2
maxCalibrationPoints = 256
maxSemanticEvidencePerEntry = 12
maxSemanticSourceRunes = 300
maxSemanticMembers = 4
// A standardized fused score can leave -1..1; the bound only rejects a
// value in the wrong unit.
minScoreBasisPoints = -100000
maxScoreBasisPoints = 100000
)
// Clone copies the members and the calibration points.
func (policy MatchingSemanticsPolicy) Clone() MatchingSemanticsPolicy {
policy.Members = slices.Clone(policy.Members)
policy.Calibration = slices.Clone(policy.Calibration)
return policy
}
// Validate rejects a malformed section.
func (policy MatchingSemanticsPolicy) Validate() error {
const location = "MatchingSemanticsPolicy.Validate"
if err := policy.validateMembers(); err != nil {
return err
}
if len(policy.Calibration) < minCalibrationPoints || len(policy.Calibration) > maxCalibrationPoints {
return invalidPolicy(location, fmt.Sprintf("matching.semantics.calibration needs between %d and %d points", minCalibrationPoints, maxCalibrationPoints))
}
for index, point := range policy.Calibration {
if err := firstError(
checkRange(location, "matching.semantics.calibration.score_bp", point.Score, minScoreBasisPoints, maxScoreBasisPoints),
checkRange(location, "matching.semantics.calibration.probability_bp", point.Probability, 0, basisPointsPerUnit),
); err != nil {
return err
}
if index > 0 {
previous := policy.Calibration[index-1]
if point.Score < previous.Score || point.Probability < previous.Probability {
return invalidPolicy(location, "matching.semantics.calibration must not decrease")
}
}
}
if first, last := policy.Calibration[0], policy.Calibration[len(policy.Calibration)-1]; first.Score == last.Score {
return invalidPolicy(location, "matching.semantics.calibration must span a cosine range")
}
if err := firstError(
checkRange(location, "matching.semantics.skill_medium_bp", policy.SkillMedium, 1, basisPointsPerUnit),
checkRange(location, "matching.semantics.skill_high_bp", policy.SkillHigh, policy.SkillMedium, basisPointsPerUnit),
checkRange(location, "matching.semantics.task_medium_bp", policy.TaskMedium, 1, basisPointsPerUnit),
checkRange(location, "matching.semantics.task_high_bp", policy.TaskHigh, policy.TaskMedium, basisPointsPerUnit),
checkRange(location, "matching.semantics.max_evidence_per_entry", policy.MaxEvidencePerEntry, 0, maxSemanticEvidencePerEntry),
); err != nil {
return err
}
if policy.Source == "" || utf8.RuneCountInString(policy.Source) > maxSemanticSourceRunes || singleLineTextProblem(policy.Source, maxSemanticSourceRunes) != "" {
return invalidPolicy(location, "matching.semantics.source must name the data behind the values")
}
return nil
}
func (policy MatchingSemanticsPolicy) validateMembers() error {
const location = "MatchingSemanticsPolicy.Validate"
if len(policy.Members) == 0 || len(policy.Members) > maxSemanticMembers {
return invalidPolicy(location, fmt.Sprintf("matching.semantics.members needs between 1 and %d members", maxSemanticMembers))
}
var total BasisPoints
seen := make(map[SemanticModel]struct{}, len(policy.Members))
for _, member := range policy.Members {
if err := member.Model.Validate(); err != nil {
return invalidPolicy(location, "matching.semantics.members model identity is malformed")
}
if _, repeated := seen[member.Model]; repeated {
return invalidPolicy(location, "matching.semantics.members repeats a model")
}
seen[member.Model] = struct{}{}
if err := firstError(
checkRange(location, "matching.semantics.members.weight_bp", member.Weight, 1, basisPointsPerUnit),
checkRange(location, "matching.semantics.members.mean_bp", member.Mean, -basisPointsPerUnit32, basisPointsPerUnit32),
checkRange(location, "matching.semantics.members.standard_deviation_bp", member.StandardDeviation, 1, basisPointsPerUnit32),
); err != nil {
return err
}
total += member.Weight
}
if total != basisPointsPerUnit {
return invalidPolicy(location, "matching.semantics.members weights must add up to 1.0000")
}
return nil
}
// basisPointsPerUnit32 is basisPointsPerUnit for int32 fields.
const basisPointsPerUnit32 = int32(basisPointsPerUnit)
// Probability maps a fused score to Sem in micro units (1e-6), interpolating
// linearly between calibration points in integer arithmetic. A score at a
// repeated point takes the higher probability, the right limit of the step.
func (policy MatchingSemanticsPolicy) Probability(score float64) int64 {
const microPerBasisPoint = 100
points := policy.Calibration
if len(points) == 0 {
return 0
}
// The score in micro units, rounded half away from zero.
value := int64(math.Round(score * 1_000_000))
micro := func(point MatchingCalibrationPoint) (int64, int64) {
return int64(point.Score) * microPerBasisPoint, int64(point.Probability) * microPerBasisPoint
}
firstX, firstY := micro(points[0])
if value < firstX {
return firstY
}
for index := len(points) - 1; index >= 0; index-- {
x0, y0 := micro(points[index])
if value < x0 {
continue
}
if index == len(points)-1 {
return y0
}
x1, y1 := micro(points[index+1])
if x1 == x0 {
return y1
}
return y0 + ((y1-y0)*(value-x0)+(x1-x0)/2)/(x1-x0)
}
return firstY
}
// ItemBand returns the explanation band of an item similarity for a skill or
// a task requirement, or "" below the medium threshold.
func (policy MatchingSemanticsPolicy) ItemBand(task bool, cosine float64) SemanticSimilarityBand {
medium, high := policy.SkillMedium, policy.SkillHigh
if task {
medium, high = policy.TaskMedium, policy.TaskHigh
}
scaled := cosine * float64(basisPointsPerUnit)
switch {
case scaled >= float64(high):
return SemanticSimilarityHigh
case scaled >= float64(medium):
return SemanticSimilarityMedium
default:
return ""
}
}
// SemanticSimilarityBand is the coarse band of an explanation item.
type SemanticSimilarityBand string
const (
SemanticSimilarityHigh SemanticSimilarityBand = "high"
SemanticSimilarityMedium SemanticSimilarityBand = "medium"
)
// Giga-Embeddings-instruct-480M at the pinned revision with the service
// prompt recipe; the ML service reports the same identity.
const (
GigaEmbeddingsModelID = "ai-sage/Giga-Embeddings-instruct-480M-0826"
GigaEmbeddingsModelRevision = "1763d603adac8057bd6482a708001b0ed2e0a903"
GigaEmbeddingsPromptVersion = "giga-card-mean-v1"
)
// DemoMatchingSemanticsPolicy returns the semantic section fitted on the DEV
// split of the LincodexMatch research (30 needs, 3220 judged pairs, 994 with
// consensus >= 2):
// - Calibration is the isotonic fit of P(consensus >= 2) on the cosine of
// the need view with the query prompt and the profile view without one
// (ECE 0.015-0.049 against 0.17-0.57 for the raw cosine), rounded to four
// decimals.
// - The item thresholds are where an isotonic fit of P(pair relevant) on
// the best item cosine of a requirement reaches 0.5 (medium) and 0.7
// (high): skills 0.3673 and 0.4607, tasks 0.2997 and 0.4192.
//
// The research profiles carry experience texts that the anonymous card does
// not, so product cosines are lower; the values are a calibrated starting
// point, not a product measurement.
func DemoMatchingSemanticsPolicy() MatchingSemanticsPolicy {
return MatchingSemanticsPolicy{
Members: []MatchingSemanticMember{{
Model: SemanticModel{
ID: GigaEmbeddingsModelID, Revision: GigaEmbeddingsModelRevision, PromptVersion: GigaEmbeddingsPromptVersion,
},
Weight: basisPointsPerUnit, Mean: 0, StandardDeviation: basisPointsPerUnit32,
}},
Calibration: demoSemanticCalibration(),
SkillMedium: 3673,
SkillHigh: 4607,
TaskMedium: 2997,
TaskHigh: 4192,
MaxEvidencePerEntry: 6,
Source: "LincodexMatch research 2026-10-10, DEV split, giga-480m isotonic fit (reports/step3)",
}
}
func demoSemanticCalibration() []MatchingCalibrationPoint {
return []MatchingCalibrationPoint{
{674, 0}, {2120, 0}, {2120, 45}, {2567, 45},
{2570, 154}, {2692, 154}, {2692, 458}, {2970, 458},
{2972, 735}, {3064, 735}, {3067, 758}, {3319, 758},
{3319, 833}, {3334, 833}, {3335, 1000}, {3345, 1000},
{3345, 1006}, {3666, 1006}, {3669, 1071}, {3726, 1071},
{3727, 1702}, {3762, 1702}, {3763, 1744}, {3837, 1744},
{3838, 1962}, {3998, 1962}, {3999, 2000}, {4002, 2000},
{4003, 2143}, {4018, 2143}, {4019, 2353}, {4070, 2353},
{4070, 2674}, {4130, 2674}, {4130, 2816}, {4286, 2816},
{4287, 3404}, {4330, 3404}, {4331, 3497}, {4462, 3497},
{4463, 4000}, {4494, 4000}, {4494, 4286}, {4503, 4286},
{4506, 4583}, {4537, 4583}, {4538, 5000}, {4543, 5000},
{4543, 5117}, {4760, 5117}, {4760, 5667}, {4795, 5667},
{4795, 5714}, {4822, 5714}, {4824, 5769}, {4852, 5769},
{4854, 5890}, {4935, 5890}, {4935, 6111}, {4949, 6111},
{4950, 7097}, {4988, 7097}, {4988, 7324}, {5078, 7324},
{5078, 7647}, {5108, 7647}, {5113, 7714}, {5161, 7714},
{5162, 7778}, {5392, 7778}, {5394, 8049}, {5461, 8049},
{5463, 9167}, {5532, 9167}, {5533, 9259}, {5926, 9259},
{5932, 9574}, {6260, 9574}, {6269, 10000}, {7049, 10000},
}
}
+242
View File
@@ -0,0 +1,242 @@
package domain
import (
"encoding/json"
"errors"
"math"
"slices"
"strings"
"testing"
"github.com/google/uuid"
)
func TestNeedSemanticDocumentMirrorsTheResearchViewWithConfirmedValuesOnly(t *testing.T) {
grade, domainText, source := GradeJunior, " e-commerce,\n catalog ", "Vacancy:\n\tbuild the catalog"
confirmed := NeedValueSource{Origin: NeedValueManual}
snapshot := NeedSnapshot{
ID: uuid.New(), Title: "Junior backend developer", SourceText: &source,
Requirements: NeedRequirements{
Grade: NeedValue[GradeCode]{Status: NeedValueConfirmed, Value: &grade},
Domain: NeedValue[string]{Status: NeedValueConfirmed, Value: &domainText},
RequiredSkills: []NeedSkill{
{Name: "Python", Status: NeedItemConfirmed, Source: confirmed},
{Name: "Secret suggestion", Status: NeedItemExtracted, Source: confirmed},
},
DesiredSkills: []NeedSkill{{Name: "FastAPI", Status: NeedItemConfirmed, Source: confirmed}},
Tasks: []NeedTask{{Text: "build card endpoints", Status: NeedItemConfirmed, Source: confirmed}},
},
}
document := NewNeedSemanticDocument(snapshot)
want := "Title: Junior backend developer\nGrade: junior\nDomain: e-commerce, catalog\nRequired skills: Python\n" +
"Desired skills: FastAPI\nTasks:\n- build card endpoints\nDescription: Vacancy: build the catalog"
if document.Whole.Text != want {
t.Fatalf("need view =\n%q\nwant\n%q", document.Whole.Text, want)
}
keys := make([]string, 0, len(document.Items))
for _, item := range document.Items {
keys = append(keys, item.Key+"="+item.Label)
}
if got := strings.Join(keys, ","); got != "required_skill:0=Python,desired_skill:0=FastAPI,task:0=build card endpoints" {
t.Fatalf("items = %s", got)
}
if NewNeedSemanticDocument(snapshot).Whole.ContentDigest() != document.Whole.ContentDigest() {
t.Fatal("the same snapshot renders a different digest")
}
}
func TestCandidateSemanticDocumentReadsOnlyTheCard(t *testing.T) {
declared := GradeMiddle
description := "Idempotent receiver"
card := AnonymousCandidateViewDTO{
Skills: []CandidateViewSkillCode{CandidateViewSkillKafka, CandidateViewSkillGo},
Categories: []CandidateViewCategory{{Specialization: SpecializationBackend, Grade: GradeJunior}},
SelfAssessment: []CandidateViewSelfAssessment{{Specialization: SpecializationDSML, DeclaredGrade: &declared}},
Projects: []CandidateViewProject{
{Title: "Ledger", Description: &description, Stack: []string{"Go"}, RepositoryVerified: true},
{Title: "Unverified", Stack: []string{}},
},
}
evidence := map[int]RepositoryEvidence{
0: {Description: "Payments ledger", Topics: []string{"payments"}, Languages: []string{"Go"}, ReadmeExcerpt: strings.Repeat("r", 700)},
1: {Description: "must not be used: the card does not mark it verified"},
}
document := NewCandidateSemanticDocument(card, evidence)
lines := strings.Split(document.Whole.Text, "\n")
if lines[0] != "Roles: backend (junior); ds_ml (middle)" || lines[1] != "Stack: go, kafka" || lines[2] != "Projects:" {
t.Fatalf("card view = %q", document.Whole.Text)
}
if !strings.HasPrefix(lines[3], "- Ledger: Idempotent receiver; Stack: Go; Repository: Payments ledger; Topics: payments; Languages: Go; README: ") ||
strings.Count(lines[3], "r") > maxReadmeRunesInView+20 {
t.Fatalf("project line = %q", lines[3])
}
if strings.Contains(document.Whole.Text, "must not be used") {
t.Fatal("evidence of an unverified project entered the view")
}
var projectKeys []string
for _, item := range document.Items {
if item.Kind == SemanticItemProject {
projectKeys = append(projectKeys, item.Key+"="+item.Label)
}
}
if strings.Join(projectKeys, ",") != "project:0=Ledger,project:1=Unverified" {
t.Fatalf("project items = %v", projectKeys)
}
if !NewCandidateSemanticDocument(AnonymousCandidateViewDTO{}, nil).IsEmpty() {
t.Fatal("an empty card renders text")
}
}
func TestSemanticVectorsEncodeExactlyAndRejectInvalidValues(t *testing.T) {
values := []float32{0.6, -0.8, 0}
vector, err := NewSemanticVector(values)
if err != nil {
t.Fatalf("NewSemanticVector() error = %v", err)
}
decoded, err := DecodeSemanticVector(vector.Encode(), 3)
if err != nil || len(decoded) != 3 || decoded[0] != 0.6 || decoded[1] != -0.8 {
t.Fatalf("round trip = %v, %v", decoded, err)
}
if cosine, ok := vector.Cosine(decoded); !ok || math.Abs(cosine-1) > 1e-6 {
t.Fatalf("Cosine(self) = %v", cosine)
}
if _, ok := vector.Cosine(SemanticVector{1}); ok {
t.Fatal("vectors of different dimensions were compared")
}
for _, invalid := range [][]float32{{}, {2, 0}, {float32(math.NaN()), 1}} {
if _, err := NewSemanticVector(invalid); !errors.Is(err, ErrInvalidSemanticVector) {
t.Errorf("NewSemanticVector(%v) accepted an invalid vector", invalid)
}
}
if _, err := DecodeSemanticVector([]byte{1, 2, 3}, 1); !errors.Is(err, ErrInvalidSemanticVector) {
t.Fatal("a stored vector of the wrong length was accepted")
}
}
func TestSemanticFusedScoreStandardizesAndNeedsEveryMember(t *testing.T) {
single := DemoMatchingSemanticsPolicy()
if score, ok := single.FusedScore([]float64{0.42}); !ok || score != 0.42 {
t.Fatalf("single-member score = %v, %v, want the cosine itself", score, ok)
}
ensemble := single.Clone()
ensemble.Members[0].Weight, ensemble.Members[0].Mean, ensemble.Members[0].StandardDeviation = 4000, 3000, 1000
ensemble.Members = append(ensemble.Members, MatchingSemanticMember{
Model: SemanticModel{ID: "Qwen/Qwen3-Embedding-0.6B", Revision: "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3", PromptVersion: "qwen3-v1"},
Weight: 6000, Mean: 5000, StandardDeviation: 500,
})
if err := ensemble.validateMembers(); err != nil {
t.Fatalf("ensemble members invalid: %v", err)
}
// 0.4 * (0.5 - 0.3) / 0.1 + 0.6 * (0.55 - 0.5) / 0.05 = 0.8 + 0.6.
if score, ok := ensemble.FusedScore([]float64{0.5, 0.55}); !ok || math.Abs(score-1.4) > 1e-12 {
t.Fatalf("ensemble score = %v, %v, want 1.4", score, ok)
}
if _, ok := ensemble.FusedScore([]float64{0.5}); ok {
t.Fatal("a score was fused without every member")
}
if ensemble.ExplanationModel() != single.Members[0].Model {
t.Fatal("the first member must explain entries")
}
ensemble.Members[0].Model = ensemble.Members[1].Model
if err := ensemble.validateMembers(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("a repeated member was accepted: %v", err)
}
}
func TestSemanticCalibrationInterpolatesClipsAndKeepsSteps(t *testing.T) {
policy := MatchingSemanticsPolicy{Calibration: []MatchingCalibrationPoint{
{Score: 2000, Probability: 0}, {Score: 3000, Probability: 0}, {Score: 3000, Probability: 4000}, {Score: 5000, Probability: 8000},
}}
for _, test := range []struct {
cosine float64
want int64
}{
{-0.5, 0}, {0.25, 0}, {0.3, 400_000}, {0.4, 600_000}, {0.5, 800_000}, {0.9, 800_000},
} {
if got := policy.Probability(test.cosine); got != test.want {
t.Errorf("Probability(%v) = %d, want %d", test.cosine, got, test.want)
}
}
demo := DemoMatchingSemanticsPolicy()
if err := demo.Validate(); err != nil {
t.Fatalf("demo semantics invalid: %v", err)
}
previous := int64(-1)
for cosine := 0.0; cosine <= 1.0; cosine += 0.01 {
value := demo.Probability(cosine)
if value < previous || value < 0 || value > 1_000_000 {
t.Fatalf("Probability is not monotone in [0,1] at %v: %d after %d", cosine, value, previous)
}
previous = value
}
if band := demo.ItemBand(true, 0.45); band != SemanticSimilarityHigh {
t.Fatalf("task band at 0.45 = %q", band)
}
if band := demo.ItemBand(false, 0.40); band != SemanticSimilarityMedium {
t.Fatalf("skill band at 0.40 = %q", band)
}
if band := demo.ItemBand(false, 0.30); band != "" {
t.Fatalf("skill band at 0.30 = %q, want none", band)
}
}
func TestSemanticPolicyValidationAndDocumentRoundTrip(t *testing.T) {
for name, edit := range map[string]func(*MatchingSemanticsPolicy){
"decreasing calibration": func(policy *MatchingSemanticsPolicy) {
policy.Calibration = []MatchingCalibrationPoint{{Score: 1000, Probability: 5000}, {Score: 2000, Probability: 4000}}
},
"one point": func(policy *MatchingSemanticsPolicy) { policy.Calibration = policy.Calibration[:1] },
"high below mid": func(policy *MatchingSemanticsPolicy) { policy.SkillHigh = policy.SkillMedium - 1 },
"no source": func(policy *MatchingSemanticsPolicy) { policy.Source = "" },
"bad model": func(policy *MatchingSemanticsPolicy) { policy.Members[0].Model.Revision = "main branch" },
"no members": func(policy *MatchingSemanticsPolicy) { policy.Members = nil },
"weights short": func(policy *MatchingSemanticsPolicy) { policy.Members[0].Weight = 9999 },
"zero deviation": func(policy *MatchingSemanticsPolicy) { policy.Members[0].StandardDeviation = 0 },
"repeated model": func(policy *MatchingSemanticsPolicy) {
policy.Members[0].Weight = 5000
policy.Members = append(policy.Members, policy.Members[0])
},
"evidence limit": func(policy *MatchingSemanticsPolicy) { policy.MaxEvidencePerEntry = 13 },
} {
semantics := DemoMatchingSemanticsPolicy()
edit(&semantics)
if err := semantics.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Errorf("%s: Validate() = %v, want ErrInvalidPolicy", name, err)
}
}
v5 := DemoProductPolicyV5()
if v5.Matching.FitSemanticsWeight != 5000 || v5.Matching.FitCoverageWeight+v5.Matching.FitDomainWeight+v5.Matching.FitSemanticsWeight != basisPointsPerUnit {
t.Fatalf("V5 weights = %+v", v5.Matching)
}
if v4 := DemoProductPolicyV4(); v4.Matching.FitSemanticsWeight != 1000 || v4.Matching.Semantics != nil {
t.Fatal("V4 must stay the PRD point without a semantic section")
}
encoded, _, err := encodeProductPolicy(v5)
if err != nil {
t.Fatalf("encodeProductPolicy(V5) error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy(V5) error = %v", err)
}
if decoded.Matching == nil || decoded.Matching.Semantics == nil ||
len(decoded.Matching.Semantics.Calibration) != len(v5.Matching.Semantics.Calibration) ||
!slices.Equal(decoded.Matching.Semantics.Members, v5.Matching.Semantics.Members) {
t.Fatal("the semantic section did not survive the document round trip")
}
var document map[string]any
if err := json.Unmarshal(encoded, &document); err != nil {
t.Fatalf("decode document: %v", err)
}
matching := document["matching"].(map[string]any)
semantics := matching["semantics"].(map[string]any)
delete(semantics, "source")
broken, _ := json.Marshal(document)
if _, err := decodeProductPolicy(broken); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("a semantic section without a source decoded: %v", err)
}
if err := v5.Validate(); err != nil {
t.Fatalf("V5 Validate() = %v", err)
}
}
+102
View File
@@ -0,0 +1,102 @@
package domain
import (
"encoding/binary"
"errors"
"fmt"
"math"
"regexp"
)
// ErrInvalidSemanticVector reports a vector that cannot be stored or used.
var ErrInvalidSemanticVector = errors.New("invalid semantic vector")
const (
// MaxSemanticDimension matches the ML contract bound of one vector.
MaxSemanticDimension = 4096
// semanticNormTolerance is how far a stored vector may be from unit
// length; float32 encoding stays far below it.
semanticNormTolerance = 1e-3
maxSemanticModelText = 200
)
var semanticModelTextPattern = regexp.MustCompile(`^[A-Za-z0-9._/-]{1,200}$`)
// SemanticModel identifies the encoder of a vector: the model, the pinned
// revision of its weights, and the prompt and pooling recipe. Vectors of two
// different models are never compared.
type SemanticModel struct {
ID string
Revision string
PromptVersion string
}
// Validate rejects an empty or malformed model identity.
func (model SemanticModel) Validate() error {
for _, part := range []string{model.ID, model.Revision, model.PromptVersion} {
if len(part) > maxSemanticModelText || !semanticModelTextPattern.MatchString(part) {
return fmt.Errorf("domain.SemanticModel.Validate - model identity is malformed: %w", ErrInvalidSemanticVector)
}
}
return nil
}
// SemanticVector is one L2-normalized float32 vector.
type SemanticVector []float32
// NewSemanticVector checks the dimension, finiteness, and unit length.
func NewSemanticVector(values []float32) (SemanticVector, error) {
const location = "domain.NewSemanticVector"
if len(values) == 0 || len(values) > MaxSemanticDimension {
return nil, fmt.Errorf("%s - dimension is out of range: %w", location, ErrInvalidSemanticVector)
}
var norm float64
for _, value := range values {
if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) {
return nil, fmt.Errorf("%s - value is not finite: %w", location, ErrInvalidSemanticVector)
}
norm += float64(value) * float64(value)
}
if math.Abs(math.Sqrt(norm)-1) > semanticNormTolerance {
return nil, fmt.Errorf("%s - vector is not normalized: %w", location, ErrInvalidSemanticVector)
}
return append(SemanticVector(nil), values...), nil
}
// Encode stores the vector as little-endian float32: exact, compact (four
// bytes a dimension), and independent of the platform.
func (vector SemanticVector) Encode() []byte {
encoded := make([]byte, 4*len(vector))
for index, value := range vector {
binary.LittleEndian.PutUint32(encoded[4*index:], math.Float32bits(value))
}
return encoded
}
// DecodeSemanticVector reads a stored vector of the given dimension.
func DecodeSemanticVector(encoded []byte, dimension int) (SemanticVector, error) {
if dimension <= 0 || dimension > MaxSemanticDimension || len(encoded) != 4*dimension {
return nil, fmt.Errorf("domain.DecodeSemanticVector - length does not match the dimension: %w", ErrInvalidSemanticVector)
}
vector := make(SemanticVector, dimension)
for index := range vector {
vector[index] = math.Float32frombits(binary.LittleEndian.Uint32(encoded[4*index:]))
}
return vector, nil
}
// Cosine is the dot product of two normalized vectors, summed in float64 in
// index order without fused multiply-add so the same vectors give the same value on every platform. It
// returns false for vectors of different dimensions.
func (vector SemanticVector) Cosine(other SemanticVector) (float64, bool) {
if len(vector) == 0 || len(vector) != len(other) {
return 0, false
}
var sum float64
for index := range vector {
// The explicit conversion rounds the product before the addition,
// so no platform fuses them into one multiply-add with another result.
sum += float64(float64(vector[index]) * float64(other[index])) //nolint:gosec // the lengths are equal, checked above
}
return sum, true
}
+310
View File
@@ -0,0 +1,310 @@
package domain
import (
"crypto/sha256"
"fmt"
"log/slog"
"slices"
"strings"
"unicode/utf8"
)
// SemanticViewVersion names the text rendering below. It is hashed into the
// content digest of every view, so a change of the rendering never reuses a
// vector of the old one.
const SemanticViewVersion = "semantic-views-v1"
const (
// maxSemanticViewRunes keeps a whole view under the 8000-character input
// limit of the ML contract; the model truncates at its token limit.
maxSemanticViewRunes = 7000
// maxSemanticItemRunes bounds one item text.
maxSemanticItemRunes = 2000
// maxReadmeRunesInView is the README excerpt length that one project
// contributes, so ten projects still fit into one view.
maxReadmeRunesInView = 600
// MaxSemanticNeedItems bounds the requirement items of one need: the
// contract limits required, desired skills and tasks to 20 each.
MaxSemanticNeedItems = 60
)
// SemanticSubjectKind is the owner of a stored vector.
type SemanticSubjectKind string
const (
SemanticSubjectCandidate SemanticSubjectKind = "candidate"
SemanticSubjectNeed SemanticSubjectKind = "need"
)
// SemanticItemKind is the kind of one text of a view.
type SemanticItemKind string
const (
// SemanticItemWhole is the whole view of a candidate or a need; Sem is
// the calibrated cosine of the two whole views.
SemanticItemWhole SemanticItemKind = "whole"
// Candidate items: one published project, the recognized stack, the roles.
SemanticItemProject SemanticItemKind = "project"
SemanticItemStack SemanticItemKind = "stack"
SemanticItemRoles SemanticItemKind = "roles"
// Need items: one confirmed requirement.
SemanticItemRequiredSkill SemanticItemKind = "required_skill"
SemanticItemDesiredSkill SemanticItemKind = "desired_skill"
SemanticItemTask SemanticItemKind = "task"
)
// SemanticItem is one text to encode. Key is stable inside a subject:
// "whole", "stack", "roles", or "<kind>:<position>". Label is the text that
// an explanation may show for it (a published project title or a
// requirement text) and is empty for other kinds. The text is personal data
// of a candidate or the need text of an organization: never log it.
type SemanticItem struct {
Key string
Kind SemanticItemKind
Text string
Label string
// Position is the index of the project or requirement the item names.
Position int
}
func (SemanticItem) String() string { return "[semantic item]" }
func (SemanticItem) GoString() string { return "[semantic item]" }
func (SemanticItem) LogValue() slog.Value {
return slog.StringValue("[semantic item]")
}
// ContentDigest is the SHA-256 of the rendering version, the item key, and
// the text. A stored vector is current only while its digest matches.
func (item SemanticItem) ContentDigest() [sha256.Size]byte {
return sha256.Sum256([]byte(SemanticViewVersion + "\x00" + item.Key + "\x00" + item.Text))
}
// LabelDigest is the SHA-256 of the label, so a stored project vector can be
// matched to the title that the card shows without storing the title twice.
func (item SemanticItem) LabelDigest() []byte {
if item.Label == "" {
return nil
}
digest := sha256.Sum256([]byte(item.Label))
return digest[:]
}
// SemanticLabelDigest returns the digest of a label as LabelDigest computes it.
func SemanticLabelDigest(label string) []byte {
return SemanticItem{Label: label}.LabelDigest()
}
// SemanticDocument is the rendered view of one subject: the whole text and
// its items in a stable order.
type SemanticDocument struct {
Whole SemanticItem
Items []SemanticItem
}
// All returns the whole view followed by the items.
func (document SemanticDocument) All() []SemanticItem {
return append([]SemanticItem{document.Whole}, document.Items...)
}
// IsEmpty reports a view without any text, which has nothing to encode.
func (document SemanticDocument) IsEmpty() bool { return document.Whole.Text == "" }
// RepositoryEvidence is the public metadata of a verified repository that a
// published project links. It feeds ranking only; no field of it is shown.
type RepositoryEvidence struct {
Description string
Topics []string
Languages []string
ReadmeExcerpt string
}
func (RepositoryEvidence) String() string { return "[repository evidence]" }
func (RepositoryEvidence) GoString() string { return "[repository evidence]" }
func (RepositoryEvidence) LogValue() slog.Value {
return slog.StringValue("[repository evidence]")
}
// cleanText collapses every run of white space to one space, as the
// research views did, so line breaks and indentation never change a vector.
func cleanText(value string) string { return strings.Join(strings.Fields(value), " ") }
// truncateRunes cuts a text to at most limit runes.
func truncateRunes(value string, limit int) string {
if utf8.RuneCountInString(value) <= limit {
return value
}
runes := []rune(value)
return strings.TrimSpace(string(runes[:limit]))
}
// NewCandidateSemanticDocument renders the published card of a candidate.
// It reads only the anonymous card content: the roles and grades that the
// card shows, its recognized stack codes, and its published projects, plus
// the public metadata of the repositories the card marks verified (keyed by
// project position). Private profile text such as experience summaries is
// never part of it.
func NewCandidateSemanticDocument(card AnonymousCandidateViewDTO, evidence map[int]RepositoryEvidence) SemanticDocument {
var document SemanticDocument
var lines []string
if roles := semanticRoles(card); roles != "" {
text := "Roles: " + roles
lines = append(lines, text)
document.Items = append(document.Items, SemanticItem{Key: string(SemanticItemRoles), Kind: SemanticItemRoles, Text: text})
}
if len(card.Skills) > 0 {
codes := make([]string, 0, len(card.Skills))
for _, skill := range card.Skills {
codes = append(codes, string(skill))
}
slices.Sort(codes)
text := "Stack: " + strings.Join(codes, ", ")
lines = append(lines, text)
document.Items = append(document.Items, SemanticItem{Key: string(SemanticItemStack), Kind: SemanticItemStack, Text: text})
}
if len(card.Projects) > 0 {
lines = append(lines, "Projects:")
for position, project := range card.Projects {
var repository *RepositoryEvidence
if found, ok := evidence[position]; ok && project.RepositoryVerified {
repository = &found
}
text := truncateRunes(projectText(project, repository), maxSemanticItemRunes)
lines = append(lines, "- "+text)
document.Items = append(document.Items, SemanticItem{
Key: fmt.Sprintf("%s:%d", SemanticItemProject, position), Kind: SemanticItemProject,
Text: text, Label: project.Title, Position: position,
})
}
}
whole := truncateRunes(strings.Join(lines, "\n"), maxSemanticViewRunes)
document.Whole = SemanticItem{Key: string(SemanticItemWhole), Kind: SemanticItemWhole, Text: whole}
return document
}
// semanticRoles lists the specializations of the card in catalog order with
// the confirmed grade when the card shows a category, else the declared grade.
func semanticRoles(card AnonymousCandidateViewDTO) string {
grades := make(map[SpecializationCode]string)
shown := make(map[SpecializationCode]bool)
for _, assessment := range card.SelfAssessment {
shown[assessment.Specialization] = true
if assessment.DeclaredGrade != nil {
grades[assessment.Specialization] = string(*assessment.DeclaredGrade)
}
}
for _, category := range card.Categories {
shown[category.Specialization] = true
grades[category.Specialization] = string(category.Grade)
}
var roles []string
for _, code := range specializationCodes {
if !shown[code] {
continue
}
if grade := grades[code]; grade != "" {
roles = append(roles, fmt.Sprintf("%s (%s)", code, grade))
} else {
roles = append(roles, string(code))
}
}
return strings.Join(roles, "; ")
}
func projectText(project CandidateViewProject, repository *RepositoryEvidence) string {
head := cleanText(project.Title)
if project.Description != nil && cleanText(*project.Description) != "" {
head += ": " + cleanText(*project.Description)
}
parts := []string{head}
if len(project.Stack) > 0 {
parts = append(parts, "Stack: "+cleanText(strings.Join(project.Stack, ", ")))
}
if repository != nil {
if description := cleanText(repository.Description); description != "" {
parts = append(parts, "Repository: "+description)
}
if len(repository.Topics) > 0 {
parts = append(parts, "Topics: "+cleanText(strings.Join(repository.Topics, ", ")))
}
if len(repository.Languages) > 0 {
parts = append(parts, "Languages: "+cleanText(strings.Join(repository.Languages, ", ")))
}
if readme := truncateRunes(cleanText(repository.ReadmeExcerpt), maxReadmeRunesInView); readme != "" {
parts = append(parts, "README: "+readme)
}
}
return strings.Join(parts, "; ")
}
// NewNeedSemanticDocument renders a need snapshot as the research need view
// and lists one item per confirmed requirement. Only confirmed values enter,
// the same ones the search scores; the title and the source text are the
// organization's own text of that snapshot.
func NewNeedSemanticDocument(snapshot NeedSnapshot) SemanticDocument {
requirements := snapshot.Requirements
required := confirmedSkillNames(requirements.RequiredSkills)
desired := confirmedSkillNames(requirements.DesiredSkills)
var tasks []string
for _, task := range requirements.Tasks {
if task.Status == NeedItemConfirmed && cleanText(task.Text) != "" {
tasks = append(tasks, cleanText(task.Text))
}
}
lines := needViewLines(snapshot, required, desired, tasks)
document := SemanticDocument{Whole: SemanticItem{
Key: string(SemanticItemWhole), Kind: SemanticItemWhole, Text: truncateRunes(strings.Join(lines, "\n"), maxSemanticViewRunes),
}}
appendRequirements := func(kind SemanticItemKind, texts []string) {
for position, text := range texts {
if len(document.Items) >= MaxSemanticNeedItems {
return
}
document.Items = append(document.Items, SemanticItem{
Key: fmt.Sprintf("%s:%d", kind, position), Kind: kind,
Text: truncateRunes(text, maxSemanticItemRunes), Label: text, Position: position,
})
}
}
appendRequirements(SemanticItemRequiredSkill, required)
appendRequirements(SemanticItemDesiredSkill, desired)
appendRequirements(SemanticItemTask, tasks)
return document
}
// needViewLines renders the lines of the research need view.
func needViewLines(snapshot NeedSnapshot, required, desired, tasks []string) []string {
requirements := snapshot.Requirements
lines := []string{"Title: " + cleanText(snapshot.Title)}
if requirements.Grade.Status == NeedValueConfirmed && requirements.Grade.Value != nil {
lines = append(lines, "Grade: "+string(*requirements.Grade.Value))
}
if requirements.Domain.Status == NeedValueConfirmed && requirements.Domain.Value != nil && cleanText(*requirements.Domain.Value) != "" {
lines = append(lines, "Domain: "+cleanText(*requirements.Domain.Value))
}
if len(required) > 0 {
lines = append(lines, "Required skills: "+strings.Join(required, "; "))
}
if len(desired) > 0 {
lines = append(lines, "Desired skills: "+strings.Join(desired, "; "))
}
if len(tasks) > 0 {
lines = append(lines, "Tasks:")
for _, task := range tasks {
lines = append(lines, "- "+task)
}
}
if snapshot.SourceText != nil && cleanText(*snapshot.SourceText) != "" {
lines = append(lines, "Description: "+cleanText(*snapshot.SourceText))
}
return lines
}
func confirmedSkillNames(skills []NeedSkill) []string {
var names []string
for _, skill := range skills {
if skill.Status == NeedItemConfirmed && cleanText(skill.Name) != "" {
names = append(names, cleanText(skill.Name))
}
}
return names
}
+6
View File
@@ -89,6 +89,11 @@ const (
CardFieldSelfAssessment CardField = "self_assessment"
CardFieldWorkFormats CardField = "work_formats"
CardFieldSalaryCompatibility CardField = "salary_compatibility"
// CardFieldProjects publishes the projects of the profile: title,
// description, stack, and whether a linked repository is verified public.
// It is the one free-text group of the card and is excluded from cohort
// generalization; the repository address never reaches it.
CardFieldProjects CardField = "projects"
)
const (
@@ -103,6 +108,7 @@ var cardFields = []CardField{
CardFieldCategories, CardFieldStack, CardFieldExperience,
CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation,
CardFieldSelfAssessment, CardFieldWorkFormats, CardFieldSalaryCompatibility,
CardFieldProjects,
}
// CardFields returns every card field the contract defines.