Files
classroomio/prd/exercise-question-types [DONE]
Rotimi BestRotimi Bestgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>Cursor AgentAbdulmuizz HamzatAdeyemi Adetunji
1e9a82e912 feat: complete rewrite of course (#622)
* theming improvements

* border style improvements

* refactor: migrate org routes to server-side data fetching

Move client-side API calls to server-side load functions for better
performance, security, and SEO. Implement permission-based course filtering

* refactor: clean up course and community components

This commit removes unused components and files related to courses and community features, streamlining the codebase. It also updates various routes to enhance performance and maintainability. Additionally, it introduces new types and constants for better type safety and organization.

* refactor: fix video formatting on website and other styles

* refactor: update course and dashboard components for improved styling and functionality

* more icon improvements

* refactor: streamline course and dashboard components

This commit updates various course and dashboard components for improved styling and functionality. It includes the removal of unused files, updates to imports and exports, and enhancements to type safety. Additionally, it introduces new routes and optimizes existing ones for better performance and maintainability.

* refactor: enhance lesson completion logic

* chore: delete all emails on dashboard and move other api routes to backend.

move all emails to the backend and

* feat: Refactor API and database queries for courses, quizzes, and lessons, migrating Supabase functions and schema management.

* get app loading

* fix ui and build error of cio/api

* refactor: move direct database queries to query layer

- Create query functions: getCourseWithOrgData, getOrganizationByCourseId, updateCourseVersion, updateLessonsSectionId, getProfileByGroupMemberId, getQuestionTypesByIds
- Refactor services to use query functions instead of direct db queries
- Add transaction support to updateCourseVersion and updateLessonsSectionId
- Fix getProfileByGroupMemberId to return profile directly (not nested)
- Fix updateLessonsSectionId to use .returning() instead of rowCount

This aligns services with architecture pattern where services orchestrate queries rather than executing them directly.

* exercise saving improvements

* fix and optimise exercise creation

* refactor: update dialog components for improved styling and functionality

- Adjusted dialog content width and maximum constraints for better responsiveness.
- Changed heading font size for consistency in the new exercise modal.
- Replaced CloseIcon with CrossIcon for a more modern appearance in dialog close button.

* refactor: enhance course and exercise management components

- Introduced new components for exercise creation, editing, and viewing, improving user experience.
- Refactored existing lesson and exercise components for better organization and maintainability.
- Updated routing for exercises and lessons to streamline navigation within the course structure.
- Added new utility functions and constants to support content management across the application.

* feat: implement course content management API and UI components

- Added new API routes for updating and deleting course content, enhancing content management capabilities.
- Introduced new Svelte components for displaying and managing course content, including content lists and action handlers.
- Updated existing course routing to integrate new content management features.
- Refactored content-related utility functions for improved organization and maintainability.

* refactor: remove Supabase references and implement course section management

- Removed Supabase-related environment variables and Dockerfile arguments to streamline configuration.
- Introduced a new section management API with routes for creating, updating, deleting, and reordering course sections.
- Updated course services to handle section operations, ensuring consistency in course content management.
- Refactored existing lesson section logic to align with the new course section structure, enhancing maintainability.

* chore: update .prettierignore to exclude additional file types

- Added exclusions for SQL and environment files to the Prettier ignore list.
- Included Dockerfile and .prettierignore itself to prevent formatting issues.

* feat: enhance course content management with translation support and UI improvements

- Added translation keys for user-facing text in course-related components, ensuring all UI copy is sourced from translation files.
- Updated lesson and exercise creation components to utilize translation keys for success and error messages, improving localization.
- Refactored course content management components to streamline the creation and editing process, enhancing user experience.
- Introduced new constants for content options and stepper states to standardize component behavior and improve maintainability.
- Improved styling and functionality of course content modals and steppers for better user interaction.

* feat: enhance course content management and UI components

- Updated .prettierignore to exclude storybook-static directory.
- Improved exercise creation logic by refining option handling and adding UUID support for option values.
- Enhanced navigation component with debugging output for custom links.
- Introduced a new method in CourseApi to update content items locally, improving state management during navigation.
- Added caching for exercise templates by tag in ExerciseTemplateApi to optimize performance.
- Refactored lesson and exercise components for better organization and maintainability, including updates to modal styling and functionality.
- Implemented local patching for lesson and exercise list items to ensure UI consistency after updates.

* student + teacher invite (not fully tested)

* refactor: streamline course team member middleware

- Removed unnecessary console logging and timing for checking user permissions.
- Simplified the logic for determining if a user is a course team member or organization admin.

* reorder course sidebar to move content to its own page.

* feat: implement unified course enrollment route and API

- Introduced a new enrollment route `/course/:slug/enroll` to replace the previous invite system.
- Unified enrollment logic for free and paid courses, allowing direct enrollment for free courses and invite token validation for paid courses.
- Updated course landing page to redirect to the new enrollment route for free courses.
- Removed obsolete invite routes and related logic, streamlining the enrollment process.
- Enhanced API with a new `POST /course/:courseId/enroll` endpoint for handling enrollments.
- Added rate limiting for enrollment requests to prevent abuse.
- Updated UI components to reflect changes in enrollment flow and messaging.

* chore: update docker stack, docs, and auth token automation

* chore: make prettier check ignore unknown file types

* fix: avoid using authClient on server file and keep authClient client focused

* chore: always get the server on demand depending on the environment

* chore: update dashboard configuration and Docker setup for environment variables

- Modified the Svelte configuration to directly use the PUBLIC_SERVER_URL environment variable.
- Enhanced the Docker Compose file to include health check formatting and added environment variable arguments for the dashboard build.
- Updated the Dockerfile to echo environment variable values during the build process, ensuring clarity on the configuration being used.

* chore: enhance Docker setup and documentation for production deployment

- Added a new production Docker Compose file and example environment file for published images.
- Updated README and usage documentation to include instructions for deploying with production images.
- Modified Svelte configuration to standardize the use of the posthog domain.
- Removed unnecessary console logs from the API client and layout server files for cleaner output.
- Improved overall clarity in Docker documentation regarding self-hosting and image publishing.

* chore(db): log function name in query catch blocks (console.error 'funcName error:', error)

Co-authored-by: Cursor <[email protected]>

* fix: multiple refresh issue

* fix: server key not passed to api

* fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation

- Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware.
- Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware.
- Adjusted examples in Docker setup and self-hosting documentation to reflect these changes.

* fix migration script

* fix: improve language handling and add database reset script

- Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary.
- Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding.

* feat: add promote ungrouped section functionality and enhance document handling in dashboard

- Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials.
- Updated the dashboard to include a new component for displaying content count badges for lessons and exercises.
- Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents.
- Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions.
- Refactored existing components for better readability and maintainability, including updates to lesson and document lists.

* chore: use root env file for docker compose

* docs: document docker no-build startup flow

* chore: add no-build option to docker full stack script

* fix(email): handle SMTP TLS mode by port

* feat(auth): add configurable cookie domain env and docs

* apps/dashboard/src/lib/utils/services/auth/session.ts

* fix(email): make sender configurable via SMTP_SENDER

* chore(i18n): regenerate locale translations and support language targeting

* chore(config): switch api to PUBLIC_SERVER_URL

* fix(i18n): persist selected locale across navigation

* feat(assets): implement organization asset management routes and services

- Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets.
- Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion.
- Integrated YouTube metadata resolution and asset attachment/detachment functionalities.
- Updated organization routes to include the new asset management routes.
- Enhanced error handling for asset-related operations.

* fix(document-list): update conditional rendering for edit mode in document list

* debug self hosted layout setup

* refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering

* feat: tags

* chore: tags roadmap + translations

* fix(api): add authMiddleware to exercise, invites, and content routers

- exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes
- invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes
- contentRouter: add authMiddleware to PUT route (DELETE already had it)

Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring
authMiddleware to be applied first. This aligns with lessonRouter pattern and
ensures explicit middleware contract regardless of global session middleware.

Co-authored-by: Rotimi Best <[email protected]>

* fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes

These routes require admin/tutor role per JSDoc but were using
courseMemberMiddleware which allows any course member including students.
Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR
group members and org admins.

Co-authored-by: Rotimi Best <[email protected]>

* chore: unify pricing component between dashboard and website (#630)

* feat: modularize pricing card

* feat: initia implementation of pricing togge

* fix: minor amendment

* refactor: update pricing components for improved layout and styling

- Adjusted spacing in the pricing card layout for better visual consistency.
- Modified button styles and sizes for enhanced usability.
- Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic.

* add handle click

* chore(css): update Tailwind CSS output with new utility classes and theme variables

* fix(api): enable orgMemberMiddleware for stats route

This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code.

---------

Co-authored-by: Rotimi Best <[email protected]>

* pass query parameter to signup from pricing page

* ui updates to pricing cards

* commit all PRDs

* add open api spec to api prd

* make blue default theme

* more prds

* sync option id sequence on question update

* docs: more classroomio features

* chore: more ui improvements

* docs: new component docs

* chore: CSP Configuration (#638)

* feat(validation): add GitHub repository name validation

- Add ZRepositoryName schema for validating GitHub repo names
- Add ZRepositoryOwner for owner/username validation
- Add ZRepositoryIdentifier for owner/repo format
- Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names
- Add translation keys for validation messages

Fixes #637

Co-authored-by: Rotimi Best <[email protected]>

* Revert "feat(validation): add GitHub repository name validation"

This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce.

* feat(dashboard): make CSP external domains configurable via env

Move hardcoded external domains from svelte.config.js to .env configuration
for on-premise deployments with strict security policies, data residency
constraints, or CISO-driven allowlists.

- ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives
- CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS,
  CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override
- When unset, defaults retain current SaaS behavior (backward compatible)

Fixes #637

Co-authored-by: Rotimi Best <[email protected]>

* fix(dashboard): self-hosted CSP uses only env vars, no defaults

Co-authored-by: Rotimi Best <[email protected]>

* fix(dashboard): add all classroomio.com domains to CSP defaults

Co-authored-by: Rotimi Best <[email protected]>

* docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides

Co-authored-by: Rotimi Best <[email protected]>

* feat(docker): pass CSP domain env vars as build args to dashboard

Co-authored-by: Rotimi Best <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Rotimi Best <[email protected]>

* feat: add SSO and token authentication routes and services

- Introduced new routes for SSO and token authentication under the organization namespace.
- Implemented SSO connection management including creation, update, activation, and deletion.
- Added token authentication configuration with support for secret rotation and status retrieval.
- Enhanced error handling for SSO and token authentication processes.
- Updated existing routes and services to integrate new functionalities.
- Improved gradebook service to fetch student marks and exercises.
- Refactored API structure for better organization and maintainability.

* update translations

* fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641)

Co-authored-by: Cursor Agent <[email protected]>

* feat: new exercise question types

* MinIO S3 storage backend (#639)

* feat(storage): add MinIO/S3-compatible object storage backend

- Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3)
- Create storage config module with Cloudflare R2 fallback for backward compatibility
- Refactor s3.ts to use configurable client and bucket names from config
- Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN)
- Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets
- Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads
- Update self-hosting and Cloudflare docs with MinIO option
- Update .env examples and docker USAGE.md

Fixes #635

Co-authored-by: Rotimi Best <[email protected]>

* docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides

Co-authored-by: Rotimi Best <[email protected]>

* feat(media): refactor media management and integrate MinIO support

- Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components.
- Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion.
- Enhanced environment variable management for MinIO in the `.env.example` file.
- Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard.
- Introduced new media components for asset management, including asset cards and usage dialogs.

This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions.

* feat(dashboard): enhance logging and refactor auth session handling

- Added console logging for event and environment variables in hooks.server.ts to aid debugging.
- Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency.
- Updated Dockerfile to ensure the dashboard build output is present before starting the application.
- Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker.

These changes improve the observability of the application and streamline the authentication process.

* refactor(dashboard): remove debug logging and enhance Postgres healthcheck

- Removed console logging for event and environment variables in hooks.server.ts to clean up the code.
- Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready.
- Expanded self-hosting documentation to include troubleshooting steps for database recovery issues.

These changes improve code clarity and reliability in service startup sequences.

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Rotimi Best <[email protected]>

* feat: add Plyr media player icons and PDF.js integration

- Introduced new Plyr SVG icons for media player controls in both course and dashboard applications.
- Updated Plyr player configuration to use local icon assets.
- Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability.
- Enhanced PDF viewer modal z-index for better visibility.

This update improves the media player experience and ensures consistent access to necessary resources.

* feat: enhance account and organization services with type definitions and promise return types

- Updated `getAccountData` to return a structured result type including profile and organizations.
- Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety.
- Added new type imports for organization-related data structures to improve clarity and maintainability.

These changes improve type safety and enhance the overall structure of the account and organization services.

* feat: implement Redis caching for presigned URLs and refactor API interactions

- Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance.
- Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability.
- Updated various components to utilize the new `presignApi` methods for document and video upload/download operations.
- Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures.

These changes optimize the presigned URL generation process and streamline API interactions across the application.

* fix: add better-auth dependency to dashboard (#645)

* chore: unify exercise answer data format

* feat: make selfhosting run under one org for simplicity (#647)

* feat: implement self-hosting PRD + license key system

Self-hosting single-org:
- Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists
- Auto-add non-members as students in GET /account bootstrap
- getOrgSiteInfo: root domain returns single org for self-hosted
- App init: route to /lms when self-hosted + no orgs
- Hide org switcher and Add Org modal when self-hosted

Invite-only signup:
- Add settings.signup.inviteOnly via ZUpdateOrganization
- Allow public signups toggle in org auth settings
- Signup page: hide form when invite-only and no invite context
- Landing page nav: respect inviteOnly for signup link

First signup auto-verify:
- Self-hosted first signup (no orgs) auto-verifies email in createProfileHook

License key system:
- LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API
- Feature gates: SSO, token-auth, no-tracking (PostHog/Senja)
- requireLicense middleware for API routes
- Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI
- docs/LICENSE_API_CONTRACT.md for external API spec

Co-authored-by: Rotimi Best <[email protected]>

* feat: get rid of carbon completely

* chore: license verification happens only for selfhosted instance

* fix: in self hosted instance, orgSite is the default

* docs: how to write math in cio editor

* Update packages/db/src/queries/organization/organization.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update apps/api/src/services/license.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: translations, cursor pr reviews, simplify license fetching and check

* refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic

* refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss

* more selfhosting improvements

* feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided

* pr reviews

* fix: correct query parameter handling in course navigation

* pr reviews

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Rotimi Best <[email protected]>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Rotimi Best <[email protected]>
Co-authored-by: Abdulmuizz Hamzat <[email protected]>
Co-authored-by: Adeyemi Adetunji <[email protected]>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-09 11:18:22 +01:00
..

Exercise Question Types Expansion PRD

Status

  • In progress

Date

  • February 24, 2026

Implementation Plan

Purpose

Expand ClassroomIO exercise questions beyond single answer, multiple answers, and paragraph, so instructors can run stronger assessments, reduce manual grading where possible, and collect richer assignment submissions inside the LMS.

Problem Statement

Current exercise functionality is constrained by three legacy question types and a grading/answer model tuned for those types. This creates four product issues:

  1. Limited assessment design for instructors.
  2. Lower auto-grading coverage.
  3. Weak first-class support for assignment-style submissions.
  4. Increased instructor grading overhead and external-tool leakage.

Current-State Audit

Area Current State Gaps
Question types RADIO, CHECKBOX, TEXTAREA only No true/false, numeric, fill-blank, matching, ordering, file-upload, hotspot
DB question_type Seeded from packages/db/src/utils/seed/questionType.ts Typename coverage too narrow
Validation constants QUESTION_TYPE in packages/utils/src/validation/constants.ts contains only 3 numeric IDs Hardcoded numeric assumptions are fragile as type set grows
Exercise validation packages/utils/src/validation/exercise/exercise.ts has option rules for radio/checkbox + textarea No schema-per-type authoring or submission validation
Exercise authoring UI edit-mode.svelte renders only radio, checkbox, textarea No renderer registry or extensibility contract
Exercise taking UI view-mode.svelte answer flow assumes options or open text No type-specific interaction patterns for new formats
Submission model question_answer stores answers[] + open_answer No structured payload for richer responses (fill blanks, ordering, matching, uploads)
Attempt controls No max-attempt rule or attempt scoring strategy on exercise Cannot configure highest/latest/average grading behavior
Test controls No persisted timer/randomization/availability settings on exercise Missing in-schema support for test-mode controls
File response support No exercise-question-level upload config Cannot do per-question file constraints

Data Sources Checked

  • packages/db/src/schema.ts
  • packages/db/src/utils/seed/questionType.ts
  • packages/db/src/queries/exercise/exercise.ts
  • packages/utils/src/validation/constants.ts
  • packages/utils/src/validation/exercise/exercise.ts
  • apps/api/src/routes/course/exercise.ts
  • apps/api/src/services/exercise/exercise.ts
  • apps/api/src/services/exercise/utils.ts
  • apps/api/src/services/submission/submission.ts
  • apps/api/src/services/course/clone.ts
  • apps/dashboard/src/lib/features/ui/question/constants.ts
  • apps/dashboard/src/lib/features/course/components/exercise/edit-mode.svelte
  • apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte
  • apps/dashboard/src/lib/features/course/components/exercise/functions.ts
  • apps/dashboard/src/lib/features/course/components/exercise/store.ts
  • apps/dashboard/src/lib/features/course/api/exercise.svelte.ts

Primary Users

  • Instructors creating tests and assignments.
  • Students answering exercises on desktop and mobile.
  • Admins and tutors grading and reviewing progress.

Goals

  1. Support additional objective and subjective question types.
  2. Increase auto-grading coverage for objective formats.
  3. Add first-class assignment upload support at question level.
  4. Keep authoring UX consistent across question types.
  5. Add explicit exercise-level controls for attempts, scoring rule, answer reveal, and test behavior.

Non-Goals (v1)

  • Online proctoring.
  • AI-generated grading feedback.
  • Code execution/judging sandboxes.
  • LTI/QTI export.
  • Negative marking.
  • Audio/video response question type.

Confirmed Decisions

  1. Code execution is out of scope.
  2. Upload size limits are plan-based: Free 2MB, Paid 10MB.
  3. Resubmission policy is exercise-level, not per question.
  4. Rollout phases remain P0, P1, P2.
  5. If an exercise contains short answer or paragraph, final grading is manual.
  6. Numeric-answer grading mode is configurable.
  7. Fill-in-the-blank does not support multiple accepted answers per blank in v1.
  8. Partial credit is enabled by default where supported.
  9. Partial credit settings are question-level with exercise-level override.
  10. File upload configuration is per question.
  11. Exercise settings include max attempts.
  12. Correct-answer visibility is exercise-level configurable.
  13. Test-only controls are in scope.
  14. Allowed upload file types in v1: PDF, DOCX, PPTX, XLSX, ZIP, and images.
  15. Attempt grading rule is exercise-level configurable: highest, latest, average.
  16. Upload question accepts exactly one file in v1.

Proposed Question Types

Type Auto-gradable Partial Credit Assignment Fit Test Fit Phase
True/False Yes No Medium High P0
Short Answer (single-line) No N/A High High P0
Numeric Answer Yes Optional Medium High P0
Fill in the Blank Yes Yes Medium High P0
File Upload No N/A High Low P0
Matching Yes Yes Medium High P1
Ordering/Sequence Yes Yes Medium High P1
Hotspot/Image Labeling Yes Optional Medium Medium P2

Functional Requirements

Authoring

  • Instructor can choose question type from a type picker.
  • Instructor can configure:
    • prompt
    • points
    • required/optional
    • per-question instructions
    • type-specific settings
  • Instructor can define answer key for auto-graded types.
  • Instructor can configure scoring mode (all_or_nothing or partial) where supported.
  • Instructor can preview question behavior before publish.

Student Experience

  • Students can answer all released types on desktop and mobile.
  • Answers autosave while taking exercise.
  • One exercise can contain mixed question types.
  • File upload question enforces allowed MIME/extensions and plan-based limits.
  • File upload question accepts one file in v1.

Grading

  • Objective types auto-grade immediately unless exercise is in manual-only mode.
  • Manual types route to grading queue with teacher feedback.
  • Instructors can override auto-graded scores.
  • Gradebook stores per-question points and final exercise score.
  • Exercise-level auto-grade toggle can only be enabled when all active question types are auto-gradable; otherwise it must be disabled with a hint message.

Attempts and Test Controls

  • Exercise-level settings:
    • maxAttempts
    • attemptScoringRule (highest, latest, average)
    • showCorrectAnswers policy
    • timerSeconds (optional)
    • randomizeQuestionOrder
    • randomizeOptionOrder
    • availability window (availableFrom, availableTo)

Technical Design

1. Canonical Question Type Registry

Keep one canonical source for question type metadata used by API and dashboard.

Target package:

  • packages/question-types/src/ (new, published as @cio/question-types)

Registry includes:

  • stable key (TRUE_FALSE, SHORT_ANSWER, etc.)
  • DB typename
  • DB id (resolved at startup/seed, not hardcoded in scattered files)
  • auto-gradable flag
  • partial-credit support
  • submission payload schema key
  • rollout phase

1.1 Canonical Renderer Components

Keep question renderer components in @cio/ui and keep all shared logic/contracts in @cio/question-types.

Target package:

  • packages/ui/src/custom/exercise-question/ (new)
  • exports via packages/ui/src/index.ts

Rules:

  • renderer registry/contracts live in @cio/question-types.
  • answer serialization and shared form-state utilities live in @cio/question-types.
  • render contract object lives in @cio/question-types (ExerciseQuestionRenderContract / ExerciseQuestionListRenderContract) and is deterministic for the same inputs.
  • question type renderer components live in @cio/ui/custom/exercise-question.
  • @cio/ui/custom/exercise-question is components-only and does not own shared exercise logic.
  • dashboard screens consume type keys/contracts from @cio/question-types and renderers from @cio/ui/custom/exercise-question.

1.2 Cross-App File Contract

  • The complete individual file list for reusable shared packages is defined in implementation-plan.md under Shared Package File Contract (Cross-App Reuse).
  • Shared package code must stay app-agnostic so any app can consume it to build an exercise/forms product.

2. Data Model Changes

question table

Add:

  • settings (jsonb, default {}, not null)
  • scoring_mode (varchar, default all_or_nothing)
  • manual_grading_required (boolean, default false)

settings examples:

  • numeric: { "mode": "exact" | "tolerance_abs" | "tolerance_pct", "tolerance": number }
  • upload: { "maxFiles": 1, "allowedTypes": [...], "maxSizeMb": 2|10 }
  • matching: { "shuffleLeft": true, "shuffleRight": true }

question_answer table

Add:

  • payload (jsonb, default {}, not null)

Keep existing answers[] and open_answer for backward compatibility during migration; new types write to payload.

exercise table

Add:

  • max_attempts (integer, default 1)
  • attempt_scoring_rule (varchar, default latest)
  • show_correct_answers (varchar, default after_grading)
  • timer_seconds (integer, nullable)
  • randomize_question_order (boolean, default false)
  • randomize_option_order (boolean, default false)
  • available_from (timestamptz, nullable)
  • available_to (timestamptz, nullable)

submission table

Add:

  • attempt_number (integer, default 1)
  • finalized_score (double precision, nullable)
  • grading_mode (varchar, default auto_or_manual)

3. Validation Layer

Update/expand packages/utils/src/validation/exercise/:

  • question-base.ts (shared prompt/points/rules)
  • question-true-false.ts
  • question-short-answer.ts
  • question-numeric.ts
  • question-fill-blank.ts
  • question-file-upload.ts
  • question-matching.ts
  • question-ordering.ts
  • question-hotspot.ts
  • compose into:
    • ZExerciseCreate
    • ZExerciseUpdate
    • ZExerciseSubmissionCreate

Validation must run:

  • in API routes
  • in dashboard before submit/update
  • in grading service for defensive checks

4. API Layer Changes

Primary touchpoints:

  • apps/api/src/routes/course/exercise.ts
  • apps/api/src/services/exercise/exercise.ts
  • apps/api/src/services/exercise/utils.ts
  • apps/api/src/services/submission/submission.ts
  • packages/db/src/queries/exercise/exercise.ts

Key changes:

  1. Accept/store question settings and scoringMode.
  2. Support typed answer payload writes to question_answer.payload.
  3. Enforce attempt limits before creating a submission.
  4. Compute final grade using attemptScoringRule.
  5. Auto/manual grading decision based on question mix.
  6. Support file-response references through existing assets model.

5. Dashboard Layer Changes

Primary touchpoints:

  • packages/ui/src/custom/exercise-question/* (new shared UI component set; components only)
  • packages/ui/src/index.ts
  • apps/dashboard/src/lib/features/course/components/exercise/edit-mode.svelte
  • apps/dashboard/src/lib/features/course/components/exercise/view-mode.svelte
  • apps/dashboard/src/lib/features/course/components/exercise/functions.ts
  • apps/dashboard/src/lib/features/course/components/exercise/store.ts
  • apps/dashboard/src/lib/features/course/api/exercise.svelte.ts
  • apps/dashboard/src/lib/features/course/utils/types.ts
  • translations in apps/dashboard/src/lib/utils/translations/en.json

Refactor plan:

  1. Introduce registry/contracts in @cio/question-types and map question type keys to shared UI renderers.
  2. Keep existing mode structure (edit, view, preview) but remove hardcoded if RADIO/CHECKBOX/TEXTAREA branching.
  3. Add type-specific renderer components under packages/ui/src/custom/exercise-question.
  4. Add translation keys for new types and setting labels.
  5. Add exercise-level auto-grade toggle with eligibility guard and hint message when blocked by manual-only question types.

6. Legacy Compatibility and Migration

  1. Existing exercises keep working without migration rewrite of question data.
  2. New columns default safely ({} / false / null / default enums).
  3. question_type seed extends with new typenames.
  4. Replace hardcoded numeric assumptions where present.

Known cleanup item discovered during audit:

  • apps/api/src/services/course/clone.ts uses QUESTION_TYPE_TEXTAREA = 2, while shared constant maps TEXTAREA = 3.
  • This must be corrected before rollout to avoid option-cloning regressions for paragraph questions.

Progress Update (Feb 26, 2026)

Completed in branch:

  1. Shared package contracts/registry implemented in @cio/question-types.
  2. Dashboard renderer logic centralized via shared render contracts and shared @cio/ui/custom/exercise-question components.
  3. Shared question renderer component files implemented for legacy and expanded question types.
  4. Clone service question-type ID mismatch fixed to use shared constants.

Still pending for grading engine milestone:

  1. End-to-end server auto-grading engine across non-legacy types.
  2. Exercise-level auto-grade toggle + disabled-state hint behavior.
  3. Full per-type validation/attempt-rule enforcement rollout in API.

Rollout Plan

Phase 1 (P0)

Question types:

  • True/False
  • Short Answer
  • Numeric
  • Fill in the Blank
  • File Upload

Required deliverables:

  1. DB columns for settings/payload/attempt controls.
  2. Validation and API support for P0 types.
  3. Dashboard renderer registry + P0 components.
  4. Attempt scoring rule support.
  5. Migration + seed updates.

Phase 2 (P1)

Question types:

  • Matching
  • Ordering/Sequence

Required deliverables:

  1. Partial-credit grading helpers.
  2. Enhanced analytics aggregation for pair/order correctness.
  3. UX polish for drag/drop and accessibility.

Phase 3 (P2)

Question types:

  • Hotspot/Image Labeling

Required deliverables:

  1. Image coordinate mapping schema.
  2. Responsive touch/mobile interaction hardening.
  3. Additional grading explainability in teacher UI.

Testing Requirements

API

  • Schema validation tests for each type (create/update/submit).
  • Grading tests:
    • all-or-nothing
    • partial-credit
    • manual-required fallback
  • Attempt rule tests (highest, latest, average).
  • Upload constraint tests by plan limit.

Dashboard

  • Component tests for each type renderer in edit/take modes.
  • Store tests for autosave and answer serialization.
  • Integration tests for submission payload generation.

Regression

  • Existing three types must pass unchanged behavior tests.
  • Exercise cloning must preserve all supported question types correctly.

Build and Verification Commands

  1. pnpm --filter @cio/db build
  2. pnpm --filter @cio/utils build
  3. pnpm --filter @cio/api build
  4. pnpm --filter @cio/dashboard build

Success Metrics (90 Days Post-Launch)

  1. 40% of newly created exercises include at least one new type.
  2. 25% reduction in average grading time per exercise.
  3. 20% increase in completion for assignment-heavy exercises.
  4. 30% increase in auto-graded question share in test exercises.

Risks and Mitigations

  1. Hardcoded question-type IDs may cause logic drift.
    • Mitigation: canonical registry + typename-based mapping.
  2. Rich payload types can increase complexity in submission parsing.
    • Mitigation: strict per-type schema and shared serializer/deserializer utilities.
  3. File uploads can introduce abuse/security risk.
    • Mitigation: MIME/size validation, one-file v1 cap, server-side checks, existing asset safeguards.

Open Questions

  1. Should short answer support optional case-insensitive exact-match auto-grading in v1.1?
  2. For fill-in-the-blank, should punctuation normalization be strict or relaxed by default?
  3. Should hotspot remain P2 or shift post-P2 depending on demand?