feat(annotate): token-cheap annotation with record output and a runner

The LLM now only labels speech emotions, music changes and sprite exits; speaker,
kind, location, time of day and positions are derived deterministically. Adds
`annotate run` (claude CLI by default, any stdin/stdout command), a hash-keyed
text cache and a usage log; removes the per-line JSON format and its schema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-19 04:41:59 +02:00
1 parent f3017295d8
commit 3d2a91af49
6 files changed
+1098 -761

No files matched your search

+581 -309
View File
File diff suppressed because it is too large. Load diff
+72 -79
View File
@@ -1,88 +1,81 @@
# Task: annotate one chunk of a verse play for a visual novel
You annotate chunk `{{chunk_id}}`. Do not read or write any other file than the two below.
- Input (read it): `{{chunk_path}}`
- Output (write it, nothing else): `{{cache_path}}`
You annotate a passage of a play for a visual novel. You only make three kinds of judgement:
the emotion of each speech, the background music mood, and which characters enter or leave
the stage. Everything else (who speaks, place, time of day, positions) is already decided.
Reply with records only: no prose, no markdown, no code fences, no blank explanations.
## Input
The chunk JSON has `scene`, `allowed`, `context_before` (earlier lines, read-only context,
do not annotate them) and `lines`. Each line has `id`, `kind`, `speaker`, `speaker_note`,
`text` and `defaults`.
## Output
One JSON file, exactly this shape:
```json
{
"chunk_id": "<copy from input>",
"input_sha256": "<copy from input>",
"annotations": [
{
"id": "<line id>",
"speaker": "<defaults.speaker>",
"kind": "<defaults.kind>",
"emotion": "neutral",
"location": "<defaults.location>",
"time_of_day": "<defaults.time_of_day>",
"on_stage": [{"character": "faust", "position": "left"}],
"music": null
}
]
}
```
SCENE <id> "<heading>" | <location> | <time of day> | sprite cast: <id> (<name>), ... | on stage at start: <ids>
[S<n> <SPEAKER>] a speech (speaker turn) with number n
<NNNN> <verse line> a spoken line; NNNN is its 4-digit line number
(D<NNNN> <text>) a stage direction or cast list; not spoken
```
Rules:
1. Exactly one annotation per input line, in the same order, same `id`s. No extras, no omissions.
2. Copy `speaker`, `kind`, `location`, `time_of_day` verbatim from the line's `defaults`.
3. `emotion`: one of `allowed.emotions`, chosen from the meaning of the verse in its context
(read `context_before` and the neighbouring lines).
4. `on_stage`: the characters present in the scene at that moment, not only the speaker.
Only ids from `allowed.characters`, each at most once per line, `position` one of
`left`, `center`, `right`. Include present characters even if
they are never drawn (the Lord, the Spirit): the renderer filters them. Use `[]` for
lyric text with nobody in the scene (the Dedicatoria).
5. `music`: a mood from `allowed.music` only at a real mood shift (a new scene, a hymn
starting, the Spirit appearing); `null` on every other line. Never repeat the same mood.
6. Output only valid JSON, no comments, no extra keys, no markdown fences in the file.
## Emotions
- `neutral`: plain statement, exposition, stage business, questions of fact.
- `joyful`: warmth, laughter, praise, light banter. Comic exchanges between the Clown and
the Director: joyful or ironic.
- `melancholic`: lyric longing, memory, loss, weariness. The Dedicatoria is melancholic
("Tornáis de nuevo, hermosas imágenes flotantes...").
- `solemn`: sacred, ceremonial, grave. The archangels' hymn and the Lord's words are solemn.
- `ironic`: sarcasm, wit, mockery, cynicism. Mephistopheles' sly remarks are ironic, even
when they sound polite.
- `angry`: rage, scorn, disgust, bitter rebuke.
- `fearful`: terror, dread, shrinking back. Faust before the Earth Spirit ("aterrado") is fearful.
- `ecstatic`: rapture, exaltation, overwhelming vision. Faust at the sign of the Macrocosm.
Faust's despair is melancholic or angry; his ecstasy is ecstatic.
Check `speaker_note` too (for example "aterrado" means fearful). Do not default everything
to `neutral`; do not swing wildly between lines of one continuous thought.
## Staging
- Work out who is in the scene from the cast list (a `cast` line is only a list of who is
there), the stage directions and who has spoken so far (use `context_before`).
- A character who has not yet entered or who has left must not appear in `on_stage`.
- Positions must stay stable within the scene: once a character is `left`, keep them `left`
in every later line. With two characters use `left` and `right`; a third takes `center`.
- Stage directions say who enters, leaves or appears; apply them from the line after.
## Before finishing
Run this and make sure the line for `{{chunk_id}}` says `ok`:
## Output records (one per line)
```
{{status_cmd}} {{chunk_id}}
S <speech> <emotion> REQUIRED once for every speech [S<n> ...] shown (emotion at its start)
L <line> <emotion> optional: the emotion changes from that spoken line on, inside its speech
M <line> <music> music from that line on; the FIRST record must be an M at the first
line shown or the first spoken line (so the chunk starts with music)
E <line> +id -id ... optional: sprite characters entering (+) or leaving (-) at that line
```
If it reports `invalid` or `stale`, fix the file (never edit the input) and run it again.
Finish with one short line saying the chunk is ok.
- Speech and line numbers are plain integers as printed (`S 12`, `L 82`; leading zeros are fine).
- `L`, `M` and `E` may name any line of the input (`M` and `E` also a direction line); `L` needs
a spoken line. At most one `S`, `L` or `M` record per speech or line.
- Use ONLY the emotion and music words listed below. Emotions and music moods are different
lists (there is no "scornful" or "ominous" emotion; "ominous" is a music mood only).
- `E` ids come only from "sprite cast". A sprite character who speaks is placed on stage
automatically at their first line, so `+id` is only useful for a character who enters and
stays silent (it is ignored for anyone who speaks later in this input). `E` is mainly for exits:
`-id` at the line where the character leaves (a direction such as "exits", or the last thing
they say before the text moves on). A `-id` is only valid for a character who is
on stage at that line. Characters marked `*` in "on stage at start" are fixed on stage: never
list them. Leave `E` out when nothing changes (most chunks need few or no `E` records).
- Never invent ids, emotions or moods. Allowed values are listed below.
## Emotions (what the speaker's face and voice convey)
- neutral: plain statement, narration, exposition, calm conversation.
- joyful: delight, laughter, cheerful banter, praise, gratitude.
- melancholic: sorrow, longing, nostalgia, weariness, despair turned inward.
- solemn: reverence, formality, ritual, prayer, deference to authority, grave pronouncements.
- ironic: mockery, sarcasm, wit, playful cynicism, knowing double meanings.
- angry: rage, scorn, contempt, bitter reproach, violent refusal.
- fearful: terror, anxiety, awe mixed with dread, shrinking back.
- ecstatic: rapture, exaltation, wild enthusiasm, visionary excitement.
Do not give a character one emotion for the whole scene. Read each speech: a cynic is not
ironic in every line (deferent and solemn before a superior, angry or scornful when speaking of
others' folly, neutral when just informing). Prefer `L` records inside long speeches whenever
the tone turns (a question after a lament, a vow after doubt, an outburst, a prayer), but do not
add them for tiny shifts. Choose from what the text says, not from the character's reputation.
A chorus or group speaks with one voice: label the mood of the passage.
## Music moods
- contemplative: reflection, study, quiet or intimate scenes, melancholy.
- comic: farce, banter, drinking, popular or satirical episodes.
- sacred: heaven, religion, hymns, reverence.
- ominous: danger, the demonic, dread, pacts, death.
- mystical: magic, apparitions, visions, supernatural wonder.
- none: silence.
Set the mood at the first line, then change it only when the scene's atmosphere really turns
(an apparition, a new place, a shift from comic to grave). A typical chunk has one to four
`M` records. Chunks that continue an earlier part of the scene should keep the mood that
fits the text unless it clearly turns.
## Example
```
M 1 sacred
S 1 solemn
L 7 joyful
E 14 -alice
S 2 neutral
M 20 mystical
E 24 -bob +carl
```
+2 -2
View File
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "vnpipe/annotated.schema.json",
"title": "Annotated play",
"description": "Output of `vnpipe annotate merge`: parsed lines plus one annotation each. The `ann` and line definitions duplicate annotation.schema.json and parsed.schema.json (schema.py has no cross-file registry); tests/test_annotation_schema.py guards against drift.",
"description": "Output of `vnpipe annotate merge`: parsed lines plus one annotation each. The line definition duplicates parsed.schema.json (schema.py has no cross-file registry) and the ann enums mirror annotate.py; tests/test_annotation_schema.py guards against drift.",
"type": "object",
"required": [
"work",
@@ -24,7 +24,7 @@
"items": {
"type": "string"
},
"description": "Chunks filled with deterministic fallback annotations instead of LLM output"
"description": "Chunks filled with deterministic fallback annotations (neutral emotion, no sprite entrances beyond speakers) because they have no valid LLM output"
},
"scenes": {
"type": "array",
-47
View File
@@ -1,47 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "vnpipe/annotation.schema.json",
"title": "Line annotations",
"description": "One annotation per parsed line. Produced by LLM sub-agents per chunk, merged and validated by `vnpipe annotate merge`. Enumerations of cast ids and locations are checked against work.toml at merge time.",
"type": "object",
"required": ["chunk_id", "input_sha256", "annotations"],
"additionalProperties": false,
"properties": {
"chunk_id": {"type": "string"},
"input_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"annotations": {
"type": "array",
"items": {"$ref": "#/$defs/annotation"}
}
},
"$defs": {
"position": {"enum": ["left", "center", "right"]},
"annotation": {
"type": "object",
"required": ["id", "speaker", "kind", "emotion", "location", "time_of_day", "on_stage"],
"additionalProperties": false,
"properties": {
"id": {"type": "string"},
"speaker": {"type": ["string", "null"], "description": "Cast id; 'narrator' for stage directions, the work's lyric voice id for unattributed verse"},
"kind": {"enum": ["dialogue", "narration", "stage_direction"]},
"emotion": {"enum": ["neutral", "joyful", "melancholic", "solemn", "ironic", "angry", "fearful", "ecstatic"]},
"location": {"type": "string"},
"time_of_day": {"enum": ["dawn", "day", "dusk", "night", "timeless"]},
"on_stage": {
"type": "array",
"description": "Characters visible (or present) while this line is shown, with stage position",
"items": {
"type": "object",
"required": ["character", "position"],
"additionalProperties": false,
"properties": {
"character": {"type": "string"},
"position": {"$ref": "#/$defs/position"}
}
}
},
"music": {"enum": ["contemplative", "comic", "sacred", "ominous", "mystical", "none", null], "description": "Optional music mood; null = keep current"}
}
}
}
}
+421 -258
View File
@@ -1,4 +1,5 @@
import json
import sys
from pathlib import Path
import pytest
@@ -24,6 +25,9 @@ id = "two"
location = "yard"
time_of_day = "night"
[staging.one]
cast = { bob = "right" }
[cast.narrator]
name = ""
[cast.voice]
@@ -35,11 +39,40 @@ sprite = true
[cast.bob]
name = "Bob"
sprite = true
[cast.carl]
name = "Carl"
sprite = true
[cast.dora]
name = "Dora"
sprite = true
[cast.god]
name = "God"
sprite = false
"""
# Fake runner: counts calls, then answers from $FAKE_ANSWERS (a JSON file: chunk id ->
# list of answers, one per call) as the claude envelope (or plain text if FAKE_PLAIN is set).
FAKE_RUNNER = r"""
import json, os, re, sys
text = sys.stdin.read()
chunk = re.search(r'^SCENE (\S+)', text).group(1)
part = re.search(r'part (\d+)/', text)
key = chunk + ("_c%02d" % int(part.group(1)) if part else "_c01")
state = os.environ["FAKE_STATE"]
answers = json.load(open(os.environ["FAKE_ANSWERS"]))[key]
open(state, "a").write(key + "\n")
calls = sum(1 for l in open(state) if l.strip() == key)
answer = answers[min(calls - 1, len(answers) - 1)]
if answer is None:
sys.exit(3)
if os.environ.get("FAKE_PLAIN"):
print(answer)
else:
print(json.dumps({"result": answer, "is_error": False, "total_cost_usd": 0.001,
"usage": {"input_tokens": 10, "output_tokens": 5,
"cache_creation_input_tokens": 100, "cache_read_input_tokens": 7}}))
"""
def _line(scene, n, speech, stanza=0, kind="verse", speaker="alice", note=None):
return {
@@ -55,29 +88,27 @@ def _line(scene, n, speech, stanza=0, kind="verse", speaker="alice", note=None):
}
def _scene_lines(scene, speeches):
"""speeches: list of (speaker, line count)."""
lines = []
for si, (speaker, count) in enumerate(speeches):
for _ in range(count):
lines.append(_line(scene, len(lines) + 1, si, speaker=speaker))
return lines
def make_work(tmp_path: Path, parsed_scenes) -> Work:
def make_work(tmp_path: Path, scenes) -> Work:
root = tmp_path / "work"
(root / "data").mkdir(parents=True, exist_ok=True)
(root / "work.toml").write_text(WORK_TOML, encoding="utf-8")
parsed = {"work": "t", "source_sha256": "b" * 64, "scenes": parsed_scenes}
parsed = {"work": "t", "source_sha256": "b" * 64, "scenes": scenes}
(root / "data/parsed.json").write_text(json.dumps(parsed), encoding="utf-8")
return load_work(root)
@pytest.fixture
def work(tmp_path):
one = _scene_lines("one", [("alice", 3), ("bob", 2)])
one.insert(0, _line("one", 0, 0, kind="cast"))
one.insert(2, _line("one", 99, 0, kind="direction"))
# scene one: 0 cast, 1-3 alice (speech 0), 4 direction, 5-6 bob (speech 1),
# 7-8 carl (speech 2), 9 alice (speech 3)
one = [
_line("one", 1, 0, kind="cast"),
*[_line("one", n, 0) for n in (2, 3, 4)],
_line("one", 5, 0, kind="direction"),
*[_line("one", n, 1, speaker="bob") for n in (6, 7)],
*[_line("one", n, 2, speaker="carl") for n in (8, 9)],
_line("one", 10, 3),
]
two = [_line("two", i + 1, 0, speaker=None) for i in range(2)]
scenes = [
{"id": "one", "heading": "ONE", "lines": one},
@@ -91,286 +122,418 @@ def chunks_of(work):
return annotate.build_chunks(work, parsed)
def good_cache(work, chunk, **line_over):
anns = []
for line in chunk["lines"]:
anns.append(
{
"id": line["id"],
**line["defaults"],
"emotion": "joyful",
"on_stage": [{"character": "alice", "position": "left"}],
"music": None,
}
)
doc = {
"chunk_id": chunk["chunk_id"],
"input_sha256": chunk["input_sha256"],
"annotations": anns,
}
return doc
ONE_OK = "M 1 sacred\nS 0 solemn\nL 4 joyful\nS 1 neutral\nS 2 angry\nS 3 ironic\n"
TWO_OK = "M 1 none\nS 0 neutral\n"
def put_cache(work, doc):
path = annotate.cache_dir(work) / f"{doc['chunk_id']}.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(doc), encoding="utf-8")
def runner_env(tmp_path, monkeypatch, answers, plain=False):
script = tmp_path / "fake_runner.py"
script.write_text(FAKE_RUNNER, encoding="utf-8")
ans = tmp_path / "answers.json"
ans.write_text(json.dumps(answers), encoding="utf-8")
state = tmp_path / "calls.txt"
monkeypatch.setenv("FAKE_ANSWERS", str(ans))
monkeypatch.setenv("FAKE_STATE", str(state))
if plain:
monkeypatch.setenv("FAKE_PLAIN", "1")
else:
monkeypatch.delenv("FAKE_PLAIN", raising=False)
return f"{sys.executable} {script}", state
def fill_all(work):
for chunk in chunks_of(work):
put_cache(work, good_cache(work, chunk))
def run_cli(work, *argv):
return main(["--work", str(work.root), "annotate", *argv])
# ---------------------------------------------------------------- chunking
# ---------------------------------------------------------------- chunking and rendering
def test_defaults_and_content(work):
def test_chunks_are_whole_speeches_and_never_cross_scenes(work):
one, two = chunks_of(work)
assert [c["chunk_id"] for c in (one, two)] == ["one_c01", "two_c01"]
by_id = {ln["id"]: ln for ln in one["lines"]}
assert by_id["one_0000"]["defaults"] == {
"speaker": "narrator",
"kind": "stage_direction",
"location": "hall",
"time_of_day": "day",
}
assert by_id["one_0099"]["defaults"]["kind"] == "stage_direction"
assert by_id["one_0001"]["defaults"]["speaker"] == "alice"
assert by_id["one_0001"]["defaults"]["kind"] == "dialogue"
# Unattributed verse -> narration spoken by the lyric voice
assert two["lines"][0]["defaults"] == {
"speaker": "voice",
"kind": "narration",
"location": "yard",
"time_of_day": "night",
}
allowed = one["allowed"]
assert allowed["characters"] == ["alice", "bob", "god"]
assert "narrator" in allowed["speakers"] and "voice" in allowed["speakers"]
assert allowed["locations"] == ["hall", "yard"]
assert "neutral" in allowed["emotions"] and "left" in allowed["positions"]
assert one["context_before"] == []
assert one["prompt_version"] == annotate.prompt_version()
assert (one.id, two.id) == ("one_c01", "two_c01")
assert one.speeches == [0, 1, 2, 3] and two.speeches == [0]
assert (one.first, one.last) == (1, 10)
def test_never_crosses_scenes_and_respects_limit(tmp_path):
scenes = [
{"id": "one", "heading": "ONE", "lines": _scene_lines("one", [("alice", 30)] * 5)},
{"id": "two", "heading": "TWO", "lines": _scene_lines("two", [("bob", 7)])},
def test_long_scene_splits_on_speech_boundaries(tmp_path, monkeypatch):
monkeypatch.setattr(annotate, "MAX_CHUNK_LINES", 4)
lines = [
*[_line("one", n, 0) for n in (1, 2, 3)],
*[_line("one", n, 1, speaker="bob") for n in (4, 5, 6)],
*[_line("one", n, 2) for n in (7, 8)],
]
work = make_work(tmp_path, scenes)
work = make_work(tmp_path, [{"id": "one", "heading": "ONE", "lines": lines}])
chunks = chunks_of(work)
assert [c["chunk_id"] for c in chunks] == ["one_c01", "one_c02", "one_c03", "two_c01"]
for chunk in chunks:
assert len(chunk["lines"]) <= 60
assert {ln["id"].rsplit("_", 1)[0] for ln in chunk["lines"]} == {chunk["scene"]["id"]}
assert [len(c["lines"]) for c in chunks] == [60, 60, 30, 7]
assert [[annotate.line_no(ln["id"]) for ln in c.lines] for c in chunks] == [
[1, 2, 3],
[4, 5, 6],
[7, 8],
]
assert [c.id for c in chunks] == ["one_c01", "one_c02", "one_c03"]
assert "part 2/3" in chunks[1].text
# later chunks list the sprite speakers seen so far plus the pinned cast
assert "on stage at start: bob*, alice" in chunks[2].text
def test_splits_at_speech_boundaries(tmp_path):
speeches = [("alice", 25), ("bob", 25), ("alice", 25), ("bob", 10)]
work = make_work(
tmp_path, [{"id": "one", "heading": "O", "lines": _scene_lines("one", speeches)}]
)
chunks = chunks_of(work)
assert [len(c["lines"]) for c in chunks] == [50, 35]
assert chunks[1]["lines"][0]["id"] == "one_0051"
assert len(chunks[1]["context_before"]) == 6
assert chunks[1]["context_before"][-1]["id"] == "one_0050"
def test_oversized_speech_splits_at_stanza_then_hard(tmp_path):
lines = [_line("one", i + 1, 0, stanza=i // 50) for i in range(100)] # two stanzas of 50
work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}])
assert [len(c["lines"]) for c in chunks_of(work)] == [50, 50]
lines = [_line("one", i + 1, 0, stanza=0) for i in range(130)]
work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}])
assert [len(c["lines"]) for c in chunks_of(work)] == [60, 60, 10]
def test_hash_deterministic_and_content_sensitive(work, tmp_path):
first = [c["input_sha256"] for c in chunks_of(work)]
assert first == [c["input_sha256"] for c in chunks_of(work)]
parsed, _ = annotate.load_parsed(work)
parsed["scenes"][0]["lines"][1]["text"] = "changed"
changed = annotate.build_chunks(work, parsed)
assert changed[0]["input_sha256"] != first[0]
assert changed[1]["input_sha256"] == first[1]
def test_prompt_change_invalidates_hash(work, monkeypatch, tmp_path):
before = chunks_of(work)[0]["input_sha256"]
fake = tmp_path / "prompt.md"
fake.write_text("different prompt", encoding="utf-8")
monkeypatch.setattr(annotate, "PROMPT_PATH", fake)
assert chunks_of(work)[0]["input_sha256"] != before
def test_chunk_command_writes_and_removes_stale(work, capsys):
assert main(["--work", str(work.root), "annotate", "chunk"]) == 0
out = annotate.chunks_dir(work)
assert sorted(p.name for p in out.glob("*.json")) == ["one_c01.json", "two_c01.json"]
(out / "gone_c09.json").write_text("{}", encoding="utf-8")
snapshot = (out / "one_c01.json").read_bytes()
main(["--work", str(work.root), "annotate", "chunk"])
assert not (out / "gone_c09.json").exists()
assert (out / "one_c01.json").read_bytes() == snapshot
assert json.loads(snapshot)["chunk_id"] == "one_c01"
assert "removed stale gone_c09.json" in capsys.readouterr().out
def test_unconfigured_scene_or_speaker_fails(tmp_path):
scenes = [{"id": "zzz", "heading": "Z", "lines": [_line("zzz", 1, 0)]}]
with pytest.raises(annotate.AnnotateError):
chunks_of(make_work(tmp_path, scenes))
scenes = [{"id": "one", "heading": "O", "lines": [_line("one", 1, 0, speaker="ghost")]}]
with pytest.raises(annotate.AnnotateError):
chunks_of(make_work(tmp_path / "b", scenes))
# ---------------------------------------------------------------- status / merge
def test_status_states(work, capsys):
def test_render_format(work):
one, two = chunks_of(work)
assert annotate.check_cache(work, one)[0] == "missing"
put_cache(work, good_cache(work, one))
assert annotate.check_cache(work, one) == ("ok", [])
bad = good_cache(work, two)
bad["input_sha256"] = "c" * 64
put_cache(work, bad)
assert annotate.check_cache(work, two)[0] == "stale"
(annotate.cache_dir(work) / "two_c01.json").write_text("{nope", encoding="utf-8")
assert annotate.check_cache(work, two)[0] == "invalid"
assert main(["--work", str(work.root), "annotate", "status"]) == 0
lines = one.text.splitlines()
assert lines[0] == (
'SCENE one "ONE" | hall | day | sprite cast: bob (Bob), alice (Alice), carl (Carl)'
" | on stage at start: bob*"
)
assert "(D0001 text one 1)" in lines # cast list is shown as a direction
assert lines[2:5] == ["[S0 ALICE]", "0002 text one 2", "0003 text one 3"]
assert "(D0005 text one 5)" in lines
assert "[S1 BOB]" in lines
# unattributed verse: header without a name; no sprite cast
assert two.text.splitlines()[0].endswith("sprite cast: - | on stage at start: -")
assert "[S0]" in two.text
def test_input_hash_covers_text_and_prompt(work, monkeypatch):
before = chunks_of(work)[0].input_sha
assert chunks_of(work)[0].input_sha == before
monkeypatch.setattr(annotate, "prompt_version", lambda: "other")
assert chunks_of(work)[0].input_sha != before
def test_prompt_lists_the_vocabularies():
text = annotate.PROMPT_PATH.read_text(encoding="utf-8")
for word in (*annotate.EMOTIONS, *annotate.MUSIC):
assert f"- {word}:" in text
def test_prompt_command_prints_instructions_and_input(work, capsys):
assert run_cli(work, "prompt", "one_c01") == 0
out = capsys.readouterr().out
assert "one_c01: ok" in out and "two_c01: invalid" in out
assert "summary: 2 chunks: 1 ok, 0 missing, 0 stale, 1 invalid" in out
assert "Output records" in out and "[S0 ALICE]" in out
with pytest.raises(SystemExit):
run_cli(work, "prompt", "nope")
def merge_main(work, *extra):
return main(["--work", str(work.root), "annotate", "merge", *extra])
# ---------------------------------------------------------------- parsing and validation
def test_merge_ok_and_idempotent(work, capsys):
fill_all(work)
assert merge_main(work) == 0
out = work.path("data/annotated.json")
first = out.read_bytes()
assert merge_main(work) == 0
assert out.read_bytes() == first
doc = json.loads(first)
assert doc["fallback_chunks"] == []
assert doc["parsed_sha256"] and doc["work"] == "t"
line = doc["scenes"][0]["lines"][0]
assert line["id"] == "one_0000" and line["text"] and line["ann"]["emotion"] == "joyful"
assert "id" not in line["ann"] and line["ann"]["music"] is None
assert first.endswith(b"\n")
def parse(work, text, idx=0):
return annotate.parse_records(text, chunks_of(work)[idx])
def break_cache(work, mutate):
chunk = chunks_of(work)[0]
doc = good_cache(work, chunk)
mutate(doc)
path = annotate.cache_dir(work) / "one_c01.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(doc), encoding="utf-8")
def test_parse_valid_records(work):
rec = parse(work, ONE_OK + "E 6 -alice\n\n")
assert rec.speech == {0: "solemn", 1: "neutral", 2: "angry", 3: "ironic"}
assert rec.change == {4: "joyful"}
assert rec.music == {1: "sacred"}
assert rec.events == {6: [("-", "alice")]}
@pytest.mark.parametrize(
("mutate", "expect"),
("text", "message"),
[
(lambda d: d.update(input_sha256="d" * 64), "stale"),
(lambda d: d["annotations"].pop(), "missing lines"),
(lambda d: d["annotations"].reverse(), "not in chunk order"),
(lambda d: d["annotations"][1].update(kind="narration"), "kind is 'narration'"),
(lambda d: d["annotations"][1].update(speaker="bob"), "speaker is 'bob'"),
(lambda d: d["annotations"][1].update(location="yard"), "location is 'yard'"),
(lambda d: d["annotations"][1].update(time_of_day="dawn"), "time_of_day is 'dawn'"),
(
lambda d: d["annotations"][1].update(
on_stage=[{"character": "zed", "position": "left"}]
),
"unknown character 'zed'",
),
(
lambda d: d["annotations"][1].update(
on_stage=[
{"character": "bob", "position": "left"},
{"character": "bob", "position": "right"},
]
),
"more than once",
),
(
lambda d: d["annotations"][1].update(
on_stage=[{"character": "narrator", "position": "left"}]
),
"unknown character 'narrator'",
),
(lambda d: d["annotations"][1].update(emotion="happy"), "schema"),
(lambda d: d.update(chunk_id="two_c01"), "chunk_id"),
(ONE_OK.replace("S 0 solemn", "S 0 happy"), "unknown emotion 'happy'"),
(ONE_OK.replace("sacred", "loud"), "unknown music mood 'loud'"),
(ONE_OK + "E 6 +zed\n", "unknown sprite id '\\+zed'"),
(ONE_OK + "E 6 -carl\n", "carl is not on stage at that line"),
(ONE_OK + "E 3 -bob\n", "bob is fixed on stage"),
(ONE_OK + "E 6 +god\n", "unknown sprite id '\\+god'"), # no sprite
(ONE_OK + "E 6 alice\n", "bad or unknown sprite id 'alice'"),
(ONE_OK.replace("S 3 ironic\n", ""), "missing S record for speech 3"),
(ONE_OK + "S 9 neutral\n", "unknown speech 9"),
(ONE_OK + "S 0 neutral\n", "duplicate S record for speech 0"),
(ONE_OK + "L 99 joyful\n", "line outside the chunk"),
(ONE_OK + "L 5 joyful\n", "L needs a spoken line"), # direction line
(ONE_OK + "M 99 comic\n", "line outside the chunk"),
(ONE_OK + "hello\n", "unrecognised record"),
(ONE_OK + "S 1\n", "unrecognised record"),
("S 0 solemn\n" + ONE_OK, "first record must be an M"),
(ONE_OK.replace("M 1 sacred", "M 6 sacred"), "first record must be an M"),
("", "empty output"),
],
)
def test_merge_rejects_bad_cache(work, capsys, mutate, expect):
two = chunks_of(work)[1]
put_cache(work, good_cache(work, two))
break_cache(work, mutate)
assert merge_main(work) == 1
err = capsys.readouterr().err
assert "one_c01" in err and expect in err
assert not work.path("data/annotated.json").exists()
def test_parse_errors(work, text, message):
with pytest.raises(annotate.ParseError, match=message):
parse(work, text)
def test_merge_without_cache_lists_all_problems(work, capsys):
assert merge_main(work) == 1
err = capsys.readouterr().err
assert "one_c01: missing" in err and "two_c01: missing" in err
def test_redundant_entrances_are_dropped_and_event_lines_merge(work):
rec = parse(work, ONE_OK + "E 6 +alice\nE 6 -alice\n")
assert rec.events == {6: [("-", "alice")]} # +alice is redundant: she speaks again at 10
def test_merge_fallback(work, capsys):
put_cache(work, good_cache(work, chunks_of(work)[1]))
assert merge_main(work, "--fallback") == 0
captured = capsys.readouterr()
assert "warning: one_c01: missing" in captured.err
doc = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8"))
assert doc["fallback_chunks"] == ["one_c01"]
lines = {ln["id"]: ln["ann"] for s in doc["scenes"] for ln in s["lines"]}
# cast/direction line before anyone spoke: nobody on stage
assert lines["one_0000"]["on_stage"] == []
assert lines["one_0000"]["emotion"] == "neutral" and lines["one_0000"]["music"] is None
# alice speaks first -> left; bob joins -> right, alice stays
assert lines["one_0001"]["on_stage"] == [{"character": "alice", "position": "left"}]
assert lines["one_0005"]["on_stage"] == [
{"character": "alice", "position": "left"},
def test_first_music_may_sit_on_the_first_spoken_line(work):
assert parse(work, ONE_OK.replace("M 1 sacred", "M 2 sacred")).music == {2: "sacred"}
def test_parse_reports_every_problem(work):
with pytest.raises(annotate.ParseError) as err:
parse(work, ONE_OK.replace("solemn", "x").replace("neutral", "y"))
assert str(err.value).count("unknown emotion") == 2
# ---------------------------------------------------------------- expansion
def expand(work, rec_text_by_chunk):
"""Expand scene one/two like merge does; returns per-line annotations by id."""
out, music, stages = {}, None, {}
for chunk in chunks_of(work):
text = rec_text_by_chunk.get(chunk.id)
rec = annotate.parse_records(text, chunk) if text else None
stage = stages.setdefault(
chunk.scene_id, annotate.Stage(annotate.pinned_cast(work, chunk.scene_id))
)
items, music = annotate.expand_chunk(work, chunk, rec, stage, music)
out.update({ln["id"]: it for ln, it in zip(chunk.lines, items, strict=True)})
return out
def test_expansion_emotions_and_defaults(work):
ann = expand(work, {"one_c01": ONE_OK})
assert ann["one_0001"]["kind"] == "stage_direction" and ann["one_0001"]["speaker"] == "narrator"
assert ann["one_0002"]["emotion"] == "solemn" and ann["one_0003"]["emotion"] == "solemn"
assert ann["one_0004"]["emotion"] == "joyful" # L applies from that line on
assert ann["one_0005"]["emotion"] == "neutral" # directions are neutral
assert ann["one_0006"]["emotion"] == "neutral"
assert ann["one_0008"]["emotion"] == "angry"
assert ann["one_0010"]["emotion"] == "ironic" # new speech restarts at its S emotion
assert ann["one_0002"]["location"] == "hall" and ann["one_0002"]["time_of_day"] == "day"
assert ann["one_0002"]["kind"] == "dialogue" and ann["one_0002"]["speaker"] == "alice"
def test_first_music_covers_the_lead_in(work):
ann = expand(work, {"one_c01": ONE_OK.replace("M 1 sacred", "M 2 sacred")})
assert ann["one_0001"]["music"] == "sacred"
ann = expand(work, {"one_c01": ONE_OK.replace("M 1 sacred", "M 2 comic")})
assert ann["one_0001"]["music"] == "comic" # not a mood carried over from elsewhere
def test_expansion_unattributed_verse_uses_lyric_voice(work):
ann = expand(work, {})
assert ann["two_0001"]["speaker"] == "voice" and ann["two_0001"]["kind"] == "narration"
assert ann["two_0001"]["on_stage"] == [] # voice has no sprite
def test_expansion_auto_enter_and_positions(work):
ann = expand(work, {"one_c01": ONE_OK})
# bob is pinned right from the start; alice speaks first and takes the first free slot
assert ann["one_0001"]["on_stage"] == [{"character": "bob", "position": "right"}]
assert ann["one_0002"]["on_stage"] == [
{"character": "bob", "position": "right"},
{"character": "alice", "position": "left"},
]
# the ok chunk is kept as annotated by the LLM
assert lines["two_0001"]["emotion"] == "joyful"
assert [s["character"] for s in ann["one_0008"]["on_stage"]] == ["bob", "alice", "carl"]
assert ann["one_0008"]["on_stage"][2]["position"] == "center"
def test_expansion_exit_and_stable_position(work):
text = ONE_OK + "E 6 -alice\n"
ann = expand(work, {"one_c01": text})
assert [s["character"] for s in ann["one_0005"]["on_stage"]] == ["bob", "alice"]
assert [s["character"] for s in ann["one_0006"]["on_stage"]] == ["bob"]
# alice speaks again at line 10 and re-enters at her original position
last = {s["character"]: s["position"] for s in ann["one_0010"]["on_stage"]}
assert last["alice"] == "left" and last["bob"] == "right"
assert last["carl"] == "center"
def test_pinned_character_cannot_be_removed(work):
chunk = chunks_of(work)[0]
rec = annotate.parse_records(ONE_OK, chunk)
rec.events[3] = [("-", "bob")]
items, _ = annotate.expand_chunk(work, chunk, rec, annotate.Stage({"bob": "right"}), None)
assert "bob" in [s["character"] for s in items[2]["on_stage"]]
def test_expansion_music_carries_forward_across_chunks_and_scenes(work):
ann = expand(work, {"one_c01": ONE_OK + "M 8 mystical\n"})
assert ann["one_0001"]["music"] == "sacred"
assert ann["one_0007"]["music"] == "sacred" and ann["one_0008"]["music"] == "mystical"
assert ann["two_0001"]["music"] == "mystical" # no records for scene two: carried over
ann = expand(work, {"one_c01": ONE_OK, "two_c01": TWO_OK})
assert ann["two_0001"]["music"] == "none"
def test_stage_carries_across_chunks(tmp_path, monkeypatch):
monkeypatch.setattr(annotate, "MAX_CHUNK_LINES", 3)
lines = [
*[_line("one", n, 0) for n in (1, 2, 3)],
*[_line("one", n, 1, speaker="carl") for n in (4, 5, 6)],
*[_line("one", n, 2, speaker="bob") for n in (7, 8, 9)],
]
work = make_work(tmp_path, [{"id": "one", "heading": "ONE", "lines": lines}])
ann = expand(
work,
{
"one_c01": "M 1 comic\nS 0 neutral\n",
"one_c02": "M 4 comic\nS 1 neutral\nE 5 -alice\n",
"one_c03": "M 7 comic\nS 2 neutral\n",
},
)
assert [s["character"] for s in ann["one_0009"]["on_stage"]] == ["bob", "carl"]
# ---------------------------------------------------------------- runner, retry, cache
def test_run_caches_logs_usage_and_skips_cached(work, tmp_path, monkeypatch, capsys):
runner, state = runner_env(tmp_path, monkeypatch, {"one_c01": [ONE_OK], "two_c01": [TWO_OK]})
assert run_cli(work, "run", "--runner", runner, "--jobs", "2") == 0
cache = annotate.cache_dir(work)
body = (cache / "one_c01.txt").read_text(encoding="utf-8")
assert body.startswith("# input=") and "model=haiku" in body and "S 0 solemn" in body
rows = annotate.usage_rows(work)
assert sorted(r["chunk"] for r in rows) == ["one_c01", "two_c01"]
assert rows[0]["input_tokens"] == 10 and rows[0]["cache_creation_tokens"] == 100
assert rows[0]["cost_usd"] == 0.001 and rows[0]["model"] == "haiku" and "seconds" in rows[0]
assert len(state.read_text().split()) == 2
# second run: everything cached, runner not called again
capsys.readouterr()
assert run_cli(work, "run", "--runner", runner) == 0
assert "2 cached" in capsys.readouterr().out
assert len(state.read_text().split()) == 2
assert run_cli(work, "status") == 0
assert "2 done, 0 pending, 0 failed" in capsys.readouterr().out
def test_run_accepts_plain_text_and_filters_with_only(work, tmp_path, monkeypatch, capsys):
runner, state = runner_env(tmp_path, monkeypatch, {"one_c01": [ONE_OK]}, plain=True)
assert run_cli(work, "run", "--runner", runner, "--only", "one_*") == 0
assert state.read_text().split() == ["one_c01"]
assert annotate.usage_rows(work)[0]["input_tokens"] == 0
capsys.readouterr()
run_cli(work, "status")
assert "1 done, 1 pending, 0 failed" in capsys.readouterr().out
def test_other_model_reruns_and_prompt_change_makes_stale(work, tmp_path, monkeypatch, capsys):
runner, state = runner_env(tmp_path, monkeypatch, {"one_c01": [ONE_OK, ONE_OK]})
run_cli(work, "run", "--runner", runner, "--only", "one_c01")
run_cli(work, "run", "--runner", runner, "--only", "one_c01", "--model", "sonnet")
assert len(state.read_text().split()) == 2
assert "model=sonnet" in (annotate.cache_dir(work) / "one_c01.txt").read_text()
monkeypatch.setattr(annotate, "prompt_version", lambda: "changed")
capsys.readouterr()
run_cli(work, "status")
out = capsys.readouterr().out
assert "one_c01: stale" in out and "0 done, 2 pending" in out
def test_retry_appends_error_then_succeeds(work, tmp_path, monkeypatch):
bad = ONE_OK.replace("S 3 ironic\n", "")
runner, state = runner_env(tmp_path, monkeypatch, {"one_c01": [bad, ONE_OK]})
ok, _ = annotate.annotate_chunk(work, chunks_of(work)[0], runner, "haiku")
assert ok and len(state.read_text().split()) == 2
assert [r["attempt"] for r in annotate.usage_rows(work)] == [1, 2]
assert "S 3 ironic" in (annotate.cache_dir(work) / "one_c01.txt").read_text()
def test_retry_prompt_contains_the_error(work, monkeypatch):
seen = []
def fake(template, model, text):
seen.append(text)
return annotate.Reply("M 1 comic" if len(seen) == 1 else ONE_OK, {}, 0.0, 0.1)
monkeypatch.setattr(annotate, "run_command", fake)
ok, _ = annotate.annotate_chunk(work, chunks_of(work)[0], "x", "haiku")
assert ok
assert seen[1].startswith(chunks_of(work)[0].text)
assert "missing S record for speech 0" in seen[1] and "M 1 comic" in seen[1]
def test_failed_chunk_does_not_stop_others(work, tmp_path, monkeypatch, capsys):
runner, _ = runner_env(
tmp_path, monkeypatch, {"one_c01": ["garbage", "still garbage"], "two_c01": [TWO_OK]}
)
assert run_cli(work, "run", "--runner", runner) == 1
cache = annotate.cache_dir(work)
assert not (cache / "one_c01.txt").exists() and (cache / "one_c01.failed").exists()
assert (cache / "two_c01.txt").exists()
capsys.readouterr()
run_cli(work, "status")
out = capsys.readouterr().out
assert "one_c01: failed" in out and "1 done, 0 pending, 1 failed" in out
# a later run retries the failed chunk only
runner, state = runner_env(tmp_path, monkeypatch, {"one_c01": [ONE_OK]})
assert run_cli(work, "run", "--runner", runner) == 0
assert state.read_text().split().count("two_c01") == 1 # not asked again
assert not (cache / "one_c01.failed").exists()
def test_runner_crash_is_a_failure(work, tmp_path, monkeypatch):
runner, _ = runner_env(tmp_path, monkeypatch, {"one_c01": [None], "two_c01": [TWO_OK]})
assert run_cli(work, "run", "--runner", runner) == 1
assert (annotate.cache_dir(work) / "two_c01.txt").exists()
def test_envelope_error_is_runner_error(monkeypatch):
class Proc:
returncode = 0
stdout = json.dumps({"result": "boom", "is_error": True})
stderr = ""
monkeypatch.setattr(annotate.subprocess, "run", lambda *a, **k: Proc())
with pytest.raises(annotate.RunnerError, match="boom"):
annotate.run_command("cmd", "haiku", "x")
def test_default_runner_command_substitution(monkeypatch):
seen = {}
class Proc:
returncode = 0
stdout = "M 1 comic"
stderr = ""
def fake(args, **kwargs):
seen["args"], seen["input"] = args, kwargs["input"]
return Proc()
monkeypatch.setattr(annotate.subprocess, "run", fake)
annotate.run_command(annotate.DEFAULT_RUNNER, "haiku", "hello")
args = seen["args"]
assert (
args[:3] == ["env", "MAX_THINKING_TOKENS=0", "claude"]
and args[3] == "-p"
and args[args.index("--model") + 1] == "haiku"
)
assert args[args.index("--tools") + 1] == ""
assert args[args.index("--system-prompt-file") + 1] == str(annotate.PROMPT_PATH)
assert seen["input"] == "hello"
# ---------------------------------------------------------------- merge
def test_merge_partial_uses_fallback_and_reports(work, tmp_path, monkeypatch, capsys):
runner, _ = runner_env(tmp_path, monkeypatch, {"one_c01": [ONE_OK]})
run_cli(work, "run", "--runner", runner, "--only", "one_c01")
assert run_cli(work, "merge", "--strict") == 1
assert not work.path("data/annotated.json").exists()
capsys.readouterr()
assert run_cli(work, "merge") == 0
cap = capsys.readouterr()
assert "scene two: NOT annotated" in cap.err and "scene one" not in cap.err
doc = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8"))
assert doc["fallback_chunks"] == ["two_c01"]
first = doc["scenes"][0]["lines"][1]
assert first["ann"]["emotion"] == "solemn" and first["id"] == "one_0002"
assert list(first["ann"]) == list(annotate.ANN_ORDER)
assert doc["scenes"][1]["lines"][0]["ann"]["emotion"] == "neutral"
def test_merge_is_deterministic(work, tmp_path, monkeypatch):
runner, _ = runner_env(tmp_path, monkeypatch, {"one_c01": [ONE_OK], "two_c01": [TWO_OK]})
run_cli(work, "run", "--runner", runner)
assert run_cli(work, "merge", "--strict") == 0
first = work.path("data/annotated.json").read_bytes()
merge_main(work, "--fallback")
run_cli(work, "merge", "--strict")
assert work.path("data/annotated.json").read_bytes() == first
assert json.loads(first)["fallback_chunks"] == []
def test_fallback_skips_characters_without_sprite(tmp_path):
lines = [_line("one", 1, 0, speaker="god"), _line("one", 2, 1, speaker="alice")]
work = make_work(tmp_path, [{"id": "one", "heading": "O", "lines": lines}])
result = annotate.merge(work, fallback=True)
anns = [ln["ann"] for ln in result.document["scenes"][0]["lines"]]
assert anns[0]["on_stage"] == []
assert anns[1]["on_stage"] == [{"character": "alice", "position": "left"}]
# ---------------------------------------------------------------- prompt
def test_prompt_fills_placeholders(work):
text = annotate.render_prompt(work, "one_c01")
assert "{{" not in text
root = work.root.resolve()
assert str(root / "annotations/chunks/one_c01.json") in text
assert str(root / "annotations/cache/one_c01.json") in text
assert "annotate status one_c01" in text
with pytest.raises(SystemExit):
annotate.render_prompt(work, "nope_c01")
def test_unconfigured_scene_is_an_error(work):
parsed, _ = annotate.load_parsed(work)
parsed["scenes"][0]["id"] = "zzz"
with pytest.raises(annotate.AnnotateError):
annotate.build_chunks(work, parsed)
+22 -66
View File
@@ -3,7 +3,7 @@ import json
import pytest
from vnpipe import SCHEMA_DIR
from vnpipe import SCHEMA_DIR, annotate
from vnpipe.schema import SchemaError, validate
SHA = "a" * 64
@@ -24,69 +24,10 @@ def _ann(**over):
return ann
def _cache(**over):
doc = {"chunk_id": "s_c01", "input_sha256": SHA, "annotations": [_ann()]}
doc.update(over)
return doc
def _load(name):
return json.loads((SCHEMA_DIR / f"{name}.schema.json").read_text(encoding="utf-8"))
def test_valid_annotation_cache():
validate(_cache(), "annotation")
def test_music_is_optional():
ann = _ann()
del ann["music"]
validate(_cache(annotations=[ann]), "annotation")
@pytest.mark.parametrize("key", ["chunk_id", "input_sha256", "annotations"])
def test_cache_required_fields(key):
doc = _cache()
del doc[key]
with pytest.raises(SchemaError):
validate(doc, "annotation")
@pytest.mark.parametrize(
"key", ["id", "speaker", "kind", "emotion", "location", "time_of_day", "on_stage"]
)
def test_annotation_required_fields(key):
ann = _ann()
del ann[key]
with pytest.raises(SchemaError):
validate(_cache(annotations=[ann]), "annotation")
@pytest.mark.parametrize(
"over",
[
{"emotion": "happy"},
{"kind": "verse"},
{"time_of_day": "noon"},
{"music": "loud"},
{"extra": 1},
{"on_stage": [{"character": "faust", "position": "top"}]},
{"on_stage": [{"character": "faust"}]},
{"on_stage": [{"character": "faust", "position": "left", "scale": 2}]},
],
)
def test_annotation_bad_values(over):
with pytest.raises(SchemaError):
validate(_cache(annotations=[_ann(**over)]), "annotation")
def test_cache_rejects_extra_field_and_bad_hash():
with pytest.raises(SchemaError):
validate(_cache(extra=1), "annotation")
with pytest.raises(SchemaError):
validate(_cache(input_sha256="xyz"), "annotation")
def _annotated():
ann = _ann()
del ann["id"]
@@ -136,15 +77,30 @@ def test_annotated_rejects_problems():
def test_annotated_definitions_match_source_schemas():
"""annotated.schema.json duplicates definitions from the other schemas; keep them in sync."""
annotated = _load("annotated")["$defs"]
source = _load("annotation")["$defs"]
expected = copy.deepcopy(source["annotation"])
expected["required"].remove("id")
del expected["properties"]["id"]
assert annotated["ann"] == expected
assert annotated["position"] == source["position"]
assert annotated["ann"]["properties"]["emotion"]["enum"] == list(annotate.EMOTIONS)
assert annotated["ann"]["properties"]["music"]["enum"] == [*annotate.MUSIC, None]
assert annotated["position"]["enum"] == list(annotate.POSITIONS)
parsed_line = _load("parsed")["properties"]["scenes"]["items"]["properties"]["lines"]["items"]
line = copy.deepcopy(annotated["line"])
assert line["required"] == [*parsed_line["required"], "ann"]
del line["properties"]["ann"]
assert line["properties"] == parsed_line["properties"]
@pytest.mark.parametrize(
"over",
[
{"kind": "verse"},
{"time_of_day": "noon"},
{"music": "loud"},
{"extra": 1},
{"on_stage": [{"character": "faust", "position": "top"}]},
{"on_stage": [{"character": "faust"}]},
],
)
def test_annotated_bad_ann_values(over):
doc = _annotated()
doc["scenes"][0]["lines"][0]["ann"].update(over)
with pytest.raises(SchemaError):
validate(doc, "annotated")