@okhay-p/mivra 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +2 -0
  2. package/THIRD_PARTY_NOTICES.md +250 -0
  3. package/dist/chunk-B47HA6IQ.js +2294 -0
  4. package/dist/chunk-B47HA6IQ.js.map +7 -0
  5. package/dist/{chunk-ODFBAPPH.js → chunk-DYXNHODU.js} +9 -3
  6. package/dist/chunk-DYXNHODU.js.map +7 -0
  7. package/dist/{chunk-KUKQU7EQ.js → chunk-VHOVRHI3.js} +38 -10
  8. package/dist/{chunk-KUKQU7EQ.js.map → chunk-VHOVRHI3.js.map} +2 -2
  9. package/dist/cli.js +807 -44
  10. package/dist/cli.js.map +4 -4
  11. package/dist/{client-5YDLS4KV.js → client-4UG5W5NJ.js} +2 -2
  12. package/dist/exercise-child.js +37 -0
  13. package/dist/exercise-child.js.map +7 -0
  14. package/dist/extract-child.js +1 -1
  15. package/dist/python-child.js +51 -0
  16. package/dist/python-child.js.map +7 -0
  17. package/dist/{start-76LKE3DL.js → start-SX3BCBIN.js} +1215 -237
  18. package/dist/start-SX3BCBIN.js.map +7 -0
  19. package/drizzle/0019_public_doctor_faustus.sql +1 -0
  20. package/drizzle/0020_early_wolfpack.sql +3 -0
  21. package/drizzle/meta/0019_snapshot.json +2288 -0
  22. package/drizzle/meta/0020_snapshot.json +2297 -0
  23. package/drizzle/meta/_journal.json +14 -0
  24. package/package.json +6 -1
  25. package/web/assets/emscripten-module-uFzwHH0Y.wasm +0 -0
  26. package/web/assets/emscripten-module.browser-D72eEgXo.js +1 -0
  27. package/web/assets/exercise-workers/exercise.worker-DzC1lTCg.js +265 -0
  28. package/web/assets/exercise-workers/python-exercise.worker-CtSr-syJ.js +236 -0
  29. package/web/assets/ffi-4V2b7xu3.js +1 -0
  30. package/web/assets/index-D3M-SX0V.js +538 -0
  31. package/web/assets/index-DUFQVtIh.css +1 -0
  32. package/web/assets/module-ES6BEMUI-Chb6aYUZ.js +1 -0
  33. package/web/assets/notes-graph.worker-Dqb5HK34.js +1 -0
  34. package/web/assets/render.worker-D6KYAHiU.js +537 -0
  35. package/web/index.html +8 -3
  36. package/dist/chunk-ODFBAPPH.js.map +0 -7
  37. package/dist/chunk-YACRW47X.js +0 -1203
  38. package/dist/chunk-YACRW47X.js.map +0 -7
  39. package/dist/start-76LKE3DL.js.map +0 -7
  40. package/web/assets/index-C_DsRKCc.css +0 -1
  41. package/web/assets/index-DbKDW1xS.js +0 -413
  42. package/web/assets/notes-graph.worker-DaVQvftJ.js +0 -1
  43. package/web/assets/render.worker-BAfybD27.js +0 -416
  44. /package/dist/{client-5YDLS4KV.js.map → client-4UG5W5NJ.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../protocol/src/code-exercise.ts", "../../protocol/src/code-exercise-runner.ts", "../../protocol/src/code-exercise-python.ts", "../../protocol/src/index.ts", "../../protocol/src/artifact-math-input.ts", "../../protocol/src/math-text.ts", "../../protocol/src/algorithm-trace.ts", "../../protocol/src/code-walkthrough.ts", "../../protocol/src/composition.ts", "../../protocol/src/course.ts", "../../protocol/src/graph.ts", "../../protocol/src/multiple-choice.ts", "../../protocol/src/project-milestone.ts", "../../protocol/src/set-diagram.ts", "../../protocol/src/table.ts", "../../protocol/src/worked-steps.ts", "../../protocol/src/lesson.ts", "../../protocol/src/memory.ts", "../../protocol/src/document.ts", "../../protocol/src/vault.ts", "../../protocol/src/knowledge.ts"],
4
+ "sourcesContent": ["import { z } from \"zod\";\n\n/**\n * code_exercise v1: a single-file coding exercise the learner edits and runs in the browser (ADR-016). The\n * tutor writes the instructions, starter code, test cases and a reference solution. When the exercise is\n * created the server runs the reference against every case, and the expected results come from that run,\n * never from text the model typed; an exercise whose reference fails is rejected. The reference solution\n * and the hidden cases' expected results stay on the server. The browser runs the learner's code on every\n * case and reports what it produced; the server compares that with the expected results (grading is\n * deterministic, ADR-006, though the outputs come from the browser and aren't tamper-proof, ADR-016).\n *\n * JavaScript runs in QuickJS (code-exercise-runner.ts) and Python in Pyodide (code-exercise-python.ts), with the\n * same case kinds, limits and comparison for both.\n */\n\nexport const EXERCISE_LANGUAGES = [\"javascript\", \"python\"] as const;\nexport const ExerciseLanguage = z.enum(EXERCISE_LANGUAGES);\nexport type ExerciseLanguage = z.infer<typeof ExerciseLanguage>;\n\nexport const MAX_EXERCISE_CASES = 20;\n/** Starter code and the reference solution. */\nexport const MAX_EXERCISE_CODE_CHARS = 10_000;\n/** The learner's code as submitted: room to grow past the starter. */\nexport const MAX_SUBMITTED_CODE_CHARS = 50_000;\nexport const MAX_CASE_INPUT_CHARS = 10_000;\n/** One case's captured output (stdout and stderr together) and its return value's JSON, each. */\nexport const MAX_CASE_OUTPUT_CHARS = 20_000;\nexport const MAX_CASE_ERROR_CHARS = 2_000;\n\n/**\n * The limits one case runs under, in the browser and on the server alike. For JavaScript, QuickJS's interrupt\n * handler stops it after `timeMs`, its WebAssembly memory can't grow past `memoryBytes` (QuickJS's own baseline\n * included), and its stack is capped below the JavaScript engine's own, so deep recursion fails cleanly. Python\n * gets the same time and output limits through Pyodide's interrupt check; its memory can't be capped (ADR-016),\n * and its recursion limit is Python's default.\n */\nexport const EXERCISE_LIMITS = {\n timeMs: 2_000,\n memoryBytes: 64 * 1024 * 1024,\n stackBytes: 384 * 1024,\n outputChars: MAX_CASE_OUTPUT_CHARS,\n} as const;\nexport type ExerciseLimits = { timeMs: number; memoryBytes: number; stackBytes: number; outputChars: number };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst PYTHON_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst PYTHON_KEYWORDS = new Set(\n \"False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield\".split(\" \"),\n);\n\nconst hidden = z\n .boolean()\n .optional()\n .describe(\"Hidden from the learner's view until they submit: use for edge cases. At least one case must be visible.\");\n\nexport const ExerciseStdioCaseInput = z\n .object({\n kind: z.literal(\"stdio\"),\n stdin: z\n .string()\n .max(MAX_CASE_INPUT_CHARS)\n .describe('The text the program reads: in JavaScript the global `stdin` string or `readLine()`, in Python input() or sys.stdin. Use \"\" for none.'),\n hidden,\n })\n .strict();\n\nexport const ExerciseCallCaseInput = z\n .object({\n kind: z.literal(\"call\"),\n args: z\n .string()\n .max(MAX_CASE_INPUT_CHARS)\n .describe('The arguments to call functionName with, as a JSON array, e.g. \"[[3, 1, 2], 2]\" or \"[]\".'),\n hidden,\n })\n .strict();\n\nexport const ExerciseCaseInput = z.discriminatedUnion(\"kind\", [ExerciseStdioCaseInput, ExerciseCallCaseInput]);\nexport type ExerciseCaseInput = z.infer<typeof ExerciseCaseInput>;\n\n/** What the reference produced for a case: printed output for stdio, the return value's JSON for a call. */\nexport const ExerciseExpected = z.union([\n z.object({ stdout: z.string().max(MAX_CASE_OUTPUT_CHARS) }).strict(),\n z.object({ returned: z.string().max(MAX_CASE_OUTPUT_CHARS) }).strict(),\n]);\nexport type ExerciseExpected = z.infer<typeof ExerciseExpected>;\n\nconst exerciseFields = {\n concept: z\n .string()\n .trim()\n .min(1)\n .max(80)\n .describe('Short label for the concept being practised, e.g. \"array reduce\". Used to track progress.'),\n title: z.string().trim().min(1).max(120),\n instructions: z\n .string()\n .trim()\n .min(1)\n .max(4000)\n .describe(\"What the learner's code must do, as markdown. Say exactly what to print or return, and for stdio how the input is laid out.\"),\n language: ExerciseLanguage,\n starterCode: z\n .string()\n .max(MAX_EXERCISE_CODE_CHARS)\n .describe(\"The code the editor starts with, e.g. the function's signature with an empty body. May be empty.\"),\n functionName: z\n .string()\n .regex(IDENTIFIER)\n .max(80)\n .optional()\n .describe(\"The function call cases call, declared at the top level of the learner's code. Required when there are call cases.\"),\n};\n\nfunction checkCases(spec: { language: ExerciseLanguage; functionName?: string; cases: ExerciseCaseInput[] }, ctx: z.RefinementCtx) {\n if (spec.language === \"python\" && spec.functionName !== undefined && (!PYTHON_IDENTIFIER.test(spec.functionName) || PYTHON_KEYWORDS.has(spec.functionName))) {\n ctx.addIssue({ code: \"custom\", path: [\"functionName\"], message: \"functionName must be a Python identifier\" });\n }\n if (spec.cases.every((c) => c.hidden)) ctx.addIssue({ code: \"custom\", path: [\"cases\"], message: \"at least one case must be visible\" });\n const calls = spec.cases.some((c) => c.kind === \"call\");\n if (calls && !spec.functionName) ctx.addIssue({ code: \"custom\", path: [\"functionName\"], message: \"functionName is required for call cases\" });\n spec.cases.forEach((c, i) => {\n if (c.kind !== \"call\") return;\n let args: unknown;\n try {\n args = JSON.parse(c.args);\n } catch {\n return ctx.addIssue({ code: \"custom\", path: [\"cases\", i, \"args\"], message: \"args must be a JSON array\" });\n }\n if (!Array.isArray(args)) ctx.addIssue({ code: \"custom\", path: [\"cases\", i, \"args\"], message: \"args must be a JSON array\" });\n });\n}\n\n/** The tool's input: what the model writes. Expected results aren't part of it; the server computes them. */\nexport const CodeExerciseInput = z\n .object({\n ...exerciseFields,\n cases: z.array(ExerciseCaseInput).min(1).max(MAX_EXERCISE_CASES).describe(\"1-20 test cases. Keep each fast: every case has a 2 s limit.\"),\n referenceSolution: z\n .string()\n .min(1)\n .max(MAX_EXERCISE_CODE_CHARS)\n .describe(\"A complete correct solution. Mivra runs it on every case to get the expected results; it is never shown to the learner. It must be deterministic (no random numbers or clock time).\"),\n })\n .strict()\n .superRefine(checkCases);\nexport type CodeExerciseInput = z.infer<typeof CodeExerciseInput>;\n\nexport const ExerciseCase = z.discriminatedUnion(\"kind\", [\n ExerciseStdioCaseInput.extend({ expected: ExerciseExpected }),\n ExerciseCallCaseInput.extend({ expected: ExerciseExpected }),\n]);\nexport type ExerciseCase = z.infer<typeof ExerciseCase>;\n\n/** The stored spec: the input with each case's expected result from the reference run. */\nexport const CodeExerciseSpec = z\n .object({\n ...exerciseFields,\n cases: z.array(ExerciseCase).min(1).max(MAX_EXERCISE_CASES),\n referenceSolution: z.string().max(MAX_EXERCISE_CODE_CHARS),\n })\n .strict();\nexport type CodeExerciseSpec = z.infer<typeof CodeExerciseSpec>;\n\n/** A case as the client sees it: hidden cases carry their input (the browser runs them) but not their expected result. */\nexport const ExercisePublicCase = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"stdio\"), stdin: z.string(), hidden: z.boolean(), expected: ExerciseExpected.optional() }).strict(),\n z.object({ kind: z.literal(\"call\"), args: z.string(), hidden: z.boolean(), expected: ExerciseExpected.optional() }).strict(),\n]);\nexport type ExercisePublicCase = z.infer<typeof ExercisePublicCase>;\n\nexport const CodeExercisePublic = z\n .object({\n concept: z.string(),\n title: z.string(),\n instructions: z.string(),\n language: ExerciseLanguage,\n starterCode: z.string(),\n functionName: z.string().optional(),\n cases: z.array(ExercisePublicCase),\n })\n .strict();\nexport type CodeExercisePublic = z.infer<typeof CodeExercisePublic>;\n\nexport function toCodeExercisePublic(spec: CodeExerciseSpec): CodeExercisePublic {\n return {\n concept: spec.concept,\n title: spec.title,\n instructions: spec.instructions,\n language: spec.language,\n starterCode: spec.starterCode,\n ...(spec.functionName ? { functionName: spec.functionName } : {}),\n cases: spec.cases.map((c) => {\n const isHidden = c.hidden ?? false;\n const input = c.kind === \"stdio\" ? { kind: \"stdio\" as const, stdin: c.stdin } : { kind: \"call\" as const, args: c.args };\n return { ...input, hidden: isHidden, ...(isHidden ? {} : { expected: c.expected }) };\n }),\n };\n}\n\n/** What running one case produced. `returned` is the return value's JSON (or \"undefined\" in JavaScript), for call cases only. */\nexport const ExerciseCaseRun = z\n .object({\n stdout: z.string().max(MAX_CASE_OUTPUT_CHARS),\n stderr: z.string().max(MAX_CASE_OUTPUT_CHARS).optional(),\n returned: z.string().max(MAX_CASE_OUTPUT_CHARS).optional(),\n error: z.string().max(MAX_CASE_ERROR_CHARS).optional(),\n })\n .strict();\nexport type ExerciseCaseRun = z.infer<typeof ExerciseCaseRun>;\n\n/** A submission: the learner's code and what it produced on every case, in case order. */\nexport const CodeExerciseAnswer = z\n .object({\n code: z.string().max(MAX_SUBMITTED_CODE_CHARS),\n results: z.array(ExerciseCaseRun).min(1).max(MAX_EXERCISE_CASES),\n })\n .strict();\nexport type CodeExerciseAnswer = z.infer<typeof CodeExerciseAnswer>;\n\nexport const CodeExerciseGrade = z\n .object({\n correct: z.boolean(),\n passed: z.number().int().nonnegative(),\n total: z.number().int().positive(),\n cases: z.array(z.object({ passed: z.boolean() }).strict()),\n })\n .strict();\nexport type CodeExerciseGrade = z.infer<typeof CodeExerciseGrade>;\n\n/**\n * Printed output as it's compared: line endings as \\n, trailing whitespace dropped from each line and trailing\n * blank lines dropped. Leading whitespace and blank lines between lines count.\n */\nexport function normaliseOutput(text: string): string {\n return text\n .replace(/\\r\\n?/g, \"\\n\")\n .split(\"\\n\")\n .map((line) => line.replace(/[ \\t]+$/, \"\"))\n .join(\"\\n\")\n .replace(/\\n+$/, \"\");\n}\n\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === \"object\") {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical((value as Record<string, unknown>)[key])]));\n }\n return value;\n}\n\n/** Whether two return values' JSON texts are the same value. Object key order doesn't matter; \"undefined\" matches only itself. */\nexport function sameReturnValue(a: string, b: string): boolean {\n if (a === \"undefined\" || b === \"undefined\") return a === b;\n try {\n return JSON.stringify(canonical(JSON.parse(a))) === JSON.stringify(canonical(JSON.parse(b)));\n } catch {\n return false;\n }\n}\n\n/** Whether a run produced a case's expected result. A run that threw or hit a limit never passes. */\nexport function casePassed(expected: ExerciseExpected, run: ExerciseCaseRun): boolean {\n if (run.error !== undefined) return false;\n if (\"stdout\" in expected) return normaliseOutput(run.stdout) === normaliseOutput(expected.stdout);\n return run.returned !== undefined && sameReturnValue(run.returned, expected.returned);\n}\n\n/** The expected result recorded from a reference run. Throws if the run failed. */\nexport function expectedFrom(testCase: ExerciseCaseInput, run: ExerciseCaseRun): ExerciseExpected {\n if (run.error !== undefined) throw new Error(run.error);\n if (testCase.kind === \"stdio\") return { stdout: normaliseOutput(run.stdout) };\n if (run.returned === undefined) throw new Error(\"The function returned nothing Mivra could record\");\n return { returned: run.returned };\n}\n\n/** Deterministic grader. Throws if the answer doesn't report one result per case. */\nexport function gradeCodeExercise(spec: CodeExerciseSpec, answer: CodeExerciseAnswer): CodeExerciseGrade {\n if (answer.results.length !== spec.cases.length) {\n throw new RangeError(`Expected results for ${spec.cases.length} cases, got ${answer.results.length}`);\n }\n const cases = spec.cases.map((c, i) => ({ passed: casePassed(c.expected, answer.results[i]!) }));\n const passed = cases.filter((c) => c.passed).length;\n return { correct: passed === cases.length, passed, total: cases.length, cases };\n}\n", "import type { QuickJSContext, QuickJSHandle, QuickJSWASMModule } from \"quickjs-emscripten-core\";\nimport { EXERCISE_LIMITS, MAX_CASE_ERROR_CHARS, type ExerciseCaseInput, type ExerciseCaseRun, type ExerciseLimits } from \"./code-exercise.js\";\n\n/**\n * Runs one JavaScript exercise case in QuickJS (ADR-016). The browser's worker and the server's reference\n * check both call this, so the learner's code and the reference run the same way. Each case gets a fresh\n * QuickJS instance whose WebAssembly memory has a fixed maximum (QuickJS's own malloc limit can't see block\n * sizes in this build, so it isn't used), a deadline through the interrupt handler, and a stack limit. The\n * guest sees only standard JavaScript plus `console`, the case's `stdin` and `readLine()`: no DOM, network,\n * file system or timers. The caller supplies the QuickJS module, so this file imports only its types.\n *\n * The interrupt handler runs between bytecode instructions, so a long native call (a huge `Array.fill`, say)\n * can overrun the deadline. Callers keep a hard limit of their own around a case: the browser terminates its\n * worker, and the server kills the reference check's process.\n */\n\nconst FILENAME = \"solution.js\";\n\n// Trusted setup, run before the learner's code. Values are shown the same way in both runs, so stdio cases\n// compare like with like.\nconst PRELUDE = `(() => {\n const write = globalThis.__mivra_write;\n const text = globalThis.__mivra_stdin;\n delete globalThis.__mivra_write;\n delete globalThis.__mivra_stdin;\n const show = (value) => {\n if (typeof value === \"string\") return value;\n if (typeof value === \"function\") return \"[Function \" + (value.name || \"anonymous\") + \"]\";\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Error) return String(value);\n try { const json = JSON.stringify(value); if (json !== undefined) return json; } catch {}\n }\n return String(value);\n };\n const line = (args) => Array.prototype.map.call(args, show).join(\" \");\n const out = function () { write(0, line(arguments)); };\n const err = function () { write(1, line(arguments)); };\n globalThis.console = { log: out, info: out, debug: out, warn: err, error: err };\n const lines = text === \"\" ? [] : text.replace(/\\\\r\\\\n?/g, \"\\\\n\").replace(/\\\\n$/, \"\").split(\"\\\\n\");\n let next = 0;\n globalThis.stdin = text;\n globalThis.readLine = () => (next < lines.length ? lines[next++] : null);\n})();`;\n\nconst SERIALISE = `(value) => {\n if (value === undefined) return \"undefined\";\n const json = JSON.stringify(value);\n return json === undefined ? \"undefined\" : json;\n}`;\n\nexport interface RunCaseOptions {\n code: string;\n functionName?: string;\n testCase: ExerciseCaseInput;\n limits?: ExerciseLimits;\n /** The clock, for tests. */\n now?: () => number;\n}\n\nclass Capped {\n stdout = \"\";\n stderr = \"\";\n exceeded = false;\n constructor(private readonly limit: number) {}\n write(stream: number, text: string) {\n if (this.exceeded) return;\n const line = `${text}\\n`;\n const room = this.limit - this.stdout.length - this.stderr.length;\n if (line.length > room) this.exceeded = true;\n const kept = line.slice(0, Math.max(0, room));\n if (stream === 0) this.stdout += kept;\n else this.stderr += kept;\n }\n}\n\nexport const OUTPUT_EXCEEDED = (chars: number) => `Output limit exceeded (${chars.toLocaleString(\"en-US\")} characters).`;\nexport const STACK_EXCEEDED = \"Stack limit exceeded: the code recursed too deeply.\";\nconst formatBytes = (bytes: number) => `${Math.round(bytes / (1024 * 1024))} MB`;\n\n/** Runs one case and reports what it printed, returned or threw. Never throws for anything the guest does. */\nexport function runExerciseCase(module: QuickJSWASMModule, { code, functionName, testCase, limits = EXERCISE_LIMITS, now = Date.now }: RunCaseOptions): ExerciseCaseRun {\n const output = new Capped(limits.outputChars);\n const deadline = now() + limits.timeMs;\n let timedOut = false;\n const runtime = module.newRuntime();\n runtime.setMaxStackSize(limits.stackBytes);\n runtime.setInterruptHandler(() => {\n if (now() > deadline) timedOut = true;\n return timedOut || output.exceeded;\n });\n\n const describe = (vm: QuickJSContext, handle: QuickJSHandle): string => {\n if (timedOut) return `Time limit exceeded (${limits.timeMs / 1000} s): the code ran too long, or never stopped.`;\n if (output.exceeded) return OUTPUT_EXCEEDED(limits.outputChars);\n let message = \"The code threw an error.\";\n try {\n const dumped = vm.dump(handle) as unknown;\n if (dumped && typeof dumped === \"object\" && \"message\" in dumped) {\n const { name, message: text, stack } = dumped as { name?: unknown; message?: unknown; stack?: unknown };\n message = `${typeof name === \"string\" ? name : \"Error\"}: ${String(text)}`;\n const line = typeof stack === \"string\" ? new RegExp(`${FILENAME.replace(\".\", \"\\\\.\")}:(\\\\d+)`).exec(stack)?.[1] : undefined;\n if (line) message += ` (line ${line})`;\n } else {\n message = `Uncaught ${typeof dumped === \"string\" ? dumped : JSON.stringify(dumped) ?? String(dumped)}`;\n }\n } catch {\n // The context may be unusable after running out of memory.\n }\n return friendly(message);\n };\n const friendly = (message: string) => {\n if (/out of memory/i.test(message)) return `Memory limit exceeded (${formatBytes(limits.memoryBytes)}).`;\n if (/stack overflow|call stack size/i.test(message)) return STACK_EXCEEDED;\n return message;\n };\n\n const finish = (outcome: { returned?: string; error?: string }): ExerciseCaseRun => {\n // Output past the cap is cut short, so the run can't count even if it finished before the interrupt handler ran.\n const result = output.exceeded && outcome.error === undefined ? { error: OUTPUT_EXCEEDED(limits.outputChars) } : outcome;\n return {\n stdout: output.stdout,\n ...(output.stderr ? { stderr: output.stderr } : {}),\n ...(result.returned !== undefined ? { returned: result.returned } : {}),\n ...(result.error !== undefined ? { error: result.error.slice(0, MAX_CASE_ERROR_CHARS) } : {}),\n };\n };\n\n let vm: QuickJSContext | undefined;\n try {\n vm = runtime.newContext();\n const context = vm;\n const write = context.newFunction(\"__mivra_write\", (stream, text) => {\n output.write(context.getNumber(stream), context.getString(text));\n });\n context.setProp(context.global, \"__mivra_write\", write);\n write.dispose();\n const stdin = context.newString(testCase.kind === \"stdio\" ? testCase.stdin : \"\");\n context.setProp(context.global, \"__mivra_stdin\", stdin);\n stdin.dispose();\n\n // Runs code, then any promise jobs it queued; returns the result's handle, or an error message.\n const evaluate = (source: string, filename: string): { value: QuickJSHandle } | { error: string } => {\n const result = context.evalCode(source, filename);\n if (result.error) {\n const error = describe(context, result.error);\n result.error.dispose();\n return { error };\n }\n return { value: result.value };\n };\n const settle = (handle: QuickJSHandle): { value: QuickJSHandle } | { error: string } => {\n for (;;) {\n const jobs = runtime.executePendingJobs();\n if (jobs.error) {\n const error = describe(context, jobs.error);\n jobs.error.dispose();\n handle.dispose();\n return { error };\n }\n const state = context.getPromiseState(handle);\n if (state.type === \"fulfilled\") {\n if (state.notAPromise) return { value: handle };\n handle.dispose();\n return { value: state.value };\n }\n if (state.type === \"rejected\") {\n const error = describe(context, state.error);\n state.error.dispose();\n handle.dispose();\n return { error };\n }\n if (jobs.value === 0) {\n handle.dispose();\n return { error: timedOut ? describe(context, context.undefined) : \"The returned promise never settled.\" };\n }\n }\n };\n\n const prelude = context.evalCode(PRELUDE, \"prelude.js\");\n if (prelude.error) {\n const error = describe(context, prelude.error);\n prelude.error.dispose();\n return finish({ error });\n }\n prelude.value.dispose();\n\n const ran = evaluate(code, FILENAME);\n if (\"error\" in ran) return finish(ran);\n const program = settle(ran.value);\n if (\"error\" in program) return finish(program);\n program.value.dispose();\n if (testCase.kind === \"stdio\") return finish({});\n\n const name = functionName ?? \"\";\n const call = evaluate(\n `typeof ${name} === \"function\" ? ${name}(...JSON.parse(${JSON.stringify(testCase.args)})) : (() => { throw new TypeError(${JSON.stringify(`${name} is not defined as a function`)}); })()`,\n \"call.js\",\n );\n if (\"error\" in call) return finish(call);\n const value = settle(call.value);\n if (\"error\" in value) return finish(value);\n const serialise = evaluate(SERIALISE, \"serialise.js\");\n if (\"error\" in serialise) {\n value.value.dispose();\n return finish(serialise);\n }\n const json = context.callFunction(serialise.value, context.undefined, value.value);\n serialise.value.dispose();\n value.value.dispose();\n if (json.error) {\n const error = `The return value can't be recorded as JSON: ${describe(context, json.error)}`;\n json.error.dispose();\n return finish({ error });\n }\n const returned = context.getString(json.value);\n json.value.dispose();\n if (returned.length > limits.outputChars) return finish({ error: `The return value is too large (over ${limits.outputChars.toLocaleString(\"en-US\")} characters).` });\n return finish({ returned });\n } catch (error) {\n // QuickJS itself failed, e.g. memory ran out while setting up. Report it as the case's error.\n const message = error instanceof Error ? error.message : String(error);\n const known = friendly(message);\n return finish({ error: known !== message ? known : timedOut ? `Time limit exceeded (${limits.timeMs / 1000} s).` : `The code couldn't run: ${message}` });\n } finally {\n try {\n vm?.dispose();\n runtime.dispose();\n } catch {\n // A runtime that ran out of memory can fail its own clean-up; it's dropped either way.\n }\n }\n}\n\n/** WebAssembly pages are 64 KiB. QuickJS's build starts with 16 MiB. */\nconst PAGE_BYTES = 64 * 1024;\nconst INITIAL_PAGES = 256;\n\n/** Makes a QuickJS module whose WebAssembly instance uses the given memory (see `newVariant`'s `wasmMemory`). */\nexport type QuickJSModuleFactory = (memory: WebAssembly.Memory) => Promise<QuickJSWASMModule>;\n\n/**\n * Runs one case in its own QuickJS instance, whose memory can't grow past `limits.memoryBytes`. The instance\n * is dropped afterwards, so nothing a case did (or broke) carries over to the next.\n */\nexport async function runExerciseCaseIsolated(newModule: QuickJSModuleFactory, options: RunCaseOptions): Promise<ExerciseCaseRun> {\n const limits = options.limits ?? EXERCISE_LIMITS;\n const maximum = Math.max(INITIAL_PAGES, Math.floor(limits.memoryBytes / PAGE_BYTES));\n const module = await newModule(new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum }));\n return runExerciseCase(module, { ...options, limits });\n}\n", "import { EXERCISE_LIMITS, MAX_CASE_ERROR_CHARS, type ExerciseCaseRun } from \"./code-exercise.js\";\nimport { OUTPUT_EXCEEDED, STACK_EXCEEDED, type RunCaseOptions } from \"./code-exercise-runner.js\";\n\n/**\n * Runs Python exercise cases in Pyodide (ADR-016). The browser's worker and the server's reference check both\n * call this, so the learner's code and the reference run the same way: the same harness, output capture, time\n * limit and messages. The caller loads Pyodide (with `jsglobals: {}`) and keeps it for many cases; this file\n * needs only the few methods below, so it doesn't depend on Pyodide itself.\n *\n * Python can't reach JavaScript once `createPythonCaseRunner` has run: it removes the `js` and `pyodide_js`\n * modules. That isn't a sandbox on its own, since Pyodide can still hand Python a JavaScript object, so each\n * caller also stops strings becoming code (a Content-Security-Policy without 'unsafe-eval' in the browser,\n * `--disallow-code-generation-from-strings` in Node) and removes the network from its global scope.\n *\n * Time is limited through Pyodide's interrupt check, which reads `buffer[0]` every few bytecodes: past the\n * deadline it reads SIGINT and Python raises KeyboardInterrupt, again at every check, so code that catches\n * it still stops. Between cases the deadline stays in the past, so Python that a case left to run later (a\n * callback scheduled through `pyodide.webloop`, say) is interrupted as soon as it starts. A long call into C (a huge `sum(range(...))`) doesn't check, so callers keep a hard limit of\n * their own around a case, as for QuickJS.\n */\n\nexport interface PyodideLike {\n runPython(code: string): unknown;\n setInterruptBuffer(buffer: never): void;\n unregisterJsModule(name: string): void;\n}\n\nconst SIGINT = 2;\n\nconst FILENAME = \"solution.py\";\n\n// Trusted setup, run once per interpreter. Each case gets fresh stdin, stdout, stderr, recursion limit and\n// namespace; modules the code imported stay loaded, as they would in one Python process.\nconst HARNESS = String.raw`\nimport builtins as _mivra_builtins, io as _mivra_io, json as _mivra_json, sys as _mivra_sys, traceback as _mivra_traceback\n\nfor _mivra_name in list(_mivra_sys.modules):\n if _mivra_name == \"js\" or _mivra_name.startswith(\"js.\") or _mivra_name == \"pyodide_js\" or _mivra_name.startswith(\"pyodide_js.\"):\n del _mivra_sys.modules[_mivra_name]\n\n_mivra_recursion_limit = _mivra_sys.getrecursionlimit()\n\n\nclass _MivraOutputLimit(BaseException):\n pass\n\n\nclass _MivraSink:\n def __init__(self, limit):\n self.limit = limit\n self.parts = ([], [])\n self.used = 0\n self.exceeded = False\n\n def write(self, stream, text):\n if self.exceeded:\n raise _MivraOutputLimit()\n room = self.limit - self.used\n if len(text) > room:\n self.exceeded = True\n text = text[: max(0, room)]\n self.parts[stream].append(text)\n self.used += len(text)\n if self.exceeded:\n raise _MivraOutputLimit()\n\n\nclass _MivraStream(_mivra_io.TextIOBase):\n def __init__(self, sink, stream):\n self._sink = sink\n self._stream = stream\n\n def writable(self):\n return True\n\n def write(self, text):\n if not isinstance(text, str):\n raise TypeError(\"write() argument must be str, not \" + type(text).__name__)\n self._sink.write(self._stream, text)\n return len(text)\n\n def flush(self):\n pass\n\n\ndef _mivra_describe(error):\n name = type(error).__name__\n text = str(error)\n message = name + \": \" + text if text else name\n line = None\n if isinstance(error, SyntaxError) and error.filename == \"${FILENAME}\":\n line = error.lineno\n for frame, lineno in _mivra_traceback.walk_tb(error.__traceback__):\n if frame.f_code.co_filename == \"${FILENAME}\":\n line = lineno\n return message + (\" (line \" + str(line) + \")\" if line else \"\")\n\n\ndef _mivra_run(code, function_name, kind, stdin, args_json, output_limit):\n sink = _MivraSink(output_limit)\n result = {}\n _mivra_sys.setrecursionlimit(_mivra_recursion_limit)\n _mivra_sys.stdin = _mivra_io.StringIO(stdin)\n _mivra_sys.stdout = _MivraStream(sink, 0)\n _mivra_sys.stderr = _MivraStream(sink, 1)\n try:\n namespace = {\"__name__\": \"__main__\", \"__builtins__\": _mivra_builtins}\n exec(compile(code, \"${FILENAME}\", \"exec\"), namespace)\n if kind == \"call\":\n function = namespace.get(function_name)\n if not callable(function):\n raise TypeError(function_name + \" is not defined as a function\")\n value = function(*_mivra_json.loads(args_json))\n try:\n returned = _mivra_json.dumps(value, allow_nan=False)\n except (TypeError, ValueError) as error:\n result[\"status\"] = \"error\"\n result[\"message\"] = \"The return value can't be recorded as JSON: \" + type(error).__name__ + \": \" + str(error)\n else:\n if len(returned) > output_limit:\n result[\"status\"] = \"error\"\n result[\"message\"] = \"The return value is too large (over {:,} characters).\".format(output_limit)\n else:\n result[\"returned\"] = returned\n except SystemExit as error:\n if kind == \"call\":\n result[\"status\"] = \"error\"\n result[\"message\"] = \"The code called exit() instead of returning.\"\n elif error.code not in (None, 0):\n result[\"status\"] = \"error\"\n result[\"message\"] = \"The program exited with status \" + str(error.code) + \".\"\n except _MivraOutputLimit:\n result[\"status\"] = \"output\"\n except KeyboardInterrupt:\n result[\"status\"] = \"time\"\n except RecursionError:\n result[\"status\"] = \"stack\"\n except MemoryError:\n result[\"status\"] = \"memory\"\n except BaseException as error:\n result[\"status\"] = \"error\"\n result[\"message\"] = _mivra_describe(error)\n finally:\n _mivra_sys.stdin = _mivra_sys.__stdin__\n _mivra_sys.stdout = _mivra_sys.__stdout__\n _mivra_sys.stderr = _mivra_sys.__stderr__\n result[\"stdout\"] = \"\".join(sink.parts[0])\n result[\"stderr\"] = \"\".join(sink.parts[1])\n result[\"exceeded\"] = sink.exceeded\n return _mivra_json.dumps(result)\n`;\n\ntype HarnessResult = {\n status?: \"error\" | \"output\" | \"time\" | \"stack\" | \"memory\";\n message?: string;\n stdout: string;\n stderr: string;\n returned?: string;\n exceeded: boolean;\n};\n\nexport interface PythonCaseRunner {\n /** Runs one case and reports what it printed, returned or raised. Never throws for anything the code does. */\n run(options: RunCaseOptions): ExerciseCaseRun;\n /** Set once Pyodide itself failed (a fatal error): later cases can't run, so the caller starts a new one. */\n readonly broken: boolean;\n}\n\nconst timeLimit = (ms: number) => `Time limit exceeded (${ms / 1000} s): the code ran too long, or never stopped.`;\n\n/**\n * Prepares a loaded Pyodide for exercise cases: removes Python's way to JavaScript, installs the harness and\n * the interrupt check. Call it once, before any untrusted code runs.\n */\nexport function createPythonCaseRunner(pyodide: PyodideLike, { now = Date.now }: { now?: () => number } = {}): PythonCaseRunner {\n // No case is running yet: any Python is interrupted.\n let deadline = Number.NEGATIVE_INFINITY;\n let interrupted = false;\n // Pyodide reads index 0 and writes it back to 0 once it has seen a signal; the write is ignored, so every\n // check after the deadline interrupts again.\n const buffer = new Proxy([0], {\n get(target, key) {\n if (key !== \"0\") return Reflect.get(target, key);\n if (now() <= deadline) return 0;\n interrupted = true;\n return SIGINT;\n },\n set: () => true,\n });\n for (const name of [\"js\", \"pyodide_js\"]) {\n try {\n pyodide.unregisterJsModule(name);\n } catch {\n // Not registered: nothing to remove.\n }\n }\n pyodide.runPython(HARNESS);\n const harness = pyodide.runPython(\"_mivra_run\") as (...args: unknown[]) => string;\n pyodide.setInterruptBuffer(buffer as never);\n let broken = false;\n\n return {\n get broken() {\n return broken;\n },\n run({ code, functionName, testCase, limits = EXERCISE_LIMITS }) {\n const finish = (run: { stdout?: string; stderr?: string; returned?: string; error?: string }): ExerciseCaseRun => ({\n stdout: run.stdout ?? \"\",\n ...(run.stderr ? { stderr: run.stderr } : {}),\n ...(run.returned !== undefined ? { returned: run.returned } : {}),\n ...(run.error !== undefined ? { error: run.error.slice(0, MAX_CASE_ERROR_CHARS) } : {}),\n });\n if (broken) return finish({ error: \"Python stopped working after an earlier case, so this one couldn't run.\" });\n interrupted = false;\n deadline = now() + limits.timeMs;\n let raw: string;\n try {\n raw = harness(code, functionName ?? \"\", testCase.kind, testCase.kind === \"stdio\" ? testCase.stdin : \"\", testCase.kind === \"call\" ? testCase.args : \"[]\", limits.outputChars);\n } catch (error) {\n // An interrupt landed in the harness itself, or Pyodide failed.\n if (interrupted) return finish({ error: timeLimit(limits.timeMs) });\n const message = error instanceof Error ? error.message : String(error);\n if (/fatal error/i.test(message)) broken = true;\n return finish({ error: /maximum call stack|too much recursion/i.test(message) ? STACK_EXCEEDED : `The code couldn't run: ${message}` });\n } finally {\n deadline = Number.NEGATIVE_INFINITY;\n }\n const result = JSON.parse(raw) as HarnessResult;\n const output = { stdout: result.stdout, stderr: result.stderr };\n // Output past the cap is cut short, so the run can't count even if it finished first.\n if (result.exceeded || result.status === \"output\") return finish({ ...output, error: OUTPUT_EXCEEDED(limits.outputChars) });\n if (result.status === \"time\" || interrupted) return finish({ ...output, error: timeLimit(limits.timeMs) });\n if (result.status === \"stack\") return finish({ ...output, error: STACK_EXCEEDED });\n if (result.status === \"memory\") return finish({ ...output, error: \"Memory limit exceeded: the code used more memory than the browser allows.\" });\n if (result.status === \"error\") return finish({ ...output, error: result.message ?? \"The code raised an error.\" });\n return finish({ ...output, returned: result.returned });\n },\n };\n}\n", "import { z } from \"zod\";\nimport { artifactMathInput, checkMathText } from \"./artifact-math-input.js\";\nimport { AlgorithmTraceSpec } from \"./algorithm-trace.js\";\nimport { CodeExerciseAnswer, CodeExerciseGrade, CodeExerciseInput, CodeExercisePublic, CodeExerciseSpec } from \"./code-exercise.js\";\nimport { CodeWalkthroughSpec } from \"./code-walkthrough.js\";\nimport { CompositionArtifactView, compositionArtifactKind } from \"./composition.js\";\nimport {\n InterviewContextAnswer,\n InterviewContextGrade,\n InterviewContextSpec,\n PlacementAnswer,\n PlacementGrade,\n PlacementQuestionPublic,\n PlacementQuestionSpec,\n} from \"./course.js\";\nimport { GraphSpec } from \"./graph.js\";\nimport { MultipleChoiceAnswer, MultipleChoiceGrade, MultipleChoicePublic, MultipleChoiceSpec } from \"./multiple-choice.js\";\nimport { MilestoneCheckView, MilestoneGrade, MilestoneReview, ProjectMilestoneInput, ProjectMilestonePublic, ProjectMilestoneSpec } from \"./project-milestone.js\";\nimport { SetDiagramSpec } from \"./set-diagram.js\";\nimport { TableSpec } from \"./table.js\";\nimport { WorkedStepsSpec } from \"./worked-steps.js\";\n\nexport * from \"./artifact-math-input.js\";\nexport * from \"./math-text.js\";\nexport * from \"./algorithm-trace.js\";\nexport * from \"./code-exercise.js\";\nexport * from \"./code-exercise-runner.js\";\nexport * from \"./code-exercise-python.js\";\nexport * from \"./code-walkthrough.js\";\nexport * from \"./composition.js\";\nexport * from \"./course.js\";\nexport * from \"./lesson.js\";\nexport * from \"./graph.js\";\nexport * from \"./multiple-choice.js\";\nexport * from \"./project-milestone.js\";\nexport * from \"./set-diagram.js\";\nexport * from \"./table.js\";\nexport * from \"./worked-steps.js\";\n\n/**\n * Every artifact kind the agent can produce, one tool per kind (ADR-006).\n * `input` adds current authoring checks to the stored `spec` schema, so old artifacts stay readable.\n * Bump `version` and keep the old schema when a spec changes incompatibly; stored artifacts record\n * the version they were created with.\n */\nexport const artifactKinds = {\n algorithm_trace: {\n version: 1,\n toolName: \"show_algorithm_trace\",\n description:\n \"Show the learner an interactive step-by-step trace of an algorithm running over a sequence (e.g. sliding window, two pointers, binary search, a simple sort). The learner steps through it with play/pause/step controls. Use it when watching state change step by step will make the idea click. Keep traces short (roughly 5-20 steps) and make each step's explanation say what changed and why. A code pane is optional: add `code` and each step's `lines` only when the code itself is the point, such as how an implementation's lines move the state, and leave it out when the idea matters more than any code. Write that code in the programming language the learner has shown proficiency in according to <learner_memories>; if they show none, use Python or pseudocode. Keep the code short, and highlight the lines each step is running. For code that doesn't move over a sequence, such as a plain function or a React render, use show_code_walkthrough instead of inventing an array.\",\n spec: AlgorithmTraceSpec,\n input: artifactMathInput(AlgorithmTraceSpec, [\"title\", \"steps.*.explanation\"]),\n },\n code_exercise: {\n version: 1,\n toolName: \"ask_code_exercise\",\n description:\n \"Give the learner a short JavaScript or Python coding exercise to solve in an editor in the UI, after teaching an idea they can now practise by writing code. Use the language they are learning. They run the visible cases as often as they like, then submit once; their result is reported back to you on the next turn, so don't reveal or hint at a solution in your reply. Keep it to one small function or program (a few to about 30 lines), with 3-8 fast cases. Two kinds of case: a call case calls `functionName` (defined at the top level) with JSON arguments and compares its return value as JSON (key order ignored; in Python, None is null and tuples are lists), and a stdio case runs the whole program with the case's stdin and compares what it prints (trailing whitespace and trailing blank lines ignored). Prefer call cases; use stdio for programs that read input and print. JavaScript runs as plain JavaScript with no DOM, network, modules, timers or Node APIs: only console, the global `stdin` string and `readLine()` (the next input line, or null). Python runs in Pyodide with the standard library only: no network, files, threads, subprocesses or packages to install; read input with input() or sys.stdin and print with print(). Write a correct, deterministic referenceSolution in the same language: Mivra runs it on every case to get the expected results, rejecting the exercise if it fails, and never shows it. Hide a case or two that check edge cases. The starter code should give the function's signature (or the program's outline) and no solution.\",\n spec: CodeExerciseSpec,\n input: artifactMathInput(CodeExerciseInput, [\"title\"]),\n },\n code_walkthrough: {\n version: 1,\n toolName: \"show_code_walkthrough\",\n description:\n \"Show the learner a step-by-step walkthrough of a short piece of code that isn't about a sequence: a plain function's parameters, locals and return value, or a React component's renders, handlers and state updates. Each step highlights the source lines it is at and gives a complete snapshot of the visible state (`variables`) and the visible output (`output`, plain text such as printed lines or what the page shows, e.g. \\\"Count: 0\\\"); nothing carries over between steps, so repeat whatever still applies and use [] or \\\"\\\" for none. The source stays the same on every step. Use show_algorithm_trace instead for an algorithm moving over an array or other sequence, and show_graph for a component hierarchy. Keep the code short (a few to about 20 lines) and the walkthrough short (roughly 3-12 steps). Write the code in the language the concept belongs to (JSX for React); for a language-neutral idea, use the language the learner knows from <learner_memories>, else Python or pseudocode. The snapshots are your illustration, not a real run, so get them right. For React, keep the state a render or handler sees apart from updates it queues: inside a handler, state still has the value from the render it belongs to (name it, e.g. \\\"handler.count\\\" = 0, with \\\"queued update\\\" = \\\"count + 1\\\"), and the new value and its output appear only at the next render's step.\",\n spec: CodeWalkthroughSpec,\n input: artifactMathInput(CodeWalkthroughSpec, [\"title\", \"steps.*.explanation\"]),\n },\n composition: compositionArtifactKind,\n graph: {\n version: 1,\n toolName: \"show_graph\",\n description:\n \"Show the learner a graph or tree, drawn for you, optionally with steps they can walk through. Use it for graphs, trees, BFS, DFS, shortest paths, spanning trees and tree traversals, whenever seeing the structure or watching an algorithm move over it will help. Never give coordinates: the layout is automatic. For a binary search tree or binary tree traversal, set kind to tree and give every edge a side, so a lone left child and a lone right child are drawn differently. The automatic layout may draw crossing edges that mean nothing, even when the graph is planar, so don't use this to show whether a graph is planar. Keep it small enough to read (roughly 4-15 nodes, 5-20 steps) and make each step's explanation say what changed and why. For a component hierarchy (such as React components), set kind to tree and directed to true, with one node per component instance (distinct ids for two instances of the same component, labelled with the short component name) and one edge from each parent to each child it renders, labelled with the props it passes (e.g. \\\"count\\\" or \\\"onClick\\\"). Use steps to highlight where state is owned and the nodes and edges its value flows through, with variables for simple state such as count = 1. The nodes and edges stay the same on every step: don't add callback edges back up the tree, and don't suggest that a component's output changes just because it re-renders. To show where things are and how they move between containers, such as names sharing one object, values passing through pipeline stages or tasks moving between a queue and a stack, use show_composition instead.\",\n spec: GraphSpec,\n input: artifactMathInput(GraphSpec, [\"title\", \"nodes.*.label\", \"edges.*.label\", \"steps.*.explanation\"], (spec, ctx) => {\n spec.nodes.forEach((node, i) => {\n if (node.label === undefined) checkMathText(node.id, [\"nodes\", i, \"id\"], ctx);\n });\n }),\n },\n interview_context: {\n version: 1,\n toolName: \"ask_interview_context\",\n description:\n \"Course placement interview only: ask the learner once, as the last question of the interview and in the same reply as the placement questions, whether there is anything else they want you to know about what they already understand or want to explore. They answer in their own words in the UI, or leave it blank; the answer is reported back to you with the placement results. Not graded.\",\n spec: InterviewContextSpec,\n input: artifactMathInput(InterviewContextSpec, [\"question\"]),\n },\n multiple_choice: {\n version: 1,\n toolName: \"ask_multiple_choice\",\n description:\n \"Ask the learner one multiple-choice question to check understanding of a concept you just taught. Exactly one option is correct. Write plausible wrong options that reflect real misconceptions, and give per-option feedback where useful. The learner answers in the UI; the result is reported back to you on the next turn, so do not reveal the answer in your reply. For a code prediction, put the short snippet in a fenced code block in your reply text before this call and ask what it returns, prints or displays; the question and options render maths and plain text only, so never put code fences in them.\",\n spec: MultipleChoiceSpec,\n input: artifactMathInput(MultipleChoiceSpec, [\"question\", \"options.*.text\", \"options.*.feedback\", \"explanation\"]),\n },\n placement_question: {\n version: 1,\n toolName: \"ask_placement_question\",\n description:\n \"Course placement interview only: ask the learner one quick question to find out what they already know about one concept, before the syllabus is written. Use multiple choice, true/false or yes/no. The UI always adds \\\"Not sure\\\" and \\\"Skip\\\", so never include those as options. The learner answers in the UI and the result is reported back to you, so don't reveal the answer.\",\n spec: PlacementQuestionSpec,\n input: artifactMathInput(PlacementQuestionSpec, [\"question\", \"options.*.text\", \"explanation\"]),\n },\n project_milestone: {\n version: 1,\n toolName: \"set_project_milestone\",\n description:\n \"Project course lessons only: set this lesson's milestone, the step of the project the learner builds next in their own repository, in whatever language they chose. They check it with `mivra check`, which runs their program on each case's input (on stdin, and as a file whose path replaces {input} in their command) and compares what it prints with what your Python referenceSolution prints for that input. Say exactly what to build in spec and exactly what to print in outputFormat, so a program in any language can match it; trailing spaces and trailing blank lines are ignored, everything else counts, and the program must exit with code 0. Write 3-12 small, fast cases, simplest first, that cover the milestone's edge cases. Mivra runs the reference on every case when you call this; if it fails or times out, nothing is saved and you get the reason, so fix it and call again. Use compare run_output only when the program's output is itself a program, such as generated assembly; the reference then prints what running that output should print. Every check also sends the learner's changed files to a code review, which must approve too: it fails hard-coded outputs, code that doesn't use the milestone's concept (say what it must show in reviewFocus) and seriously poor code. Use checkType review, with no cases or reference, for what output can't show (structure, a language feature, concurrency, performance); reviewFocus then says exactly what the code must show. Never show the reference or write the learner's solution.\",\n spec: ProjectMilestoneSpec,\n input: artifactMathInput(ProjectMilestoneInput, [\"title\"]),\n },\n set_diagram: {\n version: 1,\n toolName: \"show_set_diagram\",\n description:\n \"Show the learner a Venn diagram of 1 to 3 sets, with what each region contains. Use it for set operations (union, intersection, complement, difference) and inclusion-exclusion, not for more than 3 sets. Keep elements short, because they are drawn in their region. Add steps to walk through it: each step highlights exact regions (any of them, including outside every set, which needs `universe`) and says what changed and why.\",\n spec: SetDiagramSpec,\n input: artifactMathInput(SetDiagramSpec, [\"title\", \"universe\", \"sets.*.label\", \"regions.*.elements.*\", \"steps.*.explanation\", \"steps.*.variables.*.name\", \"steps.*.variables.*.value\"]),\n },\n table: {\n version: 1,\n toolName: \"show_table\",\n description:\n \"Show the learner a table: a truth table, a relation matrix or other tabular working. Use it whenever the content is really rows and columns. Add steps when filling it in or highlighting it one part at a time will help, such as working out a truth table column by column; leave them out for a table to read at a glance. Keep steps short and make each explanation say what changed and why.\",\n spec: TableSpec,\n input: artifactMathInput(TableSpec, [\"title\", \"columns.*\", \"rowHeaders.*\", \"rows.*.*\", \"steps.*.explanation\", \"steps.*.cells.*.value\"]),\n },\n worked_steps: {\n version: 1,\n toolName: \"show_worked_steps\",\n description:\n \"Show the learner a proof, an induction or combinatorics working as a sequence of steps they reveal one at a time, each a statement with its justification. Use it when the reasoning is the point and each line follows from the ones before. Use show_algorithm_trace instead for an algorithm's state changing over a sequence.\",\n spec: WorkedStepsSpec,\n input: artifactMathInput(WorkedStepsSpec, [\"title\", \"goal\", \"steps.*.label\", \"steps.*.statement\", \"steps.*.justification\"]),\n },\n} as const;\n\nexport type ArtifactKind = keyof typeof artifactKinds;\nexport const ArtifactKind = z.enum(Object.keys(artifactKinds) as [ArtifactKind, ...ArtifactKind[]]);\n\n/** Finds the kind registered for a tool name, if any. */\nexport function kindForTool(toolName: string): ArtifactKind | undefined {\n return (Object.keys(artifactKinds) as ArtifactKind[]).find((kind) => artifactKinds[kind].toolName === toolName);\n}\n\nconst ArtifactBase = { id: z.string(), createdAt: z.string().datetime() };\n\nexport const MultipleChoiceAttempt = z\n .object({ answer: MultipleChoiceAnswer, grade: MultipleChoiceGrade, createdAt: z.string().datetime() })\n .strict();\nexport type MultipleChoiceAttempt = z.infer<typeof MultipleChoiceAttempt>;\n\nexport const CodeExerciseAttempt = z\n .object({ answer: CodeExerciseAnswer, grade: CodeExerciseGrade, createdAt: z.string().datetime() })\n .strict();\nexport type CodeExerciseAttempt = z.infer<typeof CodeExerciseAttempt>;\n\nexport const InterviewContextAttempt = z\n .object({ answer: InterviewContextAnswer, grade: InterviewContextGrade, createdAt: z.string().datetime() })\n .strict();\nexport type InterviewContextAttempt = z.infer<typeof InterviewContextAttempt>;\n\nexport const MilestoneAttempt = z.object({ answer: MilestoneCheckView, grade: MilestoneGrade, createdAt: z.string().datetime() }).strict();\nexport type MilestoneAttempt = z.infer<typeof MilestoneAttempt>;\n\n/** The latest check's review verdict: separate evidence, judged by a model (ADR-016). */\nexport const MilestoneReviewAttempt = z.object({ review: MilestoneReview, createdAt: z.string().datetime() }).strict();\nexport type MilestoneReviewAttempt = z.infer<typeof MilestoneReviewAttempt>;\n\nexport const PlacementAttempt = z.object({ answer: PlacementAnswer, grade: PlacementGrade, createdAt: z.string().datetime() }).strict();\nexport type PlacementAttempt = z.infer<typeof PlacementAttempt>;\n\n/**\n * An artifact as the client receives it. Checks expose only their public view until answered;\n * after an attempt, the grade (with the correct answer and explanation) is included.\n */\nexport const ArtifactView = z.discriminatedUnion(\"kind\", [\n z\n .object({ ...ArtifactBase, kind: z.literal(\"algorithm_trace\"), version: z.literal(1), spec: AlgorithmTraceSpec })\n .strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"code_exercise\"),\n version: z.literal(1),\n spec: CodeExercisePublic,\n latestAttempt: CodeExerciseAttempt.optional(),\n })\n .strict(),\n z\n .object({ ...ArtifactBase, kind: z.literal(\"code_walkthrough\"), version: z.literal(1), spec: CodeWalkthroughSpec })\n .strict(),\n CompositionArtifactView,\n z.object({ ...ArtifactBase, kind: z.literal(\"graph\"), version: z.literal(1), spec: GraphSpec }).strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"interview_context\"),\n version: z.literal(1),\n spec: InterviewContextSpec,\n latestAttempt: InterviewContextAttempt.optional(),\n })\n .strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"multiple_choice\"),\n version: z.literal(1),\n spec: MultipleChoicePublic,\n latestAttempt: MultipleChoiceAttempt.optional(),\n })\n .strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"placement_question\"),\n version: z.literal(1),\n spec: PlacementQuestionPublic,\n latestAttempt: PlacementAttempt.optional(),\n })\n .strict(),\n z\n .object({\n ...ArtifactBase,\n kind: z.literal(\"project_milestone\"),\n version: z.literal(1),\n spec: ProjectMilestonePublic,\n /** The latest `mivra check`: a milestone is checked as often as the learner likes, and each check replaces the last. */\n latestAttempt: MilestoneAttempt.optional(),\n /** The latest check's review, if it ran and finished. */\n latestReview: MilestoneReviewAttempt.optional(),\n /** Whether the latest check passed the milestone: every case, and the review's approval. */\n passed: z.boolean().optional(),\n })\n .strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"set_diagram\"), version: z.literal(1), spec: SetDiagramSpec }).strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"table\"), version: z.literal(1), spec: TableSpec }).strict(),\n z.object({ ...ArtifactBase, kind: z.literal(\"worked_steps\"), version: z.literal(1), spec: WorkedStepsSpec }).strict(),\n]);\nexport type ArtifactView = z.infer<typeof ArtifactView>;\n\nexport * from \"./memory.js\";\nexport * from \"./document.js\";\nexport * from \"./vault.js\";\nexport * from \"./knowledge.js\";\n\n/** ChatGPT's page for the learner's plan usage and per-app limits (ADR-015). */\nexport const CHATGPT_USAGE_URL = \"https://chatgpt.com/settings/usage\";\n/**\n * The reply error when the learner's ChatGPT plan has hit a usage limit. The UI recognises it and offers\n * \"Manage usage\", as OpenAI's guidelines ask (ADR-015).\n */\nexport const CHATGPT_USAGE_LIMIT_ERROR = \"ChatGPT usage limit reached. Review your plan or this app's limit in ChatGPT settings.\";\n", "import { z } from \"zod\";\nimport { splitMath } from \"./math-text.js\";\n\nconst REPAIR = String.raw`Wrap LaTeX commands in single-dollar math delimiters, with no spaces inside: $\\displaystyle\\sum_{i=1}^{n} i$. Put \\displaystyle inside the dollars. For literal backslashes followed by two or more letters (such as C:\\Users), use forward slashes, Unicode symbols such as \u2216, or describe them in words; backticks do not escape artifact math. Correct the affected field and retry this tool call.`;\n\n// Single-letter code escapes stay literal; longer literals such as C:\\Users are still rejected.\nexport function checkMathText(value: unknown, path: (string | number)[], ctx: z.RefinementCtx) {\n if (typeof value === \"string\" && splitMath(value).some((piece) => \"text\" in piece && /\\\\[a-zA-Z]{2,}/.test(piece.text))) {\n ctx.addIssue({ code: \"custom\", path, message: REPAIR });\n }\n}\n\n/** Input-only refinements: stored v1 specs and public views must continue to accept old text. */\nexport function artifactMathInput<T extends z.ZodType>(schema: T, fields: string[], extra?: (spec: z.output<T>, ctx: z.RefinementCtx) => void) {\n return schema.superRefine((spec, ctx) => {\n const visit = (value: unknown, parts: string[], path: (string | number)[]) => {\n if (parts.length === 0) return checkMathText(value, path, ctx);\n const [key, ...rest] = parts;\n if (key === \"*\" && Array.isArray(value)) value.forEach((item, i) => visit(item, rest, [...path, i]));\n else if (value && typeof value === \"object\" && key !== undefined) visit((value as Record<string, unknown>)[key], rest, [...path, key]);\n };\n for (const field of fields) visit(spec, field.split(\".\"), []);\n extra?.(spec, ctx);\n });\n}\n", "const isSpace = (char: string | undefined) => char !== undefined && /\\s/.test(char);\nconst isDigit = (char: string | undefined) => char !== undefined && char >= \"0\" && char <= \"9\";\n\nexport type MathPiece = { text: string } | { formula: string };\n\n/** For math mode: everything is literal except `$...$` formulas, and `\\$`, which is a literal dollar. */\nexport function splitMath(source: string): MathPiece[] {\n const pieces: MathPiece[] = [];\n let literal = \"\";\n let i = 0;\n while (i < source.length) {\n const char = source[i]!;\n if (char === \"\\\\\" && source[i + 1] === \"$\") {\n literal += \"$\";\n i += 2;\n } else if (char !== \"$\") {\n literal += char;\n i += 1;\n } else if (source[i + 1] === \"$\") {\n // A dollar next to another is never a delimiter here, so \"$$x$$\" stays as written.\n while (source[i] === \"$\") {\n literal += \"$\";\n i += 1;\n }\n } else {\n const close = closingDollar(source, i);\n if (close === undefined) {\n literal += \"$\";\n i += 1;\n } else {\n if (literal) pieces.push({ text: literal });\n literal = \"\";\n pieces.push({ formula: source.slice(i + 1, close) });\n i = close + 1;\n }\n }\n }\n if (literal) pieces.push({ text: literal });\n return pieces;\n}\n\nfunction closingDollar(source: string, open: number): number | undefined {\n let close = open + 1;\n while (close < source.length && source[close] !== \"$\") {\n close += source[close] === \"\\\\\" && (source[close + 1] === \"$\" || source[close + 1] === \"\\\\\") ? 2 : 1;\n }\n if (close >= source.length || close === open + 1 || source[close + 1] === \"$\") return undefined;\n if (isSpace(source[open + 1]) || isSpace(source[close - 1]) || isDigit(source[close + 1])) return undefined;\n return /`|\\n\\s*\\n/.test(source.slice(open, close)) ? undefined : close;\n}\n", "import { z } from \"zod\";\n\n/**\n * algorithm_trace v1: a step-through view of an algorithm running over a sequence.\n * Each step can move labelled pointers, highlight index ranges, update variables and\n * replace the sequence (for swaps/sorts). Covers sliding window, two pointers, binary\n * search and simple sorts.\n *\n * A trace can also show the code it runs (`code`), with each step naming the 1-based source lines it\n * highlights (`lines`). Both are optional, so traces without code, including stored ones, stay valid.\n * The code is text only: it is never run, and renderers show it as inert monospaced text.\n *\n * State rules (renderers must follow them):\n * - `values` persists: a step without `values` shows the previous step's sequence.\n * - `pointers`, `ranges` and `variables` do not persist: each step lists all of its own,\n * and omitting one means that step has none. So every step is fully described by itself\n * plus the current sequence, and bounds can be checked step by step.\n */\n\nconst MAX_VALUES = 64;\nconst MAX_STEPS = 200;\nexport const MAX_CODE_LINES = 40;\nexport const MAX_CODE_LINE_LENGTH = 120;\nexport const MAX_CODE_CHARS = 4000;\n\n/** A trace's source split into lines, as numbered from 1: line endings are normalised and one trailing newline is ignored. */\nexport function codeLines(source: string): string[] {\n return source.replace(/\\r\\n?/g, \"\\n\").replace(/\\n$/, \"\").split(\"\\n\");\n}\n\nconst Label = z.string().trim().min(1).max(40);\nconst Cell = z.union([z.number(), z.string().max(24)]);\nconst Index = z.number().int().nonnegative();\n\nexport const TracePointer = z\n .object({\n name: Label.describe('Pointer label shown under the cell, e.g. \"left\", \"right\", \"mid\", \"i\".'),\n index: Index.describe(\"0-based index into the sequence as it is at this step.\"),\n })\n .strict();\n\nexport const TraceRange = z\n .object({\n start: Index.describe(\"0-based start index, inclusive, within the sequence as it is at this step.\"),\n end: Index.describe(\"0-based end index, inclusive. Must be >= start and within the sequence.\"),\n label: Label.optional().describe('Optional label, e.g. \"window\".'),\n tone: z\n .enum([\"active\", \"done\", \"muted\"])\n .optional()\n .describe(\"active = current focus, done = finished/sorted, muted = ruled out. Defaults to active.\"),\n })\n .strict();\n\nexport const TraceVariable = z\n .object({\n name: Label,\n value: z.union([z.number(), z.string().max(80), z.boolean()]),\n })\n .strict();\n\nexport const TraceCode = z\n .object({\n language: z\n .string()\n .trim()\n .min(1)\n .max(30)\n .describe('The language the code is written in, e.g. \"Python\", \"TypeScript\", \"Java\" or \"pseudocode\". Shown as a label.'),\n source: z\n .string()\n .min(1)\n .max(MAX_CODE_CHARS)\n .describe(\n `The code, as plain text with newlines and its real indentation: at most ${MAX_CODE_LINES} lines of at most ${MAX_CODE_LINE_LENGTH} characters. Line 1 is the first line. No Markdown fences.`,\n ),\n })\n .strict()\n .superRefine((code, ctx) => {\n const lines = codeLines(code.source);\n if (lines.every((line) => line.trim() === \"\")) {\n ctx.addIssue({ code: \"custom\", path: [\"source\"], message: \"source has no code\" });\n }\n if (lines.length > MAX_CODE_LINES) {\n ctx.addIssue({ code: \"custom\", path: [\"source\"], message: `source has ${lines.length} lines; at most ${MAX_CODE_LINES} are allowed` });\n }\n const long = lines.findIndex((line) => line.length > MAX_CODE_LINE_LENGTH);\n if (long >= 0) {\n ctx.addIssue({ code: \"custom\", path: [\"source\"], message: `line ${long + 1} is longer than ${MAX_CODE_LINE_LENGTH} characters` });\n }\n });\n\nexport const TraceStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens in this step, in one or two sentences.\"),\n values: z\n .array(Cell)\n .min(1)\n .max(MAX_VALUES)\n .optional()\n .describe(\"The whole sequence after this step. Omit unless the values changed (e.g. a swap); omitted means unchanged.\"),\n pointers: z\n .array(TracePointer)\n .max(8)\n .optional()\n .describe(\"All pointers to show at this step. Not carried over from earlier steps: repeat any that still apply.\"),\n ranges: z\n .array(TraceRange)\n .max(8)\n .optional()\n .describe(\"All highlighted ranges at this step. Not carried over from earlier steps.\"),\n variables: z\n .array(TraceVariable)\n .max(12)\n .optional()\n .describe(\"All running state at this step, e.g. current sum, best so far. Not carried over from earlier steps.\"),\n lines: z\n .array(z.number().int().positive())\n .max(MAX_CODE_LINES)\n .optional()\n .describe(\n \"Only with code: the 1-based line numbers in code.source this step is running, highlighted beside the values. Not carried over from earlier steps; omit or leave empty to highlight none.\",\n ),\n })\n .strict();\n\nexport const AlgorithmTraceSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n values: z.array(Cell).min(1).max(MAX_VALUES).describe(\"The input sequence before the first step.\"),\n code: TraceCode.optional().describe(\n \"Optional source code shown beside the values, with each step's `lines` highlighted. Include it only when the code itself is the point.\",\n ),\n steps: z.array(TraceStep).min(1).max(MAX_STEPS),\n })\n .strict()\n .superRefine((spec, ctx) => {\n // Every pointer and range must point inside the sequence as it is at that step.\n let length = spec.values.length;\n const codeLength = spec.code ? codeLines(spec.code.source).length : 0;\n spec.steps.forEach((step, i) => {\n if (step.lines && !spec.code) {\n ctx.addIssue({ code: \"custom\", path: [\"steps\", i, \"lines\"], message: \"lines need code: add code, or remove lines\" });\n } else {\n step.lines?.forEach((line, j) => {\n if (line > codeLength) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", i, \"lines\", j],\n message: `line ${line} is outside the code (${codeLength} lines)`,\n });\n }\n });\n }\n if (step.values) length = step.values.length;\n step.pointers?.forEach((p, j) => {\n if (p.index >= length) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", i, \"pointers\", j, \"index\"],\n message: `index ${p.index} is outside the sequence (length ${length})`,\n });\n }\n });\n step.ranges?.forEach((r, j) => {\n if (r.end >= length || r.start > r.end) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"steps\", i, \"ranges\", j],\n message: `range ${r.start}..${r.end} is invalid for a sequence of length ${length}`,\n });\n }\n });\n });\n });\n\nexport type AlgorithmTraceSpec = z.infer<typeof AlgorithmTraceSpec>;\nexport type TraceStep = z.infer<typeof TraceStep>;\nexport type TraceCode = z.infer<typeof TraceCode>;\n", "import { z } from \"zod\";\nimport { MAX_CODE_LINES, TraceCode, TraceVariable, codeLines } from \"./algorithm-trace.js\";\n\n/**\n * code_walkthrough v1: a step-through illustration of code that isn't about a sequence, such as a plain\n * function or a React render (#98). The source stays fixed; each step highlights its lines and shows the\n * state and the output at that point, with an explanation.\n *\n * Every step is a complete snapshot: nothing carries over from the step before, so omitted or empty\n * `lines` highlight nothing, `variables: []` shows none and `output: \"\"` shows no output. Stepping back\n * shows exactly the earlier snapshot. The snapshots are the tutor's illustration, never a real run: the\n * code is inert text, and nothing is graded or recorded as evidence.\n */\n\nexport const MAX_WALKTHROUGH_STEPS = 200;\nexport const MAX_WALKTHROUGH_VARIABLES = 12;\nexport const MAX_WALKTHROUGH_OUTPUT = 4000;\n\nexport const CodeWalkthroughStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens at this step and why, in one or two sentences.\"),\n label: z\n .string()\n .trim()\n .min(1)\n .max(80)\n .optional()\n .describe('Optional short name for the step, e.g. \"Initial render\", \"Click handler\", \"Render 2\".'),\n lines: z\n .array(z.number().int().positive())\n .max(MAX_CODE_LINES)\n .optional()\n .describe(\"The 1-based line numbers in code.source this step is at. Not carried over: omit or leave empty to highlight none.\"),\n variables: z\n .array(TraceVariable)\n .max(MAX_WALKTHROUGH_VARIABLES)\n .describe(\n 'All the state visible at this step, each name once, e.g. \"n\", \"render.count\", \"handler.count\", \"queued update\". Not carried over: list everything that still applies, or [] for none. Values are plain text, numbers or booleans; write undefined, null or a short object as a string.',\n ),\n output: z\n .string()\n .max(MAX_WALKTHROUGH_OUTPUT)\n .describe(\n 'Everything visible as output at this step, as plain text, e.g. printed lines or what the page shows (\"Count: 0\"). Not carried over: repeat earlier output that is still visible, or \"\" for none.',\n ),\n })\n .strict();\n\nexport const CodeWalkthroughSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n code: TraceCode.describe(\"The source shown on every step. It stays the same across steps.\"),\n steps: z.array(CodeWalkthroughStep).min(1).max(MAX_WALKTHROUGH_STEPS),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const codeLength = codeLines(spec.code.source).length;\n spec.steps.forEach((step, i) => {\n step.lines?.forEach((line, j) => {\n if (line > codeLength) {\n ctx.addIssue({ code: \"custom\", path: [\"steps\", i, \"lines\", j], message: `line ${line} is outside the code (${codeLength} lines)` });\n }\n });\n const seen = new Set<string>();\n step.variables.forEach((variable, j) => {\n if (seen.has(variable.name)) {\n ctx.addIssue({ code: \"custom\", path: [\"steps\", i, \"variables\", j, \"name\"], message: `variable \"${variable.name}\" appears twice in this step` });\n }\n seen.add(variable.name);\n });\n });\n });\n\nexport type CodeWalkthroughSpec = z.infer<typeof CodeWalkthroughSpec>;\nexport type CodeWalkthroughStep = z.infer<typeof CodeWalkthroughStep>;\n", "import { z } from \"zod\";\nimport { codeLines } from \"./algorithm-trace.js\";\nimport { artifactMathInput } from \"./artifact-math-input.js\";\n\n/**\n * composition v1 (#109): entities located in containers, the references they share and how they move.\n * Covers aliasing, pipelines and queues. Graph stays the kind for topology; composition says where things\n * are. The model never gives coordinates, styles or layout hints, and code is inert text.\n *\n * State rules (renderers must follow them, through `resolveCompositionStep`):\n * - Every step is a complete snapshot, resolved from the declarations alone. Nothing carries over from the\n * step before, so back, direct seek and reset show exactly what stepping forward showed.\n * - `placements` and `hidden` account for every entity exactly once. `connections` lists every connection\n * visible in the step; one is never shown merely because both of its ends are.\n * - `state` replaces an entity's whole property list for that step. Without an entry the entity shows its\n * declared properties, never the previous step's.\n * - An entity's `body` is fixed across steps.\n *\n * Registered in `artifactKinds` and `LessonSectionKind`; the web renders it in `artifacts/Composition.tsx` (#113).\n */\n\nexport const MAX_COMPOSITION_GROUPS = 4;\nexport const MAX_COMPOSITION_ENTITIES = 16;\nexport const MAX_COMPOSITION_CONNECTIONS = 24;\nexport const MAX_COMPOSITION_STEPS = 20;\nexport const MAX_COMPOSITION_PROPERTIES = 6;\nexport const MAX_COMPOSITION_BLOCKS = 2;\nexport const MAX_COMPOSITION_CALLOUTS = 2;\nexport const MAX_COMPOSITION_CODE_LINES = 12;\nexport const MAX_COMPOSITION_CODE_LINE_LENGTH = 80;\nexport const MAX_COMPOSITION_ENTITY_BODY = 1000;\nexport const MAX_COMPOSITION_BODY = 4000;\n\nconst Id = z.string().trim().min(1).max(24);\nconst Label = z.string().trim().min(1).max(32);\n\nexport const CompositionTone = z.enum([\"active\", \"done\", \"muted\"]);\nexport type CompositionTone = z.infer<typeof CompositionTone>;\n\nexport const CompositionProperty = z\n .object({\n name: Label.describe(\"Literal property name, unique within its list. Not a formula.\"),\n value: z\n .union([z.number(), z.boolean(), z.string().max(64)])\n .describe('A number, a boolean or literal text of at most 64 characters (\"\" is allowed). Never Markdown or a formula; write a list or object as short text.'),\n })\n .strict();\nexport type CompositionProperty = z.infer<typeof CompositionProperty>;\n\nconst Properties = z.array(CompositionProperty).max(MAX_COMPOSITION_PROPERTIES);\n\nexport const CompositionBlock = z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"text\"),\n text: z.string().trim().min(1).max(280).describe(\"A short note. Only $...$ is a formula; no Markdown.\"),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"code\"),\n language: Label.describe('The language, e.g. \"Python\" or \"bytecode\". Shown as a label; any language is accepted.'),\n code: z\n .string()\n .overwrite((code) => code.replace(/\\r\\n?/g, \"\\n\"))\n .min(1)\n .max(MAX_COMPOSITION_CODE_LINES * (MAX_COMPOSITION_CODE_LINE_LENGTH + 1))\n .describe(\n `Plain text with newlines and its real indentation: at most ${MAX_COMPOSITION_CODE_LINES} lines of at most ${MAX_COMPOSITION_CODE_LINE_LENGTH} characters. No Markdown fences. Never run.`,\n ),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"math\"),\n source: z.string().trim().min(1).max(300).describe(\"One display formula as LaTeX, without dollar delimiters.\"),\n })\n .strict(),\n]);\nexport type CompositionBlock = z.infer<typeof CompositionBlock>;\n\nexport const CompositionGroup = z\n .object({\n id: Id.describe(\"Unique id, used by each step's placements.\"),\n label: Label.describe(\"The container's name. Only $...$ is a formula.\"),\n ordered: z.boolean().describe(\"True when position matters, as in a queue or stack: the first entity is then the front or top. Say which it is in the step's explanation.\"),\n })\n .strict();\nexport type CompositionGroup = z.infer<typeof CompositionGroup>;\n\nexport const CompositionEntity = z\n .object({\n id: Id.describe(\"Unique id, used by connections and steps.\"),\n label: Label.describe(\"Short name on the card. Only $...$ is a formula.\"),\n properties: Properties.describe(\"The entity's declared properties, in display order; [] for none. A step shows these unless its `state` replaces them.\"),\n body: z\n .array(CompositionBlock)\n .max(MAX_COMPOSITION_BLOCKS)\n .optional()\n .describe(\n `Up to ${MAX_COMPOSITION_BLOCKS} blocks of text, code or maths inside the card, the same on every step. Their text, code and source may total ${MAX_COMPOSITION_ENTITY_BODY} characters per entity and ${MAX_COMPOSITION_BODY} over all entities.`,\n ),\n })\n .strict();\nexport type CompositionEntity = z.infer<typeof CompositionEntity>;\n\nexport const CompositionConnection = z\n .object({\n id: Id.describe(\"Unique id, listed by each step that shows this connection.\"),\n from: Id.describe(\"Id of the entity that holds the reference.\"),\n to: Id.describe(\"Id of the entity it refers to. Must differ from `from`.\"),\n label: Label.optional().describe('Optional name of the reference, e.g. \"next\". Only $...$ is a formula.'),\n })\n .strict();\nexport type CompositionConnection = z.infer<typeof CompositionConnection>;\n\nexport const CompositionStep = z\n .object({\n label: z.string().trim().min(1).max(80).optional().describe(\"Optional literal text for the step, shown in monospace, e.g. the statement `b = a`.\"),\n explanation: z.string().trim().min(1).max(500).describe(\"What this step shows and what changed, in one or two sentences.\"),\n placements: z\n .array(\n z\n .object({\n groupId: Id,\n entityIds: z.array(Id).max(MAX_COMPOSITION_ENTITIES).describe(\"The entities in this group at this step, top to bottom; [] for an empty group.\"),\n })\n .strict(),\n )\n .max(MAX_COMPOSITION_GROUPS)\n .describe(\"Exactly one entry for every group, at every step. Not carried over from earlier steps.\"),\n hidden: z\n .array(Id)\n .max(MAX_COMPOSITION_ENTITIES)\n .describe(\"Every entity not shown at this step, e.g. before it is created. Each entity is in exactly one placement or here.\"),\n connections: z\n .array(Id)\n .max(MAX_COMPOSITION_CONNECTIONS)\n .describe(\"Ids of the connections shown at this step; [] for none. Not carried over, and both ends must be placed in a group.\"),\n state: z\n .array(z.object({ entityId: Id, properties: Properties.describe(\"The entity's whole property list at this step; [] shows none.\") }).strict())\n .max(MAX_COMPOSITION_ENTITIES)\n .optional()\n .describe(\"Entities whose properties differ from their declaration at this step, at most one entry each. Not carried over: an entity without an entry shows its declared properties again.\"),\n emphasis: z\n .array(\n z\n .object({ entityId: Id, tone: CompositionTone.describe(\"active = current focus, done = finished, muted = ruled out or idle.\") })\n .strict(),\n )\n .max(MAX_COMPOSITION_ENTITIES)\n .optional()\n .describe(\"Entities to emphasise at this step, at most one entry each. Not carried over.\"),\n callouts: z\n .array(z.object({ entityId: Id, text: z.string().trim().min(1).max(140).describe(\"A short note shown inside the card. Only $...$ is a formula.\") }).strict())\n .max(MAX_COMPOSITION_CALLOUTS)\n .optional()\n .describe(\"Notes on entities at this step, at most one per entity. Not carried over.\"),\n })\n .strict();\nexport type CompositionStep = z.infer<typeof CompositionStep>;\n\ntype Path = (string | number)[];\n\nfunction checkProperties(properties: readonly CompositionProperty[], path: Path, ctx: z.RefinementCtx) {\n const seen = new Set<string>();\n properties.forEach((property, i) => {\n if (seen.has(property.name)) {\n ctx.addIssue({ code: \"custom\", path: [...path, i, \"name\"], message: `property \"${property.name}\" appears twice in this list: keep one, or rename the other` });\n }\n seen.add(property.name);\n });\n}\n\n/** How much a block counts toward the body totals. Newlines count; a code block's language doesn't. */\nconst blockLength = (block: CompositionBlock) => (block.type === \"text\" ? block.text : block.type === \"code\" ? block.code : block.source).length;\n\nfunction checkStep(\n step: CompositionStep,\n i: number,\n declared: { groups: readonly CompositionGroup[]; entities: readonly CompositionEntity[]; connections: Map<string, CompositionConnection> },\n ctx: z.RefinementCtx,\n) {\n const n = i + 1;\n const issue = (path: Path, message: string) => ctx.addIssue({ code: \"custom\", path: [\"steps\", i, ...path], message });\n const groupIds = new Set(declared.groups.map((group) => group.id));\n const entityIds = new Set(declared.entities.map((entity) => entity.id));\n\n const placedGroups = new Set<string>();\n const where = new Map<string, string>();\n const visible = new Set<string>();\n const account = (id: string, place: string, path: Path) => {\n if (!entityIds.has(id)) return issue(path, `no entity has id \"${id}\": use a declared entity id`);\n const earlier = where.get(id);\n if (earlier !== undefined) return issue(path, `entity \"${id}\" is already ${earlier} in step ${n}: list each entity exactly once per step`);\n where.set(id, place);\n };\n step.placements.forEach((placement, j) => {\n if (!groupIds.has(placement.groupId)) issue([\"placements\", j, \"groupId\"], `no group has id \"${placement.groupId}\": use a declared group id`);\n else if (placedGroups.has(placement.groupId)) issue([\"placements\", j, \"groupId\"], `group \"${placement.groupId}\" has two placements in step ${n}: merge them into one`);\n placedGroups.add(placement.groupId);\n placement.entityIds.forEach((id, k) => {\n account(id, `in group \"${placement.groupId}\"`, [\"placements\", j, \"entityIds\", k]);\n if (groupIds.has(placement.groupId) && entityIds.has(id)) visible.add(id);\n });\n });\n for (const group of declared.groups) {\n if (!placedGroups.has(group.id)) issue([\"placements\"], `step ${n} has no placement for group \"${group.id}\": add { groupId: \"${group.id}\", entityIds: [] } if it is empty`);\n }\n step.hidden.forEach((id, j) => {\n account(id, \"hidden\", [\"hidden\", j]);\n visible.delete(id);\n });\n for (const entity of declared.entities) {\n if (!where.has(entity.id)) issue([], `entity \"${entity.id}\" is not accounted for in step ${n}: list it in one placement's entityIds, or in hidden`);\n }\n\n const shown = new Set<string>();\n step.connections.forEach((id, j) => {\n const path = [\"connections\", j];\n const connection = declared.connections.get(id);\n if (!connection) return issue(path, `no connection has id \"${id}\": use a declared connection id`);\n if (shown.has(id)) issue(path, `connection \"${id}\" is listed twice in step ${n}: list it once`);\n shown.add(id);\n for (const end of [connection.from, connection.to]) {\n if (entityIds.has(end) && !visible.has(end)) {\n issue(path, `connection \"${id}\" needs entity \"${end}\", which is not placed in a group in step ${n}: place it, or leave the connection out of this step`);\n }\n }\n });\n\n const targets = (field: \"state\" | \"emphasis\" | \"callouts\") => {\n const seen = new Set<string>();\n step[field]?.forEach(({ entityId }, j) => {\n const path = [field, j, \"entityId\"];\n if (!entityIds.has(entityId)) return issue(path, `no entity has id \"${entityId}\": use a declared entity id`);\n if (seen.has(entityId)) issue(path, `entity \"${entityId}\" has two ${field} entries in step ${n}: merge them into one`);\n seen.add(entityId);\n if (!visible.has(entityId)) issue(path, `entity \"${entityId}\" is not placed in a group in step ${n}: place it, or remove this ${field} entry`);\n });\n };\n targets(\"state\");\n targets(\"emphasis\");\n targets(\"callouts\");\n step.state?.forEach((entry, j) => checkProperties(entry.properties, [\"steps\", i, \"state\", j, \"properties\"], ctx));\n}\n\nexport const CompositionSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n groups: z.array(CompositionGroup).min(1).max(MAX_COMPOSITION_GROUPS).describe(\"The containers, in reading order. Groups don't nest.\"),\n entities: z.array(CompositionEntity).min(1).max(MAX_COMPOSITION_ENTITIES).describe(\"Everything that is ever shown, declared once. Steps place or hide each one.\"),\n connections: z\n .array(CompositionConnection)\n .max(MAX_COMPOSITION_CONNECTIONS)\n .describe(\"Every directed reference that is ever shown; [] for none. Two entities may have several, each with its own id.\"),\n steps: z.array(CompositionStep).min(1).max(MAX_COMPOSITION_STEPS).describe(\"Complete snapshots in order. One step makes a static diagram.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n // Ids are data: they are only ever compared through Map and Set, never used as object keys or selectors.\n const usedBy = new Map<string, string>();\n const declare = (id: string, what: string, path: Path) => {\n const earlier = usedBy.get(id);\n if (earlier) ctx.addIssue({ code: \"custom\", path, message: `id \"${id}\" is already used by a ${earlier}: give every group, entity and connection its own id` });\n else usedBy.set(id, what);\n };\n spec.groups.forEach((group, i) => declare(group.id, \"group\", [\"groups\", i, \"id\"]));\n spec.entities.forEach((entity, i) => declare(entity.id, \"entity\", [\"entities\", i, \"id\"]));\n spec.connections.forEach((connection, i) => declare(connection.id, \"connection\", [\"connections\", i, \"id\"]));\n\n let bodyTotal = 0;\n spec.entities.forEach((entity, i) => {\n checkProperties(entity.properties, [\"entities\", i, \"properties\"], ctx);\n let entityTotal = 0;\n entity.body?.forEach((block, j) => {\n entityTotal += blockLength(block);\n if (block.type !== \"code\") return;\n const path = [\"entities\", i, \"body\", j, \"code\"];\n const lines = codeLines(block.code);\n if (lines.every((line) => line.trim() === \"\")) ctx.addIssue({ code: \"custom\", path, message: \"code has no code: write some, or remove the block\" });\n if (lines.length > MAX_COMPOSITION_CODE_LINES) {\n ctx.addIssue({ code: \"custom\", path, message: `code has ${lines.length} lines; at most ${MAX_COMPOSITION_CODE_LINES} are allowed: shorten it` });\n }\n const long = lines.findIndex((line) => line.length > MAX_COMPOSITION_CODE_LINE_LENGTH);\n if (long >= 0) ctx.addIssue({ code: \"custom\", path, message: `line ${long + 1} is longer than ${MAX_COMPOSITION_CODE_LINE_LENGTH} characters: break or shorten it` });\n });\n bodyTotal += entityTotal;\n if (entityTotal > MAX_COMPOSITION_ENTITY_BODY) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"entities\", i, \"body\"],\n message: `entity \"${entity.id}\" has ${entityTotal} characters of body content; at most ${MAX_COMPOSITION_ENTITY_BODY} are allowed: shorten its blocks`,\n });\n }\n });\n if (bodyTotal > MAX_COMPOSITION_BODY) {\n ctx.addIssue({ code: \"custom\", path: [\"entities\"], message: `the bodies total ${bodyTotal} characters; at most ${MAX_COMPOSITION_BODY} are allowed: shorten or remove some` });\n }\n\n const entityIds = new Set(spec.entities.map((entity) => entity.id));\n spec.connections.forEach((connection, i) => {\n for (const end of [\"from\", \"to\"] as const) {\n if (!entityIds.has(connection[end])) {\n ctx.addIssue({ code: \"custom\", path: [\"connections\", i, end], message: `no entity has id \"${connection[end]}\": connections join declared entities` });\n }\n }\n if (connection.from === connection.to) {\n ctx.addIssue({ code: \"custom\", path: [\"connections\", i, \"to\"], message: `connection \"${connection.id}\" joins \"${connection.from}\" to itself: its ends must be two different entities` });\n }\n });\n\n const declared = { groups: spec.groups, entities: spec.entities, connections: new Map(spec.connections.map((connection) => [connection.id, connection])) };\n spec.steps.forEach((step, i) => checkStep(step, i, declared, ctx));\n });\nexport type CompositionSpec = z.infer<typeof CompositionSpec>;\n\n/** A reference shown on its source card: the chip that keeps a connection readable without a drawn line. */\nexport interface ResolvedCompositionReference {\n connectionId: string;\n to: string;\n toLabel: string;\n label: string | undefined;\n}\n\nexport interface ResolvedCompositionEntity {\n id: string;\n label: string;\n /** The properties shown at this step: the step's replacement if it has one, else the declared list. */\n properties: CompositionProperty[];\n body: CompositionBlock[];\n /** Undefined is neutral. */\n tone: CompositionTone | undefined;\n callout: string | undefined;\n /** This entity's visible outgoing connections, in declaration order. */\n references: ResolvedCompositionReference[];\n}\n\nexport interface ResolvedCompositionGroup extends CompositionGroup {\n /** Top to bottom. In an ordered group, the first is the front or top. */\n entities: ResolvedCompositionEntity[];\n}\n\nexport interface ResolvedCompositionStep {\n index: number;\n label: string | undefined;\n explanation: string;\n /** Every declared group in declaration order, including empty ones. */\n groups: ResolvedCompositionGroup[];\n /** The visible connections, in declaration order. */\n connections: CompositionConnection[];\n}\n\n/**\n * What one step shows, worked out from the declarations and that step alone. Shared by every renderer, so\n * stepping forward, back, seeking and resetting can't disagree. The index is clamped to the steps there are.\n */\nexport function resolveCompositionStep(spec: CompositionSpec, index: number): ResolvedCompositionStep {\n const at = Math.min(Math.max(Math.trunc(index) || 0, 0), spec.steps.length - 1);\n const step = spec.steps[at]!;\n const entities = new Map(spec.entities.map((entity) => [entity.id, entity]));\n const placed = new Map(step.placements.map((placement) => [placement.groupId, placement.entityIds]));\n const visibleIds = new Set([...placed.values()].flat().filter((id) => entities.has(id)));\n const shown = new Set(step.connections);\n const connections = spec.connections.filter((connection) => shown.has(connection.id) && visibleIds.has(connection.from) && visibleIds.has(connection.to));\n const state = new Map(step.state?.map((entry) => [entry.entityId, entry.properties]));\n const tones = new Map(step.emphasis?.map((entry) => [entry.entityId, entry.tone]));\n const callouts = new Map(step.callouts?.map((entry) => [entry.entityId, entry.text]));\n\n const resolve = (entity: CompositionEntity): ResolvedCompositionEntity => ({\n id: entity.id,\n label: entity.label,\n properties: state.get(entity.id) ?? entity.properties,\n body: entity.body ?? [],\n tone: tones.get(entity.id),\n callout: callouts.get(entity.id),\n references: connections\n .filter((connection) => connection.from === entity.id)\n .map((connection) => ({ connectionId: connection.id, to: connection.to, toLabel: entities.get(connection.to)!.label, label: connection.label })),\n });\n\n return {\n index: at,\n label: step.label,\n explanation: step.explanation,\n groups: spec.groups.map((group) => ({\n ...group,\n entities: (placed.get(group.id) ?? []).flatMap((id) => {\n const entity = entities.get(id);\n return entity ? [resolve(entity)] : [];\n }),\n })),\n connections,\n };\n}\n\n/**\n * One thing that differs between a step and the declared step before it. `text` is a full sentence built\n * from labels, for the non-motion summary and its polite announcement; the ids are for renderers that also\n * animate the change. `text` is MathText (labels may hold $...$); literal property names and values have\n * their dollars escaped, so they never turn into formulas.\n */\nexport type CompositionChange =\n | { type: \"initial\"; text: string }\n | { type: \"appeared\"; entityId: string; groupId: string; text: string }\n | { type: \"hidden\"; entityId: string; groupId: string; text: string }\n | { type: \"moved\"; entityId: string; fromGroupId: string; toGroupId: string; text: string }\n | { type: \"reordered\"; groupId: string; text: string }\n | { type: \"property_added\" | \"property_removed\" | \"property_changed\"; entityId: string; name: string; text: string }\n | { type: \"connection_added\" | \"connection_removed\"; connectionId: string; text: string };\n\nconst literal = (value: string | number | boolean) => (value === \"\" ? '\"\"' : String(value).replaceAll(\"$\", \"\\\\$\"));\n\n/**\n * The change summary for a step: what differs from the step declared before it, whichever way the learner\n * got here. The first step describes the initial state instead. Empty when nothing visible changed.\n */\nexport function compositionChanges(spec: CompositionSpec, index: number): CompositionChange[] {\n const current = resolveCompositionStep(spec, index);\n const describe = (connection: CompositionConnection, labels: Map<string, string>) =>\n `${labels.get(connection.from)} \u2192 ${labels.get(connection.to)}${connection.label === undefined ? \"\" : ` (${connection.label})`}`;\n const labels = new Map(spec.entities.map((entity) => [entity.id, entity.label]));\n\n if (current.index === 0) {\n return [\n ...current.groups.map((group): CompositionChange => ({\n type: \"initial\",\n text: group.entities.length ? `${group.label} holds ${group.entities.map((entity) => entity.label).join(\", \")}.` : `${group.label} is empty.`,\n })),\n ...current.connections.map((connection): CompositionChange => ({ type: \"initial\", text: `${describe(connection, labels)} is connected.` })),\n ];\n }\n\n const previous = resolveCompositionStep(spec, current.index - 1);\n const locate = (step: ResolvedCompositionStep) =>\n new Map(step.groups.flatMap((group) => group.entities.map((entity) => [entity.id, { group, entity }] as const)));\n const before = locate(previous);\n const after = locate(current);\n const changes: CompositionChange[] = [];\n\n // Entities in declaration order, so the summary reads the same however the placements were written.\n for (const { id, label } of spec.entities) {\n const was = before.get(id);\n const now = after.get(id);\n if (!was && now) changes.push({ type: \"appeared\", entityId: id, groupId: now.group.id, text: `${label} appears in ${now.group.label}.` });\n else if (was && !now) changes.push({ type: \"hidden\", entityId: id, groupId: was.group.id, text: `${label} leaves ${was.group.label}.` });\n else if (was && now && was.group.id !== now.group.id) {\n changes.push({ type: \"moved\", entityId: id, fromGroupId: was.group.id, toGroupId: now.group.id, text: `${label} moves from ${was.group.label} to ${now.group.label}.` });\n }\n }\n\n for (const group of current.groups) {\n const stayed = (entities: ResolvedCompositionEntity[]) => entities.map((entity) => entity.id).filter((id) => before.get(id)?.group.id === group.id && after.get(id)?.group.id === group.id);\n const order = stayed(group.entities);\n const earlier = stayed(previous.groups.find((other) => other.id === group.id)!.entities);\n if (order.some((id, i) => id !== earlier[i])) {\n changes.push({ type: \"reordered\", groupId: group.id, text: `${group.label} is reordered: ${group.entities.map((entity) => entity.label).join(\", \")}.` });\n }\n }\n\n for (const { id, label } of spec.entities) {\n const was = before.get(id)?.entity;\n const now = after.get(id)?.entity;\n if (!was || !now) continue;\n const old = new Map(was.properties.map((property) => [property.name, property.value]));\n const names = new Set(now.properties.map((property) => property.name));\n for (const { name, value } of now.properties) {\n if (!old.has(name)) changes.push({ type: \"property_added\", entityId: id, name, text: `${label} gains ${literal(name)} = ${literal(value)}.` });\n else if (old.get(name) !== value) {\n changes.push({ type: \"property_changed\", entityId: id, name, text: `${label}: ${literal(name)} changes from ${literal(old.get(name)!)} to ${literal(value)}.` });\n }\n }\n for (const { name } of was.properties) {\n if (!names.has(name)) changes.push({ type: \"property_removed\", entityId: id, name, text: `${label} loses ${literal(name)}.` });\n }\n }\n\n const wasShown = new Set(previous.connections.map((connection) => connection.id));\n const isShown = new Set(current.connections.map((connection) => connection.id));\n for (const connection of spec.connections) {\n if (isShown.has(connection.id) && !wasShown.has(connection.id)) {\n changes.push({ type: \"connection_added\", connectionId: connection.id, text: `${describe(connection, labels)} is connected.` });\n } else if (wasShown.has(connection.id) && !isShown.has(connection.id)) {\n changes.push({ type: \"connection_removed\", connectionId: connection.id, text: `${describe(connection, labels)} is disconnected.` });\n }\n }\n return changes;\n}\n\nconst DESCRIPTION =\n \"Show the learner where things are: entities as cards inside named groups, the references between them, and how that changes step by step. Use it for location, sharing and changing contents, such as two variables referring to one object (aliasing), values moving through pipeline stages, or tasks moving between a queue and a stack. Declare every group, entity and connection once, then give each step as a complete snapshot: one placement for every group (entityIds may be []), every other entity in `hidden`, and the ids of the connections shown. Nothing carries over between steps, so repeat whatever still applies; `state` replaces an entity's whole property list for that step only, and without it the entity shows its declared properties again. In an ordered group the first entity is the front or top: say in the explanation which end is which. Keep it small (roughly 3-8 entities and 3-8 steps) and make each explanation say what changed and why. Never give coordinates or styles: the layout is automatic. Code in a body is inert text. Use show_graph instead for topology, state machines, flowcharts, trees and graph algorithms, show_algorithm_trace for an algorithm over a sequence, show_code_walkthrough to explain source lines, show_table for tabular comparison, and show_set_diagram or show_worked_steps for sets and proofs.\";\n\n/** composition's entry in `artifactKinds`. */\nexport const compositionArtifactKind = {\n version: 1,\n toolName: \"show_composition\",\n description: DESCRIPTION,\n spec: CompositionSpec,\n // Code, ids, languages, property strings, step labels and display formulas are literal: no math check.\n input: artifactMathInput(CompositionSpec, [\n \"title\",\n \"groups.*.label\",\n \"entities.*.label\",\n \"entities.*.body.*.text\",\n \"connections.*.label\",\n \"steps.*.explanation\",\n \"steps.*.callouts.*.text\",\n ]),\n} as const;\n\n/** A composition as the client receives it. The spec has no private fields, so the view carries all of it. */\nexport const CompositionArtifactView = z\n .object({ id: z.string(), createdAt: z.string().datetime(), kind: z.literal(\"composition\"), version: z.literal(1), spec: CompositionSpec })\n .strict();\nexport type CompositionArtifactView = z.infer<typeof CompositionArtifactView>;\n", "import { z } from \"zod\";\n\n/**\n * Courses (ADR-011): one learning goal, a placement interview, then a syllabus of ordered topics\n * written by the AI. The learner never approves the syllabus; they change it later through the tutor.\n */\n\nexport const MAX_GOAL_CHARS = 300;\nexport const CourseGoal = z.string().trim().min(1).max(MAX_GOAL_CHARS);\n\n/**\n * A course's kind (ADR-016): `lessons` teaches through lessons with checks; `project` builds one project in the\n * learner's own repository, a milestone per syllabus topic, checked there with `mivra check`.\n */\nexport const COURSE_KINDS = [\"lessons\", \"project\"] as const;\nexport const CourseKind = z.enum(COURSE_KINDS);\nexport type CourseKind = z.infer<typeof CourseKind>;\n\n/** Body of POST /courses. */\nexport const StartCourse = z.object({ goal: CourseGoal, kind: CourseKind.optional() }).strict();\nexport type StartCourse = z.infer<typeof StartCourse>;\n\nconst ConceptName = z.string().trim().min(1).max(80);\n\n// ---------------------------------------------------------------------------------------------\n// placement_question v1: one interview question. Multiple choice, true/false or yes/no, and the\n// learner can always answer \"Not sure\" or skip it. No confidence rating (owner decision on #1).\n// ---------------------------------------------------------------------------------------------\n\nexport const PlacementQuestionSpec = z\n .object({\n concept: ConceptName.describe('The single concept this question probes, e.g. \"chain rule\". Reuse the exact name from the learner\\'s record when it is there.'),\n question: z.string().trim().min(1).max(1000),\n options: z\n .array(z.object({ text: z.string().trim().min(1).max(300) }).strict())\n .min(2)\n .max(5)\n .describe('2-5 options with distinct text. For true/false or yes/no use two options, e.g. \"True\" and \"False\". Never add a \"Not sure\" option: the UI always offers one.'),\n correctOptionIndex: z.number().int().nonnegative().describe(\"0-based index of the single correct option.\"),\n explanation: z.string().trim().min(1).max(600).describe(\"One or two sentences shown after answering: why the correct option is correct.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n if (spec.correctOptionIndex >= spec.options.length) {\n ctx.addIssue({ code: \"custom\", path: [\"correctOptionIndex\"], message: \"correctOptionIndex must point at one of the options\" });\n }\n const seen = new Map<string, number>();\n spec.options.forEach((option, i) => {\n const key = option.text.normalize(\"NFC\");\n const first = seen.get(key);\n if (first !== undefined) ctx.addIssue({ code: \"custom\", path: [\"options\", i, \"text\"], message: `duplicates option ${first}` });\n else seen.set(key, i);\n if (/^\\s*(not sure|i don'?t know|unsure|skip)\\W*$/i.test(option.text)) {\n ctx.addIssue({ code: \"custom\", path: [\"options\", i, \"text\"], message: \"Leave out Not sure / Skip: the UI always offers them\" });\n }\n });\n });\nexport type PlacementQuestionSpec = z.infer<typeof PlacementQuestionSpec>;\n\n/** What the client sees before answering. */\nexport const PlacementQuestionPublic = z\n .object({ concept: z.string(), question: z.string(), options: z.array(z.object({ text: z.string() }).strict()) })\n .strict();\nexport type PlacementQuestionPublic = z.infer<typeof PlacementQuestionPublic>;\n\nexport const toPlacementQuestionPublic = (spec: PlacementQuestionSpec): PlacementQuestionPublic => ({\n concept: spec.concept,\n question: spec.question,\n options: spec.options.map((o) => ({ text: o.text })),\n});\n\nexport const PlacementAnswer = z.union([\n z.object({ optionIndex: z.number().int().nonnegative() }).strict(),\n z.object({ unsure: z.literal(true) }).strict(),\n z.object({ skipped: z.literal(true) }).strict(),\n]);\nexport type PlacementAnswer = z.infer<typeof PlacementAnswer>;\n\nexport const PlacementResult = z.enum([\"correct\", \"incorrect\", \"unsure\", \"skipped\"]);\nexport type PlacementResult = z.infer<typeof PlacementResult>;\n\nexport const PlacementGrade = z\n .object({ result: PlacementResult, correctOptionIndex: z.number().int().nonnegative(), explanation: z.string() })\n .strict();\nexport type PlacementGrade = z.infer<typeof PlacementGrade>;\n\n/** Deterministic grader. \"Not sure\" counts as not knowing it; a skip is no evidence either way. */\nexport function gradePlacementQuestion(spec: PlacementQuestionSpec, answer: PlacementAnswer): PlacementGrade {\n let result: PlacementResult;\n if (\"optionIndex\" in answer) {\n if (!spec.options[answer.optionIndex]) throw new RangeError(`optionIndex ${answer.optionIndex} is not one of the ${spec.options.length} options`);\n result = answer.optionIndex === spec.correctOptionIndex ? \"correct\" : \"incorrect\";\n } else result = \"unsure\" in answer ? \"unsure\" : \"skipped\";\n return { result, correctOptionIndex: spec.correctOptionIndex, explanation: spec.explanation };\n}\n\n// ---------------------------------------------------------------------------------------------\n// interview_context v1: the interview's one optional free-text question (#75), asked last, so the\n// learner can say in their own words what they already know or want to explore. Not graded and\n// never evidence: the answer only tailors the syllabus.\n// ---------------------------------------------------------------------------------------------\n\n/** Most characters the learner can write in the interview's free-text answer. */\nexport const MAX_INTERVIEW_CONTEXT_CHARS = 2000;\n\nexport const InterviewContextSpec = z\n .object({\n question: z\n .string()\n .trim()\n .min(1)\n .max(300)\n .describe('The question, e.g. \"Anything else you\\'d like us to know about what you already understand or what you want to explore?\"'),\n })\n .strict();\nexport type InterviewContextSpec = z.infer<typeof InterviewContextSpec>;\n\n/** The learner's words, or a skip. Blank text counts as a skip. */\nexport const InterviewContextAnswer = z.union([\n z.object({ text: z.string().trim().max(MAX_INTERVIEW_CONTEXT_CHARS) }).strict(),\n z.object({ skipped: z.literal(true) }).strict(),\n]);\nexport type InterviewContextAnswer = z.infer<typeof InterviewContextAnswer>;\n\nexport const InterviewContextGrade = z.object({ result: z.enum([\"answered\", \"skipped\"]) }).strict();\nexport type InterviewContextGrade = z.infer<typeof InterviewContextGrade>;\n\n/** Not a grade so much as a label: whether the learner wrote anything. */\nexport const gradeInterviewContext = (answer: InterviewContextAnswer): InterviewContextGrade => ({\n result: \"text\" in answer && answer.text.length > 0 ? \"answered\" : \"skipped\",\n});\n\n// ---------------------------------------------------------------------------------------------\n// Syllabus\n// ---------------------------------------------------------------------------------------------\n\nexport const KnownSource = z.enum([\"memory\", \"test\", \"guess\"]);\nexport type KnownSource = z.infer<typeof KnownSource>;\n\nexport const SyllabusTopicInput = z\n .object({\n title: z.string().trim().min(1).max(120),\n summary: z.string().trim().min(1).max(400).describe(\"What the lesson on this topic will cover, in one or two sentences.\"),\n reason: z.string().trim().min(1).max(300).describe('Why this topic is here for this learner, e.g. \"You missed the question on local minima\".'),\n requestedByLearner: z.boolean().describe(\"True if the learner explicitly asked for this topic. Such topics are never removed automatically.\"),\n concepts: z.array(ConceptName).min(1).max(8).describe(\"Concept names this topic teaches; reuse names from the learner's record and the placement questions.\"),\n })\n .strict();\n\n/**\n * Subject icons a course can have, by Lucide name (#58). The tutor picks one when it writes the first\n * syllabus; clients map the name to an icon and fall back to a graduation cap for none or an unknown name.\n */\nexport const courseIcons = [\n \"sigma\",\n \"calculator\",\n \"code\",\n \"terminal\",\n \"cpu\",\n \"database\",\n \"network\",\n \"shield\",\n \"flask-conical\",\n \"atom\",\n \"dna\",\n \"leaf\",\n \"telescope\",\n \"globe\",\n \"landmark\",\n \"book-open\",\n \"pen-tool\",\n \"languages\",\n \"music\",\n \"palette\",\n \"camera\",\n \"brain\",\n \"users\",\n \"chart-line\",\n \"briefcase\",\n \"scale\",\n \"stethoscope\",\n \"heart-pulse\",\n \"wrench\",\n \"dumbbell\",\n] as const;\nexport const CourseIcon = z.enum(courseIcons);\nexport type CourseIcon = z.infer<typeof CourseIcon>;\n\n/** Most characters in the title the tutor gives a course. */\nexport const COURSE_TITLE_MAX = 60;\n\n/** Input of the write_syllabus tool. The server adds ids, version and timestamps. */\nexport const SyllabusInput = z\n .object({\n // Bad values parse as missing rather than failing the call: a syllabus is worth more than its label (#58).\n title: z\n .string()\n .trim()\n .min(1)\n .max(COURSE_TITLE_MAX)\n .optional()\n .catch(undefined)\n .describe('A short name for the course, 2-5 words, shown in the sidebar, e.g. \"Discrete Math: Induction\". Name what the syllabus covers, not the request.'),\n icon: CourseIcon.optional()\n .catch(undefined)\n .describe(\"The subject icon that best fits the course: sigma = maths, calculator = arithmetic or accounting, code/terminal = programming, cpu = hardware, flask-conical = chemistry, atom = physics, dna = biology, leaf = ecology, telescope = astronomy, globe = geography, landmark = history, book-open = literature, pen-tool = writing, languages = languages, palette = art, brain = psychology, users = sociology, chart-line = economics or statistics, briefcase = business, scale = law, stethoscope/heart-pulse = medicine, wrench = engineering, dumbbell = sport.\"),\n topics: z.array(SyllabusTopicInput).min(1).max(20).describe(\"The ordered topics, first to learn first. Each topic gets one lesson.\"),\n known: z\n .array(\n z\n .object({\n concept: ConceptName,\n source: KnownSource.describe(\"memory = from their record or memories; test = from this placement interview; guess = your inference\"),\n note: z.string().trim().min(1).max(200),\n })\n .strict(),\n )\n .max(20)\n .describe(\"What the learner already knows or doesn't, each labelled with where that comes from. Shown to the learner.\"),\n })\n .strict()\n .superRefine((input, ctx) => {\n const seen = new Set<string>();\n input.topics.forEach((topic, i) => {\n const key = topic.title.trim().toLowerCase();\n if (seen.has(key)) ctx.addIssue({ code: \"custom\", path: [\"topics\", i, \"title\"], message: \"Topic titles must be distinct\" });\n seen.add(key);\n });\n });\nexport type SyllabusInput = z.infer<typeof SyllabusInput>;\n\nexport const SyllabusTopic = SyllabusTopicInput.extend({ id: z.string() }).strict();\nexport type SyllabusTopic = z.infer<typeof SyllabusTopic>;\n\nexport const SyllabusView = z\n .object({\n version: z.number().int().positive(),\n source: z.enum([\"interview\", \"tutor\", \"adaptive\", \"undo\"]),\n reason: z.string().nullable(),\n changedTopicIds: z.array(z.string()),\n /** Whether the learner can undo this version: an automatic change none of whose new topics has started. */\n canUndo: z.boolean(),\n topics: z.array(SyllabusTopic),\n known: SyllabusInput.shape.known,\n createdAt: z.string().datetime(),\n })\n .strict();\nexport type SyllabusView = z.infer<typeof SyllabusView>;\n\nexport const CourseStatus = z.enum([\"interviewing\", \"active\", \"complete\"]);\nexport type CourseStatus = z.infer<typeof CourseStatus>;\n\nexport const CourseView = z\n .object({\n id: z.string(),\n sessionId: z.string(),\n goal: z.string(),\n kind: CourseKind,\n status: CourseStatus,\n syllabus: SyllabusView.nullable(),\n /** The tutor's reply that wrote the first syllabus, which ends the placement interview; null if unknown. */\n interviewMessageId: z.string().nullable(),\n createdAt: z.string().datetime(),\n })\n .strict();\nexport type CourseView = z.infer<typeof CourseView>;\n", "import { z } from \"zod\";\nimport { TraceVariable } from \"./algorithm-trace.js\";\n\n/**\n * graph v1: nodes and edges, optionally with steps that walk an algorithm over them. Covers BFS, DFS,\n * shortest paths, spanning trees and tree traversals. Self-loops and parallel edges are allowed and\n * drawn, because a multigraph is ordinary discrete maths. The model never picks coordinates: the\n * renderer computes one layout per graph, so nothing moves between steps.\n *\n * State rules (renderers must follow them):\n * - The graph itself never changes between steps.\n * - `nodeStates`, `edgeStates` and `variables` do not persist: each step lists all of its own, and\n * omitting one means that step has none. So every step is fully described by itself.\n */\n\nconst MAX_NODES = 60;\nconst MAX_EDGES = 200;\nconst MAX_STEPS = 200;\n\nconst Id = z.string().trim().min(1).max(24);\nconst Text = z.string().trim().min(1).max(24);\n\nexport const GraphTone = z.enum([\"active\", \"done\", \"muted\"]);\nexport type GraphTone = z.infer<typeof GraphTone>;\n\nconst ToneField = GraphTone.optional().describe(\n \"active = current focus, done = finished/visited, muted = ruled out. Defaults to active.\",\n);\n\nexport const GraphNode = z\n .object({\n id: Id.describe(\"Unique id, used by edges and steps. Shown on the node if it has no label.\"),\n label: Text.optional().describe(\"Short text on the node. Only $...$ is a formula, e.g. $v_1$.\"),\n })\n .strict();\n\nexport const GraphEdge = z\n .object({\n from: Id.describe(\"Id of a node. In a tree, the parent.\"),\n to: Id.describe(\"Id of a node, the same as `from` for a self-loop. In a tree, the child; children appear left to right in edge order unless they have a `side`.\"),\n side: z\n .enum([\"left\", \"right\"])\n .optional()\n .describe(\n \"Only when kind is tree: which child this is of `from`, its parent. Set it on every edge of a binary search tree or binary tree traversal, because a lone left child and a lone right child are different trees. A node has at most one child per side, and either all of its children have a side or none do.\",\n ),\n weight: z.number().optional().describe(\"Numeric weight shown on the edge. Give a weight or a label, not both.\"),\n label: Text.optional().describe(\"Text shown on the edge. Only $...$ is a formula.\"),\n })\n .strict();\n\nexport const GraphNodeState = z\n .object({ id: Id.describe(\"Id of a node.\"), tone: ToneField })\n .strict();\n\nexport const GraphEdgeState = z\n .object({\n from: Id,\n to: Id,\n nth: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe(\"Only for parallel edges, and then required: which of the edges joining these nodes, 0-based in the order of `edges`.\"),\n tone: ToneField,\n })\n .strict()\n .describe(\"An edge of the graph. In an undirected graph, from and to may be in either order.\");\n\nexport const GraphStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens in this step, in one or two sentences.\"),\n nodeStates: z\n .array(GraphNodeState)\n .max(MAX_NODES)\n .optional()\n .describe(\"The state of every node that has one at this step, at most one each. Not carried over from earlier steps: repeat any that still apply.\"),\n edgeStates: z\n .array(GraphEdgeState)\n .max(MAX_EDGES)\n .optional()\n .describe(\"The state of every edge that has one at this step, at most one each. Not carried over from earlier steps: repeat any that still apply.\"),\n variables: z\n .array(TraceVariable)\n .max(12)\n .optional()\n .describe(\"All running state at this step, e.g. the queue or current distances. Not carried over from earlier steps.\"),\n })\n .strict();\n\nconst pairKey = (from: string, to: string, directed: boolean) =>\n JSON.stringify(directed || from <= to ? [from, to] : [to, from]);\n\n/**\n * Finds which edge a step's edge state refers to, shared by the schema and renderers so they can't\n * disagree. Returns the index into `edges`, or why there isn't one.\n */\nexport function graphEdgeLookup(spec: { directed: boolean; edges: readonly { from: string; to: string }[] }) {\n const byPair = new Map<string, number[]>();\n spec.edges.forEach((edge, i) => {\n const key = pairKey(edge.from, edge.to, spec.directed);\n const indices = byPair.get(key);\n if (indices) indices.push(i);\n else byPair.set(key, [i]);\n });\n return (ref: { from: string; to: string; nth?: number | undefined }): { index: number } | { error: string } => {\n const name = `${ref.from} ${spec.directed ? \"->\" : \"--\"} ${ref.to}`;\n const indices = byPair.get(pairKey(ref.from, ref.to, spec.directed));\n if (!indices) return { error: `there is no edge ${name}` };\n if (ref.nth === undefined && indices.length > 1) return { error: `${indices.length} edges match ${name}: set nth to pick one` };\n const index = indices[ref.nth ?? 0];\n return index === undefined ? { error: `nth ${ref.nth} is out of range: ${indices.length} edges match ${name}` } : { index };\n };\n}\n\n/**\n * Each node's children in edge order, if the graph is a real tree: one root, connected, no cycles. Shared by\n * the schema and renderers so they can't disagree. Every edge must join nodes that exist.\n */\nexport function graphTreeShape(spec: {\n directed: boolean;\n nodes: readonly { id: string }[];\n edges: readonly { from: string; to: string }[];\n}): { root: string; children: Map<string, string[]> } | undefined {\n if (spec.edges.length !== spec.nodes.length - 1) return undefined;\n const ids = spec.nodes.map((node) => node.id);\n const adjacent = new Map<string, string[]>(ids.map((id) => [id, []]));\n for (const { from, to } of spec.edges) {\n adjacent.get(from)!.push(to);\n if (!spec.directed && from !== to) adjacent.get(to)!.push(from);\n }\n const roots = spec.directed ? ids.filter((id) => !spec.edges.some((edge) => edge.to === id)) : ids.slice(0, 1);\n const root = roots[0];\n if (roots.length !== 1 || root === undefined) return undefined;\n\n const children = new Map<string, string[]>();\n const pending = [root];\n while (pending.length) {\n const id = pending.pop()!;\n const next = adjacent.get(id)!.filter((other) => !children.has(other));\n children.set(id, next);\n pending.push(...next);\n }\n // With n - 1 edges, reaching all n nodes means there can't be a cycle.\n return children.size === ids.length ? { root, children } : undefined;\n}\n\n/** The rules for `side`, which only says anything about a tree that really gets drawn as one. */\nfunction checkSides(spec: Pick<GraphSpec, \"kind\" | \"directed\" | \"nodes\" | \"edges\">, ctx: z.RefinementCtx) {\n const sided = spec.edges.flatMap((edge, i) => (edge.side ? [{ edge, side: edge.side, path: [\"edges\", i, \"side\"] }] : []));\n const first = sided[0];\n if (!first) return;\n if (spec.kind !== \"tree\") {\n for (const { path } of sided) ctx.addIssue({ code: \"custom\", path, message: 'side only applies when kind is \"tree\": remove it, or set kind' });\n return;\n }\n const shape = graphTreeShape(spec);\n if (!shape) {\n ctx.addIssue({ code: \"custom\", path: first.path, message: \"side needs a real tree: connected with no cycles, and when directed, edges going parent to child from one root\" });\n return;\n }\n const sideOf = new Map<string, \"left\" | \"right\">();\n for (const { edge, side, path } of sided) {\n if (shape.children.get(edge.from)!.includes(edge.to)) sideOf.set(edge.to, side);\n else ctx.addIssue({ code: \"custom\", path, message: `side needs from to be the parent, but ${edge.to} is the parent of ${edge.from} here: swap them` });\n }\n for (const [parent, children] of shape.children) {\n const sides = children.flatMap((child) => sideOf.get(child) ?? []);\n if (sides.length > 0 && sides.length < children.length) {\n ctx.addIssue({ code: \"custom\", path: [\"edges\"], message: `node ${parent} mixes children with and without a side: give all of them one, or none` });\n }\n for (const side of [\"left\", \"right\"] as const) {\n if (sides.filter((s) => s === side).length > 1) ctx.addIssue({ code: \"custom\", path: [\"edges\"], message: `node ${parent} has two ${side} children` });\n }\n }\n}\n\nexport const GraphSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n directed: z.boolean().describe(\"True draws arrowheads from `from` to `to`.\"),\n kind: z\n .enum([\"tree\", \"graph\"])\n .optional()\n .describe(\n \"Layout hint. tree draws a rooted tree top-down, and needs a real tree: connected with no cycles, and when directed, edges going parent to child from one root. When undirected, the first node is the root. Anything else falls back to the general layout, unless an edge has a `side`, which is then an error. Defaults to graph.\",\n ),\n nodes: z.array(GraphNode).min(1).max(MAX_NODES),\n edges: z.array(GraphEdge).max(MAX_EDGES).describe(\"Self-loops and parallel edges are allowed.\"),\n steps: z.array(GraphStep).min(1).max(MAX_STEPS).optional().describe(\"Omit to show the graph without stepping through it.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const ids = new Set<string>();\n spec.nodes.forEach((node, i) => {\n if (ids.has(node.id)) ctx.addIssue({ code: \"custom\", path: [\"nodes\", i, \"id\"], message: `duplicate node id ${node.id}` });\n ids.add(node.id);\n });\n spec.edges.forEach((edge, i) => {\n for (const end of [\"from\", \"to\"] as const) {\n if (!ids.has(edge[end])) ctx.addIssue({ code: \"custom\", path: [\"edges\", i, end], message: `no node has id ${edge[end]}` });\n }\n if (edge.weight !== undefined && edge.label !== undefined) {\n ctx.addIssue({ code: \"custom\", path: [\"edges\", i], message: \"give a weight or a label, not both\" });\n }\n });\n if (spec.edges.every((edge) => ids.has(edge.from) && ids.has(edge.to))) checkSides(spec, ctx);\n const lookup = graphEdgeLookup(spec);\n spec.steps?.forEach((step, i) => {\n const seenNodes = new Set<string>();\n step.nodeStates?.forEach((state, j) => {\n const path = [\"steps\", i, \"nodeStates\", j];\n if (!ids.has(state.id)) ctx.addIssue({ code: \"custom\", path, message: `no node has id ${state.id}` });\n if (seenNodes.has(state.id)) ctx.addIssue({ code: \"custom\", path, message: `node ${state.id} has two states in one step` });\n seenNodes.add(state.id);\n });\n const seenEdges = new Set<number>();\n step.edgeStates?.forEach((state, j) => {\n const path = [\"steps\", i, \"edgeStates\", j];\n const found = lookup(state);\n if (\"error\" in found) return ctx.addIssue({ code: \"custom\", path, message: found.error });\n if (seenEdges.has(found.index)) ctx.addIssue({ code: \"custom\", path, message: `edge ${found.index} has two states in one step` });\n seenEdges.add(found.index);\n });\n });\n });\n\nexport type GraphSpec = z.infer<typeof GraphSpec>;\nexport type GraphStep = z.infer<typeof GraphStep>;\n", "import { z } from \"zod\";\n\n/**\n * multiple_choice v1: a comprehension check with exactly one correct option, graded by the\n * server without a model call (ADR-006). The full spec (with the answer) stays on the server;\n * the client gets the public view until the learner has answered.\n */\n\nexport const MultipleChoiceOption = z\n .object({\n text: z.string().trim().min(1).max(300),\n feedback: z\n .string()\n .trim()\n .min(1)\n .max(500)\n .optional()\n .describe(\"Shown if the learner picks this option: why it is right or what misconception it reflects.\"),\n })\n .strict();\n\nexport const MultipleChoiceSpec = z\n .object({\n concept: z\n .string()\n .trim()\n .min(1)\n .max(80)\n .describe('Short label for the concept being checked, e.g. \"sliding window invariant\". Used to track progress.'),\n question: z.string().trim().min(1).max(1000),\n options: z.array(MultipleChoiceOption).min(2).max(6).describe(\"2-6 options with distinct text.\"),\n correctOptionIndex: z\n .number()\n .int()\n .nonnegative()\n .describe(\"0-based index of the single correct option; must be less than the number of options.\"),\n explanation: z.string().trim().min(1).max(1000).describe(\"Shown after answering: why the correct option is correct.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n if (spec.correctOptionIndex >= spec.options.length) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"correctOptionIndex\"],\n message: \"correctOptionIndex must point at one of the options\",\n });\n }\n // Two identical options can't be told apart, but only one would be graded correct. Compare the\n // trimmed text exactly: case and inner spacing can be the point of a question (\"A\" vs \"a\",\n // \"a b\" vs \"a b\"). NFC only merges Unicode spellings that render identically.\n const seen = new Map<string, number>();\n spec.options.forEach((option, i) => {\n const key = option.text.normalize(\"NFC\");\n const first = seen.get(key);\n if (first !== undefined) {\n ctx.addIssue({ code: \"custom\", path: [\"options\", i, \"text\"], message: `duplicates option ${first}` });\n } else {\n seen.set(key, i);\n }\n });\n });\n\nexport type MultipleChoiceSpec = z.infer<typeof MultipleChoiceSpec>;\n\n/** What the client sees before answering: no answer key, no feedback. */\nexport const MultipleChoicePublic = z\n .object({\n concept: z.string(),\n question: z.string(),\n options: z.array(z.object({ text: z.string() }).strict()),\n })\n .strict();\n\nexport type MultipleChoicePublic = z.infer<typeof MultipleChoicePublic>;\n\nexport function toMultipleChoicePublic(spec: MultipleChoiceSpec): MultipleChoicePublic {\n return {\n concept: spec.concept,\n question: spec.question,\n options: spec.options.map((o) => ({ text: o.text })),\n };\n}\n\nexport const MultipleChoiceAnswer = z.object({ optionIndex: z.number().int().nonnegative() }).strict();\nexport type MultipleChoiceAnswer = z.infer<typeof MultipleChoiceAnswer>;\n\nexport const MultipleChoiceGrade = z\n .object({\n correct: z.boolean(),\n correctOptionIndex: z.number().int().nonnegative(),\n explanation: z.string(),\n feedback: z.string().optional(),\n })\n .strict();\nexport type MultipleChoiceGrade = z.infer<typeof MultipleChoiceGrade>;\n\n/** Deterministic grader. Throws if the answer points outside the options. */\nexport function gradeMultipleChoice(spec: MultipleChoiceSpec, answer: MultipleChoiceAnswer): MultipleChoiceGrade {\n const chosen = spec.options[answer.optionIndex];\n if (!chosen) throw new RangeError(`optionIndex ${answer.optionIndex} is not one of the ${spec.options.length} options`);\n return {\n correct: answer.optionIndex === spec.correctOptionIndex,\n correctOptionIndex: spec.correctOptionIndex,\n explanation: spec.explanation,\n ...(chosen.feedback ? { feedback: chosen.feedback } : {}),\n };\n}\n", "import { z } from \"zod\";\nimport { MAX_CASE_INPUT_CHARS, MAX_CASE_OUTPUT_CHARS, MAX_EXERCISE_CASES, normaliseOutput } from \"./code-exercise.js\";\n\n/**\n * project_milestone v1: one milestone of a project course (ADR-016), checked in the learner's own repository with\n * `mivra check`. The tutor writes the spec, the exact output format, test inputs and a Python reference. When the\n * milestone is created the server runs the reference on every input in Pyodide, and what it prints becomes the\n * expected output, whatever language the learner builds in. A milestone whose reference fails is rejected.\n *\n * `mivra check` fetches the cases as data (never a command), runs the learner's own command on each and reports\n * what it printed; the server compares that with the expected output after `normaliseOutput`. It also sends the\n * files changed since the last passed milestone, which a model reviews (ADR-016 step 4): passing needs every test and\n * the review's approval. A `review` milestone has no cases and passes on the review alone.\n */\n\nexport const MILESTONE_CHECK_TYPES = [\"tests\", \"review\"] as const;\nexport const MilestoneCheckType = z.enum(MILESTONE_CHECK_TYPES);\nexport type MilestoneCheckType = z.infer<typeof MilestoneCheckType>;\n\n/** How a case's result is compared: what the learner's program prints, or what its output prints when run. */\nexport const MilestoneCompare = z.enum([\"stdout\", \"run_output\"]);\nexport type MilestoneCompare = z.infer<typeof MilestoneCompare>;\n\n/** The Python reference. Longer than an exercise's: it may be a small interpreter for what the learner builds. */\nexport const MAX_MILESTONE_REFERENCE_CHARS = 20_000;\n/** What `mivra check` reports of one case's stderr, for the learner and the tutor to read. */\nexport const MAX_MILESTONE_STDERR_CHARS = 2_000;\n\n/** What `mivra check` sends for review (ADR-016): at most this many files, each this long, and this much in all. */\nexport const MAX_REVIEW_FILES = 200;\nexport const MAX_REVIEW_FILE_CHARS = 60_000;\nexport const MAX_REVIEW_TOTAL_CHARS = 240_000;\nexport const MAX_REVIEW_PATH_CHARS = 500;\n\n/** A git commit id (SHA-1 or SHA-256), lower-case hex: never anything git could read as an option. */\nexport const CommitId = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/);\n\nexport const MilestoneCaseInput = z\n .object({\n name: z.string().trim().min(1).max(80).describe('A short name the learner sees, e.g. \"empty input\" or \"nested parentheses\".'),\n input: z\n .string()\n .max(MAX_CASE_INPUT_CHARS)\n .describe(\"The case's input. The learner's program gets it on stdin and as a file whose path replaces {input} in their command. Use \\\"\\\" for none.\"),\n compare: MilestoneCompare.optional().describe(\n 'stdout (the default) compares what the learner\\'s program prints. run_output is for programs whose output is itself a program, such as a compiler\\'s generated assembly: Mivra runs that output with the learner\\'s own run-output command and compares what it prints, so the reference prints what running it should print.',\n ),\n })\n .strict();\nexport type MilestoneCaseInput = z.infer<typeof MilestoneCaseInput>;\n\nconst milestoneFields = {\n concept: z.string().trim().min(1).max(80).describe('Short label for what this milestone practises, e.g. \"tokenizing\". Used to track progress.'),\n title: z.string().trim().min(1).max(120),\n spec: z\n .string()\n .trim()\n .min(1)\n .max(6000)\n .describe(\"What the learner's program must do at this milestone, as markdown: the behaviour to add, building on the earlier milestones.\"),\n outputFormat: z\n .string()\n .trim()\n .min(1)\n .max(2000)\n .describe(\"Exactly what the program prints for an input, as markdown with an example, so any language can match it. Trailing spaces and trailing blank lines are ignored.\"),\n checkType: MilestoneCheckType.describe(\n \"tests: Mivra runs the learner's program on the cases and compares what it prints, and a code review must approve too. review: no cases or reference; the code review alone decides, for what output can't show (structure, a language feature, concurrency, performance).\",\n ),\n reviewFocus: z\n .string()\n .trim()\n .min(1)\n .max(2000)\n .optional()\n .describe(\n \"What the code review must see in the learner's code for this milestone's concept, e.g. \\\"the scanner walks the characters itself rather than splitting with a regex\\\". Required for a review milestone; optional for tests.\",\n ),\n};\n\n/** The rules between fields that a JSON schema can't say: a tests milestone has cases and a reference, a review one neither. */\nfunction milestoneRules(value: { checkType: MilestoneCheckType; cases?: unknown[]; referenceSolution?: string; reviewFocus?: string }, ctx: z.RefinementCtx) {\n if (value.checkType === \"tests\") {\n if (!value.cases || value.cases.length === 0) ctx.addIssue({ code: \"custom\", path: [\"cases\"], message: \"A tests milestone needs at least one case.\" });\n if (!value.referenceSolution) ctx.addIssue({ code: \"custom\", path: [\"referenceSolution\"], message: \"A tests milestone needs a referenceSolution.\" });\n } else {\n if (value.cases && value.cases.length > 0) ctx.addIssue({ code: \"custom\", path: [\"cases\"], message: \"A review milestone has no cases: the code review decides. Leave cases out.\" });\n if (value.referenceSolution) ctx.addIssue({ code: \"custom\", path: [\"referenceSolution\"], message: \"A review milestone has no reference. Leave referenceSolution out.\" });\n if (!value.reviewFocus) ctx.addIssue({ code: \"custom\", path: [\"reviewFocus\"], message: \"A review milestone needs reviewFocus: what the review must see in the code.\" });\n }\n}\n\n/** The tool's input. Expected outputs aren't part of it: the server computes them from the reference. */\nexport const ProjectMilestoneInput = z\n .object({\n ...milestoneFields,\n cases: z\n .array(MilestoneCaseInput)\n .max(MAX_EXERCISE_CASES)\n .optional()\n .describe(`tests only: 1-${MAX_EXERCISE_CASES} cases, simplest first, covering the milestone's edge cases. Each reference run has a 2 s limit. Leave out for review.`),\n referenceSolution: z\n .string()\n .min(1)\n .max(MAX_MILESTONE_REFERENCE_CHARS)\n .optional()\n .describe(\n \"tests only: a Python program (standard library only) that reads a case's input from stdin and prints exactly what the learner's program should print, or for a run_output case what running its output should print. Mivra runs it in Pyodide on every case to get the expected outputs and never shows it. It must be deterministic. Leave out for review.\",\n ),\n })\n .strict()\n .superRefine(milestoneRules);\nexport type ProjectMilestoneInput = z.infer<typeof ProjectMilestoneInput>;\n\nexport const MilestoneCase = MilestoneCaseInput.extend({\n expected: z.string().max(MAX_CASE_OUTPUT_CHARS),\n /** Withdrawn by the tutor after a dispute: kept for the record, never run or graded again. */\n withdrawn: z.boolean().optional(),\n}).strict();\nexport type MilestoneCase = z.infer<typeof MilestoneCase>;\n\n/** Most disputes one milestone keeps; each costs a model call. */\nexport const MAX_MILESTONE_DISPUTES = 20;\nexport const MAX_DISPUTE_REASON_CHARS = 2000;\n\n/** What the tutor decided about a dispute. A case is kept, withdrawn or corrected; a review verdict is upheld or overturned. */\nexport const MilestoneDisputeOutcome = z.enum([\"kept\", \"withdrawn\", \"corrected\", \"upheld\", \"overturned\"]);\nexport type MilestoneDisputeOutcome = z.infer<typeof MilestoneDisputeOutcome>;\n\n/** A learner's dispute of a case or a review verdict, and what the tutor decided (ADR-016). Kept on the milestone. */\nexport const MilestoneDispute = z\n .object({\n id: z.string(),\n target: z.enum([\"case\", \"review\"]),\n /** The disputed case's index in `cases`, and its name then. */\n caseIndex: z.number().int().nonnegative().optional(),\n caseName: z.string().optional(),\n reason: z.string().max(MAX_DISPUTE_REASON_CHARS),\n outcome: MilestoneDisputeOutcome,\n /** The tutor's explanation, for the learner. */\n explanation: z.string().max(2000),\n /** A corrected case as it was before. */\n before: z.object({ input: z.string(), expected: z.string() }).strict().optional(),\n createdAt: z.string().datetime(),\n })\n .strict();\nexport type MilestoneDispute = z.infer<typeof MilestoneDispute>;\n\n/** The stored spec: the input with each case's expected output (normalised) from the reference run, and its disputes. */\nexport const ProjectMilestoneSpec = z\n .object({\n ...milestoneFields,\n cases: z.array(MilestoneCase).max(MAX_EXERCISE_CASES),\n referenceSolution: z.string().max(MAX_MILESTONE_REFERENCE_CHARS).optional(),\n disputes: z.array(MilestoneDispute).max(MAX_MILESTONE_DISPUTES).optional(),\n })\n .strict();\nexport type ProjectMilestoneSpec = z.infer<typeof ProjectMilestoneSpec>;\n\n/** The cases `mivra check` runs and the grader counts, with their place in `cases`: every one not withdrawn. */\nexport const activeMilestoneCases = (spec: Pick<ProjectMilestoneSpec, \"cases\">) =>\n spec.cases.flatMap((testCase, index) => (testCase.withdrawn ? [] : [{ ...testCase, index }]));\n\n/** The learner sees every case and its expected output; only the reference stays on the server. */\nexport const ProjectMilestonePublic = z\n .object({\n concept: z.string(),\n title: z.string(),\n spec: z.string(),\n outputFormat: z.string(),\n checkType: MilestoneCheckType,\n reviewFocus: z.string().optional(),\n cases: z.array(z.object({ name: z.string(), input: z.string(), compare: MilestoneCompare, expected: z.string(), withdrawn: z.boolean().optional() }).strict()),\n disputes: z.array(MilestoneDispute),\n })\n .strict();\nexport type ProjectMilestonePublic = z.infer<typeof ProjectMilestonePublic>;\n\nexport const toProjectMilestonePublic = (spec: ProjectMilestoneSpec): ProjectMilestonePublic => ({\n concept: spec.concept,\n title: spec.title,\n spec: spec.spec,\n outputFormat: spec.outputFormat,\n checkType: spec.checkType,\n ...(spec.reviewFocus ? { reviewFocus: spec.reviewFocus } : {}),\n cases: spec.cases.map((c) => ({ name: c.name, input: c.input, compare: c.compare ?? \"stdout\", expected: c.expected, ...(c.withdrawn ? { withdrawn: true } : {}) })),\n disputes: spec.disputes ?? [],\n});\n\n/**\n * The current milestone's cases as `mivra check` fetches them (GET /courses/{id}/milestone): data only. Nothing here\n * is ever run; the only command that runs is the one the learner set with `mivra link`.\n */\nexport const MilestoneCases = z\n .object({\n courseId: z.string(),\n lessonId: z.string(),\n artifactId: z.string(),\n /** The milestone's place in the syllabus, from 1. */\n position: z.number().int().positive(),\n title: z.string(),\n checkType: MilestoneCheckType,\n /** Names this set of cases; a check reports it back, so results for cases a dispute changed meanwhile are refused. */\n revision: z.string().regex(/^[0-9a-f]{8,64}$/),\n /**\n * The commit the last passed milestone was checked at, if any: `mivra check` sends only what changed since. Only a\n * commit id, which `mivra check` hands to git as data.\n */\n since: CommitId.nullable(),\n /** The cases to run; withdrawn ones are left out. A review milestone has none. */\n cases: z.array(z.object({ name: z.string(), input: z.string().max(MAX_CASE_INPUT_CHARS), compare: MilestoneCompare }).strict()).max(MAX_EXERCISE_CASES),\n })\n .strict();\nexport type MilestoneCases = z.infer<typeof MilestoneCases>;\n\n/** Why a case produced no comparable output. */\nexport const MilestoneRunError = z.enum([\"timeout\", \"output_limit\", \"start_failed\", \"no_run_output_command\"]);\nexport type MilestoneRunError = z.infer<typeof MilestoneRunError>;\n\n/** What running one case produced on the learner's machine. `stdout` is normalised, and cut short if `truncated`. */\nexport const MilestoneCaseResult = z\n .object({\n stdout: z.string().max(MAX_CASE_OUTPUT_CHARS),\n truncated: z.boolean().optional(),\n stderr: z.string().max(MAX_MILESTONE_STDERR_CHARS).optional(),\n /** The exit code, or null if it was killed or never started. */\n exitCode: z.number().int().nullable(),\n error: MilestoneRunError.optional(),\n })\n .strict();\nexport type MilestoneCaseResult = z.infer<typeof MilestoneCaseResult>;\n\n/** One file `mivra check` sends for review: its path from the folder holding `.mivra.json`, and its text. */\nexport const ReviewFile = z.object({ path: z.string().min(1).max(MAX_REVIEW_PATH_CHARS), content: z.string().max(MAX_REVIEW_FILE_CHARS) }).strict();\nexport type ReviewFile = z.infer<typeof ReviewFile>;\n\n/**\n * Why a changed file wasn't sent. Only reasons that say nothing about a secret are ever sent to the server: a\n * secret-looking file is left out without its name, and ignored files aren't changes at all.\n */\nexport const ReviewSkipReason = z.enum([\"binary\", \"too_large\", \"size_cap\", \"lockfile\"]);\nexport type ReviewSkipReason = z.infer<typeof ReviewSkipReason>;\n\n/** What a check sends besides the results, for the review: the changed files, what was left out and the commit. */\nconst reviewFields = {\n /** The commit checked out when the check ran (the files may have changed since), if the repository has one. */\n commit: CommitId.optional(),\n /** Where the files came from: git, or nowhere outside a git repository (nothing is sent then). */\n source: z.enum([\"git\", \"none\"]).optional(),\n files: z.array(ReviewFile).max(MAX_REVIEW_FILES).optional(),\n /** Paths of changed files that weren't sent, and why. */\n skipped: z.array(z.object({ path: z.string().max(MAX_REVIEW_PATH_CHARS), reason: ReviewSkipReason }).strict()).max(1000).optional(),\n /** Paths deleted since the last passed milestone. */\n deleted: z.array(z.string().max(MAX_REVIEW_PATH_CHARS)).max(1000).optional(),\n};\n\n/** Body of POST /artifacts/{id}/checks: one result per case `GET \u2026/milestone` sent, in its order, and the changed files. */\nexport const MilestoneCheckAnswer = z\n .object({\n results: z.array(MilestoneCaseResult).max(MAX_EXERCISE_CASES),\n /** The `revision` of the cases that ran. Left out by a `mivra check` from before disputes. */\n revision: z.string().max(64).optional(),\n ...reviewFields,\n })\n .strict()\n .superRefine((answer, ctx) => {\n const total = (answer.files ?? []).reduce((sum, file) => sum + file.content.length, 0);\n if (total > MAX_REVIEW_TOTAL_CHARS) ctx.addIssue({ code: \"custom\", path: [\"files\"], message: `At most ${MAX_REVIEW_TOTAL_CHARS} characters of files can be sent.` });\n });\nexport type MilestoneCheckAnswer = z.infer<typeof MilestoneCheckAnswer>;\n\nexport const MilestoneGrade = z\n .object({\n /** Every case that ran passed (true when there were none to run). Not the milestone's pass: that needs the review too. */\n correct: z.boolean(),\n passed: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n /** One per case that ran, with its index in the spec's `cases` (missing in grades from before disputes: then in order). */\n cases: z.array(z.object({ passed: z.boolean(), case: z.number().int().nonnegative().optional() }).strict()),\n })\n .strict();\nexport type MilestoneGrade = z.infer<typeof MilestoneGrade>;\n\n/** Whether one case's run matches: it exited with 0, wasn't cut short, and printed the expected output. */\nexport function milestoneCasePassed(expected: string, run: MilestoneCaseResult): boolean {\n return run.error === undefined && !run.truncated && run.exitCode === 0 && normaliseOutput(run.stdout) === normaliseOutput(expected);\n}\n\n/**\n * Deterministic grader (ADR-006) over the cases not withdrawn, which the answer reports in order. Throws if it doesn't\n * report one result for each.\n */\nexport function gradeMilestone(spec: ProjectMilestoneSpec, answer: Pick<MilestoneCheckAnswer, \"results\">): MilestoneGrade {\n const active = activeMilestoneCases(spec);\n if (answer.results.length !== active.length) {\n throw new RangeError(`Expected results for ${active.length} cases, got ${answer.results.length}`);\n }\n const cases = active.map((c, i) => ({ passed: milestoneCasePassed(c.expected, answer.results[i]!), case: c.index }));\n const passed = cases.filter((c) => c.passed).length;\n return { correct: passed === cases.length, passed, total: cases.length, cases };\n}\n\n/** One part of the review's rubric: whether the code meets it, and why, for the learner. */\nconst ReviewCriterion = z\n .object({\n passed: z.boolean(),\n note: z.string().trim().min(1).max(1000).describe(\"One to three sentences for the learner, pointing at the file and the code you mean.\"),\n })\n .strict();\n\n/**\n * The review's rubric (ADR-016), as the model records it through its tool. The server derives the verdict: it approves\n * only if every criterion passed.\n */\nexport const MilestoneReviewInput = z\n .object({\n noHardCodedOutputs: ReviewCriterion.describe(\n \"passed is false if the program special-cases test inputs or prints canned answers instead of computing them, e.g. matching an input string and printing its expected output.\",\n ),\n concept: ReviewCriterion.describe(\"passed is true if the code really does what this milestone teaches (its concept and reviewFocus), not just something that produces the same output.\"),\n quality: ReviewCriterion.describe(\n \"passed is false only for serious problems for a learner at this stage: code that can't be followed, copy-pasted blocks instead of a loop or function, or obvious bugs the tests miss. Style preferences never fail it.\",\n ),\n summary: z.string().trim().min(1).max(1500).describe(\"What you'd tell the learner: what's good, and what to change if anything.\"),\n suggestions: z.array(z.string().trim().min(1).max(500)).max(8).describe(\"Optional next steps, most useful first. Never write the solution.\"),\n })\n .strict();\nexport type MilestoneReviewInput = z.infer<typeof MilestoneReviewInput>;\n\n/** A review's verdict, recorded as its own evidence, separate from the tests' and marked as judged by a model (ADR-016). */\nexport const MilestoneReview = MilestoneReviewInput.extend({\n approved: z.boolean(),\n judgedBy: z.literal(\"model\"),\n /** The model that reviewed, as shown in the picker. */\n model: z.string(),\n}).strict();\nexport type MilestoneReview = z.infer<typeof MilestoneReview>;\n\n/** The verdict a rubric gives: approval only when every criterion passed. */\nexport const reviewVerdict = (input: MilestoneReviewInput, model: string): MilestoneReview => ({\n ...input,\n approved: input.noHardCodedOutputs.passed && input.concept.passed && input.quality.passed,\n judgedBy: \"model\",\n model,\n});\n\n/**\n * What happened to a check's review: its verdict, or why there wasn't one. A review runs only once every case passed,\n * since it can never turn a failed test into a pass, and only when files were sent.\n */\nexport const MilestoneReviewStatus = z.discriminatedUnion(\"status\", [\n z.object({ status: z.literal(\"done\"), review: MilestoneReview }).strict(),\n z.object({ status: z.literal(\"skipped\"), reason: z.enum([\"tests_failed\", \"no_files\"]) }).strict(),\n z.object({ status: z.literal(\"failed\"), error: z.string() }).strict(),\n]);\nexport type MilestoneReviewStatus = z.infer<typeof MilestoneReviewStatus>;\n\n/** Whether a check passes the milestone: every case that ran passed, and the review approved. */\nexport const milestonePassed = (grade: Pick<MilestoneGrade, \"correct\">, review: Pick<MilestoneReview, \"approved\"> | undefined) => grade.correct && review?.approved === true;\n\n/**\n * What POST /artifacts/{id}/checks returns: the grade, each case's expected output for `mivra check` to show beside\n * what it got, the review, and whether the milestone passed.\n */\nexport const MilestoneCheckResult = z\n .object({\n grade: MilestoneGrade,\n expected: z.array(z.string()),\n review: MilestoneReviewStatus,\n passed: z.boolean(),\n })\n .strict();\nexport type MilestoneCheckResult = z.infer<typeof MilestoneCheckResult>;\n\n/** Body of POST /artifacts/{id}/disputes: the learner disputes one case (by its index in `cases`) or the latest review. */\nexport const MilestoneDisputeRequest = z.discriminatedUnion(\"target\", [\n z.object({ target: z.literal(\"case\"), caseIndex: z.number().int().nonnegative().max(MAX_EXERCISE_CASES - 1), reason: z.string().trim().min(1).max(MAX_DISPUTE_REASON_CHARS) }).strict(),\n z.object({ target: z.literal(\"review\"), reason: z.string().trim().min(1).max(MAX_DISPUTE_REASON_CHARS) }).strict(),\n]);\nexport type MilestoneDisputeRequest = z.infer<typeof MilestoneDisputeRequest>;\n\n/** The tutor's decision about a disputed case, through its tool. */\nexport const CaseDisputeDecision = z\n .object({\n outcome: z.enum([\"keep\", \"withdraw\", \"correct\"]).describe(\"keep: the case is right. withdraw: it's wrong or unfair and can't simply be fixed. correct: fix its input or the reference.\"),\n explanation: z.string().trim().min(1).max(2000).describe(\"For the learner: why, in two or three sentences.\"),\n input: z.string().max(MAX_CASE_INPUT_CHARS).optional().describe(\"correct only: the case's corrected input, if the input was wrong.\"),\n referenceSolution: z\n .string()\n .min(1)\n .max(MAX_MILESTONE_REFERENCE_CHARS)\n .optional()\n .describe(\"correct only: the whole corrected Python reference, if its output was wrong. Mivra reruns it on every case.\"),\n })\n .strict();\nexport type CaseDisputeDecision = z.infer<typeof CaseDisputeDecision>;\n\n/** A check as the learner's page shows it: the results, and the paths of the files sent rather than their text. */\nexport const MilestoneCheckView = z\n .object({\n results: z.array(MilestoneCaseResult),\n files: z.array(z.string()),\n skipped: z.array(z.object({ path: z.string(), reason: ReviewSkipReason }).strict()).optional(),\n source: z.enum([\"git\", \"none\"]).optional(),\n })\n .strict();\nexport type MilestoneCheckView = z.infer<typeof MilestoneCheckView>;\n\nexport const toMilestoneCheckView = (answer: MilestoneCheckAnswer): MilestoneCheckView => ({\n results: answer.results,\n files: (answer.files ?? []).map((f) => f.path),\n ...(answer.skipped?.length ? { skipped: answer.skipped } : {}),\n ...(answer.source ? { source: answer.source } : {}),\n});\n", "import { z } from \"zod\";\nimport { TraceVariable } from \"./algorithm-trace.js\";\n\n/**\n * set_diagram v1: a Venn diagram of up to 3 sets, with what each region contains and optional steps\n * that highlight regions. Covers union, intersection, complement, difference and inclusion-exclusion.\n *\n * A region is named by the set ids it is inside and is outside every other set, so with sets a, b and c,\n * `[\"a\", \"b\"]` is \"in a and b, not c\", and `[\"b\", \"a\"]` is the same region. `[]` is outside every set.\n * A region that isn't listed has no contents shown; a listed region with no elements and no count is empty.\n *\n * Highlights and variables do not persist: each step lists all of its own.\n */\n\nconst MAX_SETS = 3;\n/** 2^3: every region of a 3-set diagram, including outside. */\nconst MAX_REGIONS = 8;\nconst MAX_ELEMENTS = 30;\nconst MAX_STEPS = 40;\n\nconst SetId = z.string().trim().min(1).max(24);\n/** Text drawn in a tight spot in the diagram, so it stays on one line. */\nconst ONE_LINE = /^[^\\n\\r\\v\\f\\u0085\\u2028\\u2029]*$/;\nconst oneLine = (max: number) => z.string().trim().min(1).max(max).regex(ONE_LINE, \"must not contain line breaks\");\nconst Element = z.union([z.number(), oneLine(24)]);\n\n/** The same string for any ordering of the same set ids, so a region can be compared and looked up. */\nexport function setRegionKey(ids: readonly string[]): string {\n return JSON.stringify([...ids].sort());\n}\n\nconst RegionIn = z.array(SetId).max(MAX_SETS);\n\nexport const SetDiagramSet = z\n .object({\n id: SetId.describe('Short id used to refer to this set, e.g. \"a\". Unique within the diagram.'),\n label: oneLine(32).describe('Shown next to the circle, e.g. \"$A$\" or \"Multiples of 3\", on one line. Only $...$ is a formula.'),\n })\n .strict();\n\nexport const SetDiagramRegion = z\n .object({\n in: RegionIn.describe('Ids of the sets this region is inside. It is outside all the others: with sets a, b, c, [\"a\",\"b\"] means in a and b, not c. [] means outside every set and needs `universe`. No id twice.'),\n elements: z.array(Element).max(MAX_ELEMENTS).describe(\"What the region contains, each short and on one line. No element may appear twice, in this list or across regions, and 1 and \\\"1\\\" count as the same element. Empty if you only know the count, or the region is empty.\"),\n count: z\n .number()\n .int()\n .nonnegative()\n .max(1_000_000)\n .optional()\n .describe(\"How many elements the region has, when that's more than you list, e.g. for inclusion-exclusion. At least the number of elements listed.\"),\n })\n .strict();\n\nexport const SetDiagramHighlight = z\n .object({\n in: RegionIn.describe(\"The region to highlight, named like a region's `in`, with no id twice. Any region of the diagram can be highlighted, listed or not.\"),\n tone: z.enum([\"active\", \"done\", \"muted\"]).optional().describe(\"active = current focus, done = finished, muted = ruled out. Defaults to active.\"),\n })\n .strict();\n\nexport const SetDiagramStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What this step shows, in one or two sentences.\"),\n highlights: z\n .array(SetDiagramHighlight)\n .max(MAX_REGIONS)\n .optional()\n .describe(\"All regions highlighted at this step, each at most once. They apply to this step only, not carried over: repeat any that still apply.\"),\n variables: z.array(TraceVariable).max(12).optional().describe(\"All running state at this step, e.g. |A \u222A B| so far. Not carried over from earlier steps.\"),\n })\n .strict();\n\nexport const SetDiagramSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n sets: z.array(SetDiagramSet).min(1).max(MAX_SETS).describe(\"The circles, 1 to 3.\"),\n universe: oneLine(24).optional().describe('Label of the rectangle around the sets, e.g. \"$U$\", on one line. Needed to show or highlight the region outside every set, such as a complement.'),\n regions: z.array(SetDiagramRegion).max(MAX_REGIONS).describe(\"What each region contains, each region at most once.\"),\n steps: z.array(SetDiagramStep).min(1).max(MAX_STEPS).optional().describe(\"Optional walk through the diagram. Omit for a static diagram.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const ids = spec.sets.map((s) => s.id);\n spec.sets.forEach((set, i) => {\n if (ids.indexOf(set.id) !== i) ctx.addIssue({ code: \"custom\", path: [\"sets\", i, \"id\"], message: `duplicate set id \"${set.id}\"` });\n });\n\n /** Checks a list of region references, and reports any region named twice, whatever the order of its ids. */\n const checkRegions = (entries: readonly { in: string[] }[], path: (string | number)[]) => {\n const seen = new Set<string>();\n entries.forEach((entry, i) => {\n const at = [...path, i, \"in\"];\n entry.in.forEach((id, j) => {\n if (!ids.includes(id)) ctx.addIssue({ code: \"custom\", path: [...at, j], message: `unknown set \"${id}\"` });\n if (entry.in.indexOf(id) !== j) ctx.addIssue({ code: \"custom\", path: [...at, j], message: `set \"${id}\" is named twice` });\n });\n if (entry.in.length === 0 && spec.universe === undefined) {\n ctx.addIssue({ code: \"custom\", path: at, message: \"the region outside every set needs `universe`\" });\n }\n const key = setRegionKey(entry.in);\n if (seen.has(key)) ctx.addIssue({ code: \"custom\", path: at, message: `region ${key} appears more than once` });\n seen.add(key);\n });\n };\n checkRegions(spec.regions, [\"regions\"]);\n spec.steps?.forEach((step, i) => checkRegions(step.highlights ?? [], [\"steps\", i, \"highlights\"]));\n\n // Regions don't overlap, so an element in two of them would teach something false.\n const placed = new Set<string>();\n spec.regions.forEach((region, i) => {\n region.elements.forEach((element, j) => {\n if (placed.has(String(element))) {\n ctx.addIssue({ code: \"custom\", path: [\"regions\", i, \"elements\", j], message: `element \"${element}\" appears more than once; regions don't overlap` });\n }\n placed.add(String(element));\n });\n if (region.count !== undefined && region.count < region.elements.length) {\n ctx.addIssue({ code: \"custom\", path: [\"regions\", i, \"count\"], message: `count ${region.count} is less than the ${region.elements.length} elements listed` });\n }\n });\n });\n\nexport type SetDiagramSpec = z.infer<typeof SetDiagramSpec>;\nexport type SetDiagramStep = z.infer<typeof SetDiagramStep>;\nexport type SetDiagramHighlight = z.infer<typeof SetDiagramHighlight>;\n", "import { z } from \"zod\";\n\n/**\n * table v1: a truth table, relation matrix or other tabular working, optionally stepped through.\n *\n * State rules (renderers must follow them):\n * - `cells` persists: a changed cell keeps its new value on every later step.\n * - `highlight` does not persist: each step lists all of its own, and omitting it means that step has none.\n * The table's shape never changes, so every index can be checked against `rows` and `columns`.\n */\n\nconst MAX_COLUMNS = 16;\nconst MAX_ROWS = 64;\nconst MAX_STEPS = 100;\n\nconst Header = z.string().trim().min(1).max(80);\nconst CellValue = z.union([z.number(), z.boolean(), z.string().max(120)]);\nconst Index = z.number().int().nonnegative();\n\nexport const TableHighlight = z\n .object({\n row: Index.optional().describe(\"0-based data row, below the number of rows. With no column, highlights the whole row. A highlight must give a row, a column or both.\"),\n column: Index.optional().describe(\"0-based data column, below the number of columns. With no row, highlights the whole column. With both, highlights one cell.\"),\n tone: z\n .enum([\"active\", \"done\", \"muted\"])\n .optional()\n .describe(\"active = current focus, done = finished, muted = ruled out. Defaults to active. Where highlights overlap, the later one wins.\"),\n })\n .strict();\n\nexport const TableCellChange = z\n .object({\n row: Index.describe(\"0-based data row, below the number of rows.\"),\n column: Index.describe(\"0-based data column, below the number of columns.\"),\n value: CellValue.describe(\"The cell's value from this step on.\"),\n })\n .strict();\n\nexport const TableStep = z\n .object({\n explanation: z.string().trim().min(1).max(500).describe(\"What happens in this step, in one or two sentences.\"),\n highlight: z\n .array(TableHighlight)\n .max(32)\n .optional()\n .describe(\"All cells, rows and columns to highlight at this step. Not carried over from earlier steps.\"),\n cells: z\n .array(TableCellChange)\n .max(64)\n .optional()\n .describe('Cells this step fills in or changes. They keep the new value on later steps. To reveal working, start a cell as \"\" and set it here.'),\n })\n .strict();\n\nexport const TableSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n columns: z.array(Header).min(1).max(MAX_COLUMNS).describe(\"Column headers, one per data column. Don't include a header for rowHeaders.\"),\n rows: z\n .array(z.array(CellValue).min(1).max(MAX_COLUMNS))\n .min(1)\n .max(MAX_ROWS)\n .describe('Data rows, each with exactly one cell per column. A boolean shows as T or F; \"\" is a blank cell.'),\n rowHeaders: z.array(Header).max(MAX_ROWS).optional().describe(\"Optional label for each row, e.g. a relation matrix's elements. Exactly one per row.\"),\n steps: z.array(TableStep).min(1).max(MAX_STEPS).optional().describe(\"Omit for a static table. With steps, the learner steps through them.\"),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const rowCount = spec.rows.length;\n const columnCount = spec.columns.length;\n spec.rows.forEach((row, i) => {\n if (row.length !== columnCount) {\n ctx.addIssue({ code: \"custom\", path: [\"rows\", i], message: `row has ${row.length} cells but there are ${columnCount} columns` });\n }\n });\n if (spec.rowHeaders && spec.rowHeaders.length !== rowCount) {\n ctx.addIssue({ code: \"custom\", path: [\"rowHeaders\"], message: `${spec.rowHeaders.length} row headers for ${rowCount} rows` });\n }\n const checkRow = (row: number, path: (string | number)[]) => {\n if (row >= rowCount) ctx.addIssue({ code: \"custom\", path, message: `row ${row} is outside the table (${rowCount} rows)` });\n };\n const checkColumn = (column: number, path: (string | number)[]) => {\n if (column >= columnCount) ctx.addIssue({ code: \"custom\", path, message: `column ${column} is outside the table (${columnCount} columns)` });\n };\n spec.steps?.forEach((step, i) => {\n step.highlight?.forEach((h, j) => {\n const path = [\"steps\", i, \"highlight\", j];\n if (h.row === undefined && h.column === undefined) ctx.addIssue({ code: \"custom\", path, message: \"a highlight needs a row, a column or both\" });\n if (h.row !== undefined) checkRow(h.row, [...path, \"row\"]);\n if (h.column !== undefined) checkColumn(h.column, [...path, \"column\"]);\n });\n step.cells?.forEach((c, j) => {\n checkRow(c.row, [\"steps\", i, \"cells\", j, \"row\"]);\n checkColumn(c.column, [\"steps\", i, \"cells\", j, \"column\"]);\n });\n });\n });\n\nexport type TableSpec = z.infer<typeof TableSpec>;\nexport type TableStep = z.infer<typeof TableStep>;\n", "import { z } from \"zod\";\n\n/**\n * worked_steps v1: a proof, induction or combinatorics working, revealed one step at a time.\n * Every step stays on screen once revealed, so later steps can be read against earlier ones.\n */\n\nconst MAX_STEPS = 50;\n\nexport const WorkedStep = z\n .object({\n label: z.string().trim().min(1).max(40).optional().describe('Optional heading for this part of the working, e.g. \"Base case\", \"Inductive step\".'),\n statement: z\n .string()\n .trim()\n .min(1)\n .max(1000)\n .describe(\"What this step establishes, mostly as a formula in $...$. For large sums and fractions, put \\\\displaystyle INSIDE the dollars, e.g. $\\\\displaystyle\\\\sum_{i=1}^{n} i$; $$ is not available.\"),\n justification: z.string().trim().min(1).max(500).describe('Why it follows, e.g. \"by the inductive hypothesis\".'),\n })\n .strict();\n\nexport const WorkedStepsSpec = z\n .object({\n title: z.string().trim().min(1).max(120),\n goal: z.string().trim().min(1).max(500).optional().describe(\"Optional statement of what is being shown, e.g. the claim to prove.\"),\n steps: z.array(WorkedStep).min(1).max(MAX_STEPS),\n })\n .strict();\n\nexport type WorkedStepsSpec = z.infer<typeof WorkedStepsSpec>;\nexport type WorkedStep = z.infer<typeof WorkedStep>;\n", "import { z } from \"zod\";\n\n/**\n * Lessons (ADR-011): one per syllabus topic, generated when the learner reaches it. The outline comes\n * first, then one tool call per section, so each section validates on its own and appears as soon as it\n * is written. A finished lesson is frozen.\n */\n\n/** Section kinds the outline can plan: prose, or an existing artifact kind by its tool's purpose. */\nexport const LessonSectionKind = z.enum([\"prose\", \"algorithm_trace\", \"code_exercise\", \"code_walkthrough\", \"composition\", \"graph\", \"multiple_choice\", \"project_milestone\", \"set_diagram\", \"table\", \"worked_steps\"]);\nexport type LessonSectionKind = z.infer<typeof LessonSectionKind>;\n\nexport const MAX_LESSON_SECTIONS = 10;\n\nconst LessonOutlineFields = z\n .object({\n title: z.string().trim().min(1).max(120),\n sections: z\n .array(\n z\n .object({\n title: z.string().trim().min(1).max(120),\n kind: LessonSectionKind.describe(\n \"prose = write_lesson_text; multiple_choice = ask_multiple_choice (a check); code_exercise = ask_code_exercise (a JavaScript or Python exercise the learner solves and submits); project_milestone = set_project_milestone (project courses only: the milestone the learner builds in their repository); the others = the matching show_* tool.\",\n ),\n purpose: z.string().trim().min(1).max(300).describe(\"What this section does for the learner, in one sentence.\"),\n })\n .strict(),\n )\n .min(2)\n .max(MAX_LESSON_SECTIONS),\n })\n .strict();\n\n/** A lesson's outline in a course of lessons: at least one multiple-choice check, and no milestone. */\nexport const LessonOutlineInput = LessonOutlineFields.extend({\n sections: LessonOutlineFields.shape.sections.describe(`2-${MAX_LESSON_SECTIONS} sections in reading order. Include at least one multiple_choice check, usually after the idea it checks.`),\n})\n .strict()\n .superRefine((outline, ctx) => {\n if (!outline.sections.some((s) => s.kind === \"multiple_choice\")) {\n ctx.addIssue({ code: \"custom\", path: [\"sections\"], message: \"Include at least one multiple_choice check\" });\n }\n outline.sections.forEach((s, i) => {\n if (s.kind === \"project_milestone\") ctx.addIssue({ code: \"custom\", path: [\"sections\", i, \"kind\"], message: \"project_milestone is only for project courses\" });\n });\n });\nexport type LessonOutlineInput = z.infer<typeof LessonOutlineInput>;\n\n/**\n * A milestone lesson's outline in a project course (ADR-016): a few sections that prepare the learner, and exactly one\n * project_milestone section, last, for the step they build in their repository. Checks are optional.\n */\nexport const ProjectLessonOutlineInput = LessonOutlineFields.extend({\n sections: LessonOutlineFields.shape.sections.describe(\n `2-${MAX_LESSON_SECTIONS} sections in reading order: what the milestone needs, then exactly one project_milestone section, last.`,\n ),\n})\n .strict()\n .superRefine((outline, ctx) => {\n const milestones = outline.sections.filter((s) => s.kind === \"project_milestone\").length;\n if (milestones !== 1 || outline.sections.at(-1)?.kind !== \"project_milestone\") {\n ctx.addIssue({ code: \"custom\", path: [\"sections\"], message: \"Include exactly one project_milestone section, as the last section\" });\n }\n });\n\nexport const LessonTextInput = z\n .object({\n markdown: z.string().trim().min(1).max(6000).describe(\"The section's prose, as markdown with $...$ and $$...$$ maths. Don't repeat the section title as a heading.\"),\n revisits: z\n .array(z.string().min(1))\n .max(5)\n .optional()\n .describe(\"sectionIds from <previous_lesson> this section revisits. The page links back to them, so don't write links yourself.\"),\n })\n .strict();\nexport type LessonTextInput = z.infer<typeof LessonTextInput>;\n\nexport const LessonStatus = z.enum([\"generating\", \"ready\", \"failed\", \"finished\"]);\nexport type LessonStatus = z.infer<typeof LessonStatus>;\n\nexport const LessonOutlineView = z\n .object({\n title: z.string(),\n sections: z.array(z.object({ title: z.string(), kind: LessonSectionKind }).strict()),\n })\n .strict();\n\n/** A lesson as the client sees it. `artifact` holds an ArtifactView, validated by the client's renderer. */\nexport const LessonView = z\n .object({\n id: z.string(),\n courseId: z.string(),\n topicId: z.string(),\n topicTitle: z.string(),\n position: z.number().int().nonnegative(),\n status: LessonStatus,\n version: z.number().int().positive().nullable(),\n outline: LessonOutlineView.nullable(),\n sections: z.array(\n z.discriminatedUnion(\"kind\", [\n z\n .object({\n id: z.string(),\n title: z.string(),\n kind: z.literal(\"prose\"),\n markdown: z.string(),\n /** Earlier sections this one revisits, for links back to exactly what the learner saw. */\n revisits: z.array(z.object({ lessonId: z.string(), sectionId: z.string(), title: z.string(), lessonTitle: z.string() }).strict()),\n })\n .strict(),\n z.object({ id: z.string(), title: z.string(), kind: z.literal(\"artifact\"), artifact: z.unknown() }).strict(),\n ]),\n ),\n checks: z.object({ total: z.number().int().nonnegative(), answered: z.number().int().nonnegative() }).strict(),\n /** The course's current syllabus version, so a page can notice a change made while it was open. */\n syllabusVersion: z.number().int().positive().nullable(),\n /** Sections the latest version added or changed, highlighted for the learner, and why. */\n changedSectionIds: z.array(z.string()),\n changeReason: z.string().nullable(),\n /** Whether the learner can finish it now: fully written and every check answered. */\n canFinish: z.boolean(),\n error: z.string().nullable(),\n /** A failure the learner fixes elsewhere: \"lesson-model\" means the lesson model chosen in Settings can't be used. */\n errorAction: z.enum([\"lesson-model\"]).nullable(),\n createdAt: z.string().datetime(),\n finishedAt: z.string().datetime().nullable(),\n })\n .strict();\nexport type LessonView = z.infer<typeof LessonView>;\n\n/** One row per syllabus topic, in syllabus order, with its lesson if one exists. */\nexport const CourseLessonsView = z\n .object({\n topics: z.array(\n z\n .object({\n topicId: z.string(),\n title: z.string(),\n lesson: z.object({ id: z.string(), status: LessonStatus }).strict().nullable(),\n })\n .strict(),\n ),\n /** The lesson to show: the first unfinished one, or the last one once all are finished. */\n currentLessonId: z.string().nullable(),\n /** The next topic without a lesson, if the learner may start it now. */\n nextTopicId: z.string().nullable(),\n })\n .strict();\nexport type CourseLessonsView = z.infer<typeof CourseLessonsView>;\n\nconst SectionTitle = z.string().trim().min(1).max(120);\nconst SectionMarkdown = z.string().trim().min(1).max(6000);\nconst Reason = z.string().trim().min(1).max(300);\n\n/**\n * Input of change_lesson: the tutor's edit of the current lesson, on the learner's request (ADR-011).\n * One call makes one new version; the sections it adds or rewrites are highlighted.\n */\nexport const ChangeLessonInput = z\n .object({\n reason: Reason.describe('What the learner asked for, in a few words, e.g. \"Simpler intro with an example\".'),\n operations: z\n .array(\n z.discriminatedUnion(\"op\", [\n z.object({ op: z.literal(\"rewrite\"), sectionId: z.string().min(1), markdown: SectionMarkdown, title: SectionTitle.optional() }).strict()\n .describe(\"Replace a prose section's text (and optionally its title).\"),\n z.object({ op: z.literal(\"insert\"), afterSectionId: z.string().min(1).nullable(), title: SectionTitle, markdown: SectionMarkdown }).strict()\n .describe(\"Add a prose section after the given section, or first if null.\"),\n z.object({ op: z.literal(\"insert_artifact\"), afterSectionId: z.string().min(1).nullable(), title: SectionTitle, artifactId: z.string().min(1) }).strict()\n .describe(\"Add a card you created earlier in this reply (its artifactId) as a section.\"),\n z.object({ op: z.literal(\"remove\"), sectionId: z.string().min(1) }).strict(),\n z.object({ op: z.literal(\"move\"), sectionId: z.string().min(1), afterSectionId: z.string().min(1).nullable() }).strict(),\n ]),\n )\n .min(1)\n .max(10),\n })\n .strict();\nexport type ChangeLessonInput = z.infer<typeof ChangeLessonInput>;\n\n/** Input of change_syllabus: the tutor's edit of the course's future topics, on the learner's request. */\nexport const ChangeSyllabusInput = z\n .object({\n reason: Reason.describe('What the learner asked for, e.g. \"Add a topic on vectors before gradients\".'),\n operations: z\n .array(\n z.discriminatedUnion(\"op\", [\n z\n .object({\n op: z.literal(\"insert\"),\n afterTopicId: z.string().min(1).nullable().describe(\"Insert after this topic; null to insert before the first future topic.\"),\n title: SectionTitle,\n summary: z.string().trim().min(1).max(400),\n reason: Reason,\n concepts: z.array(z.string().trim().min(1).max(80)).min(1).max(8),\n })\n .strict(),\n z.object({ op: z.literal(\"edit\"), topicId: z.string().min(1), title: SectionTitle.optional(), summary: z.string().trim().min(1).max(400).optional() }).strict(),\n z.object({ op: z.literal(\"remove\"), topicId: z.string().min(1) }).strict(),\n z.object({ op: z.literal(\"move\"), topicId: z.string().min(1), afterTopicId: z.string().min(1).nullable() }).strict(),\n ]),\n )\n .min(1)\n .max(10),\n })\n .strict();\nexport type ChangeSyllabusInput = z.infer<typeof ChangeSyllabusInput>;\n\n/** Body of POST /lessons/{id}/sections: keep a tutor's Explain answer as a new section. */\nexport const AddToLesson = z\n .object({\n messageId: z.string().min(1).max(128),\n afterSectionId: z.string().min(1).max(128).nullable(),\n title: SectionTitle,\n })\n .strict();\nexport type AddToLesson = z.infer<typeof AddToLesson>;\n\nconst NewTopic = z\n .object({\n title: SectionTitle,\n summary: z.string().trim().min(1).max(400),\n concepts: z.array(z.string().trim().min(1).max(80)).min(1).max(8),\n })\n .strict();\n\n/**\n * Input of adapt_syllabus: lesson generation's own change to future topics when the learner struggled\n * (ADR-011). Insert, split or reorder only; never removes a topic. At most one per finished lesson.\n */\nexport const AdaptSyllabusInput = z\n .object({\n reason: Reason.describe('Shown to the learner, with the evidence, e.g. \"Added a chain rule refresher: you missed 3 of 4 checks on derivatives\".'),\n operation: z.discriminatedUnion(\"op\", [\n NewTopic.extend({ op: z.literal(\"insert\"), afterTopicId: z.string().min(1).nullable().describe(\"null = straight after this lesson's topic\") }).strict(),\n z.object({ op: z.literal(\"split\"), topicId: z.string().min(1), into: z.array(NewTopic).min(2).max(3) }).strict(),\n z.object({ op: z.literal(\"move\"), topicId: z.string().min(1), afterTopicId: z.string().min(1).nullable() }).strict(),\n ]),\n })\n .strict();\nexport type AdaptSyllabusInput = z.infer<typeof AdaptSyllabusInput>;\n", "import { z } from \"zod\";\n\n/** Memory entries are the model's inferences about the learner, kept apart from graded evidence (ADR-009). */\n\n/** `known` records that the learner's imported notes cover a concept (ADR-014): a claim, ranked below graded evidence. */\nexport const MemoryKind = z.enum([\"goal\", \"preference\", \"misconception\", \"known\"]);\nexport type MemoryKind = z.infer<typeof MemoryKind>;\n\n/** What the remember tool can write in chat. Only distilling imported notes writes `known`. */\nexport const RememberKind = z.enum([\"goal\", \"preference\", \"misconception\"]);\n\nexport const MemoryText = z.string().trim().min(1).max(300);\n\n/** The input of the remember tool. Source, timestamps and basis are set by the server, not the model. */\nexport const RememberInput = z\n .object({\n kind: RememberKind.describe(\"goal = what they want to learn or do; preference = how they like to learn; misconception = something they believe that is wrong.\"),\n text: MemoryText.describe(\"One short sentence about the learner. Never include the answer to a check they haven't answered.\"),\n concept: z.string().trim().min(1).max(80).optional().describe(\"Required for a misconception: the concept it is about. Use the exact name from the check or from their record, so it can be linked to their answers.\"),\n replaces: z.string().min(1).optional().describe(\"The id of a known memory this one corrects or updates.\"),\n })\n .strict()\n .superRefine((input, ctx) => {\n // Without a concept a misconception can't be linked to a wrong answer (ADR-009).\n if (input.kind === \"misconception\" && !input.concept) {\n ctx.addIssue({ code: \"custom\", path: [\"concept\"], message: \"A misconception needs a concept\" });\n }\n });\nexport type RememberInput = z.infer<typeof RememberInput>;\n\n/** How a memory is supported: a graded wrong answer, only something said in chat, or the learner's imported notes. */\nexport const MemoryBasis = z.enum([\"wrong_answer\", \"chat\", \"import\"]);\nexport type MemoryBasis = z.infer<typeof MemoryBasis>;\n\n/**\n * A memory as the learner sees it in the memory panel. A memory written while a check was unanswered\n * could give that check's answer away, so until the check is answered it is `held`, without its content.\n */\nexport const MemoryView = z\n .object({\n id: z.string(),\n kind: MemoryKind,\n held: z.boolean(),\n text: z.string().nullable(),\n concept: z.string().nullable(),\n basis: MemoryBasis.nullable(),\n /** For basis `import`, the note it was drawn from. Null otherwise, and while held. */\n source: z.object({ noteId: z.string(), importId: z.string(), importName: z.string(), path: z.string(), title: z.string() }).strict().nullable(),\n createdAt: z.string().datetime(),\n editedAt: z.string().datetime().nullable(),\n })\n .strict();\nexport type MemoryView = z.infer<typeof MemoryView>;\n\nexport const MemoryEdit = z.object({ text: MemoryText }).strict();\n\n/** Which memories a bulk delete removes: for now, everything drawn from imported notes. */\nexport const MemoryBulkDelete = z.object({ basis: z.literal(\"import\") }).strict();\n", "import { z } from \"zod\";\n\n/** The largest file the learner can upload (ADR-010). The server enforces it while reading. */\nexport const MAX_DOCUMENT_BYTES = 25 * 1024 * 1024;\n\n/** What a client sees of an uploaded document. Its text stays on the server. */\nexport const DocumentView = z.object({\n id: z.string(),\n sessionId: z.string(),\n messageId: z.string().nullable(),\n filename: z.string(),\n kind: z.enum([\"pdf\", \"pptx\"]),\n byteSize: z.number().int(),\n pageCount: z.number().int(),\n pagesWithText: z.number().int(),\n status: z.literal(\"ready\"),\n createdAt: z.string().datetime(),\n});\nexport type DocumentView = z.infer<typeof DocumentView>;\n", "import { z } from \"zod\";\nimport { DistillationView } from \"./knowledge.js\";\n\n/**\n * Importing a learner's Obsidian vault (ADR-014). A vault is hostile input (ADR-010), so every size is capped.\n * Clients send only Markdown files; the server checks each path again and skips anything else.\n */\n\n/** Most files one import can send. */\nexport const MAX_VAULT_FILES = 10_000;\n/** Longest note, in characters. */\nexport const MAX_NOTE_CHARS = 1_000_000;\n/** Largest import request body. */\nexport const MAX_VAULT_BYTES = 64 * 1024 * 1024;\nconst MAX_PATH_CHARS = 512;\n\nexport const VaultFile = z\n .object({\n /** The file's path inside the vault, with `/` between folders, e.g. `Maths/Recursion.md`. */\n path: z.string().min(1).max(MAX_PATH_CHARS),\n text: z.string().max(MAX_NOTE_CHARS),\n })\n .strict();\nexport type VaultFile = z.infer<typeof VaultFile>;\n\nconst VaultFiles = z.array(VaultFile).max(MAX_VAULT_FILES);\nconst VaultName = z.string().trim().min(1).max(120);\n\n/** Starts a new import. The name tells imports apart, so it's unique; the CLI defaults it to the vault folder's name. */\nexport const VaultImportInput = z.object({ name: VaultName, files: VaultFiles }).strict();\nexport type VaultImportInput = z.infer<typeof VaultImportInput>;\n\n/** Replaces an import's files with a new snapshot of the vault. */\nexport const VaultSnapshotInput = z.object({ files: VaultFiles }).strict();\nexport type VaultSnapshotInput = z.infer<typeof VaultSnapshotInput>;\n\nexport const VaultImportView = z\n .object({\n id: z.string(),\n name: z.string(),\n source: z.literal(\"obsidian\"),\n noteCount: z.number().int(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n /** Distilling its notes into concepts and memories, which starts after every import (ADR-014). */\n distillation: DistillationView,\n })\n .strict();\nexport type VaultImportView = z.infer<typeof VaultImportView>;\n\n/**\n * Why a file wasn't imported. `too_long` is a note over MAX_NOTE_CHARS and `symlink` a link inside a zipped\n * vault; both are reported by the zip upload and by clients that check sizes before sending. `generated` is a file Mivra\n * exported itself (frontmatter `mivra: generated`), so re-importing a vault with the export in it adds no duplicates.\n */\nexport const SkipReason = z.enum([\"not_markdown\", \"hidden\", \"bad_path\", \"duplicate\", \"too_long\", \"symlink\", \"generated\"]);\nexport type SkipReason = z.infer<typeof SkipReason>;\n\n/** What one import or re-import changed. `skipped` lists at most a few paths; `skippedCount` counts them all. */\nexport const VaultImportResult = z\n .object({\n import: VaultImportView,\n added: z.number().int(),\n updated: z.number().int(),\n removed: z.number().int(),\n unchanged: z.number().int(),\n skippedCount: z.number().int(),\n skipped: z.array(z.object({ path: z.string(), reason: SkipReason }).strict()),\n /** Links or tags left out because a note or the vault had more than the limit. */\n truncated: z.boolean(),\n })\n .strict();\nexport type VaultImportResult = z.infer<typeof VaultImportResult>;\n\nexport const NoteView = z\n .object({\n id: z.string(),\n importId: z.string(),\n path: z.string(),\n title: z.string(),\n aliases: z.array(z.string()),\n tags: z.array(z.string()),\n body: z.string(),\n updatedAt: z.string().datetime(),\n })\n .strict();\nexport type NoteView = z.infer<typeof NoteView>;\n\n/**\n * An import's notes and the links between them. A link whose target is no note in the vault has `to: null`\n * and keeps its `target`, so a client can draw it as an unresolved node, as Obsidian does.\n */\nexport const NoteGraph = z\n .object({\n notes: z.array(z.object({ id: z.string(), path: z.string(), title: z.string(), tags: z.array(z.string()) }).strict()),\n links: z.array(z.object({ from: z.string(), to: z.string().nullable(), target: z.string(), kind: z.enum([\"link\", \"embed\"]) }).strict()),\n })\n .strict();\nexport type NoteGraph = z.infer<typeof NoteGraph>;\n\n/** Most notes a graph view draws whole; an import (or filter) with more opens on the local graph instead. */\nexport const WHOLE_GRAPH_NOTES = 500;\n/** Most notes, nodes and edges one graph view sends, whatever its mode, so a 10,000-note vault stays drawable. */\nexport const MAX_GRAPH_VIEW_NOTES = 500;\nexport const MAX_GRAPH_VIEW_NODES = 1_000;\nexport const MAX_GRAPH_VIEW_EDGES = 5_000;\n/** Most tags and folders a graph view lists for its filters. */\nexport const MAX_GRAPH_FACETS = 200;\n\nexport const NoteGraphViewQuery = z\n .object({\n /** `auto` draws the whole graph when at most WHOLE_GRAPH_NOTES notes match, and the local graph otherwise. */\n mode: z.enum([\"auto\", \"local\"]).default(\"auto\"),\n /** The note the local graph is drawn around. Defaults to the matching note with the most connections. */\n focus: z.string().max(64).optional(),\n /** How many hops from the focus the local graph reaches. Sharing a tag or concept is one hop, as a link is. */\n depth: z.coerce.number().int().min(1).max(3).default(2),\n /** Only notes carrying this tag, or one nested under it (`maths` matches `maths/algebra`). */\n tag: z.string().max(200).optional(),\n /** Only notes in this folder or below it, without a trailing `/`. */\n folder: z.string().max(512).optional(),\n })\n .strict();\nexport type NoteGraphViewQuery = z.infer<typeof NoteGraphViewQuery>;\n\nexport const NoteGraphNodeKind = z.enum([\"note\", \"ghost\", \"tag\", \"concept\"]);\nexport type NoteGraphNodeKind = z.infer<typeof NoteGraphNodeKind>;\nexport const NoteGraphEdgeKind = z.enum([\"link\", \"tag\", \"concept\", \"prerequisite\", \"related\"]);\nexport type NoteGraphEdgeKind = z.infer<typeof NoteGraphEdgeKind>;\n\n/**\n * What a graph view of an import draws (ADR-014): notes, unresolved links as ghosts, and the tags and concepts that\n * connect notes. A note's `id` is the note's id; the other kinds' ids are prefixed (`tag:`, `concept:`, `ghost:`).\n * `notes` counts the matching notes a tag or concept connects, drawn or not,, and `hops` how far a node is from the focus.\n */\nexport const NoteGraphView = z\n .object({\n mode: z.enum([\"whole\", \"local\"]),\n focus: z.string().nullable(),\n depth: z.number().int(),\n totalNotes: z.number().int(),\n /** Notes matching the filters, drawn or not. */\n matchingNotes: z.number().int(),\n /** Whether the limits left matching nodes or edges out of the drawing. */\n truncated: z.boolean(),\n nodes: z.array(\n z\n .object({\n id: z.string(),\n kind: NoteGraphNodeKind,\n label: z.string(),\n path: z.string().optional(),\n notes: z.number().int().optional(),\n hops: z.number().int().optional(),\n })\n .strict(),\n ),\n edges: z.array(z.object({ from: z.string(), to: z.string(), kind: NoteGraphEdgeKind }).strict()),\n tags: z.array(z.object({ name: z.string(), notes: z.number().int() }).strict()),\n folders: z.array(z.object({ path: z.string(), notes: z.number().int() }).strict()),\n })\n .strict();\nexport type NoteGraphView = z.infer<typeof NoteGraphView>;\n\n/** A note found by title or path, for picking one to centre the graph on. */\nexport const NoteSummary = z.object({ id: z.string(), title: z.string(), path: z.string() }).strict();\nexport type NoteSummary = z.infer<typeof NoteSummary>;\n", "import { z } from \"zod\";\nimport { MemoryText } from \"./memory.js\";\n\n/**\n * Distilling imported notes into the knowledge graph (ADR-014): concepts, edges between them, and memories drawn from\n * notes. The model reads a group of notes and proposes all three through one tool; the server validates every item,\n * since the notes are hostile input (ADR-010).\n */\n\n/** A note in the group being read, by the short reference the prompt gives it (`n1`, `n2`, ...). */\nconst NoteRef = z.string().regex(/^n\\d{1,3}$/);\nconst ConceptName = z.string().trim().min(1).max(80);\n\nexport const MAX_PROPOSED_CONCEPTS = 30;\nexport const MAX_PROPOSED_EDGES = 40;\nexport const MAX_PROPOSED_MEMORIES = 30;\n\nexport const ConceptEdgeKind = z.enum([\"prerequisite\", \"related\"]);\nexport type ConceptEdgeKind = z.infer<typeof ConceptEdgeKind>;\n\n/** The input of the record_from_notes tool. Every list is required, so an empty call is rejected. */\nexport const RecordFromNotesInput = z\n .object({\n concepts: z\n .array(\n z\n .object({\n name: ConceptName.describe(\"A name from <existing_concepts> or <vault_tags> when one fits. Otherwise a new name, written as it appears in the notes.\"),\n notes: z.array(NoteRef).min(1).max(20).describe(\"The refs of the notes that cover it.\"),\n })\n .strict(),\n )\n .max(MAX_PROPOSED_CONCEPTS),\n edges: z\n .array(\n z\n .object({\n from: ConceptName,\n to: ConceptName,\n kind: ConceptEdgeKind.describe(\"prerequisite = from must be understood before to; related = they're closely linked.\"),\n note: NoteRef.describe(\"The ref of the note that shows this link.\"),\n })\n .strict(),\n )\n .max(MAX_PROPOSED_EDGES)\n .describe(\"Edges between concepts named in this call or in <existing_concepts>.\"),\n memories: z\n .array(\n z\n .object({\n kind: z.enum([\"known\", \"goal\", \"misconception\"]).describe(\"known = the notes cover this concept; goal = a goal the notes state; misconception = a wrong belief the notes state.\"),\n text: MemoryText.describe(\"One short sentence about the learner.\"),\n concept: ConceptName.optional().describe(\"Required for known and misconception: a concept named in this call or in <existing_concepts>.\"),\n note: NoteRef.describe(\"The ref of the note it comes from.\"),\n })\n .strict(),\n )\n .max(MAX_PROPOSED_MEMORIES),\n })\n .strict();\nexport type RecordFromNotesInput = z.infer<typeof RecordFromNotesInput>;\n\nexport const DistillationStatus = z.enum([\"idle\", \"queued\", \"running\", \"cancelled\", \"failed\"]);\nexport type DistillationStatus = z.infer<typeof DistillationStatus>;\n\n/**\n * Where distilling an import's notes stands. `pendingNotes` are notes not yet distilled at their current text; the\n * group counts describe the current or last run in this server process.\n */\nexport const DistillationView = z\n .object({\n status: DistillationStatus,\n pendingNotes: z.number().int(),\n groups: z.number().int(),\n groupsDone: z.number().int(),\n error: z.string().nullable(),\n /** Concepts and memories drawn from this import's notes so far. */\n concepts: z.number().int(),\n memories: z.number().int(),\n })\n .strict();\nexport type DistillationView = z.infer<typeof DistillationView>;\n\n/** Every concept drawn from notes and the edges between them, each with the notes it came from. */\nexport const ConceptGraph = z\n .object({\n concepts: z.array(z.object({ id: z.string(), name: z.string(), notes: z.array(z.string()) }).strict()),\n edges: z.array(z.object({ from: z.string(), to: z.string(), kind: ConceptEdgeKind, notes: z.array(z.string()) }).strict()),\n })\n .strict();\nexport type ConceptGraph = z.infer<typeof ConceptGraph>;\n"],
5
+ "mappings": ";AAAA,SAAS,SAAS;AAeX,IAAM,qBAAqB,CAAC,cAAc,QAAQ;AAClD,IAAM,mBAAmB,EAAE,KAAK,kBAAkB;AAGlD,IAAM,qBAAqB;AAE3B,IAAM,0BAA0B;AAEhC,IAAM,2BAA2B;AACjC,IAAM,uBAAuB;AAE7B,IAAM,wBAAwB;AAC9B,IAAM,uBAAuB;AAS7B,IAAM,kBAAkB;AAAA,EAC7B,QAAQ;AAAA,EACR,aAAa,KAAK,OAAO;AAAA,EACzB,YAAY,MAAM;AAAA,EAClB,aAAa;AACf;AAGA,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAC1B,IAAM,kBAAkB,IAAI;AAAA,EAC1B,gMAAgM,MAAM,GAAG;AAC3M;AAEA,IAAM,SAAS,EACZ,QAAQ,EACR,SAAS,EACT,SAAS,0GAA0G;AAE/G,IAAM,yBAAyB,EACnC,OAAO;AAAA,EACN,MAAM,EAAE,QAAQ,OAAO;AAAA,EACvB,OAAO,EACJ,OAAO,EACP,IAAI,oBAAoB,EACxB,SAAS,uIAAuI;AAAA,EACnJ;AACF,CAAC,EACA,OAAO;AAEH,IAAM,wBAAwB,EAClC,OAAO;AAAA,EACN,MAAM,EAAE,QAAQ,MAAM;AAAA,EACtB,MAAM,EACH,OAAO,EACP,IAAI,oBAAoB,EACxB,SAAS,0FAA0F;AAAA,EACtG;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AAG,MAAM,eAAe,CAAC,EAAE,OAAO;AAAA,EAClHA,IAAE,OAAO,EAAE,GAAG,cAAc,MAAMA,IAAE,QAAQ,OAAO,GAAG,SAASA,IAAE,QAAQ,CAAC,GAAG,MAAM,UAAU,CAAC,EAAE,OAAO;AAAA,EACvGA,IAAE,OAAO,EAAE,GAAG,cAAc,MAAMA,IAAE,QAAQ,cAAc,GAAG,SAASA,IAAE,QAAQ,CAAC,GAAG,MAAM,gBAAgB,CAAC,EAAE,OAAO;AACtH,CAAC;AAcM,IAAM,4BAA4B;",
6
+ "names": ["vm", "FILENAME", "z", "z", "z", "z", "z", "z", "Label", "z", "z", "z", "MAX_STEPS", "Id", "z", "z", "z", "z", "z", "MAX_STEPS", "z", "z", "MAX_STEPS", "Index", "z", "MAX_STEPS", "z", "z", "z", "z", "z", "z", "ConceptName", "z", "z", "z"]
7
+ }