diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 77b28dd..80e3975 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -522,7 +522,28 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e - **Cancel, never delete.** `cancelUnavailability` flips `status='cancelled'`; the row persists so historical assignment conflicts stay explainable (rule 5 in §5.3 warns, doesn't hard-block). `isUnavailable` skips non-`active` records, so a cancelled blackout no longer excludes the volunteer. - **Constraints enforced in two layers.** The pure `validateUnavailabilityRange` rejects bad ranges at the API boundary (400 with a clear message); the DB `chk_unavailability_*` CHECK constraints are the backstop so a bad range can never reach the table. -**Next: D5 — conflict engine (pure function, hard vs soft conflicts).** +## D5 — Conflict engine (hard vs soft) — DONE 2026-11-18 + +**Scope (from BUILD-PLAN.md):** conflict engine — pure function, hard vs soft conflicts. Done when: table-driven test, 10 cases, one per rule in BUILD-SPEC §7. ARCHITECTURE §5.3 / BUILD-SPEC §7. + +**Delivered:** +- `src/domain/conflicts.ts` — pure `classifyConflicts(input)` returns every reason a candidate should not take a slot, each tagged `hard` (blocks) or `soft` (warns; override with a note). Reuses the pure predicates it encodes: `isUnavailable` (D4) for blackouts, `isMentorReady` (C5) for the shadow mentor, `levelRank` (C3) for the core-skill gate. Plus `hasHardConflict` / `hardConflicts` / `softConflicts` so the picker and auto-filler filter by severity. No DB imports. +- `src/domain/conflicts.test.ts` — table-driven: one case per rule (ten cases, one per row of §5.3), plus a clean baseline, a multi-conflict case, and the branch edges (unapproved-but-active, a valid shadow pairing, never-served, unrated comfort, core skill AT the required level). 20 tests total. + +**No schema change, no route, no migration.** D5 is a pure function (zero UI, zero DB) — the BUILD-PLAN's highest-risk unit, isolated exactly that way. The data layer (D6/D8) resolves the joins and passes the facts in; this module only encodes the rules. + +**Verification (all exit 0):** +- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run` ✓ (**160** total; D5 = 20) · `next build` ✓ + +**Decisions:** +- **Hard vs soft, keyed by code.** Each conflict has a stable `code` and a `severity`. The assignment write path and auto-filler reject on `hardConflicts(...)`; the picker shows all of them, greasing the soft ones as warnings the admin overrides with a note. +- **One code per rule, ten cases.** The 10 rules map 1:1 to ARCHITECTURE §5.3 (4 hard: inactive/unapproved, duplicate-in-instance, core-skill-below-required, shadow-mentor-not-ready; 6 soft: blackout-overlap, monthly-cap, back-to-back, comfort-below-50, stale, readiness-below-threshold). The test table has exactly one case per rule. +- **Comfort never blocks (rule 14).** §7 rule 14 says self-comfort lowers rank and warns but never blocks; `comfort_below_50` is soft even though the picker treats it as a warning. +- **Never-served is not stale.** Rule 9 (staleness) requires a non-null `lastServedOn`; a volunteer who has never served the skill is a readiness/level concern (surfaced by readiness), not a "needs refresher" — flagging a beginner as stale would mislead. +- **Staleness takes a reference date.** The function is pure and deterministic, so `daysBetween(lastServedOn, today)` takes `today` as input rather than reading the clock — the test pins it to a fixed date. +- **Shadow mentor reuses `isMentorReady`.** A shadow slot (§7 rule 16) needs a mentor who is mentor-ready for that exact skill; the C5 predicate is called directly, and an unpaired shadow (`pairedMentor` null) is a hard conflict. + +**Next: D6 — candidate ranking service (availability filter → readiness → score).** --- diff --git a/src/domain/conflicts.test.ts b/src/domain/conflicts.test.ts new file mode 100644 index 0000000..8e7e5c8 --- /dev/null +++ b/src/domain/conflicts.test.ts @@ -0,0 +1,310 @@ +import { + describe, + it, + expect, +} from "vitest"; +import { type UnavailabilityRecord } from "./availability"; +import { type MentorReadyInput } from "./mentor"; +import { + classifyConflicts, + hasHardConflict, + hardConflicts, + softConflicts, + type ConflictInput, + type ConflictCode, + type ConflictSeverity, + type SkillLevel, +} from "./conflicts"; + +/** + * Conflict engine — unit D5 (ARCHITECTURE §5.3, BUILD-SPEC §7). + * + * Table-driven: one case per rule (ten cases, one per row of §5.3), plus a + * clean baseline, a multi-conflict case, and the branch edges the single + * rules contain (unapproved-but-active, a valid shadow pairing, never-served, + * unrated core comfort). + */ + +/** A conflict-free volunteer, ready for a qualified Audio slot on 2026-11-22. */ +function base(): ConflictInput { + return { + userStatus: "active", + adminApproved: true, + alreadyAssignedInInstance: false, + coreSkills: [ + { name: "Audio", requiredLevel: "qualified", verifiedLevel: "qualified" }, + ], + isShadowSlot: false, + pairedMentor: null, + occursOn: "2026-11-22", + unavailability: [], + monthlyServiceCount: 0, + maxServicesPerMonth: 3, + servesOtherServiceThatMorning: false, + coreComfortLow: 90, + lastServedOn: "2026-11-01", + staleAfterDays: 180, + today: "2026-11-22", + readinessScore: 85, + readinessWarnThreshold: 70, + }; +} + +/** One case per rule: the override that fires it, and the expected code + + * severity. The baseline is conflict-free, so each override isolates one rule. + * The `rule()` factory types each `override` against `Partial`, + * so the literals are checked (and preserved) instead of widened to `string`. */ +type RuleCase = { + name: string; + override: Partial; + code: ConflictCode; + severity: ConflictSeverity; +}; + +const rule = ( + name: string, + override: Partial, + code: ConflictCode, + severity: ConflictSeverity, +): RuleCase => ({ name, override, code, severity }); + +const cases: RuleCase[] = [ + // --- hard --- + rule( + "rule 1 — inactive volunteer blocks (hard)", + { userStatus: "inactive" }, + "inactive_or_unapproved", + "hard", + ), + rule( + "rule 1 — active but not admin-approved blocks (hard)", + { adminApproved: false }, + "inactive_or_unapproved", + "hard", + ), + rule( + "rule 2 — duplicate assignment in the same instance blocks (hard)", + { alreadyAssignedInInstance: true }, + "duplicate_in_instance", + "hard", + ), + rule( + "rule 3 — core skill below required level blocks (hard)", + { + coreSkills: [ + { name: "Audio", requiredLevel: "qualified", verifiedLevel: "assisted" }, + ], + }, + "core_skill_below_required", + "hard", + ), + rule( + "rule 4 — shadow slot without a ready mentor blocks (hard)", + { isShadowSlot: true }, + "shadow_mentor_not_ready", + "hard", + ), + // --- soft --- + rule( + "rule 5 — blackout over the instance date warns (soft)", + { + unavailability: [ + { + id: "b1", + userId: "u1", + kind: "blackout", + startsOn: "2026-11-20", + endsOn: "2026-11-25", + allDay: true, + reason: null, + rrule: null, + status: "active", + createdAt: new Date("2026-11-01T00:00:00Z"), + createdBy: "u1", + }, + ], + }, + "blackout_overlap", + "soft", + ), + rule( + "rule 6 — over the monthly cap warns (soft)", + { monthlyServiceCount: 4 }, + "monthly_cap_exceeded", + "soft", + ), + rule( + "rule 7 — back-to-back service warns (soft)", + { servesOtherServiceThatMorning: true }, + "back_to_back", + "soft", + ), + rule( + "rule 8 — comfort below 50% on a core skill warns (soft)", + { coreComfortLow: 40 }, + "comfort_below_50", + "soft", + ), + rule( + "rule 9 — stale skill warns (soft)", + { lastServedOn: "2026-04-01" }, + "skill_stale", + "soft", + ), + rule( + "rule 10 — readiness below threshold warns (soft)", + { readinessScore: 60 }, + "readiness_below_threshold", + "soft", + ), +]; + +describe("classifyConflicts — one case per rule (BUILD-SPEC §7 / §5.3)", () => { + for (const c of cases) { + it(`${c.name}`, () => { + const conflicts = classifyConflicts({ ...base(), ...c.override }); + expect(conflicts).toHaveLength(1); + expect(conflicts[0].code).toBe(c.code); + expect(conflicts[0].severity).toBe(c.severity); + }); + } +}); + +describe("classifyConflicts — edges", () => { + it("a clean, ready volunteer has no conflicts", () => { + expect(classifyConflicts(base())).toHaveLength(0); + }); + + it("a valid shadow pairing (mentor_ready) does not fire rule 4", () => { + const input = { + ...base(), + isShadowSlot: true, + pairedMentor: { + verifiedLevel: "expert", + mentorMinLevel: "qualified", + mentorOptIn: true, + adminApproved: true, + } as MentorReadyInput, + }; + expect(classifyConflicts(input)).toHaveLength(0); + }); + + it("never-served (null lastServedOn) is not stale", () => { + const input = { ...base(), lastServedOn: null }; + expect(classifyConflicts(input)).toHaveLength(0); + }); + + it("unrated core comfort (null) does not fire rule 8", () => { + const input = { ...base(), coreComfortLow: null }; + expect(classifyConflicts(input)).toHaveLength(0); + }); + + it("a core skill AT the required level does not block (rule 3)", () => { + const input = { + ...base(), + coreSkills: [ + { + name: "Audio", + requiredLevel: "qualified" as SkillLevel, + verifiedLevel: "expert" as SkillLevel, + }, + ], + }; + expect(classifyConflicts(input)).toHaveLength(0); + }); + + it("reports every conflict at once, hard first then soft", () => { + const conflicts = classifyConflicts({ + ...base(), + userStatus: "denied", + alreadyAssignedInInstance: true, + coreSkills: [ + { + name: "Audio", + requiredLevel: "qualified" as SkillLevel, + verifiedLevel: "assisted" as SkillLevel, + }, + ], + isShadowSlot: true, + unavailability: [ + { + id: "b1", + userId: "u1", + kind: "blackout", + startsOn: "2026-11-22", + endsOn: "2026-11-22", + allDay: true, + reason: null, + rrule: null, + status: "active", + createdAt: new Date("2026-11-01T00:00:00Z"), + createdBy: "u1", + }, + ] as UnavailabilityRecord[], + monthlyServiceCount: 5, + coreComfortLow: 30, + lastServedOn: "2026-01-01", + readinessScore: 40, + }); + + const codes = conflicts.map((c) => c.code); + // All four hard rules, then all applicable soft rules. + expect(codes.slice(0, 4)).toEqual([ + "inactive_or_unapproved", + "duplicate_in_instance", + "core_skill_below_required", + "shadow_mentor_not_ready", + ]); + expect(codes.slice(4)).toEqual([ + "blackout_overlap", + "monthly_cap_exceeded", + "comfort_below_50", + "skill_stale", + "readiness_below_threshold", + ]); + }); + + it("the inclusive-end blackout case: a same-day blackout covers the date", () => { + const input = { + ...base(), + unavailability: [ + { + id: "b1", + userId: "u1", + kind: "blackout", + startsOn: "2026-11-22", + endsOn: "2026-11-22", + allDay: true, + reason: null, + rrule: null, + status: "active", + createdAt: new Date("2026-11-01T00:00:00Z"), + createdBy: "u1", + }, + ] as UnavailabilityRecord[], + }; + expect(classifyConflicts(input)[0].code).toBe("blackout_overlap"); + }); +}); + +describe("severity helpers", () => { + it("hasHardConflict / hardConflicts / softConflicts split correctly", () => { + const conflicts = classifyConflicts({ + ...base(), + userStatus: "inactive", + monthlyServiceCount: 4, + }); + expect(hasHardConflict(conflicts)).toBe(true); + expect(hardConflicts(conflicts).map((c) => c.code)).toEqual([ + "inactive_or_unapproved", + ]); + expect(softConflicts(conflicts).map((c) => c.code)).toEqual([ + "monthly_cap_exceeded", + ]); + }); + + it("hasHardConflict is false when only soft conflicts exist", () => { + const conflicts = classifyConflicts({ ...base(), monthlyServiceCount: 4 }); + expect(hasHardConflict(conflicts)).toBe(false); + }); +}); diff --git a/src/domain/conflicts.ts b/src/domain/conflicts.ts new file mode 100644 index 0000000..b618362 --- /dev/null +++ b/src/domain/conflicts.ts @@ -0,0 +1,281 @@ +/** + * Conflict engine — unit D5 (ARCHITECTURE §5.3, BUILD-SPEC §7). + * + * Pure: no DB, no imports from `src/db`. It classifies every reason a + * candidate volunteer should not take a slot into **hard** (blocks the + * assignment) and **soft** (warns; the admin overrides with a note). The + * picker shows all of them; the auto-filler and the assignment write path + * reject on the hard ones. + * + * The rules (ARCHITECTURE §5.3, mapped to BUILD-SPEC §7). Exactly one per + * rule — ten cases, one per row: + * + * HARD (block): + * 1. Volunteer inactive or unapproved. §7 status / §5.3 #1 + * 2. Duplicate person in the same service instance. §7 rule 1 / §5.3 #2 + * 3. A core skill verified below the required level. §7 rule 13 / §5.3 #3 + * 4. Shadow slot without a mentor_ready paired mentor. §7 rule 16 / §5.3 #4 + * + * SOFT (warn, override with a required note): + * 5. Overlaps a submitted blackout date. §7 rule 5 / §5.3 #5 + * 6. Exceeds the monthly service cap. §7 rule 7 / §5.3 #6 + * 7. Already serves the other service that morning. §5.3 #7 + * 8. Self-rated comfort below 50% on a core skill. §7 rule 14 / §5.3 #8 + * 9. Skill stale (no service in stale_after_days). §7 rule 18 / §5.3 #9 + * 10. Readiness score below the warn threshold. §5.4 / §5.3 #10 + * + * The function takes the resolved facts (the caller resolves the joins) and + * returns every conflict, hard first then soft, so a caller can filter by + * severity. It reuses the pure predicates already written for the rules it + * encodes: `isUnavailable` (D4) for blackouts, `isMentorReady` (C5) for the + * shadow mentor, `levelRank` (C3) for the core-skill gate. + */ + +import { levelRank, type SkillLevel } from "./assessments"; +import { isMentorReady, type MentorReadyInput } from "./mentor"; +import { isUnavailable, type UnavailabilityRecord } from "./availability"; + +export { isUnavailable }; +export type { SkillLevel }; + +/** A conflict is either a hard block or a soft warning the admin overrides. */ +export type ConflictSeverity = "hard" | "soft"; + +/** Stable machine code — one per rule. Callers key on this, not the message. */ +export type ConflictCode = + // hard + | "inactive_or_unapproved" + | "duplicate_in_instance" + | "core_skill_below_required" + | "shadow_mentor_not_ready" + // soft + | "blackout_overlap" + | "monthly_cap_exceeded" + | "back_to_back" + | "comfort_below_50" + | "skill_stale" + | "readiness_below_threshold"; + +export interface Conflict { + code: ConflictCode; + severity: ConflictSeverity; + /** Human-readable; surfaced in the picker's "Why this person?" breakdown. */ + message: string; +} + +/** Everything the ten rules need. The caller resolves the joins; this module + * only encodes the rules. */ +export interface ConflictInput { + /** The candidate's status (§7 rule gating the roster). */ + userStatus: string; + /** An admin has approved the volunteer (ARCHITECTURE §5.8.5). */ + adminApproved: boolean; + + /** True when the volunteer already holds an active assignment in this + * service instance (§7 rule 1 / §5.3 #2). */ + alreadyAssignedInInstance: boolean; + + /** The position's CORE skills with the volunteer's verified level. A core + * skill below the required level hard-blocks (§7 rule 13 / §5.3 #3). */ + coreSkills: { + name: string; + requiredLevel: SkillLevel; + verifiedLevel: SkillLevel; + }[]; + + /** True when this is a trainee / shadow slot (§7 rule 16 / §5.3 #4). */ + isShadowSlot: boolean; + /** The paired mentor's competency for the skill, or null when unpaired. */ + pairedMentor: MentorReadyInput | null; + + /** The instance's local date (YYYY-MM-DD). */ + occursOn: string; + /** The volunteer's active blackout records (D4). */ + unavailability: UnavailabilityRecord[]; + + /** The volunteer's active service count this month (§7 rule 7 / §5.3 #6). */ + monthlyServiceCount: number; + /** The user's configured cap (§7 rule 7). */ + maxServicesPerMonth: number; + + /** True when the volunteer already serves the other service that morning + * (§5.3 #7). */ + servesOtherServiceThatMorning: boolean; + + /** The lowest self-reported comfort across the position's CORE skills, or + * null when every core skill is unrated (§7 rule 14 / §5.3 #8). */ + coreComfortLow: number | null; + + /** The volunteer's last completed assignment on the position's core skill, + * as YYYY-MM-DD, or null when never served. */ + lastServedOn: string | null; + /** Days without a service before the skill is stale (§7 rule 18 / §5.3 #9). */ + staleAfterDays: number; + /** The reference date (YYYY-MM-DD) for the staleness computation. */ + today: string; + + /** The volunteer's blended readiness score, 0..100 (§5.4). */ + readinessScore: number; + /** The warn threshold; below it the assignment is only a soft warning. */ + readinessWarnThreshold: number; +} + +/** Whole days between two YYYY-MM-DD dates (to - inclusive). */ +function daysBetween(from: string, to: string): number { + const msPerDay = 86_400_000; + return Math.round( + (Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / + msPerDay, + ); +} + +/** Every conflict, hard first then soft, in rule order. */ +export function classifyConflicts(input: ConflictInput): Conflict[] { + const conflicts: Conflict[] = []; + + // 1. HARD — the volunteer is not an active, admin-approved member. + if (input.userStatus !== "active" || !input.adminApproved) { + const reason = + input.userStatus === "active" + ? "not admin-approved" + : `status is ${input.userStatus}`; + conflicts.push({ + code: "inactive_or_unapproved", + severity: "hard", + message: `Volunteer is ${reason}; they cannot be assigned.`, + }); + } + + // 2. HARD — a person holds only one active assignment per instance (§7 rule 1). + if (input.alreadyAssignedInInstance) { + conflicts.push({ + code: "duplicate_in_instance", + severity: "hard", + message: + "Already assigned in this instance; a volunteer holds one active " + + "assignment per service instance.", + }); + } + + // 3. HARD — a core skill verified below the position's required level. + const below: string[] = []; + for (const skill of input.coreSkills) { + if (levelRank(skill.verifiedLevel) < levelRank(skill.requiredLevel)) { + below.push(skill.name); + } + } + if (below.length > 0) { + conflicts.push({ + code: "core_skill_below_required", + severity: "hard", + message: + `Core skill ${pluralize(below)} verified below the position's ` + + `required level; solo assignment needs a paired mentor or an audited ` + + "override.", + }); + } + + // 4. HARD — a shadow slot needs a mentor_ready paired mentor for the skill. + const mentorReady = + input.pairedMentor != null && isMentorReady(input.pairedMentor); + if (input.isShadowSlot && !mentorReady) { + conflicts.push({ + code: "shadow_mentor_not_ready", + severity: "hard", + message: + "Shadow slot without a mentor_ready paired mentor for this skill; " + + "the pairing is invalid and does not count toward coverage.", + }); + } + + // 5. SOFT — a blackout covers the instance date (warn, override with note). + if (isUnavailable(input.unavailability, input.occursOn)) { + conflicts.push({ + code: "blackout_overlap", + severity: "soft", + message: + "Overlaps a submitted blackout date; the admin overrides with a note.", + }); + } + + // 6. SOFT — over the monthly service cap. + if (input.monthlyServiceCount > input.maxServicesPerMonth) { + conflicts.push({ + code: "monthly_cap_exceeded", + severity: "soft", + message: + `${input.monthlyServiceCount} services this month exceeds the ` + + `${input.maxServicesPerMonth} cap; override with a note.`, + }); + } + + // 7. SOFT — already serving the other service that morning. + if (input.servesOtherServiceThatMorning) { + conflicts.push({ + code: "back_to_back", + severity: "soft", + message: + "Already serves the other service this morning; back-to-back is a " + + "soft warning the admin can override.", + }); + } + + // 8. SOFT — comfort below 50% on a core skill never blocks (rule 14). + if (input.coreComfortLow !== null && input.coreComfortLow < 50) { + conflicts.push({ + code: "comfort_below_50", + severity: "soft", + message: + `Self-rated comfort is ${input.coreComfortLow}% on a core skill; it ` + + "lowers rank and warns but does not block.", + }); + } + + // 9. SOFT — the skill is stale. Never-served (null) is a readiness concern, + // not a refresher, so it is intentionally excluded here. + if ( + input.lastServedOn != null && + daysBetween(input.lastServedOn, input.today) > input.staleAfterDays + ) { + conflicts.push({ + code: "skill_stale", + severity: "soft", + message: + `No service on this skill in ${input.staleAfterDays} days (last ` + + `${input.lastServedOn}); a stale skill warns but does not block.`, + }); + } + + // 10. SOFT — readiness below the warn threshold. + if (input.readinessScore < input.readinessWarnThreshold) { + conflicts.push({ + code: "readiness_below_threshold", + severity: "soft", + message: + `Readiness score ${input.readinessScore} is below the ` + + `${input.readinessWarnThreshold} warn threshold; override with a note.`, + }); + } + + return conflicts; +} + +/** True when at least one hard conflict is present. */ +export function hasHardConflict(conflicts: readonly Conflict[]): boolean { + return conflicts.some((c) => c.severity === "hard"); +} + +/** Hard conflicts only — the ones that block the assignment. */ +export function hardConflicts(conflicts: readonly Conflict[]): Conflict[] { + return conflicts.filter((c) => c.severity === "hard"); +} + +/** Soft conflicts only — the ones the admin overrides with a note. */ +export function softConflicts(conflicts: readonly Conflict[]): Conflict[] { + return conflicts.filter((c) => c.severity === "soft"); +} + +/** "skill" / "skills" for the core-skill message. */ +function pluralize(names: string[]): string { + return names.length === 1 ? names[0] : `${names.join(", ")}`; +}