Share-link generation and med math on request
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 34s

- Visitors of class and exam links can generate NCLEX-style quizzes (default
  and maximum 50 questions, 25% select-all, Python-checked, optional 5 med
  math questions) and flashcard sets from chosen class materials, once the
  owner turns it on for the link.
- 4 quizzes and 2 flashcard sets per link per day; failed attempts do not
  count; "Reset limits" in the share dialog gives a fresh allowance.
- Sets are drafts tied to the link (migration 7): listed for every visitor,
  explainable, kept off the owner's drafts list, and reviewable or savable
  from the share dialog.
- Generate gains "Include med math" with a count (default 5): exactly that
  many dosage calculation questions at the chosen difficulty, spread through
  the quiz, even when the material has none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 22:04:08 -07:00
parent 25bc03ea75
commit e945f589ce
16 changed files with 807 additions and 44 deletions

View file

@ -62,12 +62,14 @@ interface DraftRow {
saved_kind: string | null;
saved_id: string | null;
conversation_id: string | null;
/** Made by a visitor of this share link (not listed with the owner's drafts). */
share_id: string | null;
created_at: number;
updated_at: number;
}
export interface DraftMeta {
origin?: 'generate' | 'assistant' | 'convert' | 'improve' | 'import';
origin?: 'generate' | 'assistant' | 'convert' | 'improve' | 'import' | 'share';
model?: string;
request?: Record<string, unknown>;
sources?: { documentId: string; title: string }[];
@ -102,6 +104,7 @@ export function mapDraft(row: DraftRow) {
savedKind: row.saved_kind,
savedId: row.saved_id,
conversationId: row.conversation_id,
shareId: row.share_id ?? null,
itemCount: payload.kind === 'quiz' ? payload.questions.length : payload.kind === 'deck' ? payload.cards.length : payload.content.length,
createdAt: row.created_at,
updatedAt: row.updated_at,
@ -117,12 +120,22 @@ export function getDraft(db: DB, id: string): DraftDto {
export function createDraft(
db: DB,
input: { kind: DraftRow['kind']; classId?: string | null; folderId?: string | null; title: string; payload?: ContentDraft; meta?: DraftMeta; status?: DraftRow['status']; conversationId?: string | null },
input: {
kind: DraftRow['kind'];
classId?: string | null;
folderId?: string | null;
title: string;
payload?: ContentDraft;
meta?: DraftMeta;
status?: DraftRow['status'];
conversationId?: string | null;
shareId?: string | null;
},
): string {
const id = newId();
const at = now();
db.run(
`INSERT INTO drafts (id, kind, class_id, folder_id, title, payload, meta, status, conversation_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
`INSERT INTO drafts (id, kind, class_id, folder_id, title, payload, meta, status, conversation_id, share_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
id,
input.kind,
input.classId ?? null,
@ -132,6 +145,7 @@ export function createDraft(
JSON.stringify(input.meta ?? {}),
input.status ?? 'ready',
input.conversationId ?? null,
input.shareId ?? null,
at,
at,
);
@ -140,7 +154,7 @@ export function createDraft(
export function listDrafts(db: DB) {
return db
.all<DraftRow>(`SELECT * FROM drafts WHERE status IN ('generating', 'ready', 'failed') ORDER BY updated_at DESC LIMIT 50`)
.all<DraftRow>(`SELECT * FROM drafts WHERE status IN ('generating', 'ready', 'failed') AND share_id IS NULL ORDER BY updated_at DESC LIMIT 50`)
.map(mapDraft)
.map(({ payload: _payload, ...rest }) => rest);
}
@ -252,7 +266,9 @@ export function discardDraft(db: DB, id: string): void {
export function tidyDrafts(db: DB): void {
db.run(`UPDATE drafts SET status = 'failed', error = 'Generation was interrupted by a restart. Start it again.' WHERE status = 'generating'`);
db.run(`DELETE FROM drafts WHERE status IN ('saved', 'discarded') AND updated_at < ?`, now() - 14 * 86_400_000);
db.run(`DELETE FROM drafts WHERE status IN ('ready', 'failed') AND updated_at < ?`, now() - 60 * 86_400_000);
db.run(`DELETE FROM drafts WHERE status IN ('ready', 'failed') AND share_id IS NULL AND updated_at < ?`, now() - 60 * 86_400_000);
// Sets made on a share link stay with the link; failed attempts go after a week.
db.run(`DELETE FROM drafts WHERE status = 'failed' AND share_id IS NOT NULL AND updated_at < ?`, now() - 7 * 86_400_000);
}
/* ------------------------------ request ------------------------------ */
@ -286,6 +302,12 @@ export const generateRequestSchema = z.object({
difficulty: z.enum(['easy', 'medium', 'hard', 'mixed']).optional(),
/** Share of select-all-that-apply questions, 0..1. */
sataShare: z.number().min(0).max(1).optional(),
/**
* Quizzes: exactly this many medication math (dosage calculation) questions, written at the
* chosen difficulty even when the material has no calculations. Absent: calculations only
* when the material involves them.
*/
mathQuestions: z.number().int().min(0).max(25).optional(),
cardStyle: z.enum(['concise', 'detailed', 'medication', 'definition']).optional(),
noteStyle: z.enum(['study_guide', 'summary', 'outline', 'cheat_sheet']).optional(),
modelId: z.string().nullish(),
@ -358,7 +380,15 @@ const CARD_SCHEMA = {
required: ['cards'],
};
const NUMERIC_RULE = `- Only write calculation items when the source material itself involves calculations, and never more than the number allowed in the request. Calculation items (dosages, weight-based doses, IV and drip rates, conversions, intake and output) use type "numeric": the student types the number instead of choosing. Give exactly one option, the correct answer with its unit (for example "12.5 mL"), marked correct, with "why" showing the working. State the unit and the rounding rule in the stem ("Round to the nearest tenth."). Only the number is checked, so the student may leave out the unit.`;
/** What the medication math questions look like at each difficulty, when the user asks for them. */
const MATH_LEVELS: Record<string, string> = {
easy: 'single-step problems: tablets or capsules per dose, mL of an oral liquid, and simple unit conversions (g, mg, mcg; L, mL; lb to kg)',
medium: 'weight-based doses (mg/kg), mL to draw up from a vial, and IV pump rates in mL/h',
hard: 'multi-step problems: gravity drip rates in gtt/min with a drop factor, mcg/kg/min titrations, heparin units/h from a protocol, and reconstituted medications',
mixed: 'a spread from single-step dose and conversion problems to weight-based doses, IV pump rates (mL/h) and drip rates (gtt/min)',
};
const NUMERIC_RULE = `- Only write calculation items when the source material itself involves calculations (or the request asks for medication math), and never more than the number allowed in the request. Calculation items (dosages, weight-based doses, IV and drip rates, conversions, intake and output) use type "numeric": the student types the number instead of choosing. Give exactly one option, the correct answer with its unit (for example "12.5 mL"), marked correct, with "why" showing the working. State the unit and the rounding rule in the stem ("Round to the nearest tenth."). Only the number is checked, so the student may leave out the unit.`;
const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
- Test clinical judgment at the application and analysis level: recognise cues, analyse, prioritise, choose and evaluate actions. Avoid pure recall.
@ -662,6 +692,25 @@ async function broadenTopics(app: AppContext, modelId: string | null | undefined
return out;
}
/** Places the matching items at even intervals among the others, keeping each group's order. */
export function spreadEvenly<T>(list: T[], pick: (item: T) => boolean): T[] {
const chosen = list.filter(pick);
const rest = list.filter((x) => !pick(x));
if (chosen.length === 0 || rest.length === 0) return list;
const out: T[] = [];
const step = (rest.length + chosen.length) / chosen.length;
let next = Math.floor(step / 2);
let c = 0;
for (let i = 0, r = 0; i < list.length; i += 1) {
if (c < chosen.length && i >= next) {
out.push(chosen[c++]);
next = Math.floor(step / 2 + c * step);
} else if (r < rest.length) out.push(rest[r++]);
else out.push(chosen[c++]);
}
return out;
}
/** True when the material involves calculations, so calculation questions are fair game. */
export function mentionsCalculations(text: string): boolean {
return CALCULATION_RE.test(text);
@ -710,7 +759,7 @@ const NOTE_TITLES: Record<string, string> = { study_guide: 'study guide', summar
export function startGeneration(
app: AppContext,
input: z.input<typeof generateRequestSchema>,
opts: { conversationId?: string | null; origin?: DraftMeta['origin']; onProgress?: (label: string) => void } = {},
opts: { conversationId?: string | null; origin?: DraftMeta['origin']; onProgress?: (label: string) => void; shareId?: string } = {},
): { draftId: string; done: Promise<DraftDto> } {
const req = generateRequestSchema.parse(input);
if (req.classId) getClass(app.db, req.classId);
@ -727,6 +776,7 @@ export function startGeneration(
title: req.title ?? '',
status: 'generating',
conversationId: opts.conversationId ?? null,
shareId: opts.shareId ?? null,
meta: { origin: opts.origin ?? 'generate', model: resolved.model.label, request: { ...req, source: { ...req.source, text: req.source.text ? `${req.source.text.slice(0, 200)}…` : undefined } } },
});
const controller = new AbortController();
@ -795,22 +845,35 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
// Calculation questions: only when the material involves calculations, and at most 5 per
// 50-question exam (10% of a practice set).
const mathAllowed = isQuiz && mentionsCalculations([sourcesText(sources), req.focus ?? '', req.instructions ?? ''].join('\n'));
const numericCap = !mathAllowed ? 0 : req.format === 'exam' ? Math.min(5, Math.max(1, Math.round(count / 10))) : Math.max(1, Math.round(count / 10));
// Medication math on request: exactly that many, written in their own batches after the rest.
const forcedMath = isQuiz && req.mathQuestions !== undefined ? Math.min(req.mathQuestions, count) : null;
const regularCount = forcedMath === null ? count : count - forcedMath;
const numericCap =
forcedMath !== null ? forcedMath : !mathAllowed ? 0 : req.format === 'exam' ? Math.min(5, Math.max(1, Math.round(count / 10))) : Math.max(1, Math.round(count / 10));
const numericCount = () => (draft.kind === 'quiz' ? draft.questions.filter((q) => q.type === 'numeric').length : 0);
// Broad topic labels, shared with the class's existing quizzes so results group sensibly.
const knownTopics = isQuiz && req.classId ? db.all<{ topic: string }>(`SELECT DISTINCT q.topic FROM questions q JOIN quizzes z ON z.id = q.quiz_id WHERE z.class_id = ? AND q.topic != '' LIMIT 60`, req.classId).map((r) => r.topic) : [];
const runBatch = async (index: number, want: number): Promise<number> => {
const runBatch = async (index: number, want: number, math = false): Promise<number> => {
const written = items().map((x) => `- ${('stem' in x ? x.stem : x.front).replace(/\s+/g, ' ').slice(0, 140)}`);
const sataCount = Math.round(want * sata);
const numericLeft = Math.max(0, numericCap - numericCount());
// With requested math, the regular batches write none; the math batches write only those.
const numericLeft = forcedMath !== null && !math ? 0 : Math.max(0, numericCap - numericCount());
const topicsSoFar = [...new Set([...knownTopics, ...(draft.kind === 'quiz' ? draft.questions.map((q) => q.topic) : [])].filter(Boolean))];
const ask = isQuiz
const ask = math
? [
`Write ${want} medication math (dosage calculation) questions, all of type "numeric": the student types the number.`,
`Difficulty ${difficulty}: ${MATH_LEVELS[difficulty] ?? MATH_LEVELS.mixed}.`,
'These do not need to come from the course material: write standard nursing med math with realistic orders, labels and client weights, using generic drug names (drugs from the material are welcome where they fit).',
'Each stem gives the order and what is on hand, and states the unit and the rounding rule ("Round to the nearest tenth."). Exactly one option: the correct answer with its unit, marked correct, with "why" showing the working step by step (dimensional analysis or desired over have). The rationale explains the method and one safety check.',
'Set the topic to "Dosage calculation". Vary the problem types.',
]
: isQuiz
? [
`Write ${want} NCLEX-style questions${req.focus ? ` about: ${req.focus}` : ''}.`,
sata <= 0 ? 'Use only multiple-choice (single) questions, apart from calculations.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions, apart from calculations.' : `Exactly ${sataCount} of them must be select-all-that-apply (type "multi"); the rest multiple choice (single).`,
numericLeft === 0
? 'Do not write any calculation (numeric) questions in this batch.'
? `Do not write any calculation (numeric) questions in this batch.${forcedMath ? ' Calculation questions are written separately.' : ''}`
: `The material involves calculations: you may include up to ${numericLeft} calculation question${numericLeft === 1 ? '' : 's'} (type "numeric", the student types the number). Do not exceed that.`,
`Topic labels must be broad (the main condition, drug class or body system, 1-3 words), not subtypes or aspects.${topicsSoFar.length ? ` Reuse these existing topics wherever they fit: ${topicsSoFar.slice(0, 40).join(', ')}.` : ''}`,
difficulty === 'mixed' ? 'Mix difficulty: mostly medium, with a few easy and a few hard.' : `Difficulty: ${difficulty}.`,
@ -823,7 +886,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states it with the essential reasoning.' : '',
];
if (written.length > 0) ask.push(`Already written (do not repeat or closely paraphrase these):\n${written.slice(-80).join('\n')}`);
const user = [sourceBlock(sources, index), ask.filter(Boolean).join('\n')].filter(Boolean).join('\n\n======\n\n');
// Med math is standard material: the excerpts would only cost tokens.
const user = [math ? '' : sourceBlock(sources, index), ask.filter(Boolean).join('\n')].filter(Boolean).join('\n\n======\n\n');
const result = await generateStructured(app, {
task: 'generate',
@ -850,21 +914,25 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
const ref = (item.source ?? '').replace(/[[\]\s]/g, '');
item.source = sources.refs.get(ref) ?? undefined;
}
if ('stem' in item && item.type === 'numeric' && numericCount() >= numericCap) continue; // over the calculation allowance; a top-up replaces it
if ('stem' in item && item.type === 'numeric' && (numericLeft === 0 || numericCount() >= numericCap)) continue; // over the calculation allowance; a top-up replaces it
if (math && (!('stem' in item) || item.type !== 'numeric')) continue; // a math batch keeps only calculations
if ('stem' in item && item.type !== 'numeric') item.options = shuffleOptions(item.options);
seen.add(k);
(items() as (DraftQuestion | DraftCard)[]).push(item);
added += 1;
if (math ? numericCount() >= numericCap : items().length - numericCount() >= regularCount && forcedMath !== null) break;
if (items().length >= count) break;
}
if (result.truncated) notes.push('One batch hit the model output limit, so it produced fewer items than requested.');
return added;
};
// Regular items written so far (with requested math, calculations are counted separately).
const regularDone = () => (forcedMath === null ? items().length : items().length - numericCount());
let failures = 0;
for (let i = 0; i < batches && items().length < count; i += 1) {
for (let i = 0; i < Math.ceil(regularCount / perBatch) && regularDone() < regularCount; i += 1) {
if (signal.aborted) throw new AIError('aborted', 'Generation was cancelled.');
const want = Math.min(perBatch, count - items().length);
const want = Math.min(perBatch, regularCount - regularDone());
setProgress(db, draftId, 0.05 + (0.9 * items().length) / count, `Writing ${isQuiz ? 'questions' : 'cards'} ${items().length + 1}-${Math.min(count, items().length + want)} of ${count}`, draft);
try {
await runBatch(i, want);
@ -876,9 +944,9 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
}
}
// Top up when validation or de-duplication left the draft short.
for (let extra = 0; extra < 2 && items().length < count && items().length > 0; extra += 1) {
for (let extra = 0; extra < 2 && regularDone() < regularCount && items().length > 0; extra += 1) {
if (signal.aborted) break;
const want = Math.min(perBatch, count - items().length);
const want = Math.min(perBatch, regularCount - regularDone());
setProgress(db, draftId, 0.92, `Writing the last ${want} ${isQuiz ? 'questions' : 'cards'}`, draft);
try {
if ((await runBatch(batches + extra, want)) === 0) break;
@ -886,6 +954,22 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
break;
}
}
// Requested medication math, in batches of up to eight, then spread evenly through the quiz.
if (forcedMath && draft.kind === 'quiz') {
for (let attempt = 0; attempt < Math.ceil(forcedMath / perBatch) + 2 && numericCount() < forcedMath; attempt += 1) {
if (signal.aborted) throw new AIError('aborted', 'Generation was cancelled.');
const want = Math.min(perBatch, forcedMath - numericCount());
setProgress(db, draftId, 0.9, `Writing ${want} med math question${want === 1 ? '' : 's'}`, draft);
try {
if ((await runBatch(batches + 10 + attempt, want, true)) === 0 && attempt > 0) break;
} catch (err) {
if (err instanceof AIError && err.code === 'aborted') throw err;
notes.push(`A med math batch failed: ${err instanceof Error ? err.message : 'unknown error'}`);
}
}
draft.questions = spreadEvenly(draft.questions, (q) => q.type === 'numeric');
if (numericCount() < forcedMath) notes.push(`Wrote ${numericCount()} of the ${forcedMath} med math questions requested.`);
}
if (items().length === 0) throw new AIError('invalid_response', 'The model did not produce any usable items. Try again, or choose a different model for content generation.');
if (items().length < count) notes.push(`Generated ${items().length} of the ${count} requested.`);
@ -901,7 +985,7 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
// Check counts, the type mix, answer keys and calculations with Python before review.
if (draft.kind === 'quiz' && req.verify !== false) {
setProgress(db, draftId, 0.96, 'Checking the questions with Python', draft);
const checked = await verifyQuizDraft(app, draft, { count, style, sataShare: sata, difficulty, numericCap }, { modelId: req.modelId, signal, onStep: (label) => setProgress(db, draftId, 0.97, label) });
const checked = await verifyQuizDraft(app, draft, { count, style, sataShare: sata, difficulty, numericCap, numericRequested: forcedMath !== null }, { modelId: req.modelId, signal, onStep: (label) => setProgress(db, draftId, 0.97, label) });
draft.questions = checked.draft.questions;
notes.push(...checked.notes);
}

View file

@ -76,6 +76,8 @@ export interface QuizRequestFacts {
difficulty?: string;
/** Most calculation (numeric) questions allowed; 0 when the material has no calculations. */
numericCap?: number;
/** The user asked for exactly `numericCap` medication math questions (not from the material). */
numericRequested?: boolean;
}
/** Long text is shortened rather than rejected: a verbose but correct review must not be lost. */
@ -142,7 +144,7 @@ const SUBMIT_REVIEW: ToolDef = {
function rulesFor(req: QuizRequestFacts): string {
const expectedMulti = req.sataShare <= 0 ? 'none' : req.sataShare >= 1 ? 'all non-numeric questions' : `about ${Math.round(req.sataShare * 100)}% of the non-numeric questions`;
return [
`Requested: ${req.count} NCLEX-style questions, difficulty "${req.difficulty ?? 'mixed'}", select-all (multi) share: ${expectedMulti}, calculation (numeric) questions: ${req.numericCap ? `at most ${req.numericCap}` : 'none (the material has no calculations)'}.`,
`Requested: ${req.count} NCLEX-style questions, difficulty "${req.difficulty ?? 'mixed'}", select-all (multi) share: ${expectedMulti}, calculation (numeric) questions: ${req.numericRequested ? (req.numericCap ? `exactly ${req.numericCap} medication math questions, requested by the user (they need not come from the material)` : 'none') : req.numericCap ? `at most ${req.numericCap}` : 'none (the material has no calculations)'}.`,
'Rules each question must meet:',
'- single: exactly one correct option and 4 options.',
'- multi (select all that apply): at least 2 correct options; for NCLEX style 5 or 6 options with 2 to 5 correct and a stem ending with "Select all that apply."',