// Rubric, credits and the deterministic reviewer. // The reviewer is rule-based and runs with no model, so every tool works // offline. When a model is connected, marking.js can also build the JSON prompt // used by the AI marker. export const PARAGRAPH_RUBRIC = [ { id: "point", title: "Point", max: 2, guidance: "A clear, focused answer to the question that uses the text's terms. 2 = precise and relevant; 1 = general or partly off-question; 0 = missing." }, { id: "evidence", title: "Evidence", max: 2, guidance: "A short, accurate quotation embedded in the sentence. 2 = accurate, concise and well chosen; 1 = present but vague, long or loosely used; 0 = none. A quotation missing from a partial extract is not penalised." }, { id: "method", title: "Method", max: 2, guidance: "Names a technique or a deliberate authorial choice (word class, imagery, structure, form). 2 = precise terminology; 1 = vague reference to language; 0 = none." }, { id: "effect", title: "Effect", max: 3, guidance: "Explains how the method shapes the reader's response, with a developed 'because'. 3 = layered, alternative reading; 2 = clear effect explained; 1 = asserted effect; 0 = none." }, { id: "link", title: "Link", max: 1, guidance: "Ties the paragraph back to the question or the text's wider ideas. 1 = explicit link; 0 = missing." } ]; export const ESSAY_RUBRICS = { introduction: [ { id: "focus", title: "Focus", max: 2, guidance: "Directly answers the question with a shaped line of argument." }, { id: "thesis", title: "Thesis", max: 2, guidance: "A clear overall argument that the essay will prove." } ], body_1: [ { id: "point", title: "Point", max: 2, guidance: "A topic sentence that advances the argument." }, { id: "evidence", title: "Evidence", max: 2, guidance: "Up to three short, accurate quotations, embedded." }, { id: "analysis", title: "Analysis", max: 2, guidance: "Method and effect developed together." } ], body_2: [ { id: "point", title: "Point", max: 2, guidance: "A topic sentence that advances the argument." }, { id: "evidence", title: "Evidence", max: 2, guidance: "Up to three short, accurate quotations, embedded." }, { id: "analysis", title: "Analysis", max: 2, guidance: "Method and effect developed together." } ], body_3: [ { id: "point", title: "Point", max: 2, guidance: "A topic sentence that advances the argument." }, { id: "evidence", title: "Evidence", max: 2, guidance: "Up to three short, accurate quotations, embedded." }, { id: "analysis", title: "Analysis", max: 2, guidance: "Method and effect developed together." } ], conclusion: [ { id: "return", title: "Return to question", max: 2, guidance: "Answers the question again, now that the evidence is in." }, { id: "significance", title: "Wider significance", max: 2, guidance: "Connects to context, the whole text or a lasting idea." } ], cohesion: [ { id: "structure", title: "Structure", max: 2, guidance: "Paragraphs build in a deliberate order and signpost the argument." }, { id: "thread", title: "Thread of argument", max: 2, guidance: "The same argument is developed throughout, not restated." } ] }; export const ESSAY_PART_META = [ { id: "introduction", title: "Introduction", short: "Intro" }, { id: "body_1", title: "Body paragraph 1", short: "Body 1" }, { id: "body_2", title: "Body paragraph 2", short: "Body 2" }, { id: "body_3", title: "Body paragraph 3", short: "Body 3" }, { id: "conclusion", title: "Conclusion", short: "Conclusion" }, { id: "cohesion", title: "Cohesion (whole essay)", short: "Cohesion" } ]; export const CREDIT_COSTS = { paragraphWriting: 20, modelAnswer: 20, essayDeep: 30, mockExam: 40 }; export function creditsForParagraph(score) { if (score >= 10) return 50; if (score === 9) return 30; if (score >= 7) return 15; if (score >= 5) return 5; return 0; } export function creditsForEssay(score) { if (score >= 29) return 200; if (score >= 26) return 120; if (score >= 21) return 60; if (score >= 15) return 20; return 0; } export function streakMultiplier(days) { if (days >= 14) return 1.4; if (days >= 7) return 1.25; if (days >= 3) return 1.1; return 1; } export function awardCredits(base, streakDays) { if (base <= 0) return 0; return Math.round(base * streakMultiplier(streakDays)); } export function levelFor(totalEarned) { if (totalEarned <= 0) return 1; return Math.min(10, 1 + Math.floor(totalEarned / 150)); } export function levelProgress(totalEarned) { const level = levelFor(totalEarned); if (level >= 10) return 1; return (totalEarned - (level - 1) * 150) / 150; } export function levelTitle(level) { return ( [ "Starting out", "Finding your voice", "Close reader", "Confident analyst", "Sharp critic", "Precise writer", "Independent thinker", "Grade 8 habit", "Grade 9 habit", "Examiner's eye" ][Math.min(9, Math.max(0, level - 1))] ); } const DAY = 86400000; export function streakLength(isoDays) { if (!isoDays || isoDays.length === 0) return 0; const days = [...new Set(isoDays)].sort().reverse(); const today = new Date(); const start = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime(); const latest = new Date(days[0] + "T00:00:00").getTime(); if (latest !== start && latest !== start - DAY) return 0; let streak = 0; let expected = latest; for (const iso of days) { const t = new Date(iso + "T00:00:00").getTime(); if (t === expected) { streak += 1; expected -= DAY; } else if (t < expected) break; } return streak; } // --------------------------------------------------------------------------- // Texts // --------------------------------------------------------------------------- export const TEXTS = [ { id: "macbeth", title: "Macbeth", author: "William Shakespeare", kind: "Play" }, { id: "christmas-carol", title: "A Christmas Carol", author: "Charles Dickens", kind: "Novel" }, { id: "inspector-calls", title: "An Inspector Calls", author: "J. B. Priestley", kind: "Play" }, { id: "jekyll-hyde", title: "Jekyll and Hyde", author: "R. L. Stevenson", kind: "Novel" }, { id: "lord-flies", title: "Lord of the Flies", author: "William Golding", kind: "Novel" }, { id: "power-conflict", title: "Power & Conflict poems", author: "AQA anthology", kind: "Poetry" }, { id: "other", title: "Another text", author: "", kind: "Text" } ]; export const SUGGESTED_QUESTIONS = [ "How does Shakespeare present ambition in Macbeth?", "How does Dickens present Scrooge as an outsider?", "How does Priestley use the Inspector to challenge the Birlings?", "How does Stevenson present duality in Jekyll and Hyde?", "How does the writer use structure to build tension?" ]; // --------------------------------------------------------------------------- // Text analysis // --------------------------------------------------------------------------- const DOUBLE_QUOTE = /[“"]([^”"]{2,220})[”"]/g; const SINGLE_QUOTE = /(?:^|[\s(])[‘']([^’']{8,220})[’'](?=[\s.,;:!?)]|$)/g; export function wordCount(text) { return text.trim() ? text.trim().split(/\s+/).length : 0; } export function sentenceList(text) { return text .replace(/\s+/g, " ") .split(/(?<=[.!?])\s+/) .map((s) => s.trim()) .filter(Boolean); } export function normalise(text) { return " " + text .toLowerCase() .replace(/[’‘]/g, "'") .replace(/[“”]/g, '"') .replace(/[^a-z0-9' ]+/g, " ") .replace(/\s+/g, " ") .trim() + " "; } const TECHNIQUES = [ "metaphor", "simile", "personification", "imagery", "semantic field", "juxtaposition", "contrast", "repetition", "alliteration", "sibilance", "onomatopoeia", "hyperbole", "oxymoron", "symbolism", "motif", "foreshadow", "dramatic irony", "soliloquy", "stage direction", "aside", "enjambment", "caesura", "stanza", "rhyme", "rhythm", "iambic", "short sentence", "long sentence", "listing", "rule of three", "rhetorical question", "direct address", "dialect", "colloquial", "satire", "form", "structure", "verb", "noun", "adjective", "adverb", "connotation", "tone", "voice" ]; const EFFECT_VERBS = [ "suggests", "suggesting", "conveys", "conveying", "creates", "creating", "implies", "implying", "highlights", "emphasises", "emphasizes", "reveals", "revealing", "reflects", "evokes", "illustrates", "demonstrates", "underscores", "presents", "portrays", "exposes", "critiques", "challenges", "reinforces", "foreshadows", "makes the reader", "allows the reader", "shows the reader" ]; const CAUSAL = ["because", "which", "therefore", "as a result", "so that", "in order to", "this creates", "allowing", "enabling", "meaning"]; const LINK_PHRASES = ["therefore", "overall", "this shows", "this suggests", "the wider", "context", "audience", "reader", "the text", "the play", "the novel"]; function findTechniques(lower) { return TECHNIQUES.filter((t) => lower.includes(t)); } function findEffectVerbs(lower) { return EFFECT_VERBS.filter((v) => lower.includes(v)); } function questionWords(question) { const stop = new Set(["how", "does", "the", "and", "in", "of", "to", "a", "an", "is", "are", "what", "why", "writer", "present", "use", "using", "explain"]); return question .toLowerCase() .replace(/[^a-z0-9 ]+/g, " ") .split(/\s+/) .filter((w) => w.length > 2 && !stop.has(w)); } function overlap(text, words) { const lower = " " + text.toLowerCase() + " "; return words.filter((w) => lower.includes(w)).length; } export function extractQuotes(text) { const found = []; let match; DOUBLE_QUOTE.lastIndex = 0; while ((match = DOUBLE_QUOTE.exec(text)) !== null) found.push(match[1].trim()); SINGLE_QUOTE.lastIndex = 0; while ((match = SINGLE_QUOTE.exec(text)) !== null) found.push(match[1].trim()); return found.filter((q) => q.length > 1); } export function checkQuotes(text, extract) { const quotes = extractQuotes(text); const haystack = extract && extract.trim() ? normalise(extract) : null; return quotes.map((q) => { const words = wordCount(q); const inExtract = haystack ? haystack.includes(normalise(q).trim()) : null; let note = null; if (words > 12) note = "Long quotation — trim it to a few words and embed it in your sentence."; else if (inExtract === false) note = "Not found in the extract you pasted. It may be from another part of the text — check your copy."; return { text: q, words, inExtract, note }; }); } // --------------------------------------------------------------------------- // Scoring // --------------------------------------------------------------------------- function clamp(n, min, max) { return Math.max(min, Math.min(max, n)); } function scoreCriterion(id, ctx) { switch (id) { case "point": case "focus": { if (ctx.words >= 45 && ctx.overlap >= 2) return 2; if (ctx.words >= 20 && (ctx.overlap >= 1 || ctx.linkHit)) return 1; return 0; } case "thesis": { if (/(this essay will|i will argue|i will show|the essay will|argue that|thesis)/.test(ctx.lower) && ctx.words >= 25) return 2; if (ctx.overlap >= 2 && ctx.words >= 35) return 1; return 0; } case "evidence": { if (ctx.quotes.length >= 2 && ctx.quotes.some((q) => q.words <= 12)) return 2; if (ctx.quotes.length >= 1) return 1; return 0; } case "method": { if (ctx.techniques.length >= 2) return 2; if (ctx.techniques.length === 1) return 1; return 0; } case "analysis": { if (ctx.techniques.length >= 1 && ctx.effectVerbs.length >= 1 && ctx.hasBecause) return 2; if (ctx.techniques.length >= 1 || ctx.effectVerbs.length >= 1) return 1; return 0; } case "effect": { if (ctx.effectVerbs.length >= 2 && ctx.hasBecause && ctx.sentences >= 4) return 3; if (ctx.effectVerbs.length >= 1 && (ctx.hasBecause || ctx.effectVerbs.length >= 2)) return 2; if (ctx.effectVerbs.length >= 1 || ctx.hasBecause) return 1; return 0; } case "link": { if (ctx.lastSentenceOverlap >= 1 || (ctx.linkHit && ctx.overlap >= 1)) return 1; return 0; } case "return": { if (ctx.lastSentenceOverlap >= 2) return 2; if (ctx.lastSentenceOverlap >= 1 || ctx.linkHit) return 1; return 0; } case "significance": { if (/(context|society|audience|victorian|edwardian|shakespeare|priestley|dickens|stevenson|golding|modern|today)/.test(ctx.lower) && ctx.overlap >= 1) return 2; if (/(context|society|audience|victorian|edwardian|shakespeare|priestley|dickens|stevenson|golding|modern|today)/.test(ctx.lower)) return 1; return 0; } case "structure": { if (ctx.paragraphs >= 3 && /(firstly|secondly|finally|however|therefore|in contrast|moreover)/.test(ctx.lower)) return 2; if (ctx.paragraphs >= 2) return 1; return 0; } case "thread": { if (ctx.repeatedTerms >= 2 && ctx.paragraphs >= 3) return 2; if (ctx.repeatedTerms >= 1) return 1; return 0; } default: return 0; } } function noteFor(id, ctx, score, max) { const full = score === max; switch (id) { case "point": case "focus": return full ? "Focused on the question and using the text's own terms." : ctx.overlap === 0 ? "The opening does not pick up the question's key words. Name the character, relationship or idea you are answering about." : "Sharpen the opening so it answers the exact question, not the text in general."; case "thesis": return full ? "A clear overall argument is promised." : "Add one sentence that says what the whole essay will prove: 'This essay will argue that…'."; case "evidence": if (ctx.quotes.length === 0) return "No quotation. Choose two or three words and embed them in your own sentence."; if (ctx.quotes.length === 1) return "One quotation found. A second short one would let you compare or develop the point."; return full ? "Short quotations, ready to analyse." : "Trim the longest quotation: the best evidence is usually two to five words."; case "method": if (full) return "Precise technique named: " + ctx.techniques.slice(0, 2).join(", ") + "."; if (ctx.techniques.length === 1) return "One technique named (" + ctx.techniques[0] + "). Name a second choice — structure, form or a word class."; return "Name the writer's method exactly: metaphor, personification, a short sentence, a stage direction…"; case "analysis": if (full) return "Method and effect are working together."; return "Link the technique to its effect in the same sentence: 'The … suggests … because …'."; case "effect": if (full) return "Developed effect with a reason — exactly what examiners reward."; if (ctx.effectVerbs.length === 0) return "The effect is not explained yet. Add what the reader feels or understands, and why."; return "Push the effect further with 'because…', or offer an alternative reading."; case "link": return full ? "Tied back to the question." : "End by returning to the question's key words, or to the text's wider idea."; case "return": return full ? "Returns to the question with the evidence behind it." : "Answer the question again in your final sentence, now that the evidence is in."; case "significance": return full ? "Connects the detail to context or the whole text." : "Add one sentence on why this matters beyond the quotation — context, the whole text, or the reader."; case "structure": return full ? "The argument is signposted and ordered." : "Signpost the argument: 'Firstly… However… Finally…'."; case "thread": return full ? "The same argument is developed across the essay." : "Repeat one key term across paragraphs so the argument feels continuous."; default: return ""; } } export function reviewText({ text, question = "", extract = "", rubric, title = "" }) { const clean = text.trim(); const words = wordCount(clean); const sentences = sentenceList(clean); const lower = " " + clean.toLowerCase() + " "; const quotes = checkQuotes(clean, extract); const techniques = findTechniques(lower); const effectVerbs = findEffectVerbs(lower); const qWords = questionWords(question); const questionOverlap = overlap(clean, qWords); const lastSentence = sentences[sentences.length - 1] || ""; const lastSentenceOverlap = overlap(lastSentence, qWords); const paragraphs = clean.split(/\n\s*\n/).filter((p) => p.trim().length > 0).length || (words > 0 ? 1 : 0); const terms = qWords.filter((w) => (lower.match(new RegExp("\\b" + w + "\\b", "g")) || []).length >= 2); const ctx = { text: clean, lower, words, sentences: sentences.length, quotes, techniques, effectVerbs, hasBecause: CAUSAL.some((c) => lower.includes(c)), linkHit: LINK_PHRASES.some((p) => lower.includes(p)), overlap: questionOverlap, lastSentenceOverlap, paragraphs, repeatedTerms: terms.length }; const criteria = rubric.map((c) => { const raw = scoreCriterion(c.id, ctx); const score = clamp(raw, 0, c.max); return { ...c, score, note: noteFor(c.id, ctx, score, c.max) }; }); const total = criteria.reduce((sum, c) => sum + c.score, 0); const max = criteria.reduce((sum, c) => sum + c.max, 0); const sorted = [...criteria].sort((a, b) => b.score / b.max - a.score / a.max); const best = sorted[0]; const worst = sorted[sorted.length - 1]; const strengths = []; if (quotes.length) strengths.push("You used " + quotes.length + " quotation" + (quotes.length === 1 ? "" : "s") + ": " + quotes.slice(0, 2).map((q) => "“" + q.text + "”").join(", ") + "."); if (techniques.length) strengths.push("Named method" + (techniques.length === 1 ? "" : "s") + ": " + techniques.slice(0, 3).join(", ") + "."); if (ctx.hasBecause) strengths.push("You explained a cause, not just an effect — that is where analysis starts."); if (best && best.score > 0 && strengths.length < 2) strengths.push(best.title + ": " + best.note); if (strengths.length === 0) strengths.push("You have made a start. The first step is one clear point in your own words."); const allFull = criteria.every((c) => c.score === c.max); const improvements = allFull ? [] : [worst.title + ": " + worst.note]; if (quotes.some((q) => q.words > 12)) improvements.push("Trim long quotations to the few words that carry the meaning."); if (!ctx.hasBecause && words > 30) improvements.push("Add one 'because…' to turn an asserted effect into an explanation."); const nextStep = allFull ? "Full marks here. Keep this paragraph as a model, then try the same question on a second extract or build it into a full essay." : worst.id === "evidence" ? "Write the next version with two short quotations, each embedded in a sentence of your own." : worst.id === "method" ? "Rewrite one sentence to name the exact technique, then say what it makes the reader feel." : worst.id === "effect" ? "Take your strongest quotation and add: 'This suggests … because …'." : "Rewrite the weakest sentence to answer the question directly, then re-mark it."; return { total, max, criteria, strengths, improvements: improvements.slice(0, 3), nextStep, quotes, techniques, engine: "offline", title }; } export function reviewParagraph(args) { return reviewText({ ...args, rubric: PARAGRAPH_RUBRIC }); } export function reviewEssayPart(part, args) { return reviewText({ ...args, rubric: ESSAY_RUBRICS[part] || PARAGRAPH_RUBRIC }); } export function combineEssay(parts) { const total = parts.reduce((sum, p) => sum + (p ? p.total : 0), 0); const max = parts.reduce((sum, p) => sum + (p ? p.max : 0), 0); return { total, max }; } // --------------------------------------------------------------------------- // Model prompt + response parsing // --------------------------------------------------------------------------- export function buildMarkingMessages({ text, question, extract, rubric, textTitle, mode }) { const system = [ "You are Explication, a GCSE English Literature writing coach for students in England.", "You mark the student's own writing against the rubric, name what works, then name the single highest-impact improvement.", "Reply in British English, address the student as 'you'.", "Return ONE JSON object only, with this shape:", '{"scores":{"":0},"strengths":["..."],"improvements":["..."],"nextStep":"...","quoteNotes":["..."]}', "Scores must be whole numbers no higher than each criterion's maximum.", "Do not write the student's paragraph for them." ].join(" "); const rubricText = rubric.map((c) => `${c.id} (0-${c.max}): ${c.title}. ${c.guidance}`).join("\n"); const user = [ `Mode: ${mode || "paragraph"}`, textTitle ? `Text: ${textTitle}` : "", question ? `Question: ${question}` : "", `Rubric:\n${rubricText}`, extract ? `Extract the student supplied:\n"""${extract.slice(0, 4000)}"""` : "No extract supplied.", `Student writing:\n"""${text}"""` ].filter(Boolean).join("\n\n"); return [ { role: "system", content: system }, { role: "user", content: user } ]; } export function parseMarkingReply(raw, rubric) { const start = raw.indexOf("{"); const end = raw.lastIndexOf("}"); if (start === -1 || end === -1) throw new Error("The model did not return JSON."); const data = JSON.parse(raw.slice(start, end + 1)); const scores = data.scores || {}; const criteria = rubric.map((c) => { const value = Number(scores[c.id]); const score = clamp(Number.isFinite(value) ? Math.round(value) : 0, 0, c.max); return { ...c, score, note: "" }; }); const total = criteria.reduce((sum, c) => sum + c.score, 0); return { total, max: rubric.reduce((sum, c) => sum + c.max, 0), criteria, strengths: Array.isArray(data.strengths) ? data.strengths.slice(0, 4).map(String) : [], improvements: Array.isArray(data.improvements) ? data.improvements.slice(0, 3).map(String) : [], nextStep: typeof data.nextStep === "string" ? data.nextStep : "", quotes: [], techniques: [], engine: "model" }; }