Platform Architecture

Timeback Student Progression is an adaptive learning system that drives personalized student progression across six Rule 0 subjects: Math, Language/ELA, Writing, Science, Reading, and Vocabulary. Social Studies has a separate diagnostic entry flow. The platform determines which courses students take, when they advance, and what remediation they receive when they fall short — all without manual teacher intervention.

The system is organized into three domains. Student Progression covers the event-driven pipeline that moves students through grade-level courses: placement, enrollment, learning, assessment, gap analysis, and hole-filling remediation. Mastery Tests covers the test types used in assessments, how tests are assigned and delivered to students, and how answers are graded across three evaluation paths. Infrastructure covers the AWS CDK stack, PostgreSQL database, SQS queues, S3 storage, and notification systems that underpin both domains.

The architecture is fully event-driven. Adapter applications — including MobyMax, Freckle, Lalilo, Edia, VocabLoco, Alpha Phonics, and others — report student activity as Caliper events. When a student reaches 100% completion in an adapter app, a Caliper event triggers the progression pipeline, which decides the student's next step automatically.

Four external systems are central to how the platform operates: Timeback acts as the LMS and OneRoster data source, providing roster data and receiving course enrollment and test assignment instructions. PowerPath supplies the course sequencing logic, determining which course comes next in a subject sequence. The adapter apps deliver the actual learning content and report completion events. DCAN (Distributed Context Agent Network) is an external AI service provided by AlphaTest and consumed by Timeback — it identifies which specific lessons a student needs when gap analysis detects knowledge gaps after a failed assessment.

System Components

graph TB subgraph External["External Systems"] TB["Timeback Platform\n(LMS + OneRoster)"] PP["PowerPath API\n(Course Sequencing)"] APPS["Adapter Apps\n(MobyMax, Freckle, Edia, etc.)"] end subgraph Lambdas["AWS — Lambda Functions"] CAL["Caliper Listener"] PROG["Progression Lambda"] GRAD["Gradebook Lambda"] GAPA["Gap Analysis Lambda"] LR["Lesson Recommender"] end subgraph AlphaTest["AlphaTest Services"] DCAN_T["DCAN Service\n(AI Recommendations)"] end subgraph Queues["AWS — SQS Queues"] Q1["caliper-events-queue"] Q2["student-progression-queue\n(FIFO)"] Q3["gap-analysis-queue"] Q4["hole-filling-agent-queue"] end subgraph Data["Data Stores"] RDS[("PostgreSQL RDS\nmastery_track")] S3["S3 Storage"] end TB -->|"Caliper Events"| Q1 APPS -->|"Caliper Events"| Q1 Q1 --> CAL CAL -->|"100% complete"| Q2 Q2 --> PROG PROG -->|"Assign test"| TB PROG -->|"Enroll in course"| TB PROG --> PP GRAD -->|"Test graded"| Q3 Q3 --> GAPA GAPA -->|"DCAN flow"| Q4 GAPA -->|"Legacy flow"| LR Q4 --> DCAN_T DCAN_T --> RDS LR --> RDS PROG --> RDS CAL --> RDS GRAD --> S3

The diagram above shows the four component groups. External Systems are the sources of student activity data and the targets of enrollment/assignment instructions. Lambda Functions implement each stage of the pipeline as independently-scalable, event-triggered compute units. SQS Queues decouple every stage — the FIFO student-progression-queue ensures per-student ordering so concurrent events cannot corrupt state. Data Stores consist of a PostgreSQL RDS instance (the system of record for all progression state) and S3 (for gradebook artifacts and test content).

The Mastery Loop

The mastery loop is the core learning cycle that every student moves through. After placement tests route a student to their starting course, they work through the material in an adapter app. When they complete it, an automated assessment measures retention. On the standard AlphaTest route, students who score 89.5% or higher are considered to have mastered the material and advance to the next course or assessment in the sequence. Every standard non-passing end-of-course result enters targeted remediation: gap analysis identifies which concepts were missed, DCAN recommends specific lessons to fill those gaps, and the student completes a focused hole-filling course before re-attempting the assessment. Math Pre-K is the explicit exception because no valid Pre-K remediation exists. Course Sequence returns 409 remediation_unavailable; native progression returns remediation_unavailable and stops its retry check. Neither path creates a course or enrollment. This standard cycle repeats until the student demonstrates mastery and the full subject sequence is complete. Canonical PK–2 Reading uses the AlphaLiteracy battery verdict and static catalog instead of this score-based diagram.

graph TD START(["New Student"]) --> PLACE["Placement Tests"] PLACE -->|"Score-based routing"| ENROLL["Course Enrollment"] ENROLL --> LEARN["Student Takes Course\n(Adapter App)"] LEARN -->|"Caliper: pctCompleteApp = 100%"| ASSESS["End-of-Course Assessment"] ASSESS --> GRADE["Grading & Scoring"] GRADE --> DECIDE{"Accuracy\n≥ 89.5%?"} DECIDE -->|"Mastered"| NEXT["Course Sequence API:\nResolve Next Stage"] NEXT -->|"Next Course"| ENROLL NEXT -->|"Next Assessment"| ASSESS NEXT -->|"Sequence Complete"| DONE(["Subject Mastered!"]) DECIDE -->|"Not Mastered"| GAP["Gap Analysis"] GAP --> DCAN["DCAN AI:\nRecommend Lessons"] DCAN --> HF["Hole-Filling Course"] HF --> HFLEARN["Student Completes\nRemediation Lessons"] HFLEARN -->|"Caliper: 100%"| ASSESS
1 Onboarding 2 Enrollment 3 Caliper 4 Grading 5 Gap Analysis 6 DCAN 7 Hole-Filling 8 Mastery

1. Onboarding & Placement

Before a student can receive assignments from any adapter app, they need an account in that app. Onboarding is the proactive step that creates or ensures those accounts exist. The OnboardingRouterService handles the standard asynchronous app services — Edia, MathAcademy, Zearn, MobyMax, Freckle, Lalilo, Anton, VocabLoco, Membean, and eGumpp — passing the student email, grade, and subject context. Incept is a synchronous in-repo exception for Math G3-4: it rosters the student and verifies the personalized Timeback base-course copy before returning. For most apps onboarding happens before the first remediation assignment is issued. Renaissance apps (Freckle and Lalilo) require up to 24 hours to activate a new account, so they are excluded from the immediate retry path when a "student not found" error is returned mid-flow.

Placement tests determine which grade-level course a student should begin in. MAP/RIT selects the initial grade on the PowerPath placement-page path. Standard AlphaTest then sends phase-tagged placement events to the Student Progression Lambda. processProgressionEvent routes those events through processPhaseTaggedPlacementEvent, which reads the complete placement evidence and active qualifying grades before calling resolvePlacementResult. The PowerPath placements endpoint uses the same resolver.

For unresolved grades, the current standard placement ladder normally selects the next configured qualifying placement grade during descent until mastery brackets the placement boundary. For grade 6+ students with no subject RIT score, G3 is the minimum initial placement grade. Students with RIT keep RIT-derived initial placement behavior, including below-G3 starts when the RIT signal calls for it. The initial starting-grade rule selects only the first placement; it does not become a reset target after the ladder begins.

Sequential Placement Descent

Current standard AlphaTest placement-failure behavior

A result below 89.5% is failure evidence. While the student has no mastered grade and a lower qualifying assessment remains, resolvePlacementResult returns assign_placement with direction: "down". The worker assigns that next lower placement instead of jumping to the subject floor or immediately applying the failed grade's score band.

When a pass establishes the highest mastered grade, the resolver examines the next qualifying grade above it. An unresolved failure there becomes the placement boundary; otherwise the resolver assigns that next higher placement and continues upward. If the student reaches the lowest qualifying assessment without a pass, that lowest failed grade is the boundary. The boundary result's subject-grade score band then selects the assessed-grade base course or hole-filling. Mastery at the verified assessment ceiling completes placement. Reading PK–2 placement does not use AlphaTest at all: it runs on AlphaLiteracy assessment batteries (see PK–2 Reading battery runtime).

Phase-tagged placementPhase: "result_available" messages wake the resolver when a standard placement result is ready. An analysis_outcome message resumes the same owned flow after gap analysis. Assignment effects use AlphaTest's internal POST /student-progression/internal/delivery/assign-by-grade route with routing: "phase_tagged". Transient, missing-result, and pending-result states retry instead of guessing a route.

Already-mastered self-heal exception: "One grade at a time" describes the normal decision between unresolved qualifying grades, not an absolute limit on the visible grade change. On the legacy path, advancePastMasteredGrade can skip consecutive mastered grades, bounded by MAX_ADVANCE_DEPTH = 5. On the phase-tagged path, the applier validates and credits a grade_already_mastered attestation, then re-runs resolvePlacementResult from that mastery evidence. A correct self-heal can therefore move more than one grade; inspect the student's mastery evidence before classifying that movement as a routing bug.

Legacy Untagged Confidence Reset

Rollback-drain behavior, not the current standard path

Untagged placement-completion events from the old producer, queued backlog, replays, or a rollback drain retain the legacy path in handlePlacementTestCompletion. That path calls applyConfidenceResetIfEligible before determinePlacementAction and can jump a qualifying first failure directly to resolveSubjectLowestGrade(subject). The sequential-descent release bypasses this branch by routing every event with placementPhase to processPhaseTaggedPlacementEvent first.

FastMath does not use the standard AlphaTest score-evidence resolver. Its existing Course Sequence rule uses the app-reported pass flag and descends to the first placement assessment in the next configured lower grade. Reading PK–2 placement, test-out and end-of-course results are AlphaLiteracy batteries routed by the canonical Reading runtime, not by this resolver (see PK–2 Reading battery runtime).

Mastery Threshold

A score of 89.5% accuracy or higher indicates mastery. This threshold is used throughout the AlphaTest-scored system — from placement through progression. Exception: PK–2 Reading AlphaLiteracy batteries are decided by their authoritative metadata.passed flag (per-measure benchmarks), never by the 89.5% score (see PK–2 Reading battery runtime). It appears as the literal constant 89.5 in the progression rules engine, the gap analysis bypass logic, and the mastery gate in DeliveryService.

Placement Action Paths

flowchart TD START["Phase-tagged standard AlphaTest\nplacement result"] --> RESOLVE["resolvePlacementResult\nreads all evidence and qualifying grades"] RESOLVE -->|"No mastery; lower qualifying grade remains"| DOWN["assign_placement\ndirection: down"] DOWN --> MASTERED{"Target already mastered?"} MASTERED -->|"No"| NEXT["Student completes next lower placement"] MASTERED -->|"Yes; credit attested mastery"| RESOLVE NEXT --> START RESOLVE -->|"Pass brackets unresolved higher failure\nor descent reaches the floor"| BOUNDARY{"Placement boundary\nfailure score band"} BOUNDARY -->|"Below enroll threshold"| BASE["route_boundary: base_course\nEnroll at boundary grade"] BOUNDARY -->|"In remediation band"| ANALYSIS["route_boundary: analysis\nGap analysis and hole-filling"] RESOLVE -->|"Mastery; no adjacent unresolved boundary"| UP["assign_placement direction: up\nor complete at ceiling"]
Path Trigger Action Type Next Step
Down No mastered grade yet; the highest contiguous failure has a lower qualifying assessment assign_placement, direction: "down" Assign the next lower unresolved qualifying placement; if the target is already mastered, credit that evidence and re-resolve
Base boundary A pass brackets an unresolved higher failure, the lowest qualifying grade fails, or no lower active test exists; boundary score below the enrollment threshold route_boundary, base_course Enroll the student in the base course at the boundary grade
Analysis boundary The same boundary conditions, with a score inside the remediation band route_boundary, analysis Run gap analysis and create hole-filling at the boundary grade
Up / complete A mastered grade has no adjacent unresolved higher failure assign_placement with direction: "up", or complete_placement Assign the next higher qualifying placement, or complete at the ceiling (Reading PK–2 uses the AlphaLiteracy battery runtime instead)
Legacy reset Only an untagged old-producer, backlog, replay, or rollback-drain event that meets the legacy predicate applyConfidenceResetIfEligible May request resolveSubjectLowestGrade(subject); not used by the current phase-tagged standard path

Placement Boundary Thresholds and Math Exceptions

SubjectGradeEnroll BelowHole-Filling Enabled
Default placement boundary and test-outAny supported grade59.5%Yes, for scores in [59.5, 89.5)
Math placement boundary and test-outGrades 3 through 12 policy; active through Grade 1189.5%No; once the placement boundary is known, every non-passing result selects the assessed-grade base course. Grade 12 returns 404 until its assessment exists.
Math test-out and legacy untagged placementPre-K (-1)89.5%No; every non-passing result selects the Pre-K base course
Implementation Details — Placement Service

workflow/progression/shared/rules

TypeScript
// Simplified pseudocode: the phase-tagged worker and PowerPath placements
// endpoint both call resolvePlacementResult.
export type RelevantPlacementResolutionDecision =
  | { kind: 'use_starting_grade'; grade: number }
  | { kind: 'assign_placement'; grade: number; direction: 'up' | 'down' }
  | { kind: 'route_boundary'; boundary: PlacementResult; route: 'base_course' | 'analysis' }
  | { kind: 'complete_placement'; reason: 'ceiling_pass'; grade: number };

// getPlacementStartingGrade — floor used only to choose an initial placement
function getPlacementStartingGrade(
  subject,
  ageGradeRank,
  hasRitScore,
  lowestGrade = SUBJECT_STARTING_GRADE[subject],
) {
  if (!hasRitScore && ageGradeRank !== null && ageGradeRank >= 6) {
    return Math.max(lowestGrade, 3);
  }
  return lowestGrade;
}

function resolvePlacementResult({ subject, qualifyingGrades, completed, startingGrade }) {
  const highestMastery = highestPassingGrade(completed, 89.5);
  if (highestMastery !== undefined) {
    const boundary = nextUnresolvedFailureAbove(highestMastery, completed);
    if (boundary) return routePlacementBoundary(subject, boundary);
    const higherGrade = nextQualifyingGrade(highestMastery, qualifyingGrades);
    return higherGrade === undefined
      ? { kind: 'complete_placement', reason: 'ceiling_pass', grade: highestMastery }
      : { kind: 'assign_placement', grade: higherGrade, direction: 'up' };
  }

  const nextLowerGrade = nextLowerQualifyingGrade(completed, qualifyingGrades);
  if (nextLowerGrade !== undefined) {
    return { kind: 'assign_placement', grade: nextLowerGrade, direction: 'down' };
  }

  const boundary = lowestContiguousFailure(completed);
  return boundary
    ? routePlacementBoundary(subject, boundary)
    : { kind: 'use_starting_grade', grade: startingGrade };
}

// The phase-tagged applier treats grade_already_mastered as new mastery
// evidence and re-runs this resolver; the visible move can span grades.

function routePlacementBoundary(subject, boundary) {
  return {
    kind: 'route_boundary',
    boundary,
    route: resolvePlacementBoundary(subject, boundary),
  };
}

// Untagged old-producer and rollback-drain events retain the legacy
// applyConfidenceResetIfEligible -> resolveSubjectLowestGrade branch and
// advancePastMasteredGrade self-healing across consecutive mastered grades.

onboarding-router.service.ts:54

TypeScript
// Standard asynchronous router apps (10 total).
// Incept is validated and executed synchronously before this router.
export type OnboardingApp =
  | 'edia' | 'math_academy' | 'zearn' | 'mobymax'
  | 'freckle' | 'lalilo' | 'anton' | 'vocabloco'
  | 'membean' | 'egumpp';

public async onboardStudent(
  primaryApp: string | undefined | null,
  params: OnboardingParams,
): Promise<OnboardingResult | null> {
  if (!primaryApp) return null;
  const normalizedApp = primaryApp.toLowerCase().trim();
  switch (normalizedApp) {
    case 'edia': {
      const svc = EdiaOnboardingService.getInstance();
      const gradeToSend = params.isHoleFilling ? 'hole-filling' : params.grade;
      const result = await svc.onboardStudent(params.studentEmail, gradeToSend);
      // ... sets Timeback credentials if new password was issued
      return { success: true, app: 'edia', message: result.message };
    }
    case 'freckle':
    case 'lalilo':
      // Renaissance apps: ~24h activation delay — excluded from immediate retry
      return RenaissanceOnboardingService.getInstance()
        .onboardStudent(normalizedApp, params);
    // ... other cases for each app
  }
}

1.1 Cross-Subject Gates

Not every subject is available from a student's first day. Within the six-subject Rule 0 unlock loop, three subjects — Science, Vocabulary, and Writing — only become eligible for placement after two things are true: the student has mastered specific prerequisite material in another subject, and the student's grade level (derived from user.grades, not date of birth) meets the subject minimum. Both gates must pass; mastering the prerequisite while the student's grade level is below the minimum will not activate the subject, and vice versa. The remaining three subjects — Math, Reading, and Language — are day-one subjects in Rule 0. Separate placement-entry checks use PLACEMENT_GATE_RULES. Reading has a Language minimum of grade 0 there, but absent Language mastery also defaults to 0: a new student does not need a recorded Language K pass to start Reading. Social Studies uses the separate diagnostic entry flow below.

The gating logic runs on every qualifying mastery event: a standard test score ≥ 89.5%, a canonical PK–2 AlphaLiteracy battery with metadata.passed=true, or a FastMath grade mastered. When a gate's prerequisites are newly satisfied, onMasteryEvent evaluates each gated subject for unlock. If the subject is now eligible and the progression pipeline has not yet taken ownership of it (no pending assessment, no progression status published), a first placement test for the subject is assigned at its starting grade.

Mastery Definition

For a prerequisite, "mastered grade X" means the student scored ≥ 89.5% on any test (placement, test-out, or end-of-course) at grade X or higher in the prerequisite subject. An exact grade-X test is not required. For Reading PK–2, qualifying evidence at grade X is a fully graded, active AlphaLiteracy battery at grade X with metadata.passed = true (its score is not compared with 89.5%); see PK–2 Reading battery runtime. Written-test evidence from before the 2026-09-19 battery-only cutover is still read under FF_READING_K2_ORF_MASTERY_GATE (written ≥ 89.5% and a passed ORF screener, waived for summer-experience students while FF_SUMMER_EXPERIENCE_SKIP_LITERABLY_ASSESSMENTS is on). FastMath uses a separate signal: the student's highest FastMath grade mastered (gradebook rows with passedTest and gradeMastered), compared with fastMathMinimumGrade (an administrative credit also meets it), only while Science has no progression entry: Rule 0 reads no enrollments, and skips a subject with a pending test first.

Legacy Reading screener identifiers

assessmentSource: "literably" and flags such as FF_SUMMER_EXPERIENCE_SKIP_LITERABLY_ASSESSMENTS remain compatibility identifiers for the Reading screener route. They do not guarantee that Literably is the provider. AlphaLiteracy assignment is represented by a pending OneRoster line item and assessment result; AlphaLiteracy discovers that result by the student's stable OneRoster ID and later sends completion events from https://screeners.phonics.school.

Rule 0 Gate Table

Subject Day-One in Rule 0? Mastery Prerequisites Min Grade Level Starting Placement Grade
MathYes—NonePer RIT-priority rule below (defaults to K)
ReadingYes—NonePer RIT-priority rule below (defaults to K)
LanguageYes—NonePer RIT-priority rule below (defaults to K)
VocabularyGatedReading G2 or higher mastered (Reading G3+ satisfies this without K–2 ORF; at G2, a passed Grade 2 AlphaLiteracy battery, i.e. the G2 ORF benchmark; pre-cutover evidence: written ≥ 89.5% AND passed ORF screener, subject to the summer-experience waiver described above)G2+Inherited Reading starting grade, bounded by the Vocabulary sequence
WritingGatedLanguage G3 or higher mastered (≥ 89.5%)G2+Inherited Language starting grade, bounded by the Writing sequence
ScienceGatedAll of: Math G2 or higher, Reading G2 or higher, Language G2 or higher mastered, AND, before any Science work, FastMath Grade 2 or higher or the 2026-09-01 administrative FastMath credit (isFastMathGradeMet). Rule 0 sees Science work only as a progression entry, so a student whose only Science work is a course is still checked here. Reading G3+ needs no K–2 ORF evidence. At G2, Reading mastery means a passed Grade 2 AlphaLiteracy battery (pre-cutover evidence: written ≥ 89.5% AND passed ORF screener, subject to the summer-experience waiver described above).G2+G3
Multiple roster grades take the minimum

If a Timeback user record has multiple entries in user.grades (e.g., ["6", "1"]), deriveAgeGradeRank parses every entry and returns the lowest rank. The above student would be treated as G1 and blocked from Vocabulary/Writing/Science regardless of array order. This is intentional — any PK/K/G1 entry treats the student as young. Note that parseGradeRank only understands numeric strings ("6", "1") and K/PK aliases — a G-prefixed value like "G6" does not parse and is ignored.

Missing grade data is lenient

The Min Grade Level check uses ageGradeRank. Despite the name this is a grade-level derived from user.grades — no date-of-birth is involved. If no entry in user.grades parses to a grade, the check is treated leniently and not applied; mastery alone is sufficient. This avoids blocking real students whose roster lacks a grade field.

Social Studies: separate diagnostic entry

Social Studies is outside the six-subject Rule 0 unlock loop above. Its placement prerequisite in PLACEMENT_GATE_RULES is Reading G2 or higher mastered, but that alone does not authorize a new diagnostic. Diagnostic entry also requires an active, enabled, non-test student with a current student role, an eligible admission status, no withdrawal date, an email, a roster grade from G3 through G8, school opt-in, and no conflicting existing work. Unlike the Rule 0 age check, missing roster-grade data blocks diagnostic entry; this path reads the first user.grades entry.

The opted-in organization's metadata.social_studies_entry_rule selects the academic rule:

A current Grade 3+ Reading enrollment counts as Reading G2 mastered, fluency included, for Social Studies entry only. At accepted Reading mastery G2, diagnostic eligibility also checks fluency: canonical battery evidence can satisfy it; qualifying migrated mastery is exempt; the configured ORF gate and summer-experience waiver apply to other evidence. Reading G3+ needs no K–2 ORF evidence. See src/modules/powerpath/placements/socialStudiesEligibility.ts and src/common/social-studies-entry-rule.ts.

Automatic diagnostic assignment requires FF_SOCIAL_STUDIES_AUTO_ASSIGNMENT=true; checked-in production configuration enables it (stack/cdk.json context prod) and staging keeps it off. Authorized manual assignment uses the same eligibility and reservation checks without enabling automation. Existing placement work, a TimeBack Scroll Social Studies course (a course stage of the active Social Studies sequence at Grades 3–8) and completed diagnostics are preserved. Another Social Studies course, such as AP Human Geography, is not existing work: it neither stops the diagnostic nor is ended by it. When an assignment command next runs for the student, a pending diagnostic whose provider assignment has lapsed is retired; a new one is assigned only if the student meets the current entry rule; see the Social Studies entries in docs/data-dictionary/00-operational-flows.md. The diagnostic determines the next placement or course; its starting work is resolved separately from the Rule 0 subjects.

Rule 0 Unlock Flow

flowchart TD A["Mastery Event\n(standard score ≥ 89.5%, Reading battery pass, or FastMath grade mastered)"] --> B["For each gated subject\n(Science / Vocabulary / Writing)"] B --> C{"Already pipeline-active?\n(pending test OR progression status published)"} C -->|"Yes"| SKIP["Skip — no double-assign"] C -->|"No"| D{"Prerequisites met?"} D -->|"No"| WAIT["Wait for more mastery"] D -->|"Yes"| E{"Grade level ≥ G2?"} E -->|"No"| BLOCK["Blocked by min grade level"] E -->|"Yes"| F["Assign first placement test\nat subject's starting grade"]
Manual-override mastery does not bypass the grade-level check

A PK, K, or G1 student who somehow scores ≥ 89.5% on a Reading G2 test (e.g., via a manual override) will still not unlock Vocabulary. The Min Grade Level check is evaluated independently of the prerequisite check — both must pass.

The initial "pipeline-active" check uses two signals: a pending assessment and a progression status entry (any key in user.metadata.progression for that subject). In practice the pending-assessment signal means a returned assessment row for that subject with scoreStatus = "not submitted", regardless of test type. Although derivePendingAssessmentSubjects marks a subject pending for any returned row that is not "fully graded", the upstream query listAssessmentResults (workflow/progression/shared/clients/timeback.ts) only ever fetches rows whose scoreStatus is "fully graded" or "not submitted" — so "submitted", "partially graded", "not graded", and "exempt" rows never reach the resolver and cannot hold the unlock. Either signal marks the subject owned. Legacy results do not block this initial eligibility check. Before automatic progression creates Vocabulary or Writing placement work, a separate fresh guard stops when any active target-subject placement row already exists.

Only not submitted rows reach the unlock check

Because the query fetches only fully graded and not submitted rows, a test that is submitted, partially graded, not graded, or exempt is invisible to the resolver and does not hold the unlock. CS/guides triaging "why no new placement yet?" should look for a not submitted assessment row for that subject, regardless of test type (or a progression status entry), not other in-flight statuses.

Started subjects are not re-checked on FastMath

Once a subject has work, the FastMath minimum no longer applies. For Rule 0 that work is a progression entry; the placement read, native endpoints and test-out also see active courses and pending tests. Reading, Math and Language are still checked before each later placement action (guardPlacementEffectGate) and when a parked boundary resumes.

Conservative fallback when the user record can't be read

If the Timeback user fetch fails, resolveUnlockedSubjects (workflow/progression/shared/rules/subject-unlock.ts) can't read the student's progression-tracked subjects, so it falls back to the legacy activeSubjects guard: any existing assessment row for a gated subject is treated as pipeline-active and blocks the unlock. This is intentional — it avoids re-assigning duplicate placements during a transient read failure.

Starting Placement Grade — RIT-Priority Rule

Scope: this rule is the PowerPath placement-page path, not the progression pipeline

The startingGrade(RIT, lowestGrade, ageGrade) function below is called in exactly one place — src/modules/powerpath/placements/service.ts, which backs the PowerPath placement page / placement-data API. In automatic subject unlock, Vocabulary inherits the existing Reading placement start and Writing inherits the existing Language placement start, bounded by the target's active assessment sequence. Science keeps the no-RIT sequence-floor calculation. On the current phase-tagged standard path, resolvePlacementResult uses the starting grade only when there is no placement evidence. After a failure it descends through the active qualifying grades, and after mastery it resolves the adjacent boundary or moves upward without reapplying the initial floor. Only the legacy untagged Confidence Reset branch uses resolveSubjectLowestGrade(subject) as a direct reset destination.

On the PowerPath placement-page path, for Day-One subjects (Math, Reading, Language) the actual grade of the first placement test is decided by startingGrade(RIT, lowestGrade, ageGrade) in src/modules/powerpath/placements/grades.ts. The function picks the first matching branch from a strict priority order:

PriorityConditionStarting grade
1Student has a MAP Growth RIT for the subjectmax(growthRitGrade − 1, lowestAvailableGrade)
2Else: student has a MAP Screening RIT for the subjectmax(screeningRitGrade − 1, lowestAvailableGrade)
3Else: no RIT, and ageGrade ≥ 6max(lowestAvailableGrade, 3) — the G3 floor
4Else: no RIT, ageGrade < 6max(lowestAvailableGrade, 0) — i.e. K for Math/Reading/Language, G3 for Science/Vocabulary/Writing

Two things to internalize:

RIT → grade mapping

RIT scores are translated to integer grade levels by RITScoreToGrade(score, subject) in src/modules/powerpath/placements/grades.ts. Each subject has its own range table; the bounds are NWEA-aligned. Sample anchors (Math):

  • RIT < 193 → K
  • RIT 218–229 → G3
  • RIT 241–251 → G5
  • RIT 258–268 → G7
  • RIT ≥ 287 → G12

(Full table in source — Reading, Language, and Science use different ranges. Science starts at G2 because there is no K-G1 Science content.)

Gated-subject starting grades

The RIT-priority rule above governs Day-One placements. When automatic progression unlocks Vocabulary or Writing, applyUnlocks (workflow/progression/shared/rules/subject-unlock.ts) reads the existing direct-subject placement result: Vocabulary inherits Reading's startingGrade, and Writing inherits Language's startingGrade. The target subject's active assessment sequence supplies the floor and ceiling. Science keeps the existing no-RIT calculation from its live sequence floor.

RIT must be loaded before placement fires

startingGrade reads RIT from the student's assessmentResults rows (any row tagged MAP_GROWTH or MAP_SCREENING with a "RIT Score" metadata field). If the placement is assigned before NWEA data syncs into Timeback, branches 1 and 2 won't match and the function will fall back to branch 3 or 4. Onboarding flows that depend on RIT-driven placement must ensure NWEA results are imported first.

Implementation Details — Subject Prerequisites

The prerequisites are defined in src/common/placement-gate-policy.ts (PLACEMENT_GATE_RULES, Science's fastMathMinimumGrade, and the definition of work in a subject) and applied by workflow/progression/shared/rules/progression-config.ts (SUBJECT_PREREQUISITES, AGE_GATE_MIN_RANK, areSubjectPrerequisitesMet).

workflow/progression/shared/rules/subject-unlock.ts

Called by onMasteryEvent whenever a qualifying mastery signal fires (a standard score ≥ 89.5%, a canonical PK–2 AlphaLiteracy battery pass, or a FastMath grade mastered). For each gated subject, resolveUnlockedSubjects checks: (1) not already pipeline-active, (2) prerequisites satisfied, (3) grade level ≥ min. Any subject passing all three is added to the unlock list and gets a first placement test assigned at its starting grade.

If the unlock fires twice for the same subject (e.g., two simultaneous mastery events), alphatest.assignTestByGrade returns a 409 "Assignment already exists" which applyUnlocks treats as a no-op.

src/modules/powerpath/placements/grades.ts

TypeScript
// 4-priority rule that picks the first placement test's grade.
// MAP Growth RIT wins over MAP Screening RIT. No-RIT students fall
// back to the G3 floor (if age ≥ G6) or the subject's lowest grade.
export function startingGrade(RIT: RITScore, lowestGrade: number, ageGrade: number) {
  return match([RIT.GROWTH?.grade, RIT.SCREENING?.grade, lowestGrade, ageGrade])
    .with([P.number, P._, P._, P._], () => Math.max(RIT.GROWTH!.grade - 1, lowestGrade))
    .with([P._, P.number, P._, P._], () => Math.max(RIT.SCREENING!.grade - 1, lowestGrade))
    .with([P.nullish, P.nullish, P.number, P.number.and(P.number.gte(6))], () => Math.max(lowestGrade, 3))
    .with([P.nullish, P.nullish, P.number, P._], () => Math.max(lowestGrade, 0))
    .exhaustive()
}

// Subject-specific RIT → grade bands (excerpt — Math shown; Reading/Language/Science similar).
export const RITScoreToGrade = (score: number, subject: RITSubject) => match([score, subject])
  .with([P.number.and(P.number.lt(193)), "Math"], () => 0)
  .with([P.number.and(P.number.gte(193)).and(P.number.lt(206)), "Math"], () => 1)
  .with([P.number.and(P.number.gte(206)).and(P.number.lt(218)), "Math"], () => 2)
  .with([P.number.and(P.number.gte(218)).and(P.number.lt(230)), "Math"], () => 3)
  // ... (G4–G11 omitted)
  .with([P.number.and(P.number.gte(287)), "Math"], () => 12)
  .otherwise(() => -1)

RIT-driven placement only applies when the student already has at least one MAP_GROWTH or MAP_SCREENING assessmentResults row with a numeric "RIT Score" metadata field. Until that row is present, RIT.GROWTH and RIT.SCREENING are both null and the function falls through to the G3 floor / lowest-grade fallback. The RIT-1 offset and the Growth-over-Screening preference are intentional design choices documented in the source.

2. Course Enrollment & Sequencing

After placement resolves a starting grade or after a student masters a course, the system needs to determine the student's next step in the sequence. This is the job of the CourseSequenceV2Service. The service queries the PowerPath API to fetch the active course sequence for a given subject, retrieves the stages for the student's grade level, and returns a ResolvedCourse object that tells the progression lambda whether to enroll the student in a course or assign them an assessment.

The course sequence is structured as an ordered list of stages. Each stage is either a course (a unit of instruction delivered via an adapter app) or an assessment (an end-of-course test). A course stage may retain multiple courseReferences during a provider migration. The reference with the newest valid refAddedAt is canonical for new assignments; older references remain on the stage so late completions from in-flight students still resolve. Goals collapses the references into one stage: earned XP from either reference counts, but only the canonical course's curriculum contributes to the denominator.

The service uses the assessment type, raw decimal score, student's active grade, and enrollment history to select the next stage. On the phase-tagged standard placement path, resolvePlacementResult normally searches downward by selecting the next unresolved qualifying grade; already-mastered evidence can self-heal across multiple grades. Only after a pass brackets the placement boundary, the lowest qualifying grade fails, or no lower active assessment exists does that boundary score select the assessed-grade base course below 59.5% or hole-filling in [59.5, 89.5). Test-out scores use those bands immediately. At 89.5% or more, an unbounded placement result selects the next assessment and test out selects the next-grade base course. Math G3-G12 placement boundaries and test-out failures select the assessed-grade base course instead; Math Pre-K uses that exception for test out and the legacy untagged placement path. The active Math sequence implements this policy through G11. Grade 12 returns 404 until its assessment stage exists. Every standard non-passing end-of-course result selects hole-filling, except Math Pre-K, which reports remediation_unavailable. FastMath keeps its separate provider route, and Reading PK–2 is routed by the AlphaLiteracy battery runtime. HS Language uses the shared raw 89.5% mastery boundary and keeps its lower-grade fallback.

The routing table below distinguishes canonical Reading batteries and courses from legacy Reading adapters and the generic subject-grade hole-filling routes. When a course stage is resolved, the progression lambda calls the OneRoster API (via Timeback) to create the enrollment. When an assessment stage is resolved, the lambda calls assignAssessmentTest() to issue the test assignment directly.

sequenceDiagram participant P as Progression Lambda participant CS as CourseSequenceV2Service participant PP as PowerPath API participant OR as OneRoster Service participant TB as Timeback P->>CS: resolveCourseForProgression(subject, grade, testType, score) CS->>PP: getActiveSequenceId(subject) PP-->>CS: sequenceId CS->>PP: getSequenceStages(sequenceId, grade) PP-->>CS: stages[] CS->>CS: Filter course stages, match by enrollment history CS-->>P: ResolvedCourse { type, sourceId, grade } alt Course Stage P->>OR: createEnrollment(student, courseSourcedId) OR->>TB: POST /enrollments TB-->>OR: enrollment confirmed else Assessment Stage P->>P: assignAssessmentTest(student, assessmentStage) P->>TB: POST /assignments end

Subject-Grade-App Routing Matrix

Subject Grades Adapter App Caliper Sensor
MathK–5Timebacktimeback.com
Math6–8Timeback LearnTimeBack / AlphaTest
Math9–11Ediaedia.app
Language / ELAK–2Lalilolalilo.com
Language / ELA3–10Frecklefreckle.com
Writing3–9AlphaWrite(self-emitted)
Science3–8Existing sequence base / Timeback Learn remediationTimeBack / AlphaTest QTI
Reading core coursesPK–2Alpha Phonicsphonics.school
Reading assessments (placement, test-out, end-of-course)PK–2AlphaLiteracy batteries (no AlphaTest)screeners.phonics.school
Reading battery remediationPK–2Alpha Phonics hole-fillingphonics.school
Reading generic hole-filling (outside canonical PK–2)PK–1Antonanton.app
Reading generic hole-filling (outside canonical PK–2)2–8MobyMaxmobymax.com
Vocabulary3–12VocabLocovocabloco.com
Implementation Details — Course Sequence V2 Service

course-sequence-v2.service.ts:143

TypeScript
// getActiveSequenceId — fetches the active PowerPath sequence for a subject
public async getActiveSequenceId(subject: string): Promise<string> {
  const headers = await this.authHeader();
  const url = `${this.powerpathEndpoint}/course-sequence/`;
  const response = await withExponentialBackoff(
    async () => this.axios.get<{ items: ActiveSequence[] }>(url, {
      headers,
      params: { status: 'active', subject },
    }),
    { operationName: `CourseSequenceV2 GetActiveSequence (${subject})`,
      maxAttempts: 3, initialDelayMs: 1000 }
  );
  const items = response.data?.items || [];
  const match = items.find(
    (item) => item.subject.toLowerCase() === subject.toLowerCase()
  );
  if (!match) throw new Error(
    `[CourseSequenceV2] No active sequence found for subject=${subject}`
  );
  return match.id;
}

AlphaTest 2035c29c · course-sequence-v2.service.ts:238

At AlphaTest commit 2035c29c, resolveCourseForProgression returns null for placement. It returns the course before the assessment for end-of-course. A test-out score at or above the enrollment floor returns the course before the assessment. A test-out score below the enrollment floor selects a course from enrollment history. The resolver catches failures and returns null.

3. Learning & Caliper Events

The Caliper Listener is a central Lambda that acts as the gateway for all learning activity events produced by adapter apps. Events arrive via an SQS FIFO queue (caliper-events-queue) after being posted to an HTTP endpoint by each vendor's integration. Each message contains a Caliper event bundle — one or more events sharing a sensor identifier — that the Lambda must classify, validate, and route.

Before routing, the Lambda applies a multi-step filter pipeline. First, it drops bundles composed entirely of TimeSpentEvent types, which carry no meaningful completion data. Next, it initializes a ProgressionTracker object and performs an early scan of the bundle to determine whether any event represents a 100% course completion — this result influences later routing decisions. The Lambda then applies the relevant enrollment rule. Alpha Phonics course bundles are accepted only when they contain a terminal completion for a recognized PK–2 catalog course; partial or unknown-course bundles stop before notifications and enrollment lookup. A recognized terminal completion uses the native-completion bypass because the course enrollment may already have ended by the time its completion arrives. Reading screener results are a separate structural exception: a screener is an assignment inside the provider app, not an enrolled Timeback course, so both Literably and https://screeners.phonics.school results are admitted without an app-enrollment lookup.

Once the filter pipeline is satisfied, the Lambda routes the event bundle to a per-app processor. Each sensor maps to a dedicated handler (handleAlphawriteEvent, handleMobymaxEvent, handleLaliloEvent, etc.) that contains app-specific business logic. Most hole-filling-capable apps (MobyMax, VocabLoco, Anton, AlphaWrite, AlphaRead, Timeback, Edia, Freckle) look for self-emitted events at 100% to trigger progression. Lalilo is the exception: trusted Bridge events report the exact Timeback component resource and pctCompleteApp, so direct-linked 100% mastery events trigger progression immediately. MathQuest, Math Academy and Zearn require ActivityEvent + Completed, a numeric or string pctCompleteApp equal to 100, and a course matching the sensor’s core-course ID allowlist. Self-emitted markers do not exclude these core-course completions. Incept uses its dedicated sensor handler and accepts only a completion event with an authoritative pctCompleteApp >= 100 marker; partial dynamically generated syllabi never trigger progression.

When a processor confirms that a course has reached 100% completion, it sends a message to the student-progression queue to trigger the downstream progression pipeline. If the completion threshold is not met, the Lambda awards XP to the student via the Caliper system without advancing the pipeline. A ProgressionTracker ensures that progression is fired at most once per event bundle, even if multiple events in the bundle each individually qualify.

flowchart TD SQS["SQS: caliper-events-queue"] --> LAMBDA["Caliper Listener Lambda"] LAMBDA --> F1{"TimeSpentEvent?"} F1 -->|"Yes"| SKIP["Skip"] F1 -->|"No"| F2["Initialize Tracker\n+ Scan for 100%"] F2 --> F3{"Sensor-specific\ncompletion rules"} F3 -->|"HF-capable app"| SELF["Process as\nsupplementary event"] F3 -->|"Core course app"| CORE["Validate completion\nand allowlisted course"] SELF --> PROC["Route to App Processor"] CORE --> PROC PROC --> RESULT{"pctCompleteApp\n= 100%?"} RESULT -->|"Yes"| PROG["Send to\nProgression Queue"] RESULT -->|"No"| XP["Award XP\nvia Caliper"]

100% Completion Detection Rules by Sensor Type

Sensor Type Self-Emitted Events External Events Special Rules
MobyMax, VocabLoco, Anton, AlphaWrite, AlphaRead, Timeback, Edia, Freckle Count for 100% Do NOT count —
MathQuest, Math Academy, Zearn Count if valid Count if valid ActivityEvent + Completed, numeric or string pctCompleteApp equal to 100, and course sourcedId matching the sensor’s core-course allowlist; emitted markers do not affect eligibility
Incept / AlphaMath Do NOT count Canonical completion counts Requires an Incept completion event and finite pctCompleteApp >= 100; partial syllabus snapshots are ignored
Alpha Phonics (phonics.school) Do NOT count Canonical terminal events count Requires ActivityEvent + Completed, finite pctCompleteApp >= 100, and a recognized PK–2 base or hole-filling course
Reading screeners (screeners.phonics.school) Assessment result, not course completion Routes the screener pass/fail result without requiring an app enrollment; stale replays are ignored when newer Reading evidence exists
Lalilo Do NOT count Validated direct app 100% events count Direct HF events must have unit_type === 'mastery', component_resource_id, numeric pctCompleteApp, matching object.id, and matching active HF enrollment course. Non-direct HF mastery events are suppressed.
Loop Prevention

EMITTED_EVENT_SOURCE = 'hole-filling/supplementary adapter' — Events emitted by the system include this source identifier to distinguish them from student-generated events, preventing infinite processing loops. A secondary check tests whether the event's object.id ends with the EMITTED_EVENT_SUFFIX (-pctComplete) suffix as a fallback. When either marker is detected, the event is classified as self-emitted. How that classification affects completion depends on the sensor: the shared core-course predicate does not exclude events with these markers.

Deduplication Strategy

Because adapter apps can emit duplicate Caliper events — either from retries, network issues, or overlapping webhooks — the system implements a four-layer deduplication architecture to ensure that a single course completion never triggers multiple progression events or test assignments.

  1. FIFO SQS queue — caliper-events uses content-based deduplication with MessageGroupId set to sensor + student email. This guarantees sequential processing per student and prevents duplicate SQS delivery of the same event. (Converted from Standard to FIFO in PR #631 — the single biggest dedup improvement.)
  2. caliper_event_dedup table — atomic INSERT ON CONFLICT DO NOTHING keyed on (actor_email, course_id, app_name, pct_complete_app, extension_key). Extension keys vary by app (e.g., lessonModuleId for VocabLoco, lessonId/strand for MobyMax) to distinguish distinct activities within the same course. A compensation pattern ensures that if the downstream action fails after a successful dedup insert, removeEventKey() deletes the row so future retries are not blocked.
  3. Progression sentinel — a special __progression_trigger__ key in the caliper_event_dedup table prevents multiple 100% events on the same course from each independently triggering progression. Only the first event to claim this key proceeds.
  4. Downstream guards — three additional idempotency checks operate further in the pipeline: DeliveryService verifies the assignment does not already exist before creating it; the gap_analysis table confirms hole-filling is not already complete; and the hole_filling_dedup table prevents concurrent processing for the same student.
Implementation Details — processCaliperEvent, isEmittedEvent, LOOP_PREVENTION

workflow/progression/caliper-listener/index.ts — processCaliperEvent() simplified flow

TypeScript
async function processCaliperEvent(caliperEvent: any): Promise<void> {
  const sensor = caliperEvent.sensor;
  const bundledEvents = caliperEvent.data || [];

  const allEventsIgnored = bundledEvents.length > 0 && bundledEvents.every((evt: any) =>
    IGNORED_EVENT_TYPES.includes(evt?.type)
  );
  if (allEventsIgnored) {
    console.log('All events in bundle are ignored types - skipping');
    return;
  }

  const tracker: ProgressionTracker = {
    sent: false, has100pct: false, deduped: false, filtered: false, noActiveEnrollment: false
  };

  const isHoleFillingCapableSensor =
    isMobymaxSensor(sensor) || isVocablocoSensor(sensor) ||
    isLaliloSensor(sensor) || isAntonSensor(sensor) ||
    isAlphawriteSensor(sensor) || isAlphareadSensor(sensor) ||
    isTimebackSensor(sensor) ||
    sensor === ALLOWED_SENSORS.EDIA || sensor === ALLOWED_SENSORS.FRECKLE;

  tracker.has100pct = bundledEvents.some((evt: any) => {
    if (isCompletionReconciliationCandidate(evt)) return false;
    if (isCoreCourseSensor(sensor)) {
      // ActivityEvent + Completed, numeric/string 100%, allowlisted course.
      // Self-emitted markers do not exclude a core-course completion.
      return isCoreCourseCompletion(sensor, evt);
    }
    // Other sensor-specific guards are omitted from this simplified excerpt.
    const pct = evt?.generated?.extensions?.pctCompleteApp;
    if (pct === undefined || pct === null || Number(pct) < 100) return false;

    if (isLaliloSensor(sensor)) {
      return false; // handleLaliloEvent validates direct/base-course completions
    }

    if (isHoleFillingCapableSensor) {
      return isEmittedEvent(evt);   // HF-capable: self-emitted events count
    }

    return !isEmittedEvent(evt);    // Remaining native-completion paths
  });

  // ... completion prefilters, enrollment gate, then route to app processor:
  // Before dispatch, runtime removes non-completion core-course events;
  // handleCoreCourseEvent validates each remaining event again.
  if (isAlphawriteSensor(sensor))      await handleAlphawriteEvent(caliperEvent, tracker);
  else if (isAlphareadSensor(sensor))  await handleAlphareadEvent(caliperEvent, tracker);
  else if (isMobymaxSensor(sensor))    await handleMobymaxEvent(caliperEvent, tracker);
  else if (isVocablocoSensor(sensor))  await handleVocablocoEvent(caliperEvent, tracker);
  else if (isLaliloSensor(sensor))     await handleLaliloEvent(caliperEvent, tracker);
  // Lalilo direct-linked HF events set tracker.has100pct inside handleLaliloEvent
  // after course/resource validation succeeds.
  else if (isAntonSensor(sensor))      await handleAntonEvent(caliperEvent, tracker);
  else if (isTimebackSensor(sensor))   await handleTimebackEvent(caliperEvent, tracker);
  else if (isCoreCourseSensor(sensor)) {
    // Includes MathQuest, Math Academy and Zearn; require a matching course.
    const hasCoreCourseEvent = bundledEvents.some((evt: any) => {
      const courseId = extractSourcedIdFromUrl(evt?.object?.course?.id);
      return courseId && isCoreCourse(sensor, courseId);
    });
    if (hasCoreCourseEvent) await handleCoreCourseEvent(sensor, caliperEvent, tracker);
  }
}

shared/caliper-filters.ts:55 — LOOP_PREVENTION constants

TypeScript
export const LOOP_PREVENTION = {
  EMITTED_EVENT_SOURCE: 'hole-filling/supplementary adapter',
  EMITTED_EVENT_SUFFIX: '-pctComplete'
};

// IGNORED_EVENT_TYPES — bundles composed entirely of these are dropped
export const IGNORED_EVENT_TYPES = ['TimeSpentEvent'];

// CORE_COURSE_FILTERS excerpt — other core providers and additional IDs omitted.
export const CORE_COURSE_FILTERS = {
  MATH_QUEST: [
    '2a02dab2-a2a1-464f-8328-a857b7d9cdde', // MATH_QUEST_K_COURSE_ID
  ],
  MATH_ACADEMY: [
    '03ca4e3c-eac4-4fdc-9d48-28bbc8e1dd82',
    'b65b572a-cc91-409d-9279-1da1b90d40e6',
    // ... additional IDs
  ],
  ZEARN: [
    'd1e895c9-6c02-461d-a988-07760e08e9b9',
    // ... additional IDs
  ],
  REQUIRED_COMPLETION: 100
};

shared/caliper-filters.ts:156 — isEmittedEvent()

TypeScript
export const isEmittedEvent = (eventData: any): boolean => {
  const source = eventData?.generated?.extensions?.source;
  const objectId = eventData?.object?.id || '';

  return source === LOOP_PREVENTION.EMITTED_EVENT_SOURCE ||
    objectId.includes(LOOP_PREVENTION.EMITTED_EVENT_SUFFIX);
};

export const handleSelfEmittedProgression = async (
  eventData: any,
  caliperEvent: any,
  tracker: { sent: boolean },
  sendProgressionFn: (eventData: any, caliperEvent: any, tracker: any) => Promise<void>,
  label: string,
  index: number,
  total: number,
): Promise<boolean> => {
  if (!isEmittedEvent(eventData)) return false;

  const pctComplete = eventData?.generated?.extensions?.pctCompleteApp;
  if (pctComplete !== undefined && Number(pctComplete) >= 100) {
    console.log(`[${label}] Emitted event ${index + 1}/${total} with 100% completion - triggering progression`);
    try {
      await sendProgressionFn(eventData, caliperEvent, tracker);
    } catch (error) {
      console.error(`[${label}] Error triggering progression:`, error);
    }
  }
  return true;  // caller skips other processing when true
};

4. Assessment & Grading

The Gradebook Lambda evaluates student answers through three distinct paths determined by question type. When a student submits answers, the POST /gradebook/evaluate/:identifier endpoint routes to evaluateTestAnswers(), evaluateWritingAnswers(), or evaluatePhoneticAnswers() based on the question interaction types present in the QTI test. All three paths are idempotent — if an assignment has already been evaluated, the stored result is returned immediately without re-grading.

Tests are assigned to students via two entry points: assignTestByGrade() fires automatically during progression (triggered by a Caliper completion event), while assignTestToStudent() is used for manual or teacher-initiated assignment. Both produce an entry in the assignments table with a status of IN_PROGRESS. The assignment carries metadata that accumulates state as the student works — auto-saved answer state, timing data, and ultimately the graded result per question.

After grading, results flow to Timeback through a five-step reporting sequence: XP is computed, an Assessment Line Item is created or updated in the Timeback gradebook, the Assessment Result (score) is posted, a Caliper XP event is emitted, and finally a gap analysis SQS message is dispatched. The gap analysis message carries the list of incorrectly answered questions so the downstream DCAN lambda can plan remediation.

flowchart TD ANS["Student Submits Answers"] --> TYPE{"Question Type?"} TYPE -->|"Multiple Choice\nText Entry / Hottext\nHotspot / Order"| STD["Standard Grading\n(synchronous)"] TYPE -->|"Extended Text\nEssay"| AI["AI Writing Grading\n(async SQS)"] TYPE -->|"Audio Recording"| PHONE["Phonetic Grading\n(SpeechAce API)"] STD --> COMPARE["QTI Answer\nComparison"] AI --> LLM["LLM Evaluation\nLambda"] PHONE --> SPEECH["SpeechAce\nPronunciation API"] COMPARE --> RESULT["Store Result\n+ Compute XP"] LLM --> RESULT SPEECH --> RESULT RESULT --> TB["Report to Timeback:\nLine Item + Result + Caliper"] TB --> GAP["Trigger Gap Analysis\nvia SQS"]
Path Question Types Processing Latency
Standard Multiple-choice, inline-choice, text-entry, hottext, hotspot, graphic-gap-match, order, portable-custom Synchronous QTI comparison Immediate
AI / Writing Extended-text (essays) Async SQS → LLM Consumer Lambda Seconds
Phonetic Audio recordings SpeechAce API call Seconds

XP Computation

XP is computed by TimebackGradebookService.computeXpEarned() (app/backend/services/timeback/gradebook/gradebook.service.ts). The calculation applies score-based tiers, a repeat-attempt penalty for 100for100 tests, and an optional per-student xpMultiplier accommodation.

Score XP Formula Example (B = 60)
100%2 × B + 100220 XP
90–99%2 × B120 XP
80–89%B60 XP
< 80%round(B / 2)30 XP

For 100for100 tests, each repeat attempt halves the earned XP: attempt 2 receives 50%, attempt 3 receives 25%, and so on (Math.pow(0.5, attemptNumber - 1)). ISEE and unit tests are exempt from the repeat penalty and always receive base XP with no tier reduction. If the student's grade rank is below their highest-mastered grade + 1, the service returns 0 XP immediately (the student is retesting already-mastered content). An optional xpMultiplier stored in assignment metadata is applied as a final multiplicative factor before rounding.

Result Flow to Timeback

  1. GradebookService evaluates — answers compared against QTI correct responses; per-question correctness stored in assignments.metadata.
  2. Results table — one row written to results with total_questions, correct_questions, duration, and a metadata JSONB blob.
  3. Assessment Line Item created — Timeback line item represents the test as a gradebook column; reused on re-attempts via stored assessment_line_item_sourced_id.
  4. Assessment Result posted — student score sent to Timeback gradebook; stored assessment_result_sourced_id used to PUT on subsequent attempts.
  5. Caliper XP event emitted — fired when send_caliper_xp is enabled; carries pre-computed XP so Timeback can credit the student's account.
  6. Gap analysis SQS message sent — triggerGapAnalysis() dispatches a message to the gap-analysis queue containing assignmentId, wrongQuestions[], subject, and grade.
Enhanced vs. Legacy Timeback Flow
If assessment_line_item_sourced_id and assessment_result_sourced_id already exist in assignment metadata, the service takes the enhanced path — updating existing Timeback entities via PUT. Otherwise the legacy path creates new line items and results from scratch. Both paths compute XP first and run independent operations in parallel.
Implementation Details — Evaluation Functions
TypeScript
// gradebook.service.ts:691 — evaluateTestAnswers() (standard path)
async evaluateTestAnswers(
  identifier: string,
  userAnswers: { [key: string]: string[] },
  assignmentId: number,
  _meta?: { assignmentId?: string | null }
): Promise<{ [key: string]: { answer: string[], correct: number, positionCorrectness?: boolean[], barCorrectness?: { [key: string]: boolean } } }> {
  // Idempotency guard: return stored result if assignment already evaluated
  const existingResult = await runWithPostgresDbContext(true, this.config, async (db) => {
    return db.query('SELECT id FROM results WHERE assignment_id = $1', [assignmentId]);
  });
  if (existingResult.length > 0) {
    // Return stored per-question metadata or throw 403 if corrupted
    ...
  }
  // Fetch QTI correct answers, grade each question via calculateQuestionScore(),
  // store results, compute XP, report to Timeback, trigger gap analysis
}
TypeScript
// gradebook.service.ts:1341 — evaluateWritingAnswers() (AI/writing path)
async evaluateWritingAnswers(
  identifier: string,
  userAnswers: { [key: string]: string[] },
  assignmentId: number
): Promise<{ message: string, savedResponses: number }> {
  // Idempotency guard: return success if already evaluated
  const existingResult = await runWithPostgresDbContext(true, this.config, async (db) => {
    return db.query<{ id: number }>('SELECT id FROM results WHERE assignment_id = $1', [assignmentId]);
  });
  if (existingResult.length > 0) {
    return { message: 'Writing evaluation already completed', savedResponses: responseCount?.count || 0 };
  }
  // Save answers to assessment_responses (status: PENDING),
  // enqueue LLM evaluation SQS message per question,
  // finalizeWritingAssessment() called after all responses reviewed
}
TypeScript
// gradebook.service.ts:1663 — evaluatePhoneticAnswers() (SpeechAce path)
async evaluatePhoneticAnswers(
  identifier: string,
  userAnswers: { [key: string]: string[] },
  assignmentId: number
): Promise<{ message: string; gradedResponses: number }> {
  const phoneticService = new PhoneticGradebookService(this.config);
  const existingResponses = await phoneticService.getPhoneticResponsesByAssignment(assignmentId);

  for (const response of existingResponses) {
    // Call SpeechAce API per audio recording; score stored in phonetic_responses
    const graded = await phoneticService.evaluatePhoneticQuestion(
      assignmentId, response.question_id, String(response.user_id)
    );
  }
  // calculatePhoneticResults() aggregates scores;
  // binary correct = speechace_score >= PHONETIC_CORRECT_THRESHOLD
  // Results stored + Timeback reported same as standard path
}

5. Gap Analysis

Gap analysis runs immediately after grading completes. When triggerGapAnalysis() fires, it dispatches an SQS message to the gap-analysis queue carrying the assignmentId, the list of incorrectly answered questions, the subject, and the grade. The Gap Analysis Lambda consumes these messages and decides — before doing any LLM work — whether the assignment even qualifies for gap analysis. Most non-standard test types, scores at the extremes (0% or first-placement pass), and already-processed records are skipped without invoking an LLM.

For qualifying assignments, the Lambda fetches the missing context it needs (full question data, score breakdown, subject/grade derivation) from the database, then calls an LLM to identify misconception clusters from the wrong answers. The result is a structured gap report stored in the gap_analysis table with a report JSONB column containing patternClusters, per-question analyses, and overall diagnosis.

After the LLM produces the gap report, the Lambda routes based on subject type. Non-writing subjects (Math, Language, Science, Reading, Vocabulary) trigger the DCAN service by dispatching a message to the hole-filling-agent SQS queue with flowType: 'dcan'. Writing subjects skip DCAN and route directly to the legacy Lesson Recommender Lambda with flowType: 'legacy'. Both paths are idempotent — if a gap_analysis record already exists for the assignment, the Lambda returns it immediately without re-running.

flowchart TD TRIGGER["Grading Complete\n(SQS message)"] --> BYPASS{"Bypass Check"} BYPASS -->|"First placement pass\n(≥ 89.5%)"| SKIP["Skip — No Gaps"] BYPASS -->|"ISEE test"| SKIP BYPASS -->|"Unit test"| SKIP BYPASS -->|"0% accuracy"| SKIP BYPASS -->|"Pre-computed DCAN"| SKIP BYPASS -->|"Normal"| IDEMP{"Existing\ngap_analysis\nrecord?"} IDEMP -->|"Already exists"| SKIP IDEMP -->|"New"| DERIVE["Derive Missing Inputs\n(wrongQuestions, scoreData,\nsubject, grade)"] DERIVE --> LLM["LLM: Identify\nLearning Gaps"] LLM --> ROUTE{"Subject Type?"} ROUTE -->|"Non-writing"| DCAN["DCAN Pipeline\nflowType: 'dcan'"] ROUTE -->|"Writing"| LEGACY["Lesson Recommender\nflowType: 'legacy'"] DCAN --> SQS["hole-filling-agent\nSQS Queue"] LEGACY --> REC["Lesson Recommender\nLambda"]
Bypass Condition Trigger Reason
First placement pass Score ≥ 89.5% on first placement test Student already demonstrated mastery; progression advances without remediation
ISEE test Test subject matches ISEE pattern Standardized admissions test — not a diagnostic instrument
Unit test Test subject matches unit test pattern Not an end-of-course assessment; gap analysis is not applicable
Configurable analysis rules Origin/org-specific rule with ga_enabled: false Per-origin and per-org analysis rules can disable gap analysis for specific programs, test types, or grade ranges. The bypass function resolves the matching rule using origin → org → _default precedence.
100for100 origin assignment.origin === '100for100' Practice-loop tests are excluded from gap remediation flow (configured via analysis rule)
FastMath subject Subject matches FastMath pattern FastMath uses its own progression logic (configured via analysis rule)
0% accuracy Score = 0% Likely untaken or invalid attempt; sends a warning notification
Low-score placement Placement/test-out score below enrollment threshold Score triggers course enrollment directly, bypassing gap remediation
Test user Email/metadata flagged as a test account Internal test accounts are excluded from the pipeline
Routing Decision

Non-writing subjects (Math, Language, Science, Reading, Vocabulary) route to the DCAN service (flowType: 'dcan'). Writing subjects route to the legacy Lesson Recommender (flowType: 'legacy').

Code: shouldBypassGapAnalysis() — gap-analysis-bypass.ts:183
TypeScript
export async function shouldBypassGapAnalysis(config: any, assignmentId: number): Promise<BypassCheckResult> {
  const data = await fetchBypassData(config, assignmentId);

  if (!data) {
    return { shouldBypass: false };
  }

  if (isIseeTest(data.raw_subject)) {
    return { shouldBypass: true, reason: BypassReason.ISEE_TEST };
  }

  if (isUnitTest(data.raw_subject)) {
    return { shouldBypass: true, reason: BypassReason.UNIT_TEST };
  }

  if (data.origin === '100for100') {
    return { shouldBypass: true, reason: BypassReason.ORIGIN_100FOR100 };
  }

  if (isFastMath(data.raw_subject)) {
    return { shouldBypass: true, reason: BypassReason.FASTMATH_SUBJECT };
  }

  if (isTestUser(data.user_email, data.user_metadata)) {
    return { shouldBypass: true, reason: BypassReason.TEST_USER };
  }

  // Placement tests get dedicated bypass logic with count-based branching.
  // This must run before the generic low-score check to avoid incorrect thresholds.
  const placementResult = await checkPlacementBypass(config, data, assignmentId);
  if (placementResult !== null) return placementResult;

  if (isLowScorePlacementOrTestOut(data.test_type, data.correct_questions, data.total_questions)) {
    // ... returns shouldBypass: true, reason: LOW_SCORE_PLACEMENT_OR_TESTOUT
  }

  if (isZeroScore(data.correct_questions, data.total_questions)) {
    return { shouldBypass: true, reason: BypassReason.ZERO_SCORE, details: { ... } };
  }

  return { shouldBypass: false };
}
Code: processGapAnalysisEvent() — handler.ts:148
TypeScript
async function processGapAnalysisEvent(event: GapAnalysisEvent): Promise<GapAnalysisResult> {
  const config = await getConfig();
  const { assignmentId, courseCode, options } = event;

  // === Bypass check ===
  const bypassResult = await shouldBypassGapAnalysis(config, assignmentId);
  if (bypassResult.shouldBypass) {
    console.log(`[Bypass] Skipping gap analysis for assignment ${assignmentId} — reason: ${bypassResult.reason}`);
    // Persists a bypass record to gap_analysis table, sends 0% notification if needed,
    // and triggers downstream progression for placement bypass reasons.
    // Returns early without calling the LLM.
    return { status: 'bypassed', reason: bypassResult.reason };
  }

  // === Idempotency guard ===
  // If a gap_analysis record already exists for this assignment, return it immediately.
  const existing = await fetchExistingGapAnalysis(config, assignmentId);
  if (existing) {
    return { status: 'already_processed', gapAnalysisId: existing.id };
  }

  // === Derive missing inputs ===
  const { subject, grade } = await deriveSubjectAndGrade(config, assignmentId);

  // === LLM gap identification ===
  const gapReport = await runGapAnalysisLLM(config, event, subject, grade);

  // === Route to DCAN or legacy ===
  const flowType = isWritingSubject(subject) ? 'legacy' : 'dcan';
  await dispatchToNextStage(config, gapReport, flowType);

  return { status: 'processed', gapAnalysisId: gapReport.id, flowType };
}

6. DCAN — AI Recommendations

DCAN (Distributed Context Agent Network) is an external AI service provided by AlphaTest and consumed by Timeback. It analyzes student diagnostic gaps and recommends targeted remediation lessons. From the progression pipeline's perspective, DCAN is a black box: Timeback sends a gap analysis ID, and DCAN writes lesson recommendations back to the database. This section covers the integration points that matter for understanding progression flow.

External Service

DCAN is owned and operated by AlphaTest. Timeback controls the integration — triggering DCAN via SQS, consuming its output from the database, and handling failures. The internal architecture of DCAN (multi-agent orchestration, lesson subagents, reviewer quality gates) is managed by AlphaTest.

How Timeback Invokes DCAN

DCAN is invoked when the Gap Analysis Lambda dispatches a message to the hole-filling-agent SQS queue with flowType: 'dcan'. An ECS Fargate task picks up the message and runs its pipeline for the given gapAnalysisId. The task reads the gap analysis report from the database, processes it through a multi-phase AI pipeline, and writes the results back.

sequenceDiagram participant GA as Gap Analysis Lambda participant SQS as hole-filling-agent Queue participant DCAN as DCAN Service (AlphaTest) participant DB as PostgreSQL GA->>SQS: dispatch(gapAnalysisId, flowType: 'dcan') SQS->>DCAN: ECS Fargate task starts DCAN->>DB: Read gap_analysis record Note over DCAN: Multi-agent AI pipeline DCAN->>DB: jsonb_set gap_analysis.report.dcanRecommendations Note over DB: Hole-filling service reads recommendations

What DCAN Produces

DCAN writes its output to gap_analysis.report.dcanRecommendations as a JSONB field containing a RemediationPlan. This plan includes: gap group summaries, recommended lesson IDs with target app annotations, per-lesson quality verdicts (accept, accept-with-flags, reject), review notes, unmet gaps (clusters where no suitable lessons were found), and plan statistics. The downstream hole-filling service reads this field to determine which lessons to assign in which adapter apps.

If DCAN identifies no gap groups or finds no suitable lessons, it writes an empty plan. If the progression pipeline later sees flowType: 'dcan' but finds no dcanRecommendations in the record, it treats the case as non-retryable and routes it to the DLQ with a #NoLessons alert.

Failure Handling

A dedicated dcan-failure-alert Lambda monitors ECS task state changes via EventBridge. Failed tasks are retried up to 2 times with a 5-minute delay. After exhaustion, the message goes to a DLQ and a Google Chat alert fires. From the progression pipeline's perspective, a DCAN failure means the student's hole-filling is delayed until the issue is resolved or the DLQ message is redriven.

DCAN Output Schema

Field Type Description
gapGroups[] Array Gap clusters with recommended lessons per group
gapGroups[].lessons[] Array Lesson IDs, titles, app targets, and quality verdicts
summary Object Plan statistics: total clusters, lessons accepted, retries used
unmetGaps[] Array Clusters where no suitable lessons were found in the catalog
reviewNotes[] Array Quality review notes from the DCAN review process

7. Hole-Filling & Remediation

When a student fails to achieve the 89.5% mastery threshold on a standard end-of-course test, the pipeline triggers hole-filling to create a targeted remediation course. Math Pre-K is the explicit exception because no usable Pre-K hole-filling implementation exists. Course Sequence returns 409 remediation_unavailable; native progression returns remediation_unavailable and stops its retry check. Neither path creates a course or enrollment. The process begins in assignHoleFilling(), which first calls getAppForSubjectAndGrade() to select the remediation source, for example, Timeback Learn for Math grades 6–8 and Science grades 3–8, Edia for Math grades 9–11, Freckle for Language grades 3–12, or MobyMax for Reading grades 2–8. Canonical PK–2 Reading uses the static Alpha Phonics catalog described below. First-party Timeback Learn recommendations link existing OneRoster resources without a Bridge adapter call.

Happy Numbers remains a Pre-K base-course integration, not a hole-filling route. Its general base-course builder and Caliper handler continue to serve real enrollments. After the release data correction, both Happy Numbers OneRoster course records use Pre-K grade -1.

Timeback Learn rollout controls: TIMEBACK_LEARN_ROUTING_ENABLED enables first-party Math G6–8 and Science G3–8 remediation. During the receiver-first migration window, TIMEBACK_LEARN_ACCEPT_LEGACY_RECOMMENDATIONS accepts tagged or untagged Edia and MobyMax input while producer deployments converge and keeps delayed or stored recommendations recoverable. Disabling the compatibility flag restores strict ownership validation; disabling routing restores the unchanged legacy path. Science base-course selection is separate and remains on the existing sequence until that sequence is migrated and TIMEBACK_LEARN_SCIENCE_BASE_COURSES_ENABLED is enabled.

Canonical PK–2 Reading uses its own runtime and static catalog instead of this generic app map. An authoritative end-of-course failure selects the matching Alpha Phonics hole-filling course, including PreK. Placement establishes a base-course boundary; an ordinary failed test-out preserves current work. See the battery routing rules and guarded historical test-out exception. Completing a current Alpha Phonics remediation course normally assigns an end-of-course battery. Legacy sequence route only: PreK letter-sounds failures used Anton, and K–2 ORF failures used the sequence-selected Alpha Phonics remediation stage.

Two recommendation paths exist depending on subject type. The DCAN path (used for all non-writing subjects) reads pre-computed lesson recommendations directly from gap_analysis.report.dcanRecommendations in the database. These were produced earlier by the DCAN service and include lesson IDs, titles, and target app annotations. The Legacy LLM path (used for Writing subjects) calls PromptFactory to select an app-specific prompt — for example lesson_recommender_writing.ts for AlphaWrite — and makes a single-pass LLM call to generate lesson recommendations from the student's gap profile.

Both paths converge at course creation: a OneRoster course record is created in Timeback, resources (lesson IDs) are assigned to the adapter app, and the student is enrolled. Most adapter processors report completion through self-emitted Caliper events tagged with EMITTED_EVENT_SOURCE='hole-filling/supplementary adapter', which the Caliper Listener uses to detect and prevent re-entry into the main progression pipeline until the remediation course is fully complete. Lalilo is the direct-event exception: trusted Bridge events report the exact component resource and completion percentage without TimeBack recomputing or re-emitting progress.

flowchart TD START["Hole-Filling Triggered"] --> CHECK{"DCAN recommendations exist?"} CHECK -->|"Yes"| DCAN["DCAN Path"] CHECK -->|"No"| LEGACY["Legacy LLM Path"] DCAN --> FETCH["Fetch from gap_analysis.report.dcanRecommendations"] LEGACY --> PROMPT["PromptFactory selects app prompt"] PROMPT --> LLM["Single-pass LLM call"] FETCH --> FILTER["Filter by target app"] LLM --> VALIDATE["Validate against lesson catalog"] FILTER --> CREATE["Create OneRoster Course"] VALIDATE --> CREATE CREATE --> RESOURCES["Assign Resources to Adapter App"] RESOURCES --> ENROLL["Enroll Student"] ENROLL --> MONITOR["Monitor Completion via Caliper"]

DCAN Path

For non-writing subjects, getDcanRecommendations() queries the gap_analysis table for the most recent report for the given assignment. It reads report.dcanRecommendations.recommendations, flattens the lesson list, filters out any lessons with verdict: 'reject', and optionally filters by targetApp to ensure only lessons intended for the selected adapter are included. If no valid lessons remain after filtering, the system falls back to the legacy path.

Legacy LLM Path

For Writing subjects, PromptFactory.getAppForSubjectAndGrade() routes to AlphaWrite (grades 3–9). The factory also handles catalog grade-range selection — for example, Anton always fetches from PK/K/1/2 regardless of the student's grade, while Edia fetches ±2 grade levels from the student's grade. A single structured LLM call then produces the lesson recommendation list, which is validated against the live lesson catalog before course creation proceeds.

Course Creation

A OneRoster course is created with title format [AppName] Subject GN hole-filling and a unique courseCode including the student's Timeback ID. A deduplication guard in hole_filling_dedup prevents duplicate courses from being created if the same event is processed more than once. Once the course and its resource assignments are confirmed, the student is enrolled and the adapter app begins serving the remediation content.

Code: assignHoleFilling() — student-progression-track.service.ts:1198

student-progression-track.service.ts:1198

TypeScript
private async assignHoleFilling(
  assignmentId: number,
  studentTimebackId: string,
  studentEmail: string,
  subject: string,
  grade: string,
  currentCourseSourcedId: string,
  readOnly?: boolean,
  extendedCatalog?: boolean,
  flowType?: 'legacy' | 'dcan'
): Promise<void> {
  // Determine which app to use based on subject and grade
  const { getAppForSubjectAndGrade } = await import("../hole-filling/prompts/prompt-factory");
  const app = getAppForSubjectAndGrade(subject, grade);

  if (!app) {
    console.log(`Hole-filling not supported for ${subject} Grade ${grade}. Early exit.`);
    return;
  }

  // Early dedup check — prevents duplicate processing
  const dedupResult = await sql`
    INSERT INTO hole_filling_dedup (student_sourced_id, assignment_id)
    VALUES (${studentTimebackId}, ${assignmentId})
    ON CONFLICT ON CONSTRAINT hole_filling_dedup_key DO NOTHING
    RETURNING id
  `;
  if (dedupResult.length === 0) {
    console.log(`Hole-filling already created for student ${studentTimebackId} — dropping duplicate`);
    return;
  }
}
Code: getDcanRecommendations() — student-progression-track.service.ts:3369

student-progression-track.service.ts:3369

TypeScript
private async getDcanRecommendations(assignmentId: number, targetApp?: string): Promise<{
  lessons: Array<{ lesson_id: string; title: string }>;
  gapAnalysisId: string;
} | null> {
  const record = await runWithPostgresDbContext(true, this.config, async (db) => {
    return db.queryOne<{ id: string; report: any }>(
      `SELECT id, report FROM gap_analysis
       WHERE assignment_id = $1 ORDER BY created_at DESC LIMIT 1`,
      [assignmentId]
    );
  });

  if (!record?.report?.dcanRecommendations?.recommendations) {
    console.warn(`No DCAN recommendations found for assignment ${assignmentId}`);
    return null;
  }

  const allRecs = record.report.dcanRecommendations.recommendations
    .flatMap((r: any) => {
      if (r.lessons?.length) {
        return r.lessons
          .filter((l: any) => l.lessonId && l.verdict !== 'reject')
          .map((l: any) => ({ lesson_id: l.lessonId, title: l.lessonTitle || 'Lesson', app: l.app }));
      }
      return [];
    });

  let recs = targetApp ? allRecs.filter((l: any) => !l.app || l.app === targetApp) : allRecs;
  if (recs.length === 0) return null;

  return { lessons: recs, gapAnalysisId: record.id };
}
Code: getAppForSubjectAndGrade() — shared/utils/app-mapping.ts

shared/utils/app-mapping.ts

TypeScript
export function getAppForSubjectAndGrade(subject: string, grade: string): HoleFillingApp | null {
  const gradeNum = parseGradeToNumber(grade);
  if (gradeNum === null) return null;
  const normalizedSubject = normalizeSubject(subject);

  if (normalizedSubject === 'math') {
    if (gradeNum >= 0 && gradeNum <= 5) return 'timeback';    // Math K-5: native platform
    if (isTimebackLearnRoutedBand(normalizedSubject, grade)) {
      return isTimebackLearnRoutingEnabled() ? 'timeback_learn' : 'edia';
    }
    if (gradeNum >= 9 && gradeNum <= 11) return 'edia';       // Math 9-11: Edia
  }
  if (normalizedSubject === 'language') {
    if (gradeNum >= 0 && gradeNum <= 2) return 'lalilo';      // Language K-2: Lalilo
    if (gradeNum >= 3 && gradeNum <= 12) return 'freckle';    // Language 3-12: Freckle
  }
  if (normalizedSubject === 'writing') {
    if (gradeNum >= 3 && gradeNum <= 9) return 'alphawrite';  // Writing 3-9: AlphaWrite
  }
  if (normalizedSubject === 'science') {
    if (isTimebackLearnRoutedBand(normalizedSubject, grade)) {
      return isTimebackLearnRoutingEnabled() ? 'timeback_learn' : 'mobymax';
    }
  }
  if (normalizedSubject === 'reading') {
    if (gradeNum >= -1 && gradeNum <= 1) return 'anton';       // Reading PK-1: Anton
    if (gradeNum >= 2 && gradeNum <= 8) return 'mobymax';    // Reading 2-8: MobyMax
    if (gradeNum >= 9 && gradeNum <= 12) return 'alpha_read'; // Reading 9-12: AlphaRead
  }
  if (normalizedSubject === 'vocabulary') {
    if (gradeNum >= 3 && gradeNum <= 12) return 'vocabloco'; // Vocabulary 3-12: VocabLoco
  }
  return null; // Unsupported subject/grade combination
}

The custom hole-filling and pilot APIs share structured next course and assessment actions. An assessment accepts { type: "assessment", subject, grade, testType, timebackId? }; timebackId selects an exact active, supported, assignable test without requiring active-sequence membership. Hole-filling requires the assessment subject and grade to match its plan. Existing hole-filling strings (end of course, test out, placement, or a course sourced ID) remain supported. Course targets retain active-sequence validation. The owned none action remains pilot-only.

Custom Hole-Filling Courses

Choosing an endpoint: use this API to create a new course from selected lessons. For pilot enrollment into an existing course with a defined next action, see Pilot Course Assignments.

The standard hole-filling flow is fully automatic — when a student fails an assessment, the system selects remediation lessons using AI. But sometimes the academics team needs to manually intervene: hand-pick specific lessons for a student, target a particular skill gap, or override the AI’s recommendations.

The Custom Hole-Filling Course API lets you do exactly this. You choose the app, the lessons, and the student — and the system creates a properly structured course that fits seamlessly into the mastery loop. When the student completes the course, progression continues normally: they take a test, and based on their score, they either advance or receive further remediation. See the app routing matrix for which apps and grades are available.

You can use this API through the Scalar API docs — Create a custom hole-filling course and Browse lesson catalog — or have an AI coding agent handle it for you using the downloadable agent guide at the bottom of this section.

This is a safe intervention

Custom courses integrate with the existing progression pipeline. The student will either take an assessment (end of course, test out, or placement) or be enrolled in the next course from the active sequence. Manual XP courses and class enrollments are always protected and never removed.

How It Works

flowchart TD START["Educator picks lessons\nfrom the catalog"] --> CREATE["Submit the course\ncreation request"] CREATE -->|"Request accepted"| ASYNC["System processes\nin the background"] ASYNC --> LOOKUP["1. Find the student"] LOOKUP --> ASSIGN["2. Create assignments\nin the learning app"] ASSIGN --> COURSE["3. Build the course\nwith selected lessons"] COURSE --> SKIP{"skipUnenroll?"} SKIP -->|"false / omitted"| UNENROLL["4. Remove old\nsame-subject courses"] SKIP -->|"true"| ENROLL UNENROLL --> ENROLL["5. Enroll student\nin the new course"] ENROLL --> NOTIFY["Notification sent\nto Google Chat"] NOTIFY --> STUDENT["Student sees the course\nin their dashboard"] STUDENT -->|"Completes all lessons"| NEXT{"What's next?"} NEXT -->|"end of course / test out / placement"| TEST["Assessment test"] NEXT -->|"Specific course"| ENROLL2["Enroll in\nthat course"]

Step-by-Step Guide

1. Browse the Lesson Catalog

Start by finding the lessons you want to assign. The catalog endpoint lets you browse all available lessons for any supported app.

Example: MobyMax Reading, Grade 3
GET /edubridge/progression/catalog?app=mobymax&gradeLevel=3&subject=reading

The response includes a list of lessons with their IDs, names, subjects, and grade levels:

Catalog Response
{
  "app": "mobymax",
  "lessons": [
    {
      "lessonId": "mobymax_reading_1654_g3",
      "lessonName": "Identify and explain personification",
      "subject": "reading",
      "gradeLevel": "3",
      "standards": ["RL.3.4"]
    },
    {
      "lessonId": "mobymax_informational_text_1321_g3",
      "lessonName": "Distinguish fact from opinion",
      "subject": "reading",
      "gradeLevel": "3",
      "standards": ["RI.3.8"]
    }
  ],
  "pagination": { "page": 1, "limit": 100, "total": 101, "totalPages": 2 }
}
Finding the right lessons

Start with just the app parameter (no subject or grade filters) to see everything available. The response shows the subject and gradeLevel for each lesson — use those exact values to narrow down.

If you can’t find a lesson, try removing the subject filter or picking a different grade level. Some apps organize content differently than expected.

Large catalogs are paginated. Check pagination.totalPages in the response. Use page=2, page=3, etc. to see more results. You can increase the page size up to 500 with limit=500.

Timeback and AlphaWrite are different

These two apps don’t use the catalog. Their lessons are existing resources in the system. For Timeback, the lesson ID is a course component ID. For AlphaWrite, it’s a resource ID. You can find these by looking at existing courses for those apps through the API. The downloadable agent guide (below) has step-by-step instructions for finding them.

2. Create the Course

Once you’ve identified the lessons, create the course. The request includes the student’s email, the app, subject, grade, your selected lessons, and what should happen when the student finishes.

Create Course Request
POST /edubridge/progression/custom-hole-filling-course

{
  "studentEmail": "jane.doe@alpha.school",
  "subject": "Reading",
  "grade": "3",
  "app": "mobymax",
  "lessons": [
    { "lessonId": "mobymax_reading_1654_g3", "lessonName": "Identify and explain personification", "order": 1 },
    { "lessonId": "mobymax_informational_text_1321_g3", "lessonName": "Distinguish fact from opinion", "order": 2 }
  ],
  "next": "end of course"
}

The API returns 202 Accepted immediately with a job ID. The course is created in the background.

Optional Fields

FieldTypeDefaultDescription
origin string "progression" Origin identifier for the assignment that triggered this custom HF course. Propagated into the course metadata and carried forward when the follow-up assessment is assigned, so AlphaTest’s analysis rules can resolve the correct origin-specific configuration (gap analysis, DCAN, score thresholds). Use when the course is being created on behalf of a specific program or origin (e.g., "100for100", "timeback_ui").
skipUnenroll boolean false When true, the system skips step 4 (removing same-subject courses) entirely. The student keeps all their existing enrollments and is simply added to the new HF course. Useful when the student is expected to work on multiple courses in the same subject simultaneously, or when removing existing courses would disrupt their progress. When false or omitted, the standard unenrollment behavior applies — same-subject courses are removed (with safety protections) before enrollment.
assignmentId number (auto-resolved) AlphaTest assignment ID. If omitted, the server attempts to resolve it by scanning the student’s existing same-subject enrollments for course metadata containing assignmentId.
baseCourseSourcedId string (auto-resolved) Base course sourced ID for hole-filling lineage tracking. If omitted, the server resolves it from the student’s existing same-subject enrollments.
gapAnalysisId string none Gap analysis record ID for metadata tracking.
missedQuestions string[] none List of missed question IDs for metadata tracking.
Example with optional fields
POST /edubridge/progression/custom-hole-filling-course

{
  "studentEmail": "jane.doe@alpha.school",
  "subject": "Reading",
  "grade": "3",
  "app": "mobymax",
  "lessons": [
    { "lessonId": "mobymax_reading_1654_g3", "lessonName": "Identify and explain personification", "order": 1 }
  ],
  "next": "end of course",
  "origin": "100for100",
  "skipUnenroll": true
}

3. Verify the Course Was Created

After submitting, verify the course was actually created. The processing can take up to several minutes depending on the learning app.

Google Chat: A notification is sent to the same channels used by the standard progression pipeline. Look for “✅ Custom HF Course Created” (success), “⚠️ Enrollment Failed” (partial), or “❌ Custom HF Course Failed” (error).

API check: You can also verify by checking the student’s enrollments. Look for a course with customHF: true in the metadata. If using an AI coding agent, the agent guide instructs it to poll every 60 seconds for up to 10 minutes.

Supported Apps

AppHow It WorksWhere to Find Lesson IDsExample Lesson ID
MobyMaxCreates practice assignmentsCatalog APImobymax_reading_1654_g3
FreckleCreates skill-based assignmentsCatalog APIFR-CCSS-2-W.6.3.d
EdiaCreates adaptive assignmentsCatalog APImiddle_school.factors and multiples.factor_expressions
LaliloCreates literacy assignmentsCatalog API1688
VocabLocoCreates vocabulary assignmentsCatalog APIvocabloco_g1171_long_a_words
AntonCreates ELA assignmentsCatalog APIc-nateng-k/yx4m8g
TimebackLinks existing math resourcesLook up from existing courses (see agent guide)Component ID
AlphaWriteLinks existing writing resourcesLook up from existing courses (see agent guide)Resource ID

XP (Optional)

Each lesson can include an optional xp value (positive integer) to override the app’s default XP. If omitted, the system uses the app’s default for each lesson.

XP behavior varies by app

Most apps: The XP you set is applied directly to each lesson resource.

VocabLoco: One lesson expands into multiple activities. Your XP is divided equally across them (e.g. 35 XP ÷ 7 activities = 5 XP each).

Timeback and AlphaWrite: XP is ignored — these apps link existing resources that already have their own XP.

The next Field

This controls what happens when the student completes all lessons in the course:

ValueWhat HappensWhen to Use
end of courseStudent takes an end-of-course assessmentMost common — checks if the student mastered the material
test outStudent takes a test-out assessmentWhen you want to see if the student can skip ahead
placementStudent takes a placement testReserved for new incoming students to find their ideal level
Course sourced IDStudent is enrolled in that specific courseThe OneRoster sourced ID must belong to a course in the active course sequence for the subject. Only the most recent course on each stage is accepted.

Restrictions

Using a course sourced ID as the next value

If you want the student to be enrolled in a specific course after completing the hole-filling lessons (instead of taking a test), you must provide its OneRoster sourced ID from the active course sequence for the subject. Sourced IDs are opaque strings and are not required to be UUIDs. The system only accepts the most recent course on each stage — historical or swapped-out courses are rejected. See the agent guide for step-by-step instructions on how to find valid course sourced IDs.

Safety Guarantees

Agent Context File

If you or your team uses AI coding agents (Claude Code, Cursor, etc.) to create courses, download the agent guide below. It contains authentication instructions, code examples, verification steps, and safety rules that teach the agent how to use the API correctly — including how to find Timeback and AlphaWrite lesson IDs.

↓ Download Agent Guide (.md)

Pilot Course Assignments

Release status — course follow-ups verified in staging

Verified October 29, 2026: API app/sensor registration, independent next courses for students sharing a pilot, authenticated completion, durable duplicate handling, early return, unavailable-destination recovery, and automatic recovery after an interrupted worker. Synthetic test users and course fixtures were retired after verification. This change has not been deployed to production. Native assessment delivery still requires isolated end-to-end verification; use existing-course follow-ups for the initial pilot rollout.

This is the intended endpoint for pilot enrollments into existing courses. It assigns a course to a student together with an explicit action after completion, so a pilot does not leave the student without a next step. It also supports other educator-directed course assignments that need a defined follow-up. The custom hole-filling API remains the endpoint for creating a new course from selected remediation lessons.

Assign a Course With a Completion Action

The request identifies an existing course, the student, whether it replaces their current same-subject enrollment, and a required next action. For example, a student can take a pilot Math course and then move to the approved Zearn Grade 1 course. IDs below are placeholders, not executable enrollment instructions.

POST /edubridge/progression/course-assignments
Idempotency-Key: pilot-enrollment-unique-request-id
Authorization: Bearer <access-token>

{
  "studentEmail": "student@alpha.school",
  "courseSourcedId": "<pilot-course-id>",
  "replaceCurrentSubjectEnrollment": true,
  "ownerEmail": "pilot-owner@alpha.school",
  "reviewAfterDays": 7,
  "next": {
    "type": "course",
    "courseSourcedId": "<approved-zearn-grade-1-id>"
  }
}

With replaceCurrentSubjectEnrollment, only the student's current same-subject academic enrollments are ended. Already-ended history keeps its end date, spaced-repetition review courses and courses protected from automatic unenrollment are never ended, and a scheduled same-subject enrollment, or one whose course has a malformed unenrollment policy, rejects the request until it is resolved. A protected course, or one with a malformed unenrollment policy, cannot be the pilot course.

The completion action belongs to this student's assignment/enrollment, not the shared course. Students taking the same pilot course can have different follow-ups. Ordinary enrollment in that shared course must not inherit another student's pilot routing.

next must explicitly select a course, an assessment, or an intentional end to automatic progression. A missing, invalid, or unavailable target must never silently become “do nothing.” An intentional stop must record its reason and responsible owner; if the student still requires work in that subject, it also needs an explicit continuation or return plan. It is not a default or a fallback for a failed transition. The supported shapes are shown below. An intentional stop requires subjectComplete: true; use an explicit return course if work is still required.

{ "type": "assessment", "subject": "Math", "grade": 1, "testType": "end of course" }
{ "type": "none", "reason": "Subject completed", "ownerEmail": "pilot-owner@alpha.school", "subjectComplete": true }

Assessments support placement, test out, and end of course, grades -1 through 12, and Math, Reading, Language, Writing, Vocabulary, and Science. Pre-K–Grade 2 Reading assessment follow-ups are rejected before enrollment changes because they require AlphaLiteracy, which this endpoint does not deliver; choose an existing follow-up course for those pilots. Existing assessment delivery policies still apply. An already-mastered grade or a rejected assignment does not authorize a different next action. TimeBack checks only that an assignable assessment exists for the subject and grade; AlphaTest decides the test type at delivery, and its refusal holds the assignment for the owner. The organization's assessment denylist applies to placement and test-out follow-ups, not end-of-course assessments.

Requests require a service API client with administrator or progression-write scope. Registration requires administrator scope, and enabling a sensor requires an enabled, writable owning client (a read-only client cannot deliver completions). The internal worker API is reserved for the configured progression service client. Reads require administrator, progression-read, or progression-write scope; a client sees the assignments it created and those of the sensors it owns. Request bodies of these routes are never written to HTTP logs. Each assignment records ownerEmail, an immutable original request, an idempotency key scoped to the tenant and client, the exact enrollment, and the chosen next action. Reusing a key with changed input returns a conflict.

Target a Specific Assessment

Supply next.timebackId with the stable AlphaTest/QTI identifier returned by inventory. This selects that test directly, without requiring membership in the active grade sequence or changing shared sequencing. Omit it to retain normal grade-based selection. The test must be active in AlphaTest, supported, assignable, and match the requested subject and grade. Validation runs before enrollment changes and again before delivery; the receipt is verified against the specific inventory test. A missing, mismatched, superseded, or rejected test never falls back to another test. Existing mastery and duplicate-assignment policies still apply.

"next": {
  "type": "assessment",
  "subject": "Vocabulary",
  "grade": 4,
  "testType": "end of course",
  "timebackId": "<Vocabulon Grade 4 test timeback_id>"
}

Register a Pilot App Through the API

Use an existing tenant-bound service API client. App registration requires administrator scope; course assignment requires administrator or progression-write scope.

Before assigning its courses, an authorized administrator registers the app's sensor, authenticated owner, and supported completion contract through the API. Compatible apps must then be usable for pilots without adding a provider-specific allowlist entry or completion handler in a PR. Registering a sensor URL alone is not proof that an event came from its owner.

The initial completion contract uses a standard Caliper ActivityEvent with action: "Completed", generated.extensions.pctCompleteApp: 100, and canonical TimeBack student and course identifiers. The app must already expose a usable course in OneRoster. Registering its sensor does not provision vendor accounts or translate arbitrary vendor event formats.

PUT /edubridge/progression/pilot-apps/<application-sourced-id>
{
  "sensor": "https://new-pilot.example.com",
  "application": { "name": "New Pilot App", "domains": ["new-pilot.example.com"] },
  "completionMode": "course_percentage",
  "enabled": true
}

For a new application ID, supply optional application details to create the catalog entry through this API. Its owner defaults to the calling client, or an administrator may supply ownerClientAppId for an existing enabled client in the same tenant. No new OAuth client or credential is created. For an existing app, omit application; its existing owner is retained and cannot be transferred here. Sensors are unique. Once an app has assignment history, its sensor and owner cannot be reassigned. Disabling the registration blocks new assignments and completions while preserving pending recovery work.

Course compatibility: choose an active existing course with one subject and grade and active learning resources with an HTTPS launch URL. Provision and verify any required native account before enrolling a student in the pilot. This API checks catalog launchability; it cannot inspect an arbitrary vendor's learner session. Provider-generated anchors must first be provisioned through their existing onboarding API; pass the student's resulting course, not the anchor. Known follow-up providers use the existing onboarding path before the next enrollment is committed. Other compatible apps must already have working learner access.

Deliver Completion and Recover a Pilot

Send the completion to POST /edubridge/progression/course-assignment-events using the registered app owner's bearer token and Caliper event-write or administrator scope. The public Caliper endpoint alone does not authenticate pilot completion. Send ordinary XP/time events through the normal Caliper API separately; this endpoint does not award credit.

{
  "sensor": "https://new-pilot.example.com",
  "data": [{
    "id": "urn:uuid:stable-completion-event-id",
    "type": "ActivityEvent",
    "action": "Completed",
    "eventTime": "2026-10-29T20:00:00Z",
    "actor": { "id": "https://<environment-api-host>/ims/oneroster/rostering/v1p2/users/<student-id>" },
    "object": { "course": { "id": "https://<environment-api-host>/ims/oneroster/rostering/v1p2/courses/<pilot-course-id>" } },
    "generated": { "extensions": { "pctCompleteApp": 100 } }
  }]
}

The percentage must be the number 100. The actor and course URLs must use the deployment's canonical API origin. Events must belong to the assignment's enrollment period, never before the pilot assignment or its enrollment began; future events, foreign producers, and event IDs reused with changed content are rejected. Event IDs are 1–255 characters. Only course completions (a numeric pctCompleteApp of 100 or more) for a live pilot that began before the event are withheld from ordinary routing; lesson-level Completed events and progress activity keep routing normally. Retry the same stable event ID after a network interruption. A 202 means the receipt is durable, not that the next action has finished.

OperationPurpose
GET /edubridge/progression/pilot-appsList registrations visible to the client.
GET /edubridge/progression/course-assignments?status=needs_attention&limit=100&offset=0Find owned assignments requiring intervention. Paginate until a page contains fewer than limit rows; maximum page size is 200.
GET /edubridge/progression/course-assignments/{id}Read the status, owner, last error, retry time, attempt count, prior enrollments, and verified destination receipt.
POST /edubridge/progression/course-assignments/{id}/retryAfter resolving the cause, restart retries. A missing completion remains a ready pilot and does not advance.
POST /edubridge/progression/course-assignments/{id}/exitSubmit { "reason": "Pilot ended early", "next": { "type": "course", "courseSourcedId": "<return-course-id>" } }. The exit next must be a return or replacement course or assessment; none is rejected. Also supports recovery from an idle failed transition. A leased transition or one with a delivered or unconfirmed assessment cannot be replaced.

The worker runs every minute and claims one pending assignment per invocation. A 17-minute lease fences workers whose maximum lifetime is 15 minutes. Failures retry with increasing delay, capped at one hour; eight attempts, including expired workers, require owner intervention. A destination course whose app cannot onboard its grade (Zearn K–3, Math Academy and Membean 4–12, Happy Numbers Pre-K, or an unreadable grade for any onboarding app) is rejected when the assignment is created. Destination access counts only when the app's onboarding confirms it: existing credentials, skips and failed provider answers are not access, and required credential writes and launch details (for example the Zearn class code) must succeed. Failures that retrying cannot change go to needs_attention immediately with the reason: a destination app that refuses or does not support the student (for example an unsupported grade), a definitive assessment rejection, a destination course the student has already completed, an assessment receipt issued for another assignment or graded before the pilot began, and a pilot course that became protected from automatic unenrollment. Reconciliation exposes completed percentages without an authenticated receipt, inactive pilot enrollments, and overdue reviews as needs_attention. It never invents a completion from an unauthenticated percentage. The producer must replay a missing completion through the authenticated endpoint.

If assessment delivery times out, the worker retains its dispatch intent and stops automatic re-creation. Inspect the provider first, then retry with { "assessmentAssignmentId": 123 }; the API verifies that exact student's subject, grade, and assessment type in TimeBack. Only after confirming that no assessment was created may an owner retry with { "confirmAssessmentNotCreated": { "reason": "Provider audit confirms no sitting was created" } }. That explicit confirmation is recorded. Never use it to bypass an uncertain response.

reviewAfterDays defaults to 7 and accepts 1–365. The owner must monitor assignment status and resolve overdue or failed work; storing an owner email does not send an email. An explicit retry of an overdue, unfinished pilot resets its review interval. Students whose next action is unavailable retain the pilot enrollment and its progress while recovery is pending.

Required Safeguards Against Stranded Students

Statuses are ready (pilot available), pending (completion or exit awaiting follow-up), retrying, needs_attention, completed (verified next work), exited (verified early-return work), and stopped (explicit subject completion). If a next step is unavailable, expose the reason and recovery state; do not claim successful progression or choose an unapproved substitute.

Release Verification

Before presenting this endpoint as available, demonstrate the complete student journey: register an app via API, assign its existing course with a next action, receive an authenticated completion, and verify the next work is available. Also verify two students sharing a course with different next actions, rejection of missing/invalid next actions without enrollment changes, replacement failure recovery, duplicate and delayed completion delivery, a next-step outage and safe retry, a completion discovered by reconciliation, and early exit with progress preserved.

8. Mastery & Progression

Canonical PK–2 Reading uses metadata.passed and its own runtime, including passes below 89.5%. Its placement, test-out and end-of-course outcomes follow the battery rules; the standard AlphaTest diagram below does not describe that route.

On the standard AlphaTest route, a student achieves mastery when their end-of-course test accuracy reaches 89.5% or higher (MASTERY_THRESHOLD = 89.5). At this point, handleEndOfCourseTestCompletion() calls the Course Sequence API (PowerPath V2) using the student's current course sourcedId to determine what comes next. The two-call pattern queries for the active sequence ID for the subject, then fetches all stages in that sequence, resolving the next stage relative to the student's current position.

The next stage can be one of three types: course (the student is enrolled in the next learning course), assessment (the student is assigned the next end-of-course test), or end of sequence (the subject is fully complete). For each course enrollment, handleCourseCompletion() monitors Caliper events for pctCompleteApp = 100 to detect when the student finishes the course, at which point the test is assigned and the cycle restarts.

A standard failed assessment normally selects remediation. The optional back-to-course rule below can instead return the student to unfinished official coursework. HF retests inherit the originating assessment type: placement, test-out, or end-of-course. Completing a small HF plan does not mean the official course is complete.

Optional return to unfinished coursework

For an enabled subject/grade cell and student, an existing hole-filling decision with a score below 80%, or a result from 80% to below 89.5% after an earlier small plan at the grade (not a self-elected test-out), can return the student to unfinished official coursework. An explicit provider pass is excluded. This does not change the 89.5% mastery threshold, reset completed lessons, or move an existing cohort automatically.

CaseBehavior with the rule enabled
Covered non-Math placement boundary or test-out, 59.5% to below 80%Return to unfinished coursework instead of HF.
Placement/test-out already selecting base courseworkExisting route. Math already selects base coursework for failing scores, subject to completion checks.
End-of-course failure below 80%Return only when required coursework remains unfinished.
All required coursework up to the assessment is completeKeep the existing remediation route; never reset finished work.
Score from 80% to below 89.5%, first small plan at the gradeKeep the existing route (a small plan).
Score from 80% to below 89.5% after an earlier small plan at the gradeReturn only when required coursework remains unfinished (one small plan only).
Self-elected test-out from 80% to below 89.5%, or a live custom plan at the gradeKeep the existing route.

Phase-tagged placements may first descend the assessment ladder; the override applies when the deciding failure boundary resolves. The destination uses the assessment's course and the student's course history before falling back to HF base metadata or the first course stage, then finds unfinished coursework. Pending/newer tests, scheduled personalized copies, and HF builds already underway can prevent a new move.

Switch appCovered cells
alpha_scienceScience G3–8; initial rollout only
zearnMath K–2
alphamathMath G3–4
math_academyMath G6–8
alphareadReading G4–12
vocablocoVocabulary G3–5
membeanVocabulary G6–12

These labels select subject/grade cells, not a dynamic course-provider check. Supported cells do not imply rollout validation. Other cells keep existing routing.

One small plan only: a failed placement, test-out or end-of-course result from 80% to below 89.5% (a hole-filling retest inherits its cycle's type) takes the same route when the child already began a small hole-filling plan at that subject and grade before the result was completed (enrolment history in any status, not this test's plan, not a custom plan). A first 80-89.4 keeps the small plan; a child holding a live custom plan at the grade, a self-elected test-out (by origin, whatever its test-type tag), and a result with no saved result to read (origin unknown), keep existing routing.

Deployment and activation are separate

The SSM String parameter /beyond/<prefix>/features/main/retest-back-to-course is off when missing, off, or none. Use alpha_science for the initial app rollout, or alpha_science,<student-uuid> for a narrower pilot. App names and student UUIDs may be comma-separated; UUIDs alone select those students across all covered cells. on enables every covered cell and student. Invalid values and switch-read failures disable new decisions; values are cached for 30 seconds. The repeat 80–89.4 rule also needs its own parameter, /beyond/<prefix>/features/main/retest-repeat-small-plan, with the same values; it is off by default (missing, empty, off, invalid or unreadable) and runs for an app only when both parameters are on for it. A third parameter, /beyond/<prefix>/features/main/retest-placement-exit, takes subject names in any case, student UUIDs, or both comma-separated (on alone enables every covered subject; on with UUIDs is invalid and reads as off): where it is on, a placement-built hole-filling plan retests as a test-out, so a pass enrols the next grade’s base course instead of assigning the next placement. It is off when missing, invalid or unreadable, and never covers Language G8+, Reading K-2, Science G6-7, Writing G8+, static plans or a guide’s custom plan. A plan built by a failed test-out retest of this kind is an ordinary test-out plan. When AlphaTest answers that it has no test-out at the grade (no active test, including its 500 “No active-sequence tests found”, or all forms used), the placement retest is issued instead.

The stack grants read access but does not create or overwrite the parameter. Deployment preserves an existing setting. Production deployment requires explicit human approval, and activation requires authorized operator action after validation. Turning the rule off stops new decisions after cache expiry; it does not undo previous moves.

Move recovery uses runtime-owned S3 receipts in the existing progression checkpoint bucket, expiring after 30 days. Finished receipts prevent the same result from reapplying a completed move and retiring later guide-assigned work. Enrollment metadata.routedBy is an audit label, not trusted routing state.

MasteryTrack dependency: eligible placements send result_available before analysis. Ordinary test-outs in the existing HF band (for example Science at 70%) normally still wait for gap analysis/DCAN before progression dispatch. Successful analysis can reach the course-return rule; analysis failure can delay it. Coordinated early handoff is a required, non-blocking follow-up and must preserve the rollout scope and completed-course remediation exception.

See the full routing and operations contract. This page describes supported behavior, not proof that the production switch is enabled.

flowchart TD TEST["End-of-Course Test Taken"] --> GRADE["Grading"] GRADE --> SCORE{"Accuracy\n>= 89.5%?"} SCORE -->|"Mastered"| NEXT["Query Course Sequence API"] NEXT --> STAGE{"Next Stage?"} STAGE -->|"Course"| ENROLL["Enroll in Next Course"] STAGE -->|"Assessment"| ASSIGN["Assign Next Assessment"] STAGE -->|"End of Sequence"| DONE(["Subject Complete!"]) SCORE -->|"Not Mastered"| RETURN{"Course-return rule enabled, score below 80%, unfinished work, and guards allow move?"} RETURN -->|"Yes"| RESUME["Resume Official Coursework"] RESUME --> LEARN RETURN -->|"No: existing remediation route"| GAP["Gap Analysis + DCAN + Hole-Filling"] GAP --> RETRY["Student Completes Remediation"] RETRY -->|"Caliper: 100%"| TEST ENROLL --> LEARN["Student Takes Course"] LEARN -->|"Caliper: 100%"| TEST
The Mastery Cycle

The mastery loop is self-healing by design: every completion event — whether from a base course, a remediation course, or a re-taken test — flows back through the same Caliper pipeline. The system always checks pctCompleteApp = 100 to trigger the next step, ensuring the cycle repeats automatically until the student achieves mastery or the subject sequence is exhausted. There is no hard limit on the number of remediation attempts.

Code: handleCourseCompletion() — student-progression-track.service.ts:285

student-progression-track.service.ts:285

TypeScript
public async handleCourseCompletion(caliperEvent: CaliperEvent): Promise<void> {
  const eventData = caliperEvent.data[0];
  const pctComplete = eventData.generated?.extensions?.pctCompleteApp;

  if (Number(pctComplete) !== 100) {
    console.log(`Course not yet complete (${pctComplete}%), skipping progression`);
    return;
  }

  const studentEmail = eventData.actor?.email;
  const courseUrl = eventData.object?.course?.id;
  let subject = eventData.object?.subject;

  // Normalize subject for Vocabloco: events may come with "Language"
  // but should use "Vocabulary" for progression routing
  const sensor = caliperEvent?.sensor;
  if (sensor === 'https://vocabloco.com' && subject.toLowerCase() === 'language') {
    subject = 'Vocabulary';
  }

  const courseSourcedId = this.extractSourcedIdFromUrl(courseUrl);
  const studentTimebackId = this.extractSourcedIdFromUrl(eventData.actor?.id);

  // Look up enrollment to determine if this is a base course or hole-filling course,
  // then route to handleCourseEnrollment (next course) or assign the end-of-course test.
}
Code: Math Pre-K EOC stop — gap-analysis/handler.ts

gap-analysis/handler.ts

TypeScript
const bypassResult = await shouldBypassGapAnalysis(config, assignmentId);

if (bypassResult.reason === BypassReason.MATH_PRE_K_EOC_REMEDIATION_UNAVAILABLE) {
  try {
    await GoogleChatNotificationService.getInstance().sendProgressionNotification({
      event: 'Math Pre-K End-of-Course Remediation Unavailable',
      assignmentId,
      nextStep: { action: 'Progression Stopped' },
    });
  } catch (notificationError) {
    console.error('Non-blocking: failed to send Math Pre-K alert', notificationError);
  }
}

return {
  success: true,
  data: { gapAnalysis: { bypassed: true, reason: bypassResult.reason } },
  progressionTriggered: false,
};

App Routing Matrix

The progression pipeline integrates external apps as core-course providers, assessment providers, hole-filling adapters, or onboarding-only destinations. Generic hole-filling adapters require an app account before assignments can be created. Canonical PK–2 Reading follows its battery runtime; legacy sequence-owned Reading work retains its compatibility contracts described below. Once a course is complete or an assessment is graded, Caliper events flow back into the pipeline and progression resolves the next sequence stage.

flowchart TD REC["Lesson Recommendations"] --> ONBOARD{"Student Account Exists?"} ONBOARD -->|"No"| CREATE["Onboarding API Call"] CREATE --> ASSIGN ONBOARD -->|"Yes"| ASSIGN["Create Resources in Adapter App"] ASSIGN --> COURSE["Create OneRoster Course"] COURSE --> ENROLL["Enroll Student"] ENROLL --> STUDENT["Student Takes Lessons"] STUDENT --> CALIPER["Caliper Events Received"] CALIPER --> MATCH["Match to Syllabus Resources"] MATCH --> XP["Award XP"] MATCH --> PCT{"All Resources Complete?"} PCT -->|"Yes"| COMPLETE["pctCompleteApp = 100%"] COMPLETE --> PROG["Trigger Progression"] PCT -->|"No"| STUDENT
SubjectGradesAdapter AppCaliper SensorRole
MathK-5Timebacktimeback.comHole-Filling
Math6-8Timeback LearnTimeBack / AlphaTestHole-Filling
Math9-11Ediaedia.appHole-Filling
Language/ELAK-2Lalilolalilo.comHole-Filling
Language/ELA3-10Frecklefreckle.comHole-Filling
Writing3-9AlphaWrite(self-emitted)Hole-Filling
Science3-8Existing sequence / Timeback LearnTimeBack / AlphaTest QTIBase + Hole-Filling
ReadingPK-2Alpha Phonicsphonics.schoolCore Course + PK-2 Battery Remediation
ReadingPK-2AlphaLiteracyscreeners.phonics.schoolAssessment (placement, test-out, end-of-course batteries)
ReadingPK-1Antonanton.appGeneric Hole-Filling (legacy Literably LSC remediation)
Reading2-8MobyMaxmobymax.com / nice.academyGeneric Hole-Filling (canonical PK–2 uses Alpha Phonics)
Language7MobyMaxmobymax.com / nice.academyCore Course
Vocabulary3-12VocabLocovocabloco.comHole-Filling
LanguageK-12 onboarding; Grade 8 completioneGUMPPelearning.egumpp.comOnboarding + Core Completion
Vocabulary4-12 onboarding; 6-12 completionMembeanmembean.comOnboarding + Core Completion
MathKMathQuestmath-quest.playcademy.ggCore Course
Math1-2; historical KZearnzearn.orgCore Course (K completion compatibility)
Math3-4Incept / AlphaMath (after coordinated activation)alphalearn.blu.schoolCore Course
Math5-12Math Academymathacademy.comCore Course

Alpha Phonics & Reading Screeners — Reading Grades PK-2

Core Course Assessment Hole-Filling ▸

Alpha Phonics owns the Reading PK–2 base and static hole-filling courses. The canonical Reading runtime selects published, grade-matched catalog courses owned by alpha_phonics. Placement, end-of-course and test-out outcomes have different routing rules, described below. Sequence references to Mentava, Alpha Reading Fluency and Anton remain relevant to historical work and the legacy route; they do not select current canonical PK–2 remediation.

PK–2 Reading Battery Runtime (current, no AlphaTest)

Since 2026-09-19 production runs with FF_READING_PK2_BATTERY_ONLY=true (CDK context readingPk2BatteryOnlyEnabled, api-2 #2146). GET /powerpath/placement/readingAssignmentPolicy returns {"schemaVersion":1,"scope":"global","subject":"Reading","gradeRanks":[-1,0,1,2],"batteryOnly":true}. While it is on, no native AlphaTest Reading test is assigned at PK, K, G1 or G2: native assignment guards refuse it, and a native PK–2 Reading result is kept as history only and never routes progression. PK–2 Reading placement, test-out and end-of-course are all AlphaLiteracy assessment batteries (source: "alphaliteracy-assessment", line items alphaliteracy-reading-pk-v1, -k-v1, -1-v1, -2-v1), and the canonical Reading runtime (src/modules/assessments/readingRuntime.service.ts) routes them. This restriction does not disable AlphaTest for Math or Language: their own eligibility and assignment rules still apply. FastMath keeps its separate app-reported-pass flow.

  • Decision field: the battery's metadata.passed (with masteredUnits 1 or 0) is authoritative. The 0–100 score is a display value (the lowest per-measure score, where exactly meeting a benchmark scores 80). It is not compared with 89.5%, so a pass can show a score of 80–89.
  • Placement: an unbounded failure descends to the next unresolved grade; an unbounded pass ascends to the next unresolved grade. A pass below an unresolved higher failure establishes that failed grade as the base-course boundary. If every grade fails through PreK, placement enrolls the PreK base course. A pass alone does not immediately enroll the next grade's base course. A passed Grade 2 placement hands off to a Grade 3 AlphaTest placement; a Grade 3 failure uses standard placement score bands, including hole-filling when applicable.
  • Course completion: an accepted completion of a current, canonical Alpha Phonics base or hole-filling course normally assigns or reuses the same grade's end-of-course battery. A qualifying migrated failed test-out from that same instructional episode can instead be routed first, as described below. Pending or newer work is preserved.
  • End-of-course / test-out pass: enrolls the next grade's Alpha Phonics base course. A Grade 2 pass enrolls the authored Grade 3 base course from the Reading sequence (currently Reading Primer Grade 3 in MobyMax).
  • End-of-course fail: an authoritative, current result enrolls that grade's Alpha Phonics hole-filling course, including PreK. Completing it normally assigns an end-of-course battery again.
  • Test-out fail: an ordinary failed test-out returns stale and preserves current work. The guarded historical exception requires an exact migration/supersession binding, no newer or conflicting pending work, and either explicit readingSource:null and no open instruction, or the sole bound current source already complete. That qualifying result can route to grade-matched hole-filling; if its source is unfinished, the same-episode completion path may consume it later. Remediation completion normally returns to an end-of-course battery, not another test-out.
  • Gates: a passed battery at grade X is Reading mastery of grade X for the Vocabulary, Science and Social Studies prerequisites. Grade 2 placement passes hand off to Grade 3 placement; authoritative Grade 2 end-of-course or test-out passes enroll the Grade 3 base course. Subject unlocks still require their other prerequisites and roster-grade gates; Social Studies diagnostic entry has additional school and academic eligibility rules.

Battery Passing Criteria

AlphaLiteracy owns the benchmarks in battery config and the pass/score evaluator. The table below was checked against source revision e0284843 on 2026-10-29. A battery passes only when every member passes. Members run in order, and the first failed member ends the sitting.

Battery gradeMembersPass requires
PreKLSC (letter-sound correspondence, K form, 60 s)≥ 20 of 26 letters correct
KNWF (nonsense word fluency)CLS ≥ 40 and WWR ≥ 4
Grade 1NWF, then ORFNWF CLS ≥ 60 and WWR ≥ 20; ORF ≥ 67 WCPM and ≥ 90% accuracy
Grade 2ORF (oral reading fluency)≥ 104 WCPM and ≥ 90% accuracy

CLS = correct letter sounds; WWR = whole words read; WCPM = words correct per minute. The Grade 1 NWF thresholds were lowered to 60/20 on 2026-10-14, and the ORF accuracy floor was set to 90% on 2026-09-07. If this table and the AlphaLiteracy config disagree, the config wins.

Course Completion Sensor

Alpha Phonics course events use https://phonics.school. Progression requires a canonical PK–2 catalog course, ActivityEvent with action Completed, and a finite generated.extensions.pctCompleteApp >= 100. Partial and unknown-course bundles stop before notifications or enrollment lookup. Recognized terminal completions use the native-completion enrollment bypass because the course enrollment may already have ended when the completion arrives.

Reading Screener Provider

In battery-only mode, the canonical runtime creates or reuses a pending AlphaLiteracy Assessment result in OneRoster. Placement, test-out, and end-of-course work use the same provider-facing contract and grade-specific line items. The separate FF_ARF_READING_SCREENERS provider switch belongs to the legacy non-placement screener route; it does not replace the battery-only policy. AlphaLiteracy discovers every pending generic row by the student's stable OneRoster ID and materializes it without branching on assessment purpose. No direct provider assignment request, separate onboarding, or Bridge job polling is required.

Provider-Visible Course and Opaque Progression Context

TimeBack stores courseSourcedId at the top level of result metadata so AlphaLiteracy can construct the completion event's course reference. TimeBack stores the assessment purpose in metadata.testType, as it does for AlphaTest. Trigger-course data, source-result provenance, and additional private routing data remain inside metadata.progressionContext. AlphaLiteracy preserves the enclosing metadata and adds outcome fields in its final write. It does not inspect or change the context. The completion event tells TimeBack to reread the result. TimeBack then reads metadata.testType to select placement, test-out, or end-of-course progression.

Replay-Stable Completion Event

AlphaLiteracy persists stable outcome and completion facts rather than a serialized copy of the complete event payload. After the final result PUT succeeds, it deterministically rebuilds every delivery attempt with the same event ID, object ID, event time, actor, top-level course, and outcome.

Compatibility Identifiers

The internal progression discriminator remains assessmentSource: "literably", and existing feature-flag names remain unchanged. New OneRoster rows use source: "alphaliteracy-assessment", alphaliteracy-assessment-result-* result IDs and the grade-specific line items listed above. Historical K–2 placement rows use alphaliteracy-reading-placement-k-v1, alphaliteracy-reading-placement-1-v1 and alphaliteracy-reading-placement-2-v1. Their alphaliteracy-screener-battery source and arf-screener-assignment-* completion objects are compatibility evidence, not identifiers for newly assigned batteries.

Failure and Retest Flow

Under the battery-only runtime, end-of-course failures route to grade-matched Alpha Phonics hole-filling; placement and failed test-outs follow their distinct rules above. Remediation normally ends in an end-of-course battery. On the legacy (pre-battery) route, a failed PreK letter-sounds result routed to Anton letter-block remediation and a failed K–2 ORF result to the Alpha Phonics hole-filling course selected by the sequence stage's learningAppId. Completing that course assigns another Reading screener. Students already in an Alpha Reading Fluency hole-filling course may finish and re-screen through the same route; the cutover changes new enrollment selection rather than moving active students mid-course.

Historical Provider Cutover Safety

The provider handover is a manual sequence cutover after the application, sensors, OneRoster reservation flow, Goals multi-reference handling, and catalog ownership migrations are deployed. The rollout creates and verifies a rollback draft, checks every target course, appends the new references without deleting historical ones, and confirms Alpha Phonics is newest before reporting success.

Historical Provider Activation Window

  1. Deploy the complete functional stack through the alpha_phonics catalog ownership migration. Deploying the sequence script alone does not activate the cutover.
  2. Set FF_ARF_READING_SCREENERS=true on the progression Lambda to move non-placement Reading screeners to OneRoster, and verify the deployment is healthy.
  3. Run scripts/alphaPhonicsSequenceUpdate without EXECUTE=true. Inspect the exact rollback draft and sequence PATCH bodies.
  4. Run the same script with EXECUTE=true, then verify the persisted active Reading sequence, new PK–2 assignments, and both legacy and new-provider completion handling.
Rollback is a three-part operation

Before activating the generated pre-AlphaPhonics draft, set FF_ARF_READING_SCREENERS=false and deploy the pre-cutover static Reading fallback from workflow/course-sequence/get-stages/sequence-data.ts. Then activate the saved draft and verify legacy assignment routing. The catalog ownership migration does not need to be reversed because the rollback sequence points to the untouched Mentava and Alpha Reading Fluency course IDs; the newly Phonics-owned course IDs are no longer canonical.

MobyMax — Language Grade 7 Core and Reading Grades 2-8 Remediation

Core Course Hole-Filling ▸

MobyMax supplies the Language Grade 7 core course and the generic Reading G2-8 remediation adapter. Canonical PK–2 battery routing bypasses that adapter and uses Alpha Phonics; existing MobyMax work and explicit generic course requests retain their own provider contract. The event processor also accepts historical Science and Language completions. Both Caliper sensors (mobymax.com and nice.academy) route to the same MobymaxEventProcessor.

Caliper Sensor

Sensors: https://www.mobymax.com/ and https://www.nice.academy. Both map to the same processor. Processor file: mobymax-event-processor.ts (605 lines).

Event Processor

Three-tier resource matching: Tier I — exact lesson_id match against mobymaxLessonId. Tier II — fk_strand_id + normalized title (exact then containment). Tier III — title-only fallback (replay mode). XP is awarded only when accuracy ≥ 80%. A zeroed copy of the original event is emitted to prevent double XP from the base course. If accuracy < 80% and the resource has a mobymaxLessonId, lesson reassignment is triggered.

Onboarding API

PropertyValue
EndpointPOST /api/mobymax-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload (hole-filling mode):

JSON
{
  "email": "student@school.org",
  "grade": 5,
  "subject": "science",
  "account": "mobymax"
}

Three onboarding modes remain for active and legacy MobyMax work: hole-filling, base course, and course enrollment. New Science G3-8 remediation uses Timeback Learn and does not onboard students to MobyMax. Science base courses remain on the existing active sequence until the separate AlphaScience cutover is verified and enabled.

Resource Matching

Events carry lesson_id, fk_strand_id, and a title. Resources in the OneRoster syllabus store mobymaxLessonId and fkStrandId metadata. Tier I matches on lesson_id — most reliable. Tier II narrows by strand then title. When multiple resources match, pickLowestSortOrder() selects the earliest unfinished attempt. Multi-assignment responses store per-assignment metadata for later Tier I/II matching.

Key Behaviors

When the separate AlphaScience base-course flag is enabled after sequence migration, G6-8 progression uses one five-course middle-school block: Engineering Design, Chemistry, Biology, Physics, and Earth and Space Science. Until then, the existing Science base sequence remains authoritative. Timeback Learn Science hole-filling creates a targeted first-party course by linking the recommended existing resources, including PP100 QTI quizzes. Language events are normalized to reading for legacy MobyMax enrollment lookup.

Freckle — Language/ELA Grades 3-10 & Math Grades K-2

Hole-Filling ▸

Freckle is a Renaissance platform app handling Language G3-10 and Math K-2 hole-filling. Caliper events arrive from https://freckle.com and are processed by FreckleEventProcessor. Freckle shares onboarding infrastructure with Lalilo via the shared RenaissanceOnboardingService. Resource matching uses a cascading assignment ID / launch URL / title lookup.

Caliper Sensor

Sensor: https://freckle.com. Processor file: freckle-event-processor.ts (365 lines). XP per lesson: Language = 10, Math = 5.

Event Processor

Three-strategy resource lookup cascade: 1st — metadata.freckleAssignmentId numeric match; 2nd — event URL or canonical URL (student.freckle.com/assignments/targeted/{id}/session); 3rd — title match ([Freckle] - activityName). The extractFreckleAssignmentId() utility normalizes three URL formats to handle event vs. syllabus format mismatch. If accuracy < 80% and the resource has an originalLessonId, FreckleService.recreateLesson() creates a new assignment at sortOrder + 1. partial_success is accepted as a valid job terminal status.

Onboarding API

PropertyValue
EndpointPOST /api/renaissance-onboarding
AuthCognito (x-amz-security-token header)
Activation~24 hours (Renaissance accounts need time to propagate)

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 5,
  "apps": ["freckle"]
}

Special case — ~24h activation delay: Freckle and Lalilo accounts take approximately 24 hours to activate after Renaissance onboarding. The progression pipeline excludes these from immediate retry on "Student not found" — the hole-filling retry mechanism re-enqueues with a delay to give the account time to propagate. Both apps can be onboarded in a single call: "apps": ["freckle", "lalilo"].

Resource Matching

Assignment IDs are extracted from three possible sources: extensions.assignment_id, parsed from the object.id URL pattern (/activities/{id}), or the numeric activity.name. The extractFreckleAssignmentId() function handles all URL format variants.

Key Behaviors

The former MobyMax Language base course (e111d2da-...) remains a historical compatibility reference. The current Grade 8 base course is canonical EGUMPP (81fd8ee2-...). For hole-filling courses, progression is always delegated to the hole-filling system. For base courses, pctComplete === 100 triggers progression directly.

Lalilo — Language/ELA Grades K-2

Hole-Filling ▸

Lalilo is a Renaissance Learning early literacy product handling Language/ELA in grades K-2. Only unit_type: 'mastery' events are processed — all practice and assessment events are skipped at the caliper-listener level before reaching the processor. Lalilo shares the RenaissanceOnboardingService with Freckle.

Caliper Sensor

Sensor: https://app.lalilo.com. Processor file: workflow/progression/shared/event-processors/lalilo.ts. Only unit_type === 'mastery' events pass the pre-filter in caliper-listener/index.ts. TimeSpentEvent types are also filtered out before the mastery check.

Event Processor

Direct-linked Bridge events are trusted when they carry component_resource_id, numeric pctCompleteApp, and an object.id that points to the same component resource. The event course must match the student's active Lalilo hole-filling enrollment. When the validated direct-linked event reports pctCompleteApp >= 100, progression is triggered immediately from the original event. Non-direct HF mastery events are suppressed, including events with app-reported pctCompleteApp >= 100. The processor no longer recomputes completion or emits supplementary Lalilo events.

Onboarding API

PropertyValue
EndpointPOST /api/renaissance-onboarding
AuthCognito (x-amz-security-token header)
Activation~24 hours (shared Renaissance activation delay)

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 1,
  "apps": ["lalilo"]
}

There is no dedicated LaliloOnboardingService — the shared RenaissanceOnboardingService handles it. Both Freckle and Lalilo can be onboarded in a single call.

Resource Matching

Matches direct events by component_resource_id and verifies the same id appears in the OneRoster component-resource URL in object.id. Legacy lesson_id-only HF events are suppressed for the active HF course instead of falling through as base-course completions.

Key Behaviors

Kindergarten grade format: The Lalilo bridge API rejects "Kindergarten" as a grade level; it must be mapped to 0/"K". Direct-linked events with mismatched course ids, invalid pctCompleteApp, or mismatched component-resource URLs are rejected.

Edia — Math Grades 9-11 (legacy G6-8 compatibility)

Hole-Filling ▸

Edia handles active Math remediation for grades 9-11. Math G6-8 moved to Timeback Learn, while delayed reports, retries, and stored Edia plans remain recoverable during the rollout compatibility window. It is the simplest adapter in the system — EdiaEventProcessor is just 64 lines and delegates most work to the shared supplementary course handler. Edia is unique in its sublesson granularity: each parent lesson is expanded into individual sublesson entries with IDs in the format parentLessonId.sublessonId.

Caliper Sensor

Sensor: https://edia.app (exact match). Processor file: edia-event-processor.ts (64 lines). Instantiated via HoleFillingEventProcessorFactory.

Event Processor

The processor checks if the incoming event is from a hole-filling course (via OneRoster metadata). For hole-filling courses, progression is suppressed on the original event — a self-emitted event with pctCompleteApp handles it. For supplementary (non-HF) courses, progression triggers directly when pctComplete === 100. No custom matching, reassignment, or XP manipulation logic.

Onboarding API

PropertyValue
EndpointPOST /api/edia-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 9
}

For hole-filling courses, the string "hole-filling" is passed as the grade. Response includes { userId, classCode, alreadyInClass, password, passwordSet }. Onboarding failures are non-blocking — errors are logged and a Google Chat notification is sent, but the hole-filling flow continues.

Resource Matching

Sublesson granularity: catalog sync expands each Edia parent lesson into individual sublesson entries (parentLessonId.sublessonId). During LLM recommendation validation, Edia uses the full sublesson ID format for the valid lesson ID set. The HoleFillingEventProcessorFactory routes app === 'edia' to EdiaEventProcessor.

Key Behaviors

Cognito token can expire mid-session. The onboarding service mitigates this with a single-retry pattern on 401/403, invalidating the cached token before retrying. The alreadyInClass response flag indicates the student was already enrolled — onboarding is idempotent.

VocabLoco — Vocabulary Grades 3-12

Hole-Filling ▸

VocabLoco is the adapter for Vocabulary hole-filling grades 3-12. Each VocabLoco lesson has 7 module types, with resources tracked by a composite lessonModuleId ({moduleName}|{lessonTitle} format). Events are matched using a three-tier fallback: exact match, deprecated module map (Learn It! → Flashcards), and normalized fuzzy title matching. Total XP per lesson: 35 (7 modules × 5 XP each).

Caliper Sensor

Sensor: https://vocabloco.com. Processor file: vocabloco-event-processor.ts (704 lines). Dedup composite key: activity_details.activity|activity_details.wordlist.

Event Processor

Tier 1 — exact lessonModuleId match. Tier 2 — deprecated module fallback via VOCABLOCO_DEPRECATED_MODULE_MAP (e.g., Learn It! was formerly Flashcards). Tier 3 — normalizeVocablocoTitle() fuzzy match: strips HF prefix from remediation wordlists, removes punctuation and standalone "and", collapses whitespace. Orphaned Flashcards resources are auto-completed with 0 XP when the corresponding Learn It! module is already done. XP awarded only when accuracy ≥ 80%.

Onboarding API

PropertyValue
EndpointPOST /api/vocabloco-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 7,
  "holeFilling": false
}

The Lambda logs into VocabLoco as a teacher, creates the student account, and assigns grade-appropriate word lists. Response returns { username, password, grade, timebackCredentialsSet }.

Hole-filling onboarding (holeFilling: true): only ensures the account exists (created with the supplied grade if missing) and assigns no word lists — existing word lists are left untouched (nothing is removed). The progression hole-filling flow sends this so the bridge can assign the HF lessons without grade-level word lists being layered on. assignedWordLists is empty under this mode.

Resource Matching

The 7 module types: Learn It!, Connect It!, Vocabulary Test, Practice Spelling Test, Spelling Quiz, Spell and Learn, Spelling Test. Events may report "Language" instead of "Vocabulary" — both normalize to vocabulary for enrollment matching. Completion is tracked by comparing total lessonModuleId set against the pending set, recalculated after orphaned flashcard auto-completions.

Key Behaviors

Historical bugs: VocabLoco renamed "Flashcards" to "Learn It!" — old syllabi still contain both. Fixed via deprecated module map + orphaned flashcard auto-completion. Remediation wordlists prepend "HF " to titles in VocabLoco, but syllabi store them without the prefix — fixed via Tier 3 normalized matching (PR #655).

Anton — Reading Grades PK-1

Hole-Filling ▸

Anton is the generic adapter for Reading hole-filling in grades PK-1, outside canonical battery routing. Current canonical PK–2 remediation uses Alpha Phonics. Each Anton lesson is decomposed into individual levels (sub-activities), each becoming a separate resource in the OneRoster syllabus tracked by a unique puid. Events are matched by comparing generated.extensions.puid against antonLessonId in syllabus metadata. XP is 3 per activity and is gated on whether the incoming event carries XP > 0 (not an accuracy threshold).

Caliper Sensor

Sensor: https://anton.app/. Processor file: anton-event-processor.ts (471 lines). Only ActivityEvent + Completed action events (isCompletionEvent()) reach the processor; TimeSpentEvent types are filtered out first.

Event Processor

Events carry puid in generated.extensions.puid. Matched against metadata.antonLessonId in syllabus resources. Anton zeros all metric items in the zeroed event (not just xpEarned like other adapters): xpEarned, masteredUnits, totalQuestions, and correctQuestions. Completion uses buildPendingSyllabus() with +1 race-condition adjustment.

Onboarding API

PropertyValue
EndpointPOST /api/anton-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 1
}

Grade conversion: K/KINDERGARTEN → 0; PK/PRE-K → -1. Response: { email, loginCode, newAccountCreated, timebackCredentialsSet }. Failures trigger Google Chat notification to both channels; onboarding is non-blocking.

Resource Matching

Lessons are expanded into level-based resources via buildAntonResourcesFromLessons(), querying lesson_catalog_embeddings for the selected lesson IDs. Each level in raw_content.metadata.levels becomes a separate resource with title [Anton] - ({level.title}) - {lessonName} and launch URL from ANTON_GRADE_CODE_MAP: e.g., https://anton.app/en_us/learn/ela-grade-1/{normalizedLevelPath}.

Key Behaviors

XP gating uses raw incoming XP value rather than accuracy threshold — trusts Anton's own completion logic. Grade PK maps to -1 which is within Anton's supported grade range. Reading Grade 2 routes to MobyMax, not Anton.

AlphaRead — Reading (Hole-Filling)

Hole-Filling ▸

AlphaRead is a reading content platform integrated into the Caliper Listener for hole-filling remediation. Unlike most adapter apps that have dedicated event processors in hole-filling-event-processor/, AlphaRead has no standalone event processor class. Instead, its completion tracking is handled directly by CompletionListenerService.handleAlphareadCourseCompletion() — the same service that handles Timeback course completion.

Caliper Sensor

Sensor: substring match — any URL containing "alpharead" (case-insensitive), identical to AlphaWrite's matching pattern. Processor: inline in handler.ts via handleAlphareadEvent() (lines 466-493). Only isCompletionEvent() events reach the tracking logic; TimeSpentEvent types are filtered out before processing.

Event Processor

No dedicated processor class. The handler loops over all events in the Caliper envelope. Self-emitted events are detected first via handleSelfEmittedProgression() — when pctCompleteApp >= 100, progression is triggered. Non-self-emitted completion events are delegated to CompletionListenerService.handleAlphareadCourseCompletion(), which calculates completion by comparing the course syllabus against the student's progress records, then emits a new Caliper event with pctCompleteApp. This emitted event re-enters the listener and is detected as self-emitted on the next pass.

Onboarding API

No dedicated onboarding endpoint. AlphaRead, like AlphaWrite, is a native Timeback app — students already have accounts. There is no AlphaReadOnboardingService.

Resource Matching

Completion is calculated via calculateAlphareadCompletion(): the service fetches the course syllabus resource IDs and the student's completed result IDs, then uses substring matching — a syllabus resource ID is considered completed if any completed result ID includes() it. A currentEventResourceId parameter handles the race condition where the triggering event has not yet been reflected in the progress API response.

Key Behaviors

AlphaRead shares the substring-based sensor matching pattern with AlphaWrite, but its processing logic is fundamentally different: AlphaRead does not perform XP negation or dual-event emission. It emits only one event (the pctCompleteApp completion event). AlphaRead relies on FIFO queue deduplication rather than CaliperDedupService. There is no subject filter — all AlphaRead events are processed regardless of subject.

AlphaWrite — Writing Grades 3-9

Hole-Filling ▸

AlphaWrite is the sole adapter for Writing remediation grades 3-9. Grade 9 includes the Sentences G9 base course, a Grade 9 Writing assessment and AlphaWrite hole-filling. The V1 sequence tail is controlled by WRITING_G9_SEQUENCE_ENABLED (writingGradeNineSequenceEnabled: true in checked-in production configuration); V2 uses its active authored sequence. This does not imply Grade 10–12 Writing support.

AlphaWrite has a unique dual-path XP model: The duplicate base-course award is set to 0 and hidden and re-credited to the hole-filling course via a self-emitted Caliper event. AlphaWrite uses substring sensor matching ("alphawrite" anywhere in the sensor URL) and is the only adapter that is a standalone processor — not in the HoleFillingEventProcessorFactory.

Standard-lesson backend fix live October 21, 2026; course counter pending confirmation

PR #2991 is deployed: TimeBack preserves AlphaWrite’s supplied XP and supports standard-lesson retries in the assigned hole-filling course. Historical records are being reconciled separately. The selected per-course discount policy below still requires AlphaWrite to confirm its counter implementation and effective date; deploying the backend fix does not change AlphaWrite’s calculation.

Caliper Sensor

Sensor: substring match — any URL containing "alphawrite" (case-insensitive). Processor file: alphawrite-event-processor.ts. AlphaWrite emits events directly to the Caliper endpoint using OAuth2 client credentials, bypassing CompletionListenerService.

Event Processor

Dual-path detection: If the student has an active hole-filling enrollment, Path 1 activates — emit zeroed original event (set duplicate XP to 0) + emit hole-filling credit event. If no HF enrollment, Path 2 activates — treat as base course, trigger progression when pctCompleteApp ≥ 100. Resource matching: standard resources match by launchUrl; essay resources (when object.id contains "compositions:") match by stage title ([AlphaWrite] - {stageName}) using the essay stage display name map: Setup, Outline, Draft, Revise, Polish. Only Writing subject events are processed. Events with source: 'hole-filling/supplementary adapter' are skipped.

Onboarding API

No onboarding required. AlphaWrite is a native Timeback app — students already have accounts. There is no AlphaWriteOnboardingService. The processor does not call any onboarding endpoint before processing events or creating courses.

Resource Matching

Standard resources: extract the resource ID from object.id, look up its launchUrl via OneRoster, and match against the full assigned syllabus, including previously attempted lessons. A failed attempt must not prevent a later passing attempt from reaching the same hole-filling lesson. Essay resources: detect object.id containing "compositions:", extract the stage (stage-draft etc.), map to the display name, and find the syllabus resource by title [AlphaWrite] - {stage}. Deduplication uses CaliperDedupService with a composite key including the original object.id.

Standard-Lesson Repeat XP

Count completed attempts separately for each student, assigned TimeBack course, and lesson. AlphaWrite calculates the award; TimeBack preserves the supplied xpEarned without removing or applying another discount. Accuracy eligibility and bonuses remain owned by AlphaWrite. Essay rules are unchanged.

Completion in this courseRepeat multiplierExample: 28 XP before the discount
First100%28 XP
Second50%14 XP
Third25%7 XP
Fourth and later0%0 XP

The example assumes accuracy qualifies. Failed completed attempts still consume a position and may earn 0 XP; redelivering the same completion does not consume another position. A different assigned course ID starts a fresh count for the lesson. Refreshing or recreating an enrollment for the same course ID does not.

Keep the original course context when correcting or redelivering a completion. The provider's generated.attempt and alphawriteLevelAttemptId remain stable result identities; the per-course discount count must not replace them. Retries retain separate results, so a later zero-XP completion cannot overwrite earlier credit. A lesson already recorded in course progress does not count as another completed lesson on a retry.

Read Credited XP

The integration reuses GET /ims/oneroster/gradebook/v1p2/assessmentResults with gradebook read permission. See the API reference for authentication, filters, and response fields. Always filter by the student and the provider completion ID; include the expected hole-filling assessment line item when known:

filter=student.sourcedId='STUDENT_ID' AND assessmentLineItem.sourcedId='HF_LINE_ITEM_ID' AND metadata.alphawriteLevelAttemptId='COMPLETION_ID' AND status='active'

URL-encode the filter when sending it. Verify the assessment line item belongs to the expected course and use the visible result's metadata.xp. The hidden native copy is not another award. If the line item is not known, resolve the returned line items to the expected course before selecting a result. Ambiguous matches need investigation, not summation. Once the result's sourcedId is known, it can be read directly at GET /ims/oneroster/gradebook/v1p2/assessmentResults/{sourcedId}.

Caliper processing is asynchronous. Show calculated XP as pending and poll with bounded backoff until the expected visible result exists. An empty response is pending or unresolved; only a saved result with metadata.xp: 0 confirms zero credit. Keep polling scoped to the student and completion, and stop when resolved or after a bounded retry window.

Verified October 21, 2026: AlphaWrite’s existing service client successfully read a credited retry through both the direct-result endpoint and the filtered collection, and resolved its line item. New standard-lesson hole-filling results retain the provider completion ID; older records may lack it. This verifies the existing access path, not every historical record or a latency guarantee. No permission change or new receipt endpoint is required for this verified path.

Rule Version and Change Notice

This section is the partner-facing reference for AlphaWrite's progression and repeat-XP rules. The selected policy date is October 19, 2026. The backend standard-lesson retry and XP-preservation fix became effective October 21, 2026; the AlphaWrite per-course counter effective date is pending confirmation. Before future scoring or event-contract changes, agree the effective date and send the rules, examples, and rollout order through the normal partner channel. This is not an automated notification subscription or a claim that notice has already been sent.

Key Behaviors

Duplicate native credit: a standard event with a metrics collection emits a clone with xpEarned = 0, hidden: true, and no pctCompleteApp. The removeNullValues utility strips all null fields before Caliper emission (API rejects null optional fields). Progression triggers only from the self-emitted hole-filling event reaching 100%, not the original base-course event. The TWR-methodology writing prompt (lesson_recommender_writing.ts) recommends lessons across sentence, paragraph, and composition levels.

eGUMPP: Language Grade 8

Core Course ▸

eGUMPP provides the Grade 8 Language core course. The onboarding service creates accounts, and a dedicated Caliper handler completes the approved deep-linked course after every resource in the student's TimeBack lesson plan has a result.

Caliper Sensor

https://elearning.egumpp.com. The handler requires a completed activity, the Bridge deep-link marker, an internal TimeBack component-resource URL, and course 81fd8ee2-14ad-45c4-bb09-5500bddbb157.

Event Processor

The handler verifies the canonical student, Language course, and active exact-course enrollment. It reads the student's lesson plan before the course syllabus and counts assigned component resources that have at least one TimeBack result. A lesson-plan dependency failure retries the event instead of falling back to the course syllabus. Scores do not affect completion. Shared Caliper ingestion normalizes the student's email before event bundling and FIFO partitioning. Vendor pctCompleteApp values do not trigger progression.

Onboarding API

PropertyValue
EndpointPOST /api/egumpp-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 8
}

No grade range validation — the grade is sent directly to the API without range checking. Response: { email, password, newAccountCreated, timebackCredentialsSet }. The timebackCredentialsSet flag indicates the bridge Lambda handles credential storage internally; the backend does not call UserCredentialsService. The OnboardingRouterService checks Timeback for existing eGumpp credentials before calling the API — onboarding is skipped if credentials already exist. Failures trigger a Google Chat notification titled "eGumpp Auto-Rostering Failed" and are non-blocking.

Resource Matching

The current event's component-resource ID counts immediately, which closes the normal result-write race. If one or two other results remain missing, the handler waits 30 seconds and reads progress once more. At full completion, it sends the standard internal course-completion command.

Key Behaviors

Any assigned Mastery Test part is required. The handler emits no additional Caliper event and stores no course percentage. Other eGUMPP courses remain outside automated progression.

Membean — Vocabulary Grades 4-12

Onboarding + Completion ▸

Membean is an external vocabulary platform for grades 4-12; the current completion-enabled courses cover grades 6-12. TimeBack handles their base-course completion events directly, while Vocabulary hole-filling still uses VocabLoco (grades 3-12). Membean onboarding accepts an optional student_id parameter for account linking.

Caliper Sensor

https://membean.com. A native ActivityEvent/Completed with finite pctCompleteApp >= 100 enters the dedicated Membean handler.

Event Processor

The listener binds the actor ID and email to one canonical user, requires an active enrollment in the completed course, and verifies the canonical course is Membean-owned Vocabulary with a supported grade shape before queueing normal course-completion progression. The legacy G6-12 course selects its assessment from highest grade mastered + 1; ordinary single-grade courses follow the course sequence.

Onboarding API

PropertyValue
EndpointPOST /api/membean-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 9,
  "student_id": "optional-external-id"
}

Grade range validation enforces 4-12: grades below 4 or above 12 cause onboarding to be silently skipped with a warning log. The optional student_id parameter is unique to Membean among all onboarding services. Response: { membeanStudentId, email, password, newAccountCreated, classId, className, timebackCredentialsSet }. Failures are logged, return null, and do not block progression.

Resource Matching

Not applicable — Membean completion routing is course-level and does not track individual resources.

Key Behaviors

The OnboardingRouterService checks Timeback for existing Membean credentials before calling the API. The timebackCredentialsSet response flag indicates the bridge Lambda handles credential storage — the backend does not call UserCredentialsService. Vocabulary hole-filling routes to VocabLoco, not Membean.

Zearn — Math Grades 1-2 and Historical K (Core Course)

Core Course ▸

MathQuest is the configured kindergarten Math provider; Zearn remains the provider for Math grades 1-2. Historical Zearn K completions remain accepted and route to the same existing G0 assessment. MathQuest uses the same shared core-course handler. Unlike supplementary hole-filling apps, Zearn events are handled directly in workflow/progression/caliper-listener/index.ts via the shared handleCoreCourseEvent function (also used by Math Academy) — there is no separate ZearnEventProcessor. When a student completes a Zearn core course at 100% pctCompleteApp, a progression message is sent to the student-progression SQS queue. The former Grade 3 course remains accepted as a completion alias for students already in flight.

Caliper Sensor

Sensor: https://www.zearn.org. Handled inline via handleCoreCourseEvent in workflow/progression/caliper-listener/index.ts. Events only processed if courseSourcedId is in the CORE_COURSE_FILTERS.ZEARN allowlist, including historical K and G3 course IDs. Pre-processing gates: TimeSpentEvent skipped; legacy dash student filter; enrollment gate.

Event Processor

No dedicated processor class. The shared handleCoreCourseEvent iterates the caliper bundle, requires ActivityEvent + Completed with numeric or string pctCompleteApp equal to 100, verifies courseSourcedId is allowlisted, and calls sendProgressionMessage(). Math K-2 hole-filling uses Timeback native content (not Zearn).

Onboarding API

PropertyValue
EndpointPOST /api/zearn-onboarding
AuthCognito (x-amz-security-token header)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 0
}

Special case — Grade K: Send 0 for both current_grade and target_grade when onboarding Kindergarten students. The convertGradeToNumber() method maps 'K'/'KINDERGARTEN' → 0 (valid range 0-3). Grade PK/PRE-K → -1 which falls outside the valid range and causes onboarding to be silently skipped. Response: { zearnStudentId, classroomId, classroomName, classCode, username, password, newAccountCreated, movedToNewClass }. Zearn provides its own custom credentials — the router calls UserCredentialsService.setUserCredentialsCustom() (not the standard method). The classCode is also stored in enrollment metadata (zearnClassCode) via the OneRoster API.

Resource Matching

Not applicable for hole-filling — Zearn is a core course app. Zearn core courses are pre-created in Timeback with specific courseSourcedId values allowlisted in CORE_COURSE_FILTERS.ZEARN.

Key Behaviors

MathQuest, Zearn and Math Academy share the same handleCoreCourseEvent function and core-course sensor routing branch in processCaliperEvent. Grade K must use numeric 0 — not the string "K" — in the onboarding payload. Zearn custom credentials differ from Math Academy which uses a shared default password.

Incept / AlphaMath — Math Grades 3-4 (Core Course)

Core Course ▸

Target state after coordinated activation: Incept is the sole active Math core-course provider for Grades 3 and 4. The sequence cutover ran as a one-shot final deployment stage, removed from the pipeline in 2026-08 after it completed in production (re-run it manually from the git history of scripts/inceptMathSequenceUpdate). Progression resolves the grade anchor, requests Incept enrollment, and verifies the personalized deep-linked Timeback base-course copy before publishing assignment completion.

Enrollment

New Grade 3 enrollments use KG course crs_GelkRHbO0B9p; new Grade 4 enrollments use crs_grade4_atom_native_v1. Both send diagnostics and TEKS enabled, and malformed flag values fail loudly. A persisted anchor/KG readiness check prevents the new payload from being sent before migration 0148 is visible. The explicit POST /edubridge/progression/onboard-student path accepts Incept only as the sole app and runs synchronously for grade 3 or 4.

Enrollment is idempotent. An active deep-linked personalized copy is reused. Automatic progression rechecks for asynchronously provisioned copies immediately before reactivation and compensates its own mutation if provisioning wins the race. Explicit onboarding reactivates history only when no competing active academic Math enrollment exists. A successful local reactivation does not call the Incept endpoint. Existing Grade 4 personalized copies retain their historical KG-course metadata until Incept performs the coordinated external switch.

Caliper Completion

Sensor: https://alphalearn.blu.school. Incept courses expand their syllabus dynamically, so resource-count snapshots are not authoritative. The dedicated handler triggers progression only for a completion event with finite pctCompleteApp >= 100, resolving Math from the personalized Timeback course when needed.

Legacy Compatibility

The former Zearn, Math Cakes, Math Academy, and standalone TEKS Grade 3/4 course IDs remain V1/V2 aliases. Existing students can complete those courses and resolve the same downstream assessment. New assignments select the Incept anchor only after the coordinated sequence cutover.

Coordinated Activation

  1. Confirm both Incept KG courses are live and enrollable and an exhausted-verification alert exists.
  2. Run the production deployment. CDK deploys the routing/readiness code, migration 0148_register_incept_math_g3_g4.sql registers and verifies both anchors and backfills personalized-course/enrollment metadata, and ECS then rolls out the runtime. The migration deliberately changes the live shared G4 anchor to the native KG id but leaves personalized copies unchanged.
  3. The cutover ran as a one-shot final deployment stage executing scripts/inceptMathSequenceUpdate/index.ts: it captured the current stage-ID snapshot, applied the G3/G4 cutover, re-fetched the active sequence, and failed the deployment unless the persisted anchors were current. Stage and script were removed from the repo after the cutover completed in production (2026-08).
  4. Verify persisted state and reconcile every assignment created during the final sequence-read/PATCH/verification window.
  5. Allow for normal attempt-2/3 asynchronous visibility; reconcile cutover and pre-existing missing-copy DLQ messages before selective redrive.
  6. Verify one retained-legacy completion per grade, then notify Incept to switch existing Grade 4 students.
Rollback requires the captured sequence snapshot

Never restore the captured stage array over a sequence that changed after cutover; manually merge only the G3/G4 write set while preserving unrelated stages. Otherwise PATCH with allowActiveStageRemoval=true and the exact current expectedCurrentStageIds, verify persisted state, and redeploy the prior application configuration. Because routing has no enablement flag, rollback must restore the legacy stages and prior application configuration together.

Math Academy — Math Grades 5-12 (Core Course)

Core Course ▸

Math Academy handles active core-course progression for Math grades 5-12. Like Zearn, events are processed inline in workflow/progression/caliper-listener/index.ts via the shared handleCoreCourseEvent function — there is no separate MathAcademyEventProcessor. Completion events require ActivityEvent + Completed, numeric or string pctCompleteApp equal to 100, and courseSourcedId in the CORE_COURSE_FILTERS.MATH_ACADEMY allowlist. After the coordinated G3/G4 activation, the former Grade 4 course remains accepted for in-flight completion and new Grade 4 assignments use Incept; before activation, the live sequence remains authoritative. Math Academy is core-only; downstream hole-filling uses native Timeback content for G4-5, Timeback Learn for G6-8, and Edia for G9-11.

Caliper Sensor

Sensor: https://mathacademy.com. App name mapping: math_academy in SENSOR_TO_APP. Handled inline via handleCoreCourseEvent. Only events where courseSourcedId is in that sensor’s core-course allowlist can trigger progression.

Event Processor

No dedicated processor class. Shared handleCoreCourseEvent handles MathQuest, Math Academy and Zearn. Pre-processing gates: TimeSpentEvent skipped; legacy dash student filter; enrollment gate. Math Academy is explicitly not in SUPPLEMENTARY_COURSE_FILTERS.ALLOWED_SENSORS.

Onboarding API

PropertyValue
EndpointPOST /api/mathacademy-onboarding
AuthCognito (x-amz-security-token header, auto-retry on 401/403)
ActivationImmediate

Payload:

JSON
{
  "email": "student@school.org",
  "grade": 9
}

Middle-school grades 6-8: Alpha Dash defaults all three grades to Prealgebra. Timeback therefore sends the exact 6th Grade Math and 7th Grade Math catalog overrides for the new G6/G7 sequence courses; G8 continues to use the grade-default Prealgebra course. G6/G7 onboarding is blocking and reruns on the already-enrolled retry path, so course assignment cannot complete without the vendor-side course selection.

High school grades 9-12: course_name is an optional override. When omitted, the course is resolved from grade — grades 9-12 default to the traditional track (9 → Algebra I, 10 → Geometry, 11 → Algebra II, 12 → Precalculus). When provided, it selects a matching Math Academy catalog course (e.g. an Integrated Math (Honors) or SAT course); an unrecognized value falls back to the grade default. Progression auto-assigns the traditional courses with grade alone. Grade range validation: 4-12; grades below 4 or above 12 are silently skipped. Response: { maStudentId, courseName, courseId, alreadyInCourse, newAccountCreated, password, passwordSet }. When passwordSet === true, the router calls UserCredentialsService.setUserCredentials() to store credentials in Timeback's userProfiles via OneRoster API.

Resource Matching

Not applicable for hole-filling — Math Academy is a core course app. Core courses are pre-created in Timeback; the 13 allowlisted courseSourcedId values in CORE_COURSE_FILTERS.MATH_ACADEMY determine which events trigger progression. The former shared Pre-Algebra Timeback ID remains a G6/G7 sequence alias for delayed completions and stays canonical for G8.

Key Behaviors

Historical bugs: incorrect course IDs in the core course filter (fixed PRs #229, #243). Onboarding uses CognitoAuthService with auto-retry on 401/403. The credential storage uses application name 'Math Academy' (a CredentialApplicationName union type). The G6/G7 sequence cutover must wait until the paired Alpha Dash enrollment and completion mapping rollout is live. Math Academy remains core-only; remediation follows the grade-band routing described above.

Test Types & Assignment

Every assessment in the system carries a test_type property that fundamentally determines how the student's score is interpreted and what happens next in the progression pipeline. There are three test types: placement, end of course, and test out. Each has different score thresholds, different gap analysis behavior, and different rules for whether the student receives hole-filling remediation.

Standard tests are authored and managed by AlphaTest, stored in the Timeback QTI 3.0 API. Canonical PK–2 Reading batteries are owned by AlphaLiteracy and use the OneRoster battery contract instead. The local test_inventory table provides a metadata index (name, subject, grade, version) that the progression pipeline uses to select which test to assign. Assignment happens via DeliveryService.assignTestByGrade(), which queries test_inventory, filters already-taken tests, and picks the first untaken test ordered by mt_order ASC.

Standards ownership: course-sequence assessment nodes select by subject, grade, and test type; they do not select a TEKS or CCSS variant. AlphaTest's test catalog and assignment configuration own the assessment content standard. The 2026-27 G6/G7/G8 Math sequence retains its explicit grade-specific TEKS course stages independently of that assessment-content choice.

Key Principle

The default classifier treats assessment types differently. On the current standard AlphaTest placement path, 89.5% separates mastery from failure evidence, but a failure descends to the next lower qualifying placement before any three-band route is applied. Once resolvePlacementResult identifies the placement boundary, its score selects base below 59.5% or hole-filling in [59.5, 89.5). Test-out uses those three bands immediately. Every standard non-passing end-of-course result uses hole-filling, regardless of how low the score is. Math G3-G12 placement boundaries and test-out results use explicit base-course exceptions; Math Pre-K uses that exception for test out and legacy untagged placement. The active Math sequence implements this policy through G11. Grade 12 returns 404 until its assessment stage exists. For Math Pre-K end-of-course failures, Course Sequence returns 409 remediation_unavailable; native progression returns remediation_unavailable and stops its retry check.

Outcome by Test Type and Score

The table below describes standard AlphaTest score routing. Canonical PK–2 Reading follows the battery rules above, and FastMath uses its app-reported verdict. "HF" means hole-filling remediation is assigned.

Test TypeScore RangeGap AnalysisHole-Filling?Outcome
Current standard AlphaTest placement (excluding FastMath)
Placement, descent in progress< 89.5%BypassedNoAssign the next lower unresolved qualifying placement with direction: "down"; do not jump to the floor or apply the failure band yet. An already-mastered target is credited and re-resolved.
Placement boundary< 59.5%BypassedNoEnroll directly in the base course at the lowest unresolved grade above mastery, or at the lowest failed qualifying grade
Placement boundary[59.5, 89.5)RunsYesGap analysis → DCAN → hole-filling at the boundary grade
Placement≥ 89.5%BypassedNoResolve the adjacent higher failure boundary; otherwise target the next higher placement grade. Not used for Reading PK–2 (AlphaLiteracy batteries).
Default test-out bands
Test Out< 59.5%BypassedNoEnroll directly in course at assessed grade
Test Out[59.5, 89.5)RunsYesGap analysis → DCAN → hole-filling
Test Out≥ 89.5%BypassedNoEnroll in the next-grade base course
Math placement-boundary and test-out exceptions
Placement boundary / Test Out, G3-G12 policy< 89.5%BypassedNoEnroll directly in the assessed-grade base course through G11. G12 returns 404 until its assessment exists.
Legacy untagged Placement / Test Out, Pre-K< 89.5%BypassedNoEnroll directly in the Pre-K base course
End of Course
End of Course< 89.5%RunsYesGap analysis → DCAN → hole-filling
End of Course, Math Pre-K< 89.5%BypassedNoCourse Sequence: 409 remediation_unavailable. Native result: remediation_unavailable. No course or enrollment is created, and the retry check does not run.
End of Course≥ 89.5%BypassedNoEnroll in the next-grade base course; use the next assessment when no course exists
FastMath placement exception

FastMath (Math Raiders) placement completions bypass the standard placement threshold rules above. They route through the Course Sequence API using the app-reported metadata.passedTest flag rather than the 89.5% score threshold. A pass advances to the next configured fluency assessment, which may remain in the same grade. A failure descends to the first placement assessment in the next configured lower grade; at the Kindergarten floor, it routes to the Kindergarten base course. When the lower grade is already mastered or becomes fully mastered, progression lands at the unresolved failed grade’s Math Raiders base course unless later mastery evidence has superseded that failure.

The shared default enrollment floor is 59.5%. PLACEMENT_BANDS temporarily exposes the same literal values to the AlphaTest CatalogSync parser, but Timeback runtime routing does not read that export.

Placement

Standard AlphaTest placement tests use the phase-tagged resolvePlacementResult flow. A score below 89.5% normally assigns the next lower unresolved qualifying placement while one remains. The worker does not jump to resolveSubjectLowestGrade(subject) and does not immediately apply the failed grade's score band. If the requested target is already mastered, the applier credits that evidence and re-resolves, so the visible movement can span multiple grades. A pass establishes mastery; an unresolved failure at the next qualifying grade above the highest mastery becomes the boundary and its score selects the assessed-grade base course below 59.5% or hole-filling in [59.5, 89.5). Otherwise the resolver assigns that next higher placement or completes at the ceiling. Reading PK–2 has no AlphaTest placement; it uses the PK–2 Reading battery runtime. FastMath placements are the separate app-reported-pass flow described above. Math G3-G12 placement boundaries select the assessed-grade base course. The active Math sequence implements this policy through G11. Grade 12 returns 404 until its assessment stage exists.

End of Course

Native progression classifies standard end-of-course failures locally. Every standard score below 89.5% runs gap analysis and selects hole-filling without a Course Sequence call. Math Pre-K returns remediation_unavailable, creates no course or enrollment, and stops the retry check. A direct Course Sequence request for this Pre-K result returns 409 remediation_unavailable. Standard passes route through Course Sequence, which selects the next-grade base course and falls back to the next assessment when no course exists. Canonical PK–2 Reading results use the Reading runtime described above, not Course Sequence. Legacy screener results and unknown-subject fallbacks retain their Course Sequence route. HS Language uses the shared raw 89.5% mastery boundary and keeps its lower-grade fallback.

Test Out

Test-out tests use the default placement bands, not the end-of-course rule. Scores below 59.5% select base, scores in [59.5, 89.5) select hole-filling, and scores at or above 89.5% select the next-grade base course. Math G3-G12 and Math Pre-K failures select base instead. The active Math sequence implements this policy through G11. Grade 12 returns 404 until its assessment stage exists. Every generated hole-filling course stores the grade and test type that triggered it, and completion assigns the next assessment with that same grade and type. Shared static courses on the legacy route carry the triggering type on the student's enrollment metadata instead; missing legacy type keeps the explicit end-of-course inference. These standard rules do not govern canonical PK–2 Reading: an ordinary failed battery test-out preserves work, and any qualifying Reading remediation normally completes into an end-of-course battery (see the battery runtime).

Test Type Chaining

Placement → Placement: Placement type is preserved through every route. Standard AlphaTest failures normally target the next unresolved qualifying grade until a pass or the lowest qualifying failure establishes the boundary. Unbounded passes normally target the next higher qualifying grade; already-mastered evidence can self-heal across multiple grades. Reading PK–2 placement is the AlphaLiteracy battery ladder instead. The initial no-RIT G3 floor is not reapplied.
Placement boundary → Hole-Filling → Placement: A boundary failure in the hole-filling band routes to remediation. The hole-filling course stores the triggering placement grade and test type, and its completion assigns a same-grade placement retest. Hole-filling is interstitial and never completes placement onboarding. The progression pipeline's own writers record completion only after successful or verified idempotent base-course enrollment, a pass at the verified assessment ceiling, a pass with no playable higher assessment whose specified next-course effect succeeds, or a pass in a sequence-managed subject whose Course Sequence response has no next stages.
Test Out → Test Out (standard route): Test-out type is preserved through generated hole-filling courses. Canonical PK–2 Reading is an exception: its remediation normally returns to an end-of-course battery.
End of Course → End of Course: End-of-course type is similarly preserved through hole-filling back to the next assessment.

Test Delivery

The DeliveryService (app/backend/services/delivery/delivery.service.ts, ~3,100 lines) is the central assignment manager. It owns the assignments table and exposes all operations for creating, transitioning, and invalidating assignments through a REST API Lambda under /delivery/.... A separate bulk-assign Lambda supports batch assignment for entire classes via Function URL (bypassing API Gateway's 29-second timeout).

Two primary entry points feed assignment creation: assignTestToStudent (manual teacher-initiated assignment by timeback_id or test_name) and assignTestByGrade (used by the progression pipeline and placement flow — queries test_inventory, filters already-taken tests from Timeback history and local tables, picks the first untaken test ordered by mt_order ASC). Both funnel through createAssignment(), which enforces DB-level uniqueness via two partial unique indexes: one per (user_id, subject, grade_rank) and one per (user_id, test_id), both excluding COMPLETED/ABANDONED/invalidated rows. Duplicate violations (PostgreSQL code 23505) return HTTP 409 with the existing assignment. Before every assignment, a mastery gate fires when origin=progression or Timeback assessment IDs are present — it queries assignments ⋈ results for the student's highest grade with score ≥ 89.5% and blocks re-assignment of already-mastered grades. Auto-save, pause/resume, and TTS/calculator metadata are preserved across all state transitions.

StatusTransition IntoImmutable?Key Side Effect
ASSIGNEDcreateAssignment()NoTimeback line item + result created
IN_PROGRESSstartAssignment() from ASSIGNED or PAUSEDNostart_time set on first entry; timeline event appended
PAUSEDpauseAssignment() from IN_PROGRESSNoFull AssessmentState saved to metadata
COMPLETEDcompleteAssignment() from any non-terminalYesend_time set; triggers grading pipeline
ABANDONEDabandonAssignment()YesNo metadata changes

Grading & Scoring

The three evaluation paths (standard synchronous QTI, async LLM writing, SpeechAce phonetic) are covered in Pipeline Stage 4. This section documents supporting infrastructure not detailed there.

Standards Runner enriches QTI test items with academic standards alignment. A runner Lambda queries test_inventory for active tests, dispatches one SQS message per test to a processor queue (standards-runner-processor-queue), and the processor Lambda fetches the corresponding Edulastic test via the PearDeck API, matches questions to QTI items by UUID, resolves each standard identifier through the CASE API, and writes updated alignment and learningObjectiveSet metadata back to the QTI item. Candidate resolution uses a two-step strategy: direct ID lookup via metadata.edulasticId, then name-search fallback with Jaccard word similarity (threshold ≥ 0.4). Failures land in a DLQ for investigation.

ScoreXP AwardFormula
100%Double XP + bonus2 × baseXp + 100
90–99%Double XP2 × baseXp
80–89%Base XPbaseXp
<80%Half XPround(baseXp / 2)
Repeat penalty: For 100-for-100 tests (fluency tests requiring a perfect score), each additional attempt multiplies the XP by 0.5^(attemptNumber − 1). Before applying the penalty, the system checks whether the student achieved mastery (≥89.5%) on any prior attempt. An optional xpMultiplier accommodation (set in assignment metadata) scales the final XP for students with IEP/504 plans.

Database & Storage

The primary data store is an Amazon RDS PostgreSQL 17.4 instance (t4g.medium, 40 GB encrypted, Multi-AZ in production, database name mastery_track). Application code accesses it through a PostgresDb singleton (app/backend/services/database/postgres-db.ts) wrapping the postgres.js library. The singleton supports separate primary (write) and read-replica connections via getSql(isReadOnly), with pool settings of max: 10, idle_timeout: 240s, and max_lifetime: 30min. Credentials are fetched from AWS Secrets Manager with a 15-minute cache. All DB calls are wrapped by runWithPostgresDbContextWithRetry() — up to 3 retries with exponential backoff (100 ms, 200 ms, 400 ms) on transient connection errors. A secondary MySqlDb singleton connects to the legacy Alpha platform database (alphaDb) via mysql2/promise.

S3 storage: The mastery-track-assets bucket (per-environment; prod-mastery-track-assets in production) stores all binary assets. Keys follow a {kebab-title}/{sha1(sourceUrl)}.{ext} scheme for deterministic deduplication. Large API responses exceeding ~5 MB are uploaded to S3 and returned as 1-hour presigned URLs. The insights-exports/ prefix holds PDF and CSV reports from the Insights Agent. pgvector is enabled on the lesson_catalog_embeddings table for hybrid BM25 + semantic search used by the DCAN service.

TablePurposeMigration
usersStudent and teacher records with clerk_id, student_id, email01
test_inventoryTest catalog with subject, grade, version, active status metadata02
assignmentsTest assignments to students; owns the delivery status lifecycle03
resultsTest results and scores (correct_questions, total_questions)04
assessment_responsesIndividual question-level responses, scores, and AI feedback06
gap_analysisGap analysis reports stored in a JSONB report column including DCAN recommendations20
caliper_event_dedupDeduplication fingerprints for Caliper events (one of four dedup layers)25
lesson_catalog_embeddingsVoyage AI embeddings + Claude pedagogical profiles for pgvector hybrid search29
insights_conversationsPersistent multi-turn chat history for the Insights Agent34
enrollmentsStudent course enrollments synced from Timeback OneRoster—

CDK Stack & Deployment

Infrastructure is defined as a single AWS CDK v2 (TypeScript) stack in iac/mastery-track-stack.ts (MasteryTrackStack). Three environments exist: dev (account 468627576959), staging and prod (both in account 742788239312, us-east-1). A resourcePrefix (e.g. prod-, dev-) namespaces all resources. Environment-specific values live in cdk.json context keys (vpc, subnets, secretsArn, clerkJwtPublicKey, etc.). App-level secrets (API keys, Clerk secret, Anthropic key, Voyage AI key) are fetched at runtime from Secrets Manager via CONFIG_SECRET_ARN — never baked into environment variables. A separate ClerkProxyStack deploys a CloudFront + API Gateway proxy for first-party Clerk cookie auth.

Lambda / FunctionTriggerTimeoutMemory
Authoring, Delivery, Gradebook, Parser, Reporting, UserMgmt, etc.API Gateway (addService pattern)29 s512 MB default
AI AuthoringAPI Gateway + self-invoke (async)15 min3 GB
CaliperListenerAPI Gateway POST29 s512 MB
StudentProgressionLambdaSQS (student-progression-queue)15 min1 GB
GapAnalysisLambdaSQS (gap-analysis-queue)15 min1 GB
CaliperProcessorLambdaSQS (caliper-events-queue FIFO)5 min512 MB
WritingEvaluationSQSSQS (writing-evaluation-queue)15 min1 GB
HoleFillingAgentTriggerSQS (hole-filling-agent-queue)1 min256 MB
CatalogSyncLambda + CatalogSyncWorkerEventBridge schedule (daily) + SQS15 min512 MB
StandardsRunnerLambda + ProcessorManual invocation + SQS15 min512 MB
InsightsAgentProcessorSQS (insights-agent-processor-queue)15 min1 GB
BulkAssign, LessonRecommender, ManualLessonsLambda Function URL15 min512 MB
MigrationLambdaManual invocation15 min512 MB
DCAN (ECS Fargate — AlphaTest service)HoleFillingAgentTrigger → RunTaskUnbounded4 vCPU / 8 GB
SQS QueueTypeDLQ
student-progression-queueStandardYes
gap-analysis-queueStandardYes
caliper-events-queueFIFO (content-based dedup)Yes — caliper-events-dlq
writing-evaluation-queueStandardYes
hole-filling-agent-queueStandardYes
catalog-sync-queueStandardYes
standards-runner-processor-queueStandardYes
insights-agent-processor-queueStandardYes

Notifications & Monitoring

Notifications: The GoogleChatNotificationService (app/backend/services/notifications/google-chat-notification.service.ts) dispatches structured webhook messages to six dedicated Google Chat channels: Progression (test assigned, course enrolled, hole-filling triggered), Language K-2 (Reading G2 guard notifications), DLQ (dead-letter queue items from student-progression, caliper-events, and gap-analysis queues), Hole-Filling (course creation success/failure per adapter app), DCAN (completion, non-retryable errors, #NoLessons alerts), and Exhaustion (student has taken all test versions for a grade/subject). A Slack fallback in app/backend/utils/retry.ts handles some progression events. The Caliper Listener includes a ProgressionTracker safety net that fires a "Missed Progression" DLQ + Google Chat alert when a 100% completion event fails to trigger progression without a known suppression reason (dedup, filter, no enrollment).

Insights Agent is a conversational AI assistant for educators, powered by Claude Sonnet with tool-use over real assessment data. An API request stores the user message and enqueues an SQS message; a processor Lambda runs the Claude tool-use loop asynchronously and the client polls for the result. Eight tools are available: get_student_gap_analyses, get_curriculum_gap_analyses, get_question_accuracy_by_standard, get_top_missed_questions, get_test_pass_rates, get_lowest_accuracy_tests, generate_report (PDF to S3), and generate_spreadsheet (CSV to S3). Conversations are persisted in the insights_conversations table, enabling multi-turn dialogues.

Catalog Sync is the lesson embedding pipeline that populates lesson_catalog_embeddings for DCAN's hybrid search. A dispatcher Lambda (triggered daily by EventBridge) iterates all adapter app / subject / grade combinations, fetches catalogs via HoleFillingAdapterService.getCatalog(), computes a SHA-256 content hash, and enqueues only changed lessons to the catalog-sync-queue. A worker Lambda enriches each lesson with a Claude Sonnet pedagogical profile (contextual summary, instructional objective, misconceptions, intervention type, data quality rating), generates a voyage-3-lite embedding via Voyage AI, and upserts the result into lesson_catalog_embeddings with a pgvector column. The DCAN service then uses this data to find the most relevant lessons for each diagnostic gap.