253 lines
10 KiB
TypeScript
253 lines
10 KiB
TypeScript
/**
|
|
* Mentor: apprentice-to-mentor matching engine (plan todo 11 / GAP-11).
|
|
*
|
|
* `src/lib/mentor.ts`'s skill-criticality engine can flag a skill as
|
|
* "at-risk" (highly depended-on, held by few people) but stops there - it
|
|
* never says *who* an apprentice struggling with that skill could actually
|
|
* learn from. This module closes that gap: given real mentor skill
|
|
* profiles and real apprentice skill needs (both derivable from real
|
|
* `mentor.skillReview` Event Log entries - see `buildMentorProfilesFromReviews`
|
|
* / `buildApprenticeNeedsFromReviews` below), it scores candidate mentors
|
|
* against each apprentice's need and proposes the single best real match.
|
|
*
|
|
* Scoring reuses `computeDependentsCounts` from `src/lib/mentor.ts` - the
|
|
* exact dependents-count centrality `computeSkillCriticality`/
|
|
* `rankAtRiskSkills` are themselves built on - so a mentor who covers a
|
|
* highly-depended-on skill scores above one who covers a peripheral skill
|
|
* (exact skill coverage, criticality-weighted), and a mentor who also holds
|
|
* a needed skill's own prerequisites (the skill graph's real `dependsOn`
|
|
* edges) scores higher still (dependency coverage). This module never
|
|
* modifies `computeSkillCriticality`/`rankAtRiskSkills` - it only calls the
|
|
* already-landed, exported `computeDependentsCounts`.
|
|
*/
|
|
|
|
import { Rating, type Grade } from "ts-fsrs";
|
|
import { computeDependentsCounts, type SkillGraph, type SkillNode } from "./mentor.ts";
|
|
import type { SkillReviewSeedPayload } from "./mentorSchedule.ts";
|
|
|
|
/** One real mentor candidate: an account and the skill ids they have demonstrated proficiency in. */
|
|
export interface MentorProfile {
|
|
readonly accountId: string;
|
|
readonly skills: readonly string[];
|
|
}
|
|
|
|
/** One real apprentice need: an account and the skill ids they still need help with. */
|
|
export interface ApprenticeNeed {
|
|
readonly accountId: string;
|
|
readonly neededSkills: readonly string[];
|
|
}
|
|
|
|
/**
|
|
* The outcome of matching one apprentice need against the real mentor
|
|
* candidate pool. `"no-match"` is an explicit, first-class outcome - returned
|
|
* whenever no mentor covers any of the need's required skills (directly or
|
|
* through its prerequisites) - never a crash and never an arbitrary pick.
|
|
*/
|
|
export type MentorMatch =
|
|
| {
|
|
readonly status: "matched";
|
|
readonly apprenticeId: string;
|
|
readonly mentorId: string;
|
|
readonly score: number;
|
|
readonly coveredSkills: readonly string[];
|
|
readonly coveredDependencySkills: readonly string[];
|
|
}
|
|
| {
|
|
readonly status: "no-match";
|
|
readonly apprenticeId: string;
|
|
};
|
|
|
|
/** ts-fsrs's own "proficient" bar (Good or Easy) - not an invented threshold. */
|
|
const PROFICIENT_RATING_FLOOR: Grade = Rating.Good;
|
|
|
|
function isProficientRating(rating: Grade): boolean {
|
|
return rating >= PROFICIENT_RATING_FLOOR;
|
|
}
|
|
|
|
const KEY_SEPARATOR = "\u0000";
|
|
|
|
function accountSkillKey(accountId: string, skillId: string): string {
|
|
return `${accountId}${KEY_SEPARATOR}${skillId}`;
|
|
}
|
|
|
|
function splitAccountSkillKey(key: string): [accountId: string, skillId: string] {
|
|
const separatorIndex = key.indexOf(KEY_SEPARATOR);
|
|
return [key.slice(0, separatorIndex), key.slice(separatorIndex + 1)];
|
|
}
|
|
|
|
function isSkillReviewPayload(payload: unknown): payload is SkillReviewSeedPayload {
|
|
if (typeof payload !== "object" || payload === null) return false;
|
|
const candidate = payload as Record<string, unknown>;
|
|
return (
|
|
candidate.type === "mentor.skillReview" &&
|
|
typeof candidate.skillId === "string" &&
|
|
typeof candidate.learnerId === "string" &&
|
|
typeof candidate.rating === "number" &&
|
|
Number.isFinite(candidate.rating) &&
|
|
typeof candidate.reviewedAt === "string" &&
|
|
!Number.isNaN(Date.parse(candidate.reviewedAt))
|
|
);
|
|
}
|
|
|
|
/** The most recent real `mentor.skillReview` entry for every (learnerId, skillId) pair seen in `entries`. */
|
|
function latestReviewByAccountAndSkill(
|
|
entries: ReadonlyArray<{ payload: unknown }>,
|
|
): Map<string, SkillReviewSeedPayload> {
|
|
const latest = new Map<string, SkillReviewSeedPayload>();
|
|
for (const entry of entries) {
|
|
if (!isSkillReviewPayload(entry.payload)) continue;
|
|
const key = accountSkillKey(entry.payload.learnerId, entry.payload.skillId);
|
|
const existing = latest.get(key);
|
|
if (existing === undefined || Date.parse(entry.payload.reviewedAt) >= Date.parse(existing.reviewedAt)) {
|
|
latest.set(key, entry.payload);
|
|
}
|
|
}
|
|
return latest;
|
|
}
|
|
|
|
/**
|
|
* Builds real mentor profiles from `mentor.skillReview` Event Log entries:
|
|
* an account becomes a mentor candidate for a skill once their most recent
|
|
* recorded review of that skill is Good or Easy (ts-fsrs's own proficiency
|
|
* bar). An account with no reviews at that level contributes no profile -
|
|
* never a fabricated/default skill list.
|
|
*/
|
|
export function buildMentorProfilesFromReviews(
|
|
entries: ReadonlyArray<{ payload: unknown }>,
|
|
): MentorProfile[] {
|
|
const skillsByAccount = new Map<string, Set<string>>();
|
|
for (const [key, review] of latestReviewByAccountAndSkill(entries)) {
|
|
if (!isProficientRating(review.rating as Grade)) continue;
|
|
const [accountId, skillId] = splitAccountSkillKey(key);
|
|
const skills = skillsByAccount.get(accountId) ?? new Set<string>();
|
|
skills.add(skillId);
|
|
skillsByAccount.set(accountId, skills);
|
|
}
|
|
return Array.from(skillsByAccount.entries())
|
|
.map(([accountId, skills]) => ({ accountId, skills: Array.from(skills).sort() }))
|
|
.sort((a, b) => a.accountId.localeCompare(b.accountId));
|
|
}
|
|
|
|
/**
|
|
* Builds real apprentice needs from `mentor.skillReview` Event Log entries,
|
|
* scoped to `atRiskSkillIds` (the real at-risk set from `src/lib/mentor.ts`'s
|
|
* `rankAtRiskSkills` - this module never invents its own at-risk list). An
|
|
* account needs a skill when its most recent recorded review of that skill
|
|
* is Again or Hard - still struggling, not yet proficient.
|
|
*/
|
|
export function buildApprenticeNeedsFromReviews(
|
|
entries: ReadonlyArray<{ payload: unknown }>,
|
|
atRiskSkillIds: ReadonlySet<string>,
|
|
): ApprenticeNeed[] {
|
|
const needsByAccount = new Map<string, Set<string>>();
|
|
for (const [key, review] of latestReviewByAccountAndSkill(entries)) {
|
|
const [accountId, skillId] = splitAccountSkillKey(key);
|
|
if (!atRiskSkillIds.has(skillId)) continue;
|
|
if (isProficientRating(review.rating as Grade)) continue;
|
|
const needs = needsByAccount.get(accountId) ?? new Set<string>();
|
|
needs.add(skillId);
|
|
needsByAccount.set(accountId, needs);
|
|
}
|
|
return Array.from(needsByAccount.entries())
|
|
.map(([accountId, neededSkills]) => ({ accountId, neededSkills: Array.from(neededSkills).sort() }))
|
|
.sort((a, b) => a.accountId.localeCompare(b.accountId));
|
|
}
|
|
|
|
interface ScoredCandidate {
|
|
mentor: MentorProfile;
|
|
score: number;
|
|
coveredSkills: string[];
|
|
coveredDependencySkills: string[];
|
|
}
|
|
|
|
function scoreCandidate(
|
|
mentor: MentorProfile,
|
|
neededSkills: readonly string[],
|
|
prerequisiteIds: ReadonlySet<string>,
|
|
dependentsCounts: ReadonlyMap<string, number>,
|
|
): ScoredCandidate {
|
|
const mentorSkills = new Set(mentor.skills);
|
|
const coveredSkills = neededSkills.filter((skillId) => mentorSkills.has(skillId));
|
|
const coveredDependencySkills = Array.from(prerequisiteIds).filter((skillId) => mentorSkills.has(skillId));
|
|
|
|
// Exact skill coverage, weighted by the needed skill's real dependents-count
|
|
// centrality (computeDependentsCounts) - covering a more critical skill
|
|
// scores higher than covering a peripheral one.
|
|
const exactScore = coveredSkills.reduce(
|
|
(sum, skillId) => sum + 1 + (dependentsCounts.get(skillId) ?? 0),
|
|
0,
|
|
);
|
|
// Dependency coverage: the mentor also holds the needed skills' own
|
|
// prerequisites (real dependsOn edges), so they can teach the foundation
|
|
// a needed skill builds on, not just the skill label itself.
|
|
const score = exactScore + coveredDependencySkills.length;
|
|
|
|
return { mentor, score, coveredSkills, coveredDependencySkills };
|
|
}
|
|
|
|
function pickBest(candidates: ReadonlyArray<ScoredCandidate>): ScoredCandidate | undefined {
|
|
let best: ScoredCandidate | undefined;
|
|
for (const candidate of candidates) {
|
|
if (candidate.score <= 0) continue;
|
|
if (
|
|
best === undefined ||
|
|
candidate.score > best.score ||
|
|
(candidate.score === best.score && candidate.mentor.accountId.localeCompare(best.mentor.accountId) < 0)
|
|
) {
|
|
best = candidate;
|
|
}
|
|
}
|
|
return best;
|
|
}
|
|
|
|
function prerequisiteIdsFor(neededSkills: readonly string[], nodeById: ReadonlyMap<string, SkillNode>): Set<string> {
|
|
const prerequisiteIds = new Set<string>();
|
|
for (const skillId of neededSkills) {
|
|
for (const dependencyId of nodeById.get(skillId)?.dependsOn ?? []) {
|
|
if (!neededSkills.includes(dependencyId)) prerequisiteIds.add(dependencyId);
|
|
}
|
|
}
|
|
return prerequisiteIds;
|
|
}
|
|
|
|
/**
|
|
* Scores every real mentor candidate (`mentors`) against each real
|
|
* apprentice need (`needs`) over the real skill dependency `graph`, and
|
|
* returns the single best match per need - one `MentorMatch` per entry in
|
|
* `needs`, same order.
|
|
*
|
|
* An empty `mentors` or `needs` array never crashes: an empty `needs` array
|
|
* yields an empty result, and any need matched against an empty (or
|
|
* non-covering) mentor pool yields an explicit `"no-match"` result rather
|
|
* than an arbitrary pick. Ties (equal score) are broken deterministically
|
|
* by ascending mentor account id.
|
|
*/
|
|
export function matchApprenticesToMentors(
|
|
mentors: ReadonlyArray<MentorProfile>,
|
|
needs: ReadonlyArray<ApprenticeNeed>,
|
|
graph: SkillGraph,
|
|
): MentorMatch[] {
|
|
const dependentsCounts = computeDependentsCounts(graph);
|
|
const nodeById = new Map(graph.map((node) => [node.id, node]));
|
|
|
|
return needs.map((need): MentorMatch => {
|
|
const prerequisiteIds = prerequisiteIdsFor(need.neededSkills, nodeById);
|
|
const candidates = mentors
|
|
.filter((mentor) => mentor.accountId !== need.accountId)
|
|
.map((mentor) => scoreCandidate(mentor, need.neededSkills, prerequisiteIds, dependentsCounts));
|
|
|
|
const best = pickBest(candidates);
|
|
if (best === undefined) {
|
|
return { status: "no-match", apprenticeId: need.accountId };
|
|
}
|
|
return {
|
|
status: "matched",
|
|
apprenticeId: need.accountId,
|
|
mentorId: best.mentor.accountId,
|
|
score: best.score,
|
|
coveredSkills: best.coveredSkills,
|
|
coveredDependencySkills: best.coveredDependencySkills,
|
|
};
|
|
});
|
|
}
|