Files
Hankan/test/domain/turn.test.ts
MechaCat02 a1c86d9550 feat(tutor): the turn enforced — retries, evidence, the 다지기 checklist, earned progress
"The client enforces; the prompt only explains." Every rule the artifact's
tutor was merely asked to follow, it broke: it certified words on one
correct answer, scored a unit before anything was answered, used a word
from three phases ahead, answered in Korean, and invented spelling
diagnoses. The reworked app fixed each by making the client refuse. This
ports those refusals; domain/turn.ts holds the turn, testable without React.

The gate. A reply is scanned before he sees it — the side of the exercise
he must decode, through the one resolver, and its prose for Korean. A
refused draft is never stored, shown or applied: the tutor is asked again
and told exactly why. After two retries the reply is shown with its words
flagged, and the next turn names them. (The artifact's follow-up told the
tutor it could declare such a word in ::words; that contradicts the gate
and is left out.)

Marking. ::result feeds recall evidence per word. lib/srs.js is looser
than PORT.md, so the call site tightens it: one outcome per word per round,
and "learned" also needs five rounds between the first and last CORRECT
answer — lib alone counted a wrong answer as the start of the span. A
lookup is never recall. What he mistook a word for is kept. The schedule
takes at most one good grade a day from marking; in the artifact five good
rounds in one afternoon made a word "secure" by interval alone.

Phase reviews. The client holds the 다지기 checklist — each unit's rule and
every word the phase introduced, 132 items for Phase 1 — worked in batches
of ten. ::confirmed ticks a rule on the tutor's word but a word only on
evidence; "-item" puts one back; anything off the list is ignored.

Progress is earned: ignored until the unit has an answer, +25 at most per
message, a fall honoured in full, and the next unit only at 85% with three
answers — plus, in a review, nothing open. advanceUnit() enforces it too,
not only the banner.

The prompt gains a per-round tail after the shipped prompt — the practice
set (scored on the evidence, round-robin by word class, each word with the
words one letter away), the checklist, retry notes — sent as a second,
uncached system block so the stable prefix still caches.

Also: recall answers carry the letter-level jamo comparison (kept out of
his own bubble, since it is written to the model); match chips are keyed by
pair index, the bug PORT.md names; and the stand-in tutor exercises every
path offline — recall, ::result, ::confirmed, progress only after answers.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 21:09:51 +02:00

143 lines
5.5 KiB
TypeScript

/* One tutor turn, enforced — with a scripted tutor in place of a model.
The client refuses what the prompt only asks for: an exercise built from
a word he has not been given, an explanation written in Korean. A refused
draft is never returned; the tutor is asked again and told why; after
GATE_TRIES the reply is shown with its stray words named. */
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { readFileSync } from "node:fs";
import type { Db } from "@app/db/types.js";
import { GATE_TRIES } from "@lib/gate.js";
import { gateFor, metWords } from "@app/domain/gate.js";
import { noteAnswer, readProgress } from "@app/domain/progress.js";
import { applyReply, readRecent, runTurn, trimHistory } from "@app/domain/turn.js";
import type { Sample, SampleRequest } from "@app/domain/stub-tutor.js";
import { dictionaryDb } from "../helpers/dict-db.js";
const TEMPLATE = readFileSync(new URL("../../prompt/tutor-system.md", import.meta.url), "utf8");
const TODAY = 20_000;
let db: Db;
beforeEach(async () => {
db = await dictionaryDb(1);
});
afterEach(async () => {
vi.unstubAllGlobals();
await db.close();
});
/** A tutor that replies from a script, and remembers what it was sent. */
function scripted(...replies: string[]) {
const seen: SampleRequest[] = [];
const sample: Sample = async (req) => {
seen.push(req);
return { text: replies[Math.min(seen.length - 1, replies.length - 1)]! };
};
return { sample, seen };
}
/* Unit 1.1 on a fresh install: 나무 is its own word; 마셔 belongs to 2.3. */
const CLEAN = "Read these.\n\n::task translate\n나무\n바다\n::";
const STRAY = "Read these.\n\n::task translate\n나무 마셔\n::";
const KOREAN = `${"한글은 소리를 적는 글자예요. ".repeat(4)}\n\n::task translate\n나무\n::`;
async function turn(sample: Sample, onRetry = vi.fn()) {
const progress = await readProgress(db);
const gate = gateFor({ progress, met: await metWords(db) });
const result = await runTurn({
db,
sample,
template: TEMPLATE,
gate,
progress,
focus: "auto",
recent: [],
history: [],
message: "Let's start unit 1.1.",
strays: [],
onRetry,
});
return { result, onRetry };
}
describe("the gate, enforced", () => {
it("passes a reply built from allowed words at the first attempt", async () => {
const { sample, seen } = scripted(CLEAN);
const { result } = await turn(sample);
expect(seen).toHaveLength(1);
expect(result).toMatchObject({ text: CLEAN, findings: [], korean: false, retries: 0 });
});
it("refuses a draft with an ungated word, never returns it, and tells the tutor why", async () => {
const { sample, seen } = scripted(STRAY, CLEAN);
const { result, onRetry } = await turn(sample);
expect(result.text).toBe(CLEAN);
expect(result.retries).toBe(1);
expect(onRetry).toHaveBeenCalledOnce();
expect(seen[0]!.systemTail).not.toContain("NOT DELIVERED");
expect(seen[1]!.systemTail).toContain("THAT MESSAGE WAS NOT DELIVERED");
expect(seen[1]!.systemTail).toContain("마셔 (belongs to unit 2.3)");
});
it("gives up after GATE_TRIES retries and shows the reply with its words named", async () => {
const { sample, seen } = scripted(STRAY);
const { result } = await turn(sample);
expect(seen).toHaveLength(GATE_TRIES + 1);
expect(result.retries).toBe(GATE_TRIES);
expect(result.findings.map((f) => f.word)).toEqual(["마셔"]);
});
it("sends back an explanation written in Korean", async () => {
const { sample, seen } = scripted(KOREAN, CLEAN);
const { result } = await turn(sample);
expect(result.text).toBe(CLEAN);
expect(seen[1]!.systemTail).toContain("You wrote your explanation in Korean");
});
it("keeps the shipped prompt stable and puts the round in the tail", async () => {
const { sample, seen } = scripted(STRAY, CLEAN);
await turn(sample);
expect(seen[0]!.system).toBe(seen[1]!.system);
expect(seen[0]!.system).toContain("WHAT HE KNOWS");
expect(seen[0]!.systemTail).toContain("VOCABULARY DUE — WORK THESE IN");
});
});
describe("the transcript sent", () => {
it("keeps the newest turns that fit, and opens with the learner", () => {
const turns = [
{ role: "assistant" as const, content: "opening" },
{ role: "user" as const, content: "a".repeat(30) },
{ role: "assistant" as const, content: "b".repeat(30) },
];
expect(trimHistory(turns, 1000)[0]).toEqual({ role: "user", content: "Let's continue the lesson." });
expect(trimHistory(turns, 65).map((t) => t.content)).toEqual(["a".repeat(30), "b".repeat(30)]);
});
});
describe("an accepted reply", () => {
it("applies marking, then earned progress, and remembers the exercise type", async () => {
await noteAnswer(db, await readProgress(db), "My answers:\n나무 → tree\n바다 → sea");
const reply = [
"Two for two.",
"::result",
"나무 | ok",
"바다 | wrong | 바지",
"::",
"::task recall",
"tree",
"::",
"::progress 95 | good start",
].join("\n");
const { parseMessage } = await import("@app/domain/gloss.js");
const applied = await applyReply(db, parseMessage(reply), { lookups: [], today: TODAY });
expect(applied.results?.recorded).toEqual(["나무", "바다"]);
expect(applied.progress).toMatchObject({ stored: 25, ignored: false, clamped: true });
expect(await readRecent(db)).toEqual(["recall"]);
expect((await readProgress(db)).notes["1.1"]).toBe("good start");
});
});