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}, } }