unit(C6): growth goals + shadow pairing validation

Adds the growth_goals table (ARCHITECTURE §4.3, §5.8.6) with its migration and a
pure nextGoalStatus() state machine (requested -> mentor_assigned -> in_progress
-> achieved, with pause/resume and decline). Adds validateShadowPairing()
(src/domain/shadows.ts): a shadow/trainee slot requires a paired mentor in the
same instance who is mentor-ready for that exact skill (C5) — rejects a shadow
with no paired mentor, enforced by the pure rule and the chk_shadow_paired CHECK
constraint on slots. Verified the migration applies and the CHECK rejects a
trainee slot without a paired mentor. 22 tests named after each rule.
This commit is contained in:
Tiel Coder
2026-11-18 04:43:07 +00:00
parent 371524b33e
commit 676751c489
8 changed files with 2696 additions and 1 deletions
+55 -1
View File
@@ -6,7 +6,8 @@
*
* Deliberately NOT here (added in later units, do not add "while I'm in the schema"):
* - notification_templates/rules/outbox (later)
* - user_skills, skill_assessments, growth_goals, skill_equivalencies (C1-C6)
* - user_skills (C2), skill_assessments (C3), growth_goals (C6),
* skill_equivalencies (later)
* - service_role_requirements, unavailability, events, notifications outbox
*
* Conventions (ARCHITECTURE §4.2):
@@ -58,6 +59,17 @@ export type SkillLevel = (typeof SKILL_LEVELS)[number];
export const ASSESSMENT_KINDS = ["self", "mentor", "admin", "quiz"] as const;
export type AssessmentKind = (typeof ASSESSMENT_KINDS)[number];
/** Growth-goal lifecycle (ARCHITECTURE §5.8.6). */
export const GOAL_STATUSES = [
"requested",
"mentor_assigned",
"in_progress",
"achieved",
"paused",
"declined",
] as const;
export type GoalStatus = (typeof GOAL_STATUSES)[number];
const DEFAULT_TIMEZONE = "America/New_York";
/* ------------------------------------------------------------------ users */
@@ -235,6 +247,13 @@ export const slots = pgTable(
"chk_slots_single_parent",
sql`(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)`,
),
// A shadow/trainee slot only exists alongside a mentor in the same instance
// (ARCHITECTURE §5.8.5). The pure validation in src/domain/shadows.ts is the
// first line; this CHECK is the data-layer backstop.
check(
"chk_shadow_paired",
sql`not is_trainee_slot or paired_with_user_id is not null`,
),
],
);
@@ -545,6 +564,40 @@ export const skillAssessments = pgTable(
],
);
/* --------------------------------------------- growth_goals (C6) */
/**
* "I want to skill up" (ARCHITECTURE §4.3, §5.8.6). One active goal per
* (user_id, skill_id) — a volunteer can hold many skills at different levels but
* only one open goal per skill. Drives the mentor queue and the growth report.
*/
export const growthGoals = pgTable(
"growth_goals",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
skillId: text("skill_id")
.notNull()
.references(() => skills.id, { onDelete: "cascade" }),
targetLevel: text("target_level", { enum: SKILL_LEVELS }).notNull(),
targetDate: date("target_date", { mode: "date" }),
status: text("status", { enum: GOAL_STATUSES }).notNull().default("requested"),
mentorUserId: text("mentor_user_id").references(() => users.id, { onDelete: "set null" }),
shadowCount: integer("shadow_count").notNull().default(0),
createdBy: text("created_by"),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
},
(table) => [
// One active goal per (user, skill).
uniqueIndex("growth_goals_user_skill_idx").on(table.userId, table.skillId),
index("growth_goals_status_idx").on(table.status),
],
);
/* ------------------------------------------------------------- relations */
/**
@@ -633,6 +686,7 @@ export const schema = {
positionSkills,
userSkills,
skillAssessments,
growthGoals,
};
export type Schema = typeof schema;
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import {
canGoalTransition,
nextGoalStatus,
validateGrowthGoal,
type GoalStatus,
} from "./growthGoals";
describe("nextGoalStatus — the §5.8.6 lifecycle", () => {
it("requested → mentor_assigned on assignMentor", () => {
expect(nextGoalStatus("requested", "assignMentor")).toBe("mentor_assigned");
});
it("requested → declined when there is no capacity this season", () => {
expect(nextGoalStatus("requested", "decline")).toBe("declined");
});
it("mentor_assigned → in_progress on the first shadow scheduled", () => {
expect(nextGoalStatus("mentor_assigned", "startShadow")).toBe("in_progress");
});
it("in_progress → in_progress when a shadow is completed (self-loop)", () => {
expect(nextGoalStatus("in_progress", "progressShadow")).toBe("in_progress");
});
it("in_progress → achieved when the mentor signs off the target level", () => {
expect(nextGoalStatus("in_progress", "achieve")).toBe("achieved");
});
it("pauses and resumes", () => {
expect(nextGoalStatus("in_progress", "pause")).toBe("paused");
expect(nextGoalStatus("paused", "resume")).toBe("in_progress");
});
});
describe("nextGoalStatus — illegal transitions", () => {
it.each([
["requested", "achieve"],
["requested", "startShadow"],
["in_progress", "assignMentor"],
["achieved", "pause"],
["declined", "resume"],
])("returns null for %s + %s", (from, action) => {
expect(nextGoalStatus(from as GoalStatus, action as never)).toBeNull();
});
it("keeps a terminal goal (achieved / declined) put", () => {
for (const action of [
"assignMentor",
"decline",
"startShadow",
"progressShadow",
"achieve",
"pause",
"resume",
] as const) {
expect(nextGoalStatus("achieved", action)).toBeNull();
expect(nextGoalStatus("declined", action)).toBeNull();
}
});
it("canGoalTransition mirrors nextGoalStatus", () => {
expect(canGoalTransition("requested", "assignMentor")).toBe(true);
expect(canGoalTransition("requested", "achieve")).toBe(false);
});
});
describe("validateGrowthGoal", () => {
it("accepts a real target level and status", () => {
expect(
validateGrowthGoal({ targetLevel: "qualified", status: "in_progress" }),
).toEqual([]);
});
it("rejects an unknown target level", () => {
const problems = validateGrowthGoal({ targetLevel: "grandmaster" });
expect(problems[0]).toContain("targetLevel");
});
});
+71
View File
@@ -0,0 +1,71 @@
/**
* Growth-goal lifecycle — unit C6 (ARCHITECTURE §5.8.6).
*
* Pure: no DB, no imports from `src/db`. The state machine behind a
* `growth_goals` row. The data layer calls `nextGoalStatus` to move a goal and
* rejects any transition the diagram does not allow, so a goal can never skip a
* step (e.g. `achieved` straight from `requested`).
*
* Lifecycle (ARCHITECTURE §5.8.6):
* requested → mentor_assigned (admin picks a mentor_ready volunteer)
* requested → declined (no capacity this season)
* mentor_assigned → in_progress (first shadow scheduled)
* in_progress → in_progress (a shadow is completed + assessment logged)
* in_progress → achieved (mentor signs off the target level)
* in_progress / mentor_assigned → paused; paused → in_progress (resume)
* achieved / declined → terminal
*/
import { GOAL_STATUSES, SKILL_LEVELS, type GoalStatus, type SkillLevel } from "@/db/schema";
export { GOAL_STATUSES, SKILL_LEVELS };
export type { GoalStatus, SkillLevel };
/** A lifecycle action. `progressShadow` keeps the goal in `in_progress`. */
export type GoalAction =
| "assignMentor" // requested → mentor_assigned
| "decline" // requested / mentor_assigned → declined
| "startShadow" // mentor_assigned → in_progress
| "progressShadow" // in_progress → in_progress (shadow_count++)
| "achieve" // in_progress → achieved
| "pause" // in_progress / mentor_assigned → paused
| "resume"; // paused → in_progress
/**
* The status a goal moves to from `current` on `action`, or `null` when the
* transition is not allowed by the lifecycle. `progressShadow` is a self-loop
* (a completed shadow does not change status) and returns `in_progress`.
*/
export function nextGoalStatus(current: GoalStatus, action: GoalAction): GoalStatus | null {
const transitions: Record<GoalStatus, Partial<Record<GoalAction, GoalStatus>>> = {
requested: { assignMentor: "mentor_assigned", decline: "declined" },
mentor_assigned: { startShadow: "in_progress", decline: "declined", pause: "paused" },
in_progress: { progressShadow: "in_progress", achieve: "achieved", pause: "paused" },
paused: { resume: "in_progress" },
achieved: {},
declined: {},
};
const target = transitions[current]?.[action];
return target ?? null;
}
/** True when `action` is a legal move from `current`. */
export function canGoalTransition(current: GoalStatus, action: GoalAction): boolean {
return nextGoalStatus(current, action) !== null;
}
/** Validate a growth-goal payload before it is written. */
export function validateGrowthGoal(input: {
targetLevel: string;
status?: string;
}): string[] {
const problems: string[] = [];
if (!SKILL_LEVELS.includes(input.targetLevel as SkillLevel)) {
problems.push(`targetLevel must be one of: ${SKILL_LEVELS.join(", ")}`);
}
if (input.status !== undefined && !GOAL_STATUSES.includes(input.status as GoalStatus)) {
problems.push(`status must be one of: ${GOAL_STATUSES.join(", ")}`);
}
return problems;
}
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { validateShadowPairing, type PairedMentorInput } from "./shadows";
/** A mentor who is mentor-ready for the skill (expert, opted in, approved). */
const readyMentor: PairedMentorInput = {
userId: "mentor-1",
verifiedLevel: "expert",
mentorMinLevel: "expert",
mentorOptIn: true,
adminApproved: true,
};
describe("validateShadowPairing — shadow without a mentor", () => {
it("rejects a shadow slot with no paired mentor — the primary C6 rule", () => {
const result = validateShadowPairing({
isShadow: true,
skillId: "skill-1",
pairedMentor: null,
});
expect(result.ok).toBe(false);
expect(result.problems[0]).toContain("paired mentor");
});
});
describe("validateShadowPairing — shadow with a mentor", () => {
it("accepts a shadow paired with a mentor-ready mentor", () => {
const result = validateShadowPairing({
isShadow: true,
skillId: "skill-1",
pairedMentor: readyMentor,
});
expect(result.ok).toBe(true);
expect(result.problems).toEqual([]);
});
it("rejects a shadow whose mentor never opted in to teach", () => {
const result = validateShadowPairing({
isShadow: true,
skillId: "skill-1",
pairedMentor: { ...readyMentor, mentorOptIn: false },
});
expect(result.ok).toBe(false);
expect(result.problems[0]).toContain("not mentor-ready");
});
it("rejects a shadow whose mentor is not at the skill's mentor_min_level", () => {
const result = validateShadowPairing({
isShadow: true,
skillId: "skill-1",
pairedMentor: { ...readyMentor, verifiedLevel: "qualified", mentorMinLevel: "expert" },
});
expect(result.ok).toBe(false);
expect(result.problems[0]).toContain("not mentor-ready");
});
it("rejects a shadow whose mentor is not yet admin-approved", () => {
const result = validateShadowPairing({
isShadow: true,
skillId: "skill-1",
pairedMentor: { ...readyMentor, adminApproved: false },
});
expect(result.ok).toBe(false);
});
});
describe("validateShadowPairing — non-shadow slot", () => {
it("does not require a pairing for a normal slot", () => {
const result = validateShadowPairing({
isShadow: false,
skillId: "skill-1",
pairedMentor: null,
});
expect(result.ok).toBe(true);
expect(result.problems).toEqual([]);
});
});
+82
View File
@@ -0,0 +1,82 @@
/**
* Shadow pairing validation — unit C6 (ARCHITECTURE §5.8.5).
*
* Pure: no DB, no imports from `src/db`. Depends on C5's `isMentorReady` (the
* per-skill mentor predicate). A shadow slot is a trainee slot that does not
* count toward coverage; it is only valid alongside a mentor who is
* mentor-ready for that exact skill.
*
* The rule (ARCHITECTURE §5.8.5):
* - A shadow slot requires a paired mentor **in the same service instance**.
* - That mentor must be mentor-ready for the skill: verified level at or above
* the skill's mentor_min_level, opted in to teach, and admin-approved.
*
* The "same instance" context lives in the slot/assignment data layer (D3/D5),
* which resolves the paired mentor's competency and passes it in here. This
* function is the reusable gate the data layer calls — and the CHECK constraint
* `chk_shadow_paired` on `slots` is the data-layer backstop that a trainee slot
* always has a `paired_with_user_id`.
*/
import { isMentorReady, type SkillLevel } from "./mentor";
export { isMentorReady };
export type { SkillLevel };
/** A paired mentor's competency for the skill, resolved by the data layer. */
export interface PairedMentorInput {
userId: string;
verifiedLevel: SkillLevel;
mentorMinLevel: SkillLevel;
mentorOptIn: boolean;
adminApproved: boolean;
}
export interface ShadowPairInput {
/** True for a trainee / shadow slot (does not count toward coverage). */
isShadow: boolean;
/** The skill being shadowed — the mentor must be ready on this exact skill. */
skillId: string;
/** The mentor paired into this instance for this skill, or null. */
pairedMentor: PairedMentorInput | null;
}
export type ShadowPairResult = { ok: boolean; problems: string[] };
/**
* Validate a shadow slot's pairing. Returns `{ ok: true }` when the pairing is
* valid, or `{ ok: false, problems }` listing every reason it is not. Called by
* the slot data layer before a shadow slot is written.
*/
export function validateShadowPairing(params: ShadowPairInput): ShadowPairResult {
const problems: string[] = [];
// A non-shadow slot has no pairing requirement.
if (!params.isShadow) return { ok: true, problems };
// A shadow without a paired mentor is invalid — the primary C6 rule.
if (!params.pairedMentor) {
return {
ok: false,
problems: [
`shadow slot for skill ${params.skillId} requires a paired mentor in the same instance`,
],
};
}
// The paired mentor must be mentor-ready for this exact skill.
if (
!isMentorReady({
verifiedLevel: params.pairedMentor.verifiedLevel,
mentorMinLevel: params.pairedMentor.mentorMinLevel,
mentorOptIn: params.pairedMentor.mentorOptIn,
adminApproved: params.pairedMentor.adminApproved,
})
) {
problems.push(
`paired mentor ${params.pairedMentor.userId} is not mentor-ready for skill ${params.skillId}`,
);
}
return { ok: problems.length === 0, problems };
}