# Custom Hole-Filling Course - Agent Guide

This guide teaches you how to create custom hole-filling courses using the Timeback API. You are acting on behalf of an educator who wants to assign targeted remediation lessons to a specific student.

## Pilot enrollments into existing courses

The intended endpoint for pilot enrollments is **`POST /edubridge/progression/course-assignments`**, with the API title **“Assign a course with a completion action.”** It assigns an existing course and a required `next` action. This custom hole-filling guide instead covers creating a new course from selected lessons.

**Status: existing-course follow-ups verified in staging on October 29, 2026, including recovery and fixture cleanup. Production rollout and isolated end-to-end verification of native assessment delivery remain pending.** Use existing-course follow-ups for the initial pilot rollout and confirm availability in the intended environment before calling the new endpoint. The [Pilot Course Assignments section](https://api.alpha-1edtech.ai/docs/progression#pilot-course-assignments) defines the contract; the local source is [progression-pipeline-docs.html](./progression-pipeline-docs.html#pilot-course-assignments). The pilot API requires an `Idempotency-Key`, an `ownerEmail`, and an explicit `next` action. Its recovery contract includes:

- Use an existing tenant-bound service API client. Register the app and authenticated sensor owner through the API with administrator scope before pilot assignment. The existing course must be usable, and completion must follow the supported Caliper contract.
- Require an explicit next course, assessment, or intentional stop. A missing or invalid `next` must not silently stop progression. An intentional stop must have a reason and responsible owner, plus a continuation or return plan if subject work is still required.
- Store the next action on the student's assignment/enrollment, not the shared course. Do not change other students' progression by editing shared course metadata.
- Validate the pilot and next action before changing enrollments. Preserve prior progress and keep replacement recoverable if setup fails.
- Verify the next course or assessment is actually available after completion. An accepted or queued request alone is not success.
- Persist failures and recovery state, retry safely without duplicate assignments, and reconcile missing completion delivery. Unresolved transitions need a visible reason and responsible owner.
- Give early pilot exit an explicit return or replacement action; removing the pilot alone can strand the student.

## Safety Rules

**Before doing anything:**

1. **Ask the user for their API credentials** (Cognito client ID and client secret). Do not rely on credentials from a previous session - always confirm they are current. Never paste secrets into your final responses, never commit tokens or credentials to files, and never log them. Use environment variables or a local secret store when possible.
2. **Never execute a course creation request without showing the user the full payload first** and getting explicit confirmation.
3. **Always confirm the student email and lesson selection** with the user before proceeding.
4. **One student at a time.** Each API call creates a course for one student. If the user wants to create courses for multiple students, process them one at a time, confirming each.
5. **Always verify the course was created** after submitting the request. Don't assume success from a 202 response - poll until you see the course in the student's enrollments.

## Authentication

The API uses AWS Cognito OAuth2 client credentials. Ask the user for:
- `CLIENT_ID` - their Cognito app client ID
- `CLIENT_SECRET` - their Cognito app client secret

Get a token:

```bash
curl -s -X POST "https://prod-beyond-timeback-api-2-idp.auth.us-east-1.amazoncognito.com/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
```

Response:
```json
{
  "access_token": "eyJ...",
  "expires_in": 3600,
  "token_type": "Bearer"
}
```

Use the `access_token` as a Bearer token in all subsequent requests. Tokens expire after 1 hour - refresh when you get a 401.

> **Note:** The token URL above is for the production environment. If the user is working in a different environment, ask them for the correct token URL.

## Base URL

All endpoints use: `https://api.alpha-1edtech.ai`

## Step 1: Browse the Lesson Catalog

Before creating a course, you need to find the lesson IDs for the app and subject you want.

**Most apps** use the catalog endpoint. **Timeback**, **AlphaWrite**, and **Alpha Read** are exceptions - see Step 1b below.

### 1a. Catalog apps (MobyMax, Freckle, Edia, Lalilo, VocabLoco, Anton)

```bash
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/edubridge/progression/catalog?app=mobymax&gradeLevel=3&subject=reading"
```

#### Query parameters

| Parameter | Required | Description |
|-----------|----------|-------------|
| `app` | Yes | `mobymax`, `freckle`, `lalilo`, `vocabloco`, `edia`, or `anton` |
| `subject` | No | Filter by subject (e.g. `math`, `ela`, `reading`). Omit to see all. |
| `gradeLevel` | No | Filter by grade (e.g. `K`, `3`, `PK`). Omit to see all. |
| `page` | No | Page number (default: 1) |
| `limit` | No | Lessons per page (default: 100, max: 500) |

#### Response

```json
{
  "app": "mobymax",
  "lessons": [
    {
      "lessonId": "mobymax_reading_1654_g3",
      "lessonName": "Identify and explain personification",
      "subject": "reading",
      "gradeLevel": "3",
      "standards": ["RL.3.4"],
      "metadata": { "skillId": 1654, "domainTitle": "Reading Comprehension" }
    },
    {
      "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
  }
}
```

Use the `lessonId` and `lessonName` values from the response when creating the course. Use them exactly as returned - don't abbreviate, modify, or construct your own.

#### Which field to use as `lessonId`

| App | Use this as `lessonId` | Example |
|-----|----------------------|--------|
| MobyMax | `lessonId` from catalog | `mobymax_reading_1654_g3` |
| Freckle | `lessonId` from catalog | `FR-CCSS-2-W.6.3.d` |
| Edia | `lessonId` from catalog (the parent lesson ID, NOT sublesson IDs from metadata) | `middle_school.factors and multiples.factor_expressions` |
| Lalilo | `lessonId` from catalog | `1688` |
| VocabLoco | `lessonId` from catalog | `vocabloco_g1171_long_a_words` |
| Anton | `lessonId` from catalog (**group-level**, not individual levels — see Anton note below) | `c-nateng-1/79jgod` |
| Timeback | Component `sourcedId` (see Step 1b) | `0bbc6c14-d236-4764-884c-7c59c51fe1c2` |
| AlphaWrite | Reusable resource `sourcedId`, or final `alphawrite:hole-filling-essay` for G6–8 (see Step 1b) | `alphawrite-paragraphs-g7-identify-topic-sentence-resource` |
| Alpha Read | Resource `sourcedId` (the article ID) from component-resources (see Step 1b) | `article_4100001` |

> **Important for Edia:** The catalog may include `metadata.sublessons` - ignore these. Always use the top-level `lessonId`, not sublesson IDs.

#### Tips

- **Start broad:** Query with just `app` (no filters) to discover what subjects and grade levels are available. Use the `subject` and `gradeLevel` values from the response to filter.
- **Can't find a lesson?** Try removing the subject filter, or try a different grade level. Some apps organize content differently than expected.
- **Paginate through large catalogs:** Check `pagination.totalPages`. If there's more than one page, fetch subsequent pages with `page=2`, `page=3`, etc.
- **Lesson ID formats vary by app:**
  - MobyMax: `mobymax_reading_1654_g3`
  - Freckle: UUIDs or standard codes (`FR-CCSS-2-W.6.3.d`)
  - Edia: dotted paths (`middle_school.factors and multiples.factor_expressions`)
  - Lalilo: numeric IDs (`168`, `532`)
  - VocabLoco: structured IDs (`vocabloco_g1171_long_a_words`)
  - Anton: path-style IDs (`c-nateng-1/79jgod`) — **always use group-level IDs from the catalog, never individual level IDs** (see Anton note below)

#### Anton: Group lessons and automatic expansion

Anton lessons in the catalog are **groups** — each group contains multiple individual exercises (levels). When you create a course with Anton group IDs, the system automatically expands each group into its individual levels.

For example, the catalog lesson `c-nateng-1/79jgod` ("Reading - Strategies › Main Idea") expands into 6 individual levels:

| Level title | What it is |
|-------------|------------|
| Picture It | Practice activity |
| The Wizard and Daniel | Practice activity |
| Every Day Ideas | Practice activity |
| The Little Porcupine | Practice activity |
| At the Farm | Practice activity |
| Test | Mastery check |

So if you create a course with 9 Anton group lessons, the resulting course might have 50-60 individual resources (levels).

**Always use the group-level `lessonId` from the catalog** (e.g. `c-nateng-1/79jgod`), NOT the individual level IDs (e.g. `c-nateng-1/szv9k6`). The individual level IDs are not in the catalog and will be rejected.

How to tell the difference:
- ✅ **Group ID** (from catalog): `c-nateng-1/79jgod` — lesson name is a topic like "Reading - Strategies › Main Idea"
- ❌ **Level ID** (NOT from catalog): `c-nateng-1/szv9k6` — name includes a specific activity like "Reading - Strategies › Main Idea › Picture It"

If you have a list of level-specific names (like "Main Idea › Picture It", "Main Idea › The Wizard and Daniel"), find the **parent group** in the catalog instead. In this case, all the "Main Idea › ..." levels belong to the single group lesson "Reading - Strategies › Main Idea" (`c-nateng-1/79jgod`).

**Watch out for `metadata.levels` in the catalog response.** Each Anton lesson in the catalog includes a `metadata.levels` array that lists the individual levels inside the group:

```json
{
  "lessonId": "c-nateng-1/79jgod",
  "lessonName": "Reading - Strategies › Main Idea",
  "metadata": {
    "levels": [
      { "puid": "c-nateng-1/szv9k6", "title": "Picture It", "type": "normal" },
      { "puid": "c-nateng-1/oc7pkr", "title": "The Wizard and Daniel", "type": "normal" },
      { "puid": "c-nateng-1/shnynl", "title": "Every Day Ideas", "type": "normal" },
      { "puid": "c-nateng-1/ipkgdl", "title": "The Little Porcupine", "type": "normal" },
      { "puid": "c-nateng-1/f14mid", "title": "At the Farm", "type": "normal" },
      { "puid": "c-nateng-1/299u6h", "title": "Test", "type": "test" }
    ]
  }
}
```

**Do NOT use the `puid` values as lesson IDs.** The `metadata.levels` array is informational only — it shows you what the group contains so you can decide whether to include it. The system expands these automatically when you provide the top-level `lessonId`. Always use `lessonId` (`c-nateng-1/79jgod`), never `metadata.levels[].puid` (`c-nateng-1/szv9k6`).

### 1b. Timeback, AlphaWrite, and Alpha Read lessons

These apps don't use the catalog. Their lessons are existing OneRoster resources that you look up directly.

#### Timeback

For Timeback, lesson IDs are **component sourcedIds**. To find them, look at an existing Timeback course's components:

```bash
# Find existing Timeback hole-filling courses
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/?filter=metadata.primaryApp%3D'timeback'%20AND%20metadata.courseType%3D'hole-filling'&limit=5&sort=dateLastModified&orderBy=desc"
```

Response includes courses like:
```json
{
  "courses": [
    {
      "sourcedId": "cebb523b-3c47-4436-a37b-da853d56285a",
      "title": "[Timeback] Math G2 hole-filling",
      "metadata": { "primaryApp": "timeback", "courseType": "hole-filling" }
    }
  ]
}
```

Then get the component for that course:

```bash
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/components?filter=course.sourcedId%3D'COURSE_SOURCED_ID'&limit=1"
```

Response:
```json
{
  "courseComponents": [
    {
      "sourcedId": "0bbc6c14-d236-4764-884c-7c59c51fe1c2",
      "title": "[Timeback] Math G2 hole-filling - Component"
    }
  ]
}
```

The component `sourcedId` is the `lessonId` you pass to the course creation API. For `lessonName`, use the component's `title` (e.g. `"[Timeback] Math G2 hole-filling - Component"`). The system will use the actual resource titles when building the course, so the `lessonName` you provide is for reference only.

**Note:** passing a component ID links ALL resources under that component into the new course - it's a bundle, not a single lesson. You can verify what resources are under it:

```bash
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/component-resources?filter=courseComponent.sourcedId%3D'COMPONENT_SOURCED_ID'&limit=5"
```

Response:
```json
{
  "componentResources": [
    {
      "title": "Which metric unit of length is appropriate",
      "resource": { "sourcedId": "qti-test-which-metric-unit-..." },
      "sortOrder": 1
    }
  ]
}
```

#### AlphaWrite

For reusable AlphaWrite skill lessons (sentence, paragraph, and grammar practice), lesson IDs are **resource sourcedIds** directly. Use only reusable lessons from existing AlphaWrite courses:

```bash
# Find existing AlphaWrite courses
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/?filter=metadata.primaryApp%3D'alphawrite'%20AND%20metadata.courseType%3D'hole-filling'&limit=5&sort=dateLastModified&orderBy=desc"
```

Then get the component and its resources:

```bash
# Get the component
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/components?filter=course.sourcedId%3D'COURSE_SOURCED_ID'&limit=1"

# Get resources linked to that component
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/component-resources?filter=courseComponent.sourcedId%3D'COMPONENT_SOURCED_ID'&limit=10"
```

Response:
```json
{
  "componentResources": [
    {
      "title": "Identify Topic Sentences",
      "resource": { "sourcedId": "alphawrite-paragraphs-g7-identify-topic-sentence-resource" },
      "sortOrder": 1
    },
    {
      "title": "Elaborate on Paragraphs",
      "resource": { "sourcedId": "alphawrite-paragraphs-g7-elaborate-paragraphs-resource" },
      "sortOrder": 2
    }
  ]
}
```

Use the `resource.sourcedId` values as the `lessonId`, and the component-resource `title` as the `lessonName` (e.g. `"Identify Topic Sentences"`). The system uses the existing resource's title when building the course, so the `lessonName` you provide is for reference only.

##### Fresh essays (Writing grades 6–8)

Essay stages are **single-use**. Do not copy `alphawrite:compositions:*` catalog stages, `aw-hf-essay-*` stages, or UUID resources wrapping an essay into a custom plan, even if the student has not completed them yet. Inspect resource metadata as well as its ID: `originalLessonId`, nested `originalMetadata.isAWCompositions` / `essayId`, and `alphaWriteHoleFillingEssay` / `alphaWriteEssayBaseId` / `alphaWriteEssayStageId` identify essay resources. Copying them does not create fresh work.

For essay intent, include exactly one `alphawrite:hole-filling-essay` marker as the final lesson by `order`. It is valid only with `app: "alphawrite"`, `subject: "Writing"`, and grade 6, 7, or 8. Reusable skill lessons may precede it; a marker-only plan is also supported. The marker is an instruction, not a resource to fetch:

```json
{
  "studentEmail": "student@example.test",
  "subject": "Writing",
  "grade": "6",
  "app": "alphawrite",
  "lessons": [
    { "lessonId": "alphawrite:hole-filling-essay", "lessonName": "Fresh essay", "order": 1 }
  ],
  "next": "end of course"
}
```

Custom AlphaWrite plans support at most 100 lessons; resource admission reads have a 10-second deadline each. Enqueue rejects larger plans, recognizable essay-stage IDs, duplicate reusable lesson IDs, and invalid marker placement with HTTP 400. For custom plans, the builder validates queued requests before registration, course/resource writes, or enrollment changes. Retries first locate the existing course and reuse its linked resources; only missing lessons require new resource reads. A wrapped single-use essay rejects the entire plan with `alphawrite_build_failed` / `plan_validation`; it is not silently dropped from a partially accepted course. Ordinary resource lookup failures occur before registration as well. Native TimeBack custom Writing plans enforce the same single-use restriction on their resolved resources. Automatic AlphaWrite plans retain per-lesson failure and partial-success behavior.

TimeBack alone materializes the marker: it POSTs `{ "studentEmail": "…", "grade": 6 }` to the configured `ALPHAWRITE_HF_ESSAY_ENDPOINT` ending in `/register-hole-filling-essay`. The response must contain a `baseId` and exactly five ordered components (`id`, `url` or a shared registration `url`, `xp`; `title` is optional and defaults to the stage display name): Setup/identify (10 XP), Outline (50), Draft (25), Revise (25), and Polish (15), totaling 125 XP. Each component ID must begin with `baseId + ":"`. TimeBack validates launch URLs and the full stage contract, saves the registration in course metadata, and creates five resources and links. Enrollment is blocked if any requested stage or other resource fails to materialize. Existing resource XP and prior results are not rewritten.

**Retry boundary:** custom jobs use `customHfJobId` to find the same course and saved `alphaWriteHoleFillingEssayRegistration`; assignment/gap-analysis identities are fallbacks for non-custom builders. A retry with a saved registration reuses that essay and fills missing stages. A rejected legacy retry includes its existing course ID: reconcile that course and registration and recover the same job. A new custom POST creates a new job and is not a retry. Do not resubmit a successful marker request to retry enrollment.

The provider request currently carries **no idempotency key**. Existing transient-error handling retries network/timeouts and 5xx responses, and a transient course-persistence failure may occur before the registration is saved. In those windows (or a process crash between POST and persistence), another registration is possible; stored-course recovery is not end-to-end exactly-once registration. AlphaWrite/TimeBack Platform must agree on a stable request key and provider replay/lookup contract before that guarantee can be made (tracked in [edu-maintenance #1875](https://github.com/trilogy-group/edu-maintenance/issues/1875)). Reconcile ambiguous outcomes with the provider before any manual redrive. Never substitute a prior essay's stages or alter its earned credit as recovery.

#### Alpha Read

Alpha Read works exactly like AlphaWrite: lesson IDs are **resource sourcedIds** — the article IDs (e.g. `article_4100001`). Alpha Read only supports subject **Reading**. The article catalog lives in the base `Alpha Read - Grade N` courses, so find those by `primaryApp` (no `courseType` filter — the articles live on the base course, not a hole-filling course):

```bash
# Find Alpha Read courses (the "Alpha Read - Grade N" courses hold the full article catalog)
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/?filter=metadata.primaryApp%3D'alpha_read'&limit=20&sort=dateLastModified&orderBy=desc"
```

Then get the component (named `Reading Exercises`) and its resources (the articles):

```bash
# Get the component
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/components?filter=course.sourcedId%3D'COURSE_SOURCED_ID'&limit=1"

# Get resources linked to that component (the articles)
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/component-resources?filter=courseComponent.sourcedId%3D'COMPONENT_SOURCED_ID'&limit=200"
```

Response:
```json
{
  "componentResources": [
    {
      "title": "Excerpt from The Odyssey, Books 21–23 (The Return and the Bow)",
      "resource": { "sourcedId": "article_4100001" },
      "sortOrder": 1
    },
    {
      "title": "Excerpt from The Epic of Gilgamesh, Tablets I–II (The Coming of Enkidu)",
      "resource": { "sourcedId": "article_4100002" },
      "sortOrder": 2
    }
  ]
}
```

Use the `resource.sourcedId` values (the `article_*` IDs) as the `lessonId`, and the component-resource `title` as the `lessonName`. The system uses the existing resource's title when building the course, so the `lessonName` you provide is for reference only.

## Step 2: Create the Course

Once you have the lesson IDs, create the course. **Show the user the full request body and get their confirmation before sending.**

### Request

```bash
curl -s -X POST "https://api.alpha-1edtech.ai/edubridge/progression/custom-hole-filling-course" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "studentEmail": "student@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"
  }'
```

### Required fields

| Field | Type | Description |
|-------|------|-------------|
| `studentEmail` | string | The student's email address |
| `subject` | string | One of: `Math`, `Language`, `Reading`, `Writing`, `Vocabulary`, `Science` (capitalized - note the catalog returns lowercase like `reading` or `math`, so capitalize the first letter when building the course creation request) |
| `grade` | string | Grade level: `PK`, `K`, or `0`-`12` (aliases like `Kindergarten` also accepted). This is required - ask the user which grade the course is for. It should typically match the `gradeLevel` of the lessons you selected from the catalog. |
| `app` | string | The learning app (must match the catalog you browsed) |
| `lessons` | array | At least 1 lesson. Each needs `lessonId`, `lessonName`, and `order` (1-based display order - determines the sequence the student sees). Optionally include `xp` (see below). |
| `next` | object or legacy string | What happens after the student completes the course (see below) |

### The `xp` field (optional)

Each lesson can include an optional `xp` value (positive integer) to override the app's default XP-per-lesson.

```json
{ "lessonId": "mobymax_reading_1654_g3", "lessonName": "Identify and explain personification", "order": 1, "xp": 15 }
```

**Behavior by app:**
- **MobyMax, Freckle, Edia, Lalilo:** XP is applied to each generated resource. If omitted, the app's default is used.
- **Anton:** One group lesson expands into multiple individual levels. The XP you provide is divided equally across the expanded levels (minimum 1 XP per level). For example, if `c-nateng-1/79jgod` expands into 6 levels and you set `xp: 12`, each level gets 2 XP. If omitted, each level gets the app default (3 XP).
- **VocabLoco:** One lesson expands into multiple activities. The XP you provide is divided equally across them (rounded to nearest integer). For example, `xp: 35` on one lesson with 7 activities = 5 XP per activity.
- **Timeback, AlphaWrite, and Alpha Read:** XP is **ignored**. These apps link existing resources that already have their own XP assigned - it cannot be overridden.

If you don't need to override XP, simply omit the field - the system uses sensible defaults for each app.

### The `next` field

This controls what happens after the student finishes the course:

- `"end of course"` - assign an end-of-course assessment test
- `"test out"` - assign a test-out assessment
- `"placement"` - assign a placement test (reserved for new incoming students to find their ideal level)
- A course sourced ID - enroll the student directly in that specific course. **The sourced ID must belong to a course in the active course sequence for the subject.** See "Finding a valid course sourced ID" below.

Both APIs share the structured course and assessment contract:

```json
{
  "type": "assessment",
  "subject": "Vocabulary",
  "grade": 4,
  "testType": "end of course",
  "timebackId": "_test-selected-vocabulon"
}
```

`timebackId` is optional. When present, only that active, supported, assignable test may be delivered; no grade-based substitute is used. Subject and grade must match the hole-filling plan. The test need not belong to the active grade sequence. Existing string inputs remain compatible, including aliases such as `EndOfCourse` and `test-out`. `{ "type": "course", "courseSourcedId": "..." }` retains hole-filling's active-sequence validation. The owned `none` action is pilot-only; remediation must lead to work.

The structured assessment is preserved in the queue and course metadata, including retries. A retry that resumes a course with a different saved target is rejected before enrollment; omit `assignmentId` to create a fresh plan. Most common legacy choice: `"end of course"`.

### Finding a valid course sourced ID for the `next` field

If the user wants to enroll the student in a specific next course instead of assigning a test, you need to find a valid OneRoster course sourced ID from the active course sequence. Sourced IDs are opaque strings and are not required to be UUIDs. The API validates the ID server-side and rejects courses that aren't in an active sequence.

**Step 1: Get the active course sequence for the subject**

```bash
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/powerpath/course-sequence?status=active&subject=Reading"
```

Response:
```json
{
  "items": [
    {
      "id": "seq-abc-123",
      "subject": "Reading",
      "status": "active"
    }
  ]
}
```

**Step 2: Get the stages for that sequence (optionally filtered by grade)**

```bash
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/powerpath/course-sequence/seq-abc-123/stages?limit=200&grade=3"
```

Response:
```json
{
  "stages": [
    {
      "id": "stage-1",
      "type": "course",
      "title": "G3 Reading Course",
      "properties": {
        "courseReferences": [
          {
            "courseId": "8cf5f85e-3efc-425a-af0b-a2be695ee4bd",
            "refAddedAt": "2026-01-15T00:00:00Z"
          }
        ]
      }
    }
  ]
}
```

**Step 3: Pick the course sourced ID**

For each stage, look at `properties.courseReferences`. If there are multiple references, use the one with the most recent `refAddedAt` - older references are historical/swapped-out courses that the API will reject.

Use the `courseId` value as the `next` field in your course creation request.

> **Note:** If a stage has no `courseReferences`, the `stage.id` itself may be the course ID (this is a fallback for older sequences). You can also browse sequences in the <a href="https://api.alpha-1edtech.ai/scalar/#powerpath-api/tag/powerpath-course-sequence/GET/powerpath/course-sequence/">Scalar PowerPath API docs</a>.

### Optional fields

You almost never need these - omit them unless the user specifically asks. They are auto-resolved or only relevant for advanced tracking.

| Field | Type | Description |
|-------|------|-------------|
| `assignmentId` | number | AlphaTest assignment ID (auto-resolved from enrollments if omitted) |
| `baseCourseSourcedId` | string | Base course for lineage tracking (auto-resolved from enrollments if omitted) |
| `gapAnalysisId` | string | Gap analysis record ID (for tracking only) |
| `missedQuestions` | string[] | List of missed question IDs (for tracking only) |

### Response (202 Accepted)

```json
{
  "jobId": "8cf5f85e-3efc-425a-af0b-a2be695ee4bd",
  "message": "Custom HF course creation started"
}
```

The course is created asynchronously. You must verify it was created - see Step 3.

### Restrictions

- **One app per course.** All lessons must come from the same app.
- **One student per call.** To create courses for multiple students, make separate requests.
- **AlphaWrite only supports Writing.** If `app` is `alphawrite`, `subject` must be `Writing`.
- **Alpha Read only supports Reading.** If `app` is `alpha_read`, `subject` must be `Reading`.
- **Lessons must exist in the catalog** (or in OneRoster for Timeback/AlphaWrite reusable skills/Alpha Read). The AlphaWrite fresh-essay marker is the exception; never substitute existing essay stages.
- **Course sourced ID `next` must be in the active sequence.** If the user provides a course sourced ID for `next`, it must be a current course in the active course sequence for the subject. The API rejects IDs not in a sequence. See "Finding a valid course sourced ID" above.

## Step 3: Verify the Course Was Created

**Important:** A 202 response means the request was accepted, NOT that the course exists yet. You must verify.

### Polling for completion

After submitting the request, poll the student's enrollments until the NEW course appears. Here is the exact polling logic to follow:

1. **Record the current time** before making the course creation request (ISO 8601 string)
2. Get the student's `sourcedId` (once, before the loop)
3. Every 60 seconds, check the student's enrollments for a course with `metadata.customHF: true` AND `dateLastModified` after your recorded start time
4. If found, stop - the course was created successfully
5. If not found after 10 attempts (10 minutes), stop and report failure

> **Why check `dateLastModified`?** The student may already have custom HF courses from previous sessions. Filtering by time ensures you only detect the course you just created, not an old one.

```bash
# 0. Record the start time BEFORE creating the course
START_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# ... (create the course here - Step 2) ...

# 1. Get the student's sourcedId (you only need to do this once)
STUDENT_ID=$(curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/students/?filter=status%3D'active'%20AND%20email%3D'student%40alpha.school'" \
  | jq -r '.users[0].sourcedId')

# 2. Poll loop - check every 60 seconds, up to 10 times
for i in $(seq 1 10); do
  RESULT=$(curl -s -H "Authorization: Bearer YOUR_TOKEN" \
    "https://api.alpha-1edtech.ai/edubridge/enrollments/user/$STUDENT_ID" \
    | jq --arg start "$START_TIME" '.data[] | select(.course.metadata.customHF == true and .course.dateLastModified > $start) | {courseId: .course.sourcedId, title: .course.title, app: .course.metadata.primaryApp}')
  if [ -n "$RESULT" ]; then
    echo "Course found:"
    echo "$RESULT"
    break
  fi
  echo "Attempt $i/10 - course not yet created, waiting 60 seconds..."
  sleep 60
done
```

If after 10 minutes the course doesn't appear, tell the user to check Google Chat for failure notifications or contact the engineering team.

### Google Chat notifications

Notifications are also sent to the same Google Chat channels used by the standard progression pipeline:
- ✅ **"Custom HF Course Created"** - success, includes the course ID, resource count, and enrollment ID
- ⚠️ **"Enrollment Failed"** - course was created but enrollment had issues. Includes details on what went wrong and any courses that were restored.
- ❌ **"Custom HF Course Failed"** - the job failed after retries. Includes the error and number of attempts.

### Inspecting the created course

Once you have the `courseSourcedId` (from the enrollment check or the notification), you can inspect it:

```bash
curl -s -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/courses/COURSE_SOURCED_ID"
```

Look for these fields in the response:
- `metadata.customHF: true` - confirms it's a custom hole-filling course
- `metadata.primaryApp` - the learning app
- `metadata.next` - what happens after the student completes it
- `metadata.metrics.totalLessons` - number of lessons in the course

## What Happens Behind the Scenes

When you create a custom hole-filling course, the system:

1. **Looks up the student** by email in OneRoster
2. **Creates assignments** in the target learning app (MobyMax, Edia, etc.). For Timeback, AlphaWrite reusable skills, and Alpha Read, it links existing resources. An AlphaWrite fresh-essay marker instead registers one new essay and materializes its five stages. For Anton, it first creates assignments in Anton, then expands each group lesson into individual levels before building the course.
3. **Creates a course** with all the lessons as resources
4. **Removes the student from existing same-subject courses** - but protected courses like Manual XP and class enrollments are always kept
5. **Enrolls the student** in the new course

If the student doesn't have an account in the learning app, the system automatically tries to set one up first.

If enrollment fails after removing old courses, the system automatically restores the removed courses so the student is never left without a course.

## Error Handling

| Error | What it means | What to do |
|-------|--------------|------------|
| 400 | Invalid request (bad email, unsupported app, invalid grade, etc.) | Read the error message and fix the request |
| 401 | Token expired or invalid | Get a new token (see Authentication) |
| 202 then no course after 10 min | The job likely failed | Check Google Chat for failure notifications |
| 202 then ⚠️ notification | Course created but enrollment failed | The course exists but the student isn't enrolled. May need manual enrollment. |
| 202 then ❌ notification | The job failed | Check the notification for the specific error |

## Example: Full Workflow

Here's a complete example creating a MobyMax Reading course for a 3rd grader:

```bash
# 1. Get auth token
TOKEN=$(curl -s -X POST "https://prod-beyond-timeback-api-2-idp.auth.us-east-1.amazoncognito.com/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \
  | jq -r '.access_token')

# 2. Browse catalog for MobyMax Reading G3 lessons
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://api.alpha-1edtech.ai/edubridge/progression/catalog?app=mobymax&gradeLevel=3&subject=reading&limit=10" \
  | jq '.lessons[] | {lessonId, lessonName}'

# 3. Record start time, then create the course (CONFIRM WITH USER FIRST)
START_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
curl -s -X POST "https://api.alpha-1edtech.ai/edubridge/progression/custom-hole-filling-course" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "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 },
      { "lessonId": "mobymax_reading_488_g3", "lessonName": "Analyze how stanzas build on each other", "order": 3 }
    ],
    "next": "end of course"
  }'

# 4. Poll for completion (every 60 seconds, up to 10 minutes)
STUDENT_ID=$(curl -s -H "Authorization: Bearer $TOKEN" \
  "https://api.alpha-1edtech.ai/ims/oneroster/rostering/v1p2/students/?filter=status%3D'active'%20AND%20email%3D'jane.doe%40alpha.school'" \
  | jq -r '.users[0].sourcedId')

for i in $(seq 1 10); do
  RESULT=$(curl -s -H "Authorization: Bearer $TOKEN" \
    "https://api.alpha-1edtech.ai/edubridge/enrollments/user/$STUDENT_ID" \
    | jq --arg start "$START_TIME" '.data[] | select(.course.metadata.customHF == true and .course.dateLastModified > $start) | {courseId: .course.sourcedId, title: .course.title}')
  if [ -n "$RESULT" ]; then
    echo "Course created successfully:"
    echo "$RESULT"
    break
  fi
  echo "Attempt $i/10 - waiting 60 seconds..."
  sleep 60
done
```
