Files

311 lines
11 KiB
Go

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
}