diff --git a/src/lib/mentor.test.ts b/src/lib/mentor.test.ts index b7b6bd2..d1b9412 100644 --- a/src/lib/mentor.test.ts +++ b/src/lib/mentor.test.ts @@ -4,10 +4,29 @@ import { buildSkillHolderDataSource, computeDependentsCounts, computeSkillCriticality, + computeTransitiveDependentsCounts, rankAtRiskSkills, type SkillGraph, } from "./mentor"; +/** + * A deep prerequisite chain: `fire-making` is a leaf in the dependsOn tree + * (it has no prerequisites of its own) yet is an INDIRECT prerequisite of + * every other skill through the chain + * fire-making <- smelting <- tool-forging <- well-drilling. Only one skill + * (`smelting`) depends on it directly, so its DIRECT in-degree is 1, but its + * TRANSITIVE dependent count is 3. This is the finding-M2 case: a rare, deep, + * foundational skill the whole chain silently rests on. + */ +function buildDeepChainGraph(): SkillGraph { + return [ + { id: "fire-making", label: "Fire Making", dependsOn: [] }, + { id: "smelting", label: "Smelting", dependsOn: ["fire-making"] }, + { id: "tool-forging", label: "Tool Forging", dependsOn: ["smelting"] }, + { id: "well-drilling", label: "Well Drilling", dependsOn: ["tool-forging"] }, + ]; +} + function buildGraph(): SkillGraph { return [ { id: "well-repair", label: "Well Repair", dependsOn: [] }, @@ -66,6 +85,86 @@ describe("computeDependentsCounts", () => { }); }); +describe("computeTransitiveDependentsCounts (finding M2: deep/leaf prerequisites)", () => { + it("equals the direct in-degree on a shallow graph where no dependent has its own dependents", () => { + // In buildGraph() every edge is one level deep, so the transitive closure + // coincides with the direct in-degree - the fix must not change these. + const transitive = computeTransitiveDependentsCounts(buildGraph()); + const direct = computeDependentsCounts(buildGraph()); + for (const id of ["well-repair", "water-treatment", "irrigation", "electrician", "radio-repair"]) { + expect(transitive.get(id)).toBe(direct.get(id)); + } + expect(transitive.get("well-repair")).toBe(2); + expect(transitive.get("electrician")).toBe(1); + }); + + it("credits a deep foundational skill for every DAG descendant, not just its direct dependent", () => { + const graph = buildDeepChainGraph(); + const direct = computeDependentsCounts(graph); + const transitive = computeTransitiveDependentsCounts(graph); + + // fire-making is named directly by only one skill (smelting)... + expect(direct.get("fire-making")).toBe(1); + // ...but the whole chain transitively rests on it: smelting, tool-forging, + // well-drilling - three transitive dependents. + expect(transitive.get("fire-making")).toBe(3); + expect(transitive.get("smelting")).toBe(2); + expect(transitive.get("tool-forging")).toBe(1); + expect(transitive.get("well-drilling")).toBe(0); + }); + + it("dedupes duplicate edges, skips self-loops, and ignores out-of-graph ids in the closure", () => { + const graph: SkillGraph = [ + { id: "base", label: "Base", dependsOn: [] }, + // duplicated real edge + self-loop + an edge to an id not in the graph + { id: "mid", label: "Mid", dependsOn: ["base", "base", "mid", "ghost"] }, + { id: "top", label: "Top", dependsOn: ["mid"] }, + ]; + const transitive = computeTransitiveDependentsCounts(graph); + expect(transitive.get("base")).toBe(2); // mid + top, counted once each + expect(transitive.get("mid")).toBe(1); // top + expect(transitive.get("top")).toBe(0); + }); + + it("terminates and counts each node once on an (out-of-contract) cyclic graph", () => { + const graph: SkillGraph = [ + { id: "a", label: "A", dependsOn: ["b"] }, + { id: "b", label: "B", dependsOn: ["a"] }, + ]; + const transitive = computeTransitiveDependentsCounts(graph); + // Each node has exactly one other node that (transitively) depends on it; + // the visited set prevents an infinite loop and stops self-counting. + expect(transitive.get("a")).toBe(1); + expect(transitive.get("b")).toBe(1); + }); + + it("flags a deep, rarely-held foundational skill as at-risk only once criticality counts transitive dependents (finding M2 proof)", () => { + const graph = buildDeepChainGraph(); + // fire-making is held by a single resident ("survive a generation" risk). + const dataSource = buildSkillHolderDataSource([ + { payload: { type: "seed.skillHolder", skillId: "fire-making", holderCount: 1 } }, + ]); + // A threshold that demands more than one dependent before a skill is + // deemed critical. Under the OLD direct-only count, fire-making scored 1 + // and fell below this bar; under the transitive closure it scores 3. + const thresholds = { minDependentsForAtRisk: 2, maxHoldersForAtRisk: 2 }; + + // Regression anchor: the old behaviour (direct in-degree) would NOT clear + // the threshold. + expect(computeDependentsCounts(graph).get("fire-making")).toBeLessThan( + thresholds.minDependentsForAtRisk, + ); + + const results = computeSkillCriticality(graph, dataSource, thresholds); + const fireMaking = results.find((r) => r.skillId === "fire-making")!; + expect(fireMaking.dependentsCount).toBe(3); // transitive, not the direct 1 + expect(fireMaking.insufficientData).toBe(false); + expect(fireMaking.atRisk).toBe(true); // was false before the transitive fix + + expect(rankAtRiskSkills(results).map((r) => r.skillId)).toContain("fire-making"); + }); +}); + describe("buildSkillHolderDataSource", () => { it("reads holder counts live from real seed.skillHolder entries, ignoring unrelated payloads", () => { const dataSource = buildSkillHolderDataSource([ diff --git a/src/lib/mentor.ts b/src/lib/mentor.ts index ac1ce08..4ce94e2 100644 --- a/src/lib/mentor.ts +++ b/src/lib/mentor.ts @@ -1,10 +1,15 @@ /** * Mentor: skill-criticality graph engine (plan todo 47). * - * Builds a skills dependency graph and computes a simple centrality metric - * - dependents-count: how many other skills directly depend on a given - * skill - to flag "at-risk" skills: ones that are highly depended-on but - * held by few (or by an unknown number of) residents. + * Builds a skills dependency graph and computes a centrality metric + * - transitive dependents-count: how many other skills depend on a given + * skill, directly OR indirectly through a chain of prerequisites - to flag + * "at-risk" skills: ones that are highly depended-on but held by few (or by + * an unknown number of) residents. The transitive closure (not the raw + * direct in-degree) is what criticality uses, so a foundational skill buried + * deep at the base of a long prerequisite chain is credited for every skill + * whose practice ultimately rests on it - exactly the "survive a generation" + * case a direct-only count silently misses. * * Hard constraint (non-negotiable, plan todo 47): this module MUST NEVER * invent a fabricated skill-holder population number. Holder counts are @@ -84,10 +89,12 @@ export function buildSkillHolderDataSource( } /** - * Dependents-count centrality: for each skill in `graph`, how many other + * Direct dependents-count centrality: for each skill in `graph`, how many other * skills in the same graph list it directly in their `dependsOn`. A simple, * literal in-degree count over the real dependency edges - no transitive - * closure, no weighting, nothing fit to data. + * closure, no weighting, nothing fit to data. This raw in-degree is still the + * weight `src/lib/mentorMatching.ts` uses to score mentor coverage; criticality + * (`computeSkillCriticality`) uses the transitive closure below instead. * * Two defensive-but-necessary normalizations happen before counting (GAP-15): * a duplicate prerequisite edge within one skill's own `dependsOn` list is @@ -110,6 +117,57 @@ export function computeDependentsCounts(graph: SkillGraph): Map return counts; } +/** + * Transitive dependents-count centrality: for each skill in `graph`, how many + * OTHER skills depend on it directly OR indirectly - every DAG descendant in + * the dependents direction (a skill that reaches it through any chain of + * `dependsOn` edges). This is the transitive closure of + * `computeDependentsCounts`'s direct in-degree. + * + * Why criticality needs it (finding M2): a direct-only count credits a + * foundational skill solely for the skills that name it as an *immediate* + * prerequisite, so a skill deep at the base of a long chain is undercounted - + * a rare, deep prerequisite the whole settlement silently rests on scores far + * below its real criticality and can slip under the at-risk threshold. The + * transitive closure credits it for every skill whose practice ultimately + * rests on it. + * + * Edge normalization matches `computeDependentsCounts` exactly (GAP-15): a + * duplicate prerequisite edge within one skill's `dependsOn` list is deduped + * (via the `Set`), a skill's self-reference is skipped, and an edge to an id + * outside `graph` is ignored. The traversal carries a visited set, so an + * out-of-contract cycle terminates instead of looping - it never fabricates a + * count, it only closes over the real edges that are present. + */ +export function computeTransitiveDependentsCounts(graph: SkillGraph): Map { + // Reverse adjacency: directDependents[y] = skills that directly depend on y. + const directDependents = new Map>( + graph.map((skill) => [skill.id, new Set()]), + ); + for (const skill of graph) { + for (const dependencyId of new Set(skill.dependsOn)) { + if (dependencyId === skill.id) continue; + directDependents.get(dependencyId)?.add(skill.id); + } + } + + const counts = new Map(graph.map((skill) => [skill.id, 0])); + for (const skill of graph) { + const reached = new Set(); + const stack = [...(directDependents.get(skill.id) ?? [])]; + while (stack.length > 0) { + const current = stack.pop()!; + if (current === skill.id || reached.has(current)) continue; + reached.add(current); + for (const next of directDependents.get(current) ?? []) { + if (next !== skill.id && !reached.has(next)) stack.push(next); + } + } + counts.set(skill.id, reached.size); + } + return counts; +} + export interface SkillCriticalityThresholds { /** A skill needs at least this many dependents to be eligible for "at-risk". */ minDependentsForAtRisk: number; @@ -126,7 +184,7 @@ export const DEFAULT_SKILL_CRITICALITY_THRESHOLDS: SkillCriticalityThresholds = export interface SkillCriticalityResult { skillId: string; label: string; - /** Dependents-count centrality for this skill (real in-degree over `graph`'s edges). */ + /** Transitive dependents-count centrality: every skill that depends on this one, directly or indirectly, over `graph`'s edges. */ dependentsCount: number; /** Real holder count from `dataSource`, or `undefined` when that data is not present. */ holderCount: number | undefined; @@ -149,7 +207,7 @@ export function computeSkillCriticality( dataSource: SkillHolderDataSource, thresholds: SkillCriticalityThresholds = DEFAULT_SKILL_CRITICALITY_THRESHOLDS, ): SkillCriticalityResult[] { - const dependentsCounts = computeDependentsCounts(graph); + const dependentsCounts = computeTransitiveDependentsCounts(graph); return graph.map((skill) => { const dependentsCount = dependentsCounts.get(skill.id) ?? 0;