Fifth revision: share-link AI safety, sturdier generation, cleaner UI
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s

- Malformed model JSON is sent back for repair, then retried; a failed job
  starts over once before it fails. Visitors can dismiss failed sets.
- Generated sets get a short distinct name and description; flashcards are
  atomic and have no hints; standard study shows known/learning counts.
- Share links: "In progress" list, finished sets join the normal lists with a
  "New" tag, plain progress steps, newest exam first.
- Share-link AI expires after a week, can be limited to the US or Arizona
  (DB-IP Lite or Cloudflare headers) and is locked by abuse protection
  (migration 8).
- The assistant never answers from general knowledge; MCP and web search
  tools load without a manual test.
- Plain-text copy, no question count in exam mode, filler text removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-16 09:17:50 -07:00
parent d8df5edf30
commit 85d5c9186d
46 changed files with 1242 additions and 283 deletions

View file

@ -366,9 +366,8 @@ const CARD_SCHEMA = {
items: {
type: 'object',
properties: {
front: { type: 'string', description: 'Prompt side: one specific question or term.' },
back: { type: 'string', description: 'Answer side. Markdown allowed.' },
hint: { type: 'string', description: 'Optional memory hook or mnemonic. Empty string if none.' },
front: { type: 'string', description: 'Prompt side: one specific question about one fact.' },
back: { type: 'string', description: 'Only the answer: a word, number or short phrase. No explanation.' },
tags: { type: 'array', items: { type: 'string' }, description: '1-2 short topic tags.' },
},
required: ['front', 'back'],
@ -402,8 +401,9 @@ ${NUMERIC_RULE}`;
const CARD_RULES: Record<string, string> = {
concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).',
detailed: 'Each card covers one concept. Backs may use a short bullet list (up to 5 bullets) for the key points.',
concise:
`Atomic cards: each card tests exactly one fact, so it can be learned in one look. The front asks one specific question (never "describe" or "explain"). The back is only the answer: a word, a number with its unit, or a short phrase, ideally under 10 words and never more than one short sentence. No explanations, reasons, lists or paragraphs on the back. Split anything with several parts (a drug's class, action and side effects; the signs of a condition) into separate cards.`,
detailed: 'Each card covers one concept. The back is at most 3 short bullet points (a few words each), no paragraphs.',
medication:
'Make medication cards. Front: the generic drug name (with a common brand name in parentheses when well known). Back: a Markdown list with **Class**, **Action**, **Uses**, **Adverse effects** (the most important ones), **Nursing considerations** and **Client teaching**. Only include what the material supports.',
definition: 'Make term and definition cards. Front: the term. Back: a precise definition in one or two sentences, plus an example when useful.',
@ -787,7 +787,7 @@ export function startGeneration(
const controller = new AbortController();
running.set(draftId, controller);
if (opts.onProgress) progressListeners.set(draftId, opts.onProgress);
const done = runGeneration(app, draftId, req, controller.signal)
const done = runWithRestart(app, draftId, req, controller.signal)
.catch((err) => {
const message = err instanceof AIError ? err.message : err instanceof Error && 'status' in err ? err.message : 'Generation failed unexpectedly.';
if (!(err instanceof AIError) && !(err instanceof Error && 'status' in err)) app.log('error', 'Generation failed', err);
@ -824,6 +824,31 @@ function autoSaveDraft(app: AppContext, draftId: string, description: string): v
}
}
/** Failures worth starting the whole job over for: bad output and passing provider trouble. */
const RESTARTABLE = new Set(['invalid_response', 'server', 'timeout', 'network', 'rate_limit']);
/**
* Runs a generation job, and when it fails on bad model output (or a passing provider error)
* starts it over once with the same request. A second failure fails the draft.
*/
async function runWithRestart(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
try {
await runGeneration(app, draftId, req, signal);
} catch (err) {
if (signal.aborted || !(err instanceof AIError) || !RESTARTABLE.has(err.code)) throw err;
app.log('warn', 'Generation failed; starting it over once', err.message);
const kind = req.kind;
app.db.run(
`UPDATE drafts SET payload = ?, progress = 0.02, progress_label = 'Starting over', updated_at = ? WHERE id = ? AND status = 'generating'`,
JSON.stringify(emptyPayload(kind, req.title ?? '')),
now(),
draftId,
);
progressListeners.get(draftId)?.('Starting over');
await runGeneration(app, draftId, req, signal);
}
}
async function runGeneration(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal): Promise<void> {
const { db } = app;
const resolved = resolveModel(app, 'generate', req.modelId);
@ -904,7 +929,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
: [
`Write ${want} flashcards${req.focus ? ` about: ${req.focus}` : ''}.`,
sources.groups.length > 0 ? 'Cover the most testable facts across all of the excerpts.' : '',
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states it with the essential reasoning.' : '',
req.source.quizId ? 'Turn the quiz questions into flashcards: the front asks for the key fact, the back states only that fact.' : '',
'Do not write hints.',
];
if (written.length > 0) ask.push(`Already written (do not repeat or closely paraphrase these):\n${written.slice(-80).join('\n')}`);
// Med math is standard material: the excerpts would only cost tokens.
@ -1011,6 +1037,16 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
notes.push(...checked.notes);
}
// A short name and description of what this particular set covers.
if (!req.title) {
setProgress(db, draftId, 0.99, 'Naming the set', draft);
const named = await nameSet(app, draft, { classId: req.classId ?? null, modelId: req.modelId, signal, difficulty, math: numericCount() > 0 });
if (named) {
draft.title = named.title;
draft.description = named.description;
}
}
db.run(
`UPDATE drafts SET status = 'ready', title = ?, payload = ?, meta = ?, progress = 1, progress_label = '', error = '', updated_at = ? WHERE id = ?`,
draft.title,
@ -1021,6 +1057,70 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
);
}
const NAME_SCHEMA = {
type: 'object',
properties: {
title: { type: 'string', description: 'Short, specific name for this set: 2-6 words naming what it covers.' },
description: { type: 'string', description: 'One sentence (at most 25 words) saying what the set covers.' },
},
required: ['title', 'description'],
};
/**
* Asks the model for a short, distinctive title and a one-line description of a finished quiz
* or flashcard set, different from the class's other titles. Null when naming fails (the
* generic title stays).
*/
export async function nameSet(
app: AppContext,
draft: QuizDraft | DeckDraft,
opts: { classId: string | null; modelId?: string | null; signal?: AbortSignal; difficulty?: string; math?: boolean },
): Promise<{ title: string; description: string } | null> {
const isQuiz = draft.kind === 'quiz';
const taken = opts.classId
? app.db.all<{ title: string }>(`SELECT title FROM ${isQuiz ? 'quizzes' : 'decks'} WHERE class_id = ? ORDER BY created_at DESC LIMIT 80`, opts.classId).map((r) => r.title)
: [];
const lines = isQuiz
? (() => {
const counts = new Map<string, number>();
for (const q of draft.questions) counts.set(q.topic || 'General', (counts.get(q.topic || 'General') ?? 0) + 1);
const topics = [...counts].sort((a, b) => b[1] - a[1]).map(([t, n]) => `${t} (${n})`).join(', ');
return [`A quiz of ${draft.questions.length} questions. Topics: ${topics}.`, ...draft.questions.slice(0, 40).map((q) => `- ${q.stem.replace(/\s+/g, ' ').slice(0, 110)}`)];
})()
: [`A flashcard set of ${draft.cards.length} cards.`, ...draft.cards.slice(0, 60).map((c) => `- ${c.front.replace(/\s+/g, ' ').slice(0, 90)}`)];
try {
const result = await generateStructured(app, {
task: 'generate',
purpose: 'naming a set',
modelId: opts.modelId,
system: `You name study sets for a nursing student. The title is 2-6 words in title case and names the actual subject matter (for example "Heart Failure and Diuretics" or "Stroke Priorities"). Never use generic words such as Quiz, Flashcards, Practice, NCLEX, Exam, Review or Set, and no dates or numbers of items.${
opts.math ? ' The set includes medication math, so the title may mention it.' : ''
} The description is one plain sentence on what it covers.`,
messages: [{ role: 'user', content: [{ type: 'text', text: `${lines.join('\n')}${taken.length ? `\n\nTitles already used in this class (yours must differ from all of them):\n${taken.map((t) => `- ${t}`).join('\n')}` : ''}` }] }],
toolName: 'name_set',
toolDescription: 'Submit the title and description.',
schema: NAME_SCHEMA,
maxOutputTokens: 400,
signal: opts.signal,
});
const value = result.data as { title?: unknown; description?: unknown };
let title = typeof value.title === 'string' ? value.title.replace(/\s+/g, ' ').replace(/^["'“]+|["'”.]+$/g, '').trim().slice(0, 80) : '';
const description = typeof value.description === 'string' ? value.description.replace(/\s+/g, ' ').trim().slice(0, 300) : '';
if (!title) return null;
const lower = new Set(taken.map((t) => t.toLowerCase()));
if (lower.has(title.toLowerCase())) {
let n = 2;
while (lower.has(`${title} ${n}`.toLowerCase())) n += 1;
title = `${title} ${n}`;
}
return { title, description };
} catch (err) {
if (opts.signal?.aborted) throw err;
app.log('warn', 'Naming a generated set failed; keeping the default title', err instanceof Error ? err.message : err);
return null;
}
}
async function generateNote(app: AppContext, draftId: string, req: GenerateRequest, signal: AbortSignal, budgetTokens: number, window: number): Promise<void> {
const { db } = app;
const resolved = resolveModel(app, 'generate', req.modelId);