diff --git a/CHANGELOG.md b/CHANGELOG.md
index 361e146..97fedd3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,8 +11,26 @@ belong to (see the [specification](docs/spec/content-pack.md#16-versioning-of-th
First release in preparation: v0.1 "Playable".
+### Changed
+
+- Narrative pacing ([ADR 0012](docs/adr/0012-narrative-pacing.md)): packs may
+ declare `pacing` (`narrative`, `balanced`, `puzzle`). The play time budget
+ splits the target by reading share, `lexvm check` reports the reading share
+ and warns (`playtime.pacing`) when a declared pacing is missed, and
+ narrative packs get longer text budgets. The attempt rate of the play time
+ model is recalibrated from 0.5 to 1 per command (from playtest logs).
+- `lexvm generate` and the prompt kit: a `story` stage before the puzzles and
+ an editorial `review` round on the walkthrough transcript; `--pacing`,
+ `--no-review`. The authoring guide gains a section "Story and scenes".
+- *Die letzte Nacht der Reichsmark* 1.1.0: rewritten scene by scene with
+ unchanged mechanics, in plainer language (fewer harbour terms), pacing
+ `narrative`, about 65 minutes.
+- *The Locked Study*: target play time 7 minutes (the recalibrated estimate).
+
### Added
+- `lexvm transcript`: the walkthrough as a reader sees it, as Markdown.
+
- Content pack format `lexvm-pack/1`: normative
[specification](docs/spec/content-pack.md), zod schema as the single source
of truth, generated JSON Schema for editors and LLM tooling.
diff --git a/README.md b/README.md
index d88d137..cc003dd 100644
--- a/README.md
+++ b/README.md
@@ -34,8 +34,8 @@ way, type commands in German or English.
| | Adventure | Language | Length | |
|---|---|---|---|---|
-| đ”ïž | **Die letzte Nacht der Reichsmark**
*Ein Hamburger Kriminalfall, Juni 1948.* The night before the currency reform, a dock worker vanishes, accused of stealing cigarettes. Clues, interrogations and a city full of hoarded goods. | đ©đȘ Deutsch | ~45 min | Noir |
-| đ | **The Locked Study**
*A five-minute LexVM demo.* Your uncle has vanished and his study is locked. | đŹđ§ English | ~5 min | Demo |
+| đ”ïž | **Die letzte Nacht der Reichsmark**
*Ein Hamburger Kriminalfall, Juni 1948.* The night before the currency reform, a dock worker vanishes, accused of stealing cigarettes. Clues, interrogations and a city full of hoarded goods. | đ©đȘ Deutsch | ~65 min | Noir |
+| đ | **The Locked Study**
*A short LexVM demo.* Your uncle has vanished and his study is locked. | đŹđ§ English | ~7 min | Demo |
Want more? [Write your own](#-create-your-own-adventure) or
[propose one](https://github.com/nullthrone/lexvm/issues/new?template=content_pack_proposal.yml).
diff --git a/apps/web/e2e/play.spec.ts b/apps/web/e2e/play.spec.ts
index ad298aa..67647cd 100644
--- a/apps/web/e2e/play.spec.ts
+++ b/apps/web/e2e/play.spec.ts
@@ -150,7 +150,7 @@ test("plays the demo with typed commands", async ({ page }) => {
});
test("the menu offers waiting", async ({ page }) => {
- await expect(packCard(page)).toContainText("about 5 min");
+ await expect(packCard(page)).toContainText("about 7 min");
await startNewGame(page);
await page.getByRole("button", { name: "Menu" }).tap();
await sheet(page).getByRole("button", { name: "Wait" }).tap();
diff --git a/docs/adr/0012-narrative-pacing.md b/docs/adr/0012-narrative-pacing.md
new file mode 100644
index 0000000..b3a059d
--- /dev/null
+++ b/docs/adr/0012-narrative-pacing.md
@@ -0,0 +1,93 @@
+# 0012. Narrative pacing: calibrate play time by reading share, write story before data
+
+- Status: Accepted
+- Date: 2026-10-24
+
+## Context
+
+The first German pack, *Die letzte Nacht der Reichsmark*, passed every check
+and its puzzles played well, but a review found the story hard to follow:
+telegram-style sentences, scenes without arrivals or transitions, characters
+reduced to the facts a puzzle needs. The story existed, but in the design
+documents (about 20,000 words) rather than in the game text (about 6,000).
+
+The causes were in the toolchain, not in the model that wrote the text:
+
+1. **The play time budget priced reading as a cost.** `budgetForMinutes`
+ assumed 20 words of new text per walkthrough command and charged about 18
+ seconds of tapping per command against about 8 seconds of reading. A
+ 45-minute German pack was budgeted at 2,700â3,400 words in total, and the
+ guide told authors to grow a game through puzzles, "not longer
+ descriptions". Every added sentence moved a pack towards
+ `playtime.too-long`, and the repair loop cut text first.
+2. **The interaction rate was too low.** The model assumed 0.5 unproductive
+ attempts per productive command. The pack's playtest logs (180 and 226
+ commands for a 74-step walkthrough) imply about 0.9 to 1.8 after optional
+ looks and dialogue options are taken out. So the model underestimated
+ interaction time and overstated how much text a target allowed; the pack
+ had text cut to meet a target it already exceeded.
+3. **Style rules and prompts asked for brevity.** "6â14 words per sentence",
+ "rule messages 1â2 sentences", text budgets with "aim well below", and a
+ pipeline whose only prose-producing stages write YAML fields one at a
+ time. No stage wrote the story as scenes, and no check ever read the game
+ the way a player does.
+4. **No signal for narrative quality.** Verification gives precise feedback on
+ length and logic; nothing gave feedback on whether the text could be
+ followed, so every revision optimised what was measured.
+
+## Decision
+
+1. **Packs declare a `pacing`.** `narrative` (about 60% of the expected time
+ is reading), `balanced` (45%, the default for sizing) or `puzzle` (30%).
+ `budgetForMinutes` splits the target minutes by that share: interaction
+ sizes the walkthrough, reading sizes the text. `lexvm check` reports the
+ reading share of every pack and warns (`playtime.pacing`) when a declared
+ pacing is missed by more than 10 points. The warning for a narrative pack
+ that is too short suggests scene prose before more puzzles.
+2. **The attempt rate is recalibrated** from 0.5 to 1, the cautious end of the
+ playtest range. The reference demo's target moves from 5 to 7 minutes.
+3. **Narrative packs get longer text budgets** (room 1000, object 600,
+ dialogue line 600 characters); option texts and names keep their limits.
+4. **Story before data.** `lexvm generate` and the prompt kit get a `story`
+ stage between concept and puzzles: the truth with motives, a scene plan
+ (arrival, turn, way out), a revelation map and the key scenes in prose.
+ Later stages derive their texts from it. The guide gets a section "Story
+ and scenes" with rules for arrivals, transitions, the player character's
+ inner voice and sentence rhythm.
+5. **Read what the player reads.** `lexvm transcript` renders the walkthrough
+ as Markdown. A `review` stage gives the transcript and the story to the
+ model as an editor with a rubric (can it be followed, transitions, what a
+ clue means, turning points, characters, rhythm). `lexvm generate` runs one
+ review round once a pack passes; the result is verified like any repair,
+ and the last passing version is restored if it breaks.
+6. The noir pack is rewritten under these rules with its mechanics unchanged
+ (pacing `narrative`, playtime 65).
+
+## Consequences
+
+- Generated packs of the same length get fewer puzzles and more story when
+ they choose `narrative`; `balanced` packs get somewhat more text than before
+ (45% instead of an implicit 29% reading).
+- Estimates of existing packs rise by roughly 10%, because interaction is
+ priced higher.
+- `playtime.pacing` can be met by padding. The guide forbids padding, and the
+ review stage and the transcript exist to catch it; the warning is only
+ issued for packs that declare a pacing.
+- The calibration rests on two playtests of one pack. It should be revisited
+ when playtests record session durations.
+- A generation run makes two more model calls (story, review).
+
+## Alternatives considered
+
+- **Only loosen the style rules.** Longer sentences without a different budget
+ would have been cut again by the length repair and by authors chasing the
+ target; the budget is what made prose expensive.
+- **Raise the words per command globally.** One number cannot fit a puzzle box
+ and a mystery; the reading share makes the trade-off an explicit authoring
+ decision per pack.
+- **Keep the noir pack at 45 minutes.** At 60% reading this leaves about 18
+ minutes of interaction, roughly two thirds of the current mechanics. The
+ puzzles were the part of the pack that worked, so the target moved instead.
+- **An automatic prose-quality metric** (sentence length, connectives) as a
+ warning. Easy to game and a poor proxy for "can a reader follow it"; the
+ transcript review asks that question directly.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8c5fd19..1193ffe 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -21,6 +21,7 @@ instead of by accident ([ADR 0001](0001-record-architecture-decisions.md)).
| [0009](0009-vanilla-typescript-ui.md) | Vanilla TypeScript UI without a framework | Accepted |
| [0010](0010-content-licensing.md) | Content licensing | Proposed |
| [0011](0011-text-first-optional-svg-vignettes.md) | Text first, optional SVG vignettes later | Accepted |
+| [0012](0012-narrative-pacing.md) | Narrative pacing: calibrate play time by reading share, write story before data | Accepted |
## When to write an ADR
diff --git a/docs/authoring/guide.md b/docs/authoring/guide.md
index 012e09f..15bc652 100644
--- a/docs/authoring/guide.md
+++ b/docs/authoring/guide.md
@@ -21,6 +21,13 @@ object. A text parser exists but is optional. That has consequences for design:
the player can *see* every possible action, so puzzles cannot rely on obscure
verbs, and every tap should be answered with something worth reading.
+A text adventure is also a story that is *read*. Verification proves that a
+pack can be won; it cannot prove that a reader can follow it. The first noir
+pack showed the failure mode: logically sound puzzles wrapped in telegram-style
+fragments, while the actual story lived in the design documents and never
+reached the player. Section 2 ("Story and scenes") and the `pacing` setting
+exist to prevent that ([ADR 0012](../adr/0012-narrative-pacing.md)).
+
## 1. Shape and pacing
A LexVM game is short and dense: it is played in a few sittings on a phone,
@@ -35,6 +42,35 @@ often offline. The first pack targets 30â45 minutes.
- Score is a progress signal: usually 1 point per solved puzzle, 2 for a major deduction. Award each point exactly once (guard with a flag, a `not: { has: ⊠}` condition or a `once` rule). `maxScore` equals the total score collected by the walkthrough.
+## 2. Story and scenes
+
+A pack has two layers: the *mechanics* (rooms, items, rules, the puzzle
+chart) and the *story* (what happened, who wants what, what the player
+character comes to understand). The mechanics are verified; the story is
+only as good as the text the player actually reads. Two habits lose it:
+
+- writing text one data field at a time (a description here, a rule message
+ there) instead of one scene at a time, and
+- keeping the real story in design notes (the truth, the motives, the
+ backstory) and handing the player only the facts a puzzle needs.
+
+Write the story first, as scenes, then cut it into the data model. Review it
+the way the player meets it: `lexvm transcript ` prints the whole text
+of a winning play in order. Read it from start to end, or give it to an
+editor (the `review` prompt stage does that with an LLM). Could a reader
+retell what happened and why?
+
+
+## Story and scenes
+- Write the story before the data: the truth in causal order (who did what, and why), the player character's goal and how their understanding changes, and a scene plan in play order. Then derive room, object, dialogue and rule texts from the scenes.
+- Everything the ending relies on reaches the player in game text. Motives, relationships and backstory that only live in the design notes do not exist for the player.
+- Every scene has an arrival (where am I, who is here, what is at stake), a turn (something learned or changed) and a way out (why the player goes on, and where). Write the transitions: the first entry to a room, the moment after a key clue, the move from one chapter to the next (a `once` rule on `enter`, or the response that solves the puzzle).
+- Give the player character an inner voice in moderation: after a key clue or deduction, one or two sentences on what it means and what follows from it. That is how a reader keeps track of a case.
+- Characters want something the player can see, and speak like themselves. A conversation has a turning point; write it out as a scene, not as one line of information.
+- Prose rhythm: vary sentence length. Short sentences are accents, not the default; join thoughts that belong together with their logic (because, but, so, while). No telegram style, no chains of fragments, no adjective padding.
+- Review the transcript of the walkthrough (`lexvm transcript`): it must read as a story a reader can follow from start to end.
+
+
### Length budget
`playtime` is the length a pack aims for, and LexVM checks it: `lexvm check`
@@ -46,13 +82,14 @@ words. To see the budget for a length before you write, print a stage prompt
the table in [`prompts/oneshot.md`](../../prompts/oneshot.md).
-## Length budget
-- LexVM estimates the play time of a pack: reading the text the walkthrough shows (German 200, English 230 words per minute), about 10 seconds per walkthrough command and 6 per dialogue choice, plus part of the optional content (descriptions the walkthrough never examines, unchosen dialogue options, custom responses) and of the wrong attempts a player makes. `lexvm check` warns when the estimate misses `playtime` by more than 25%; set `playtime` to the target length.
-- Typical proportions: about 20 words of new text per walkthrough command; about a quarter of the walkthrough steps are dialogue choices; optional text about 60% of the walkthrough's text; about one described object for every two walkthrough commands that the walkthrough never examines.
-- Follow the size budget the prompt gives for the target length (walkthrough steps and words of player-visible text). Length comes from content, not padding: add a puzzle, a character to question, custom responses and side dialogue rather than longer descriptions (the text budgets for phone screens still apply). To shorten, cut a side puzzle or trim descriptions.
+## Length budget and pacing
+- LexVM estimates the play time of a pack: reading the text the walkthrough shows (German 200, English 230 words per minute), about 10 seconds per walkthrough command and 6 per dialogue choice, plus part of the optional content (descriptions the walkthrough never examines, unchosen dialogue options, custom responses) and about one wrong attempt per productive command. `lexvm check` warns when the estimate misses `playtime` by more than 25%; set `playtime` to the target length.
+- `pacing` says how that time divides between reading and acting: `narrative` (about 60% reading: mysteries, dramas, character stories), `balanced` (about 45%, the default), `puzzle` (about 30%: puzzle boxes, escape rooms). Declare it in the metadata; `lexvm check` then warns when the reading share leaves the band (±10 points). A narrative pack with the same play time has fewer puzzles and more story.
+- Follow the size budget the prompt gives for the target length and pacing (walkthrough steps and words of player-visible text). About a quarter of the walkthrough steps are dialogue choices; optional text is about 60% of the walkthrough's text.
+- Length comes from content, never from padding. Content is both mechanics (a puzzle, a character to question, custom responses) and story (an arrival, a turning point, what a clue means, a transition between acts). Padding is adjectives, repeated atmosphere and summaries of what the player just saw. To shorten a narrative pack, cut a side puzzle before you cut a scene.
-## 2. Puzzle dependency charts
+## 3. Puzzle dependency charts
Ron Gilbert's *puzzle dependency chart* is the tool for designing adventure
puzzles. Start at the end â the winning ending â and ask: what has to be true
@@ -102,7 +139,7 @@ no long stretch where only one node is open.
```
-## 3. The LucasArts rules: the `forgiving` policy
+## 4. The LucasArts rules: the `forgiving` policy
LexVM follows the design philosophy that Ron Gilbert summarised in *Why
Adventure Games Suck* and that LucasArts games made famous: the player should
@@ -123,7 +160,7 @@ can no longer lead to a win.
- No timed puzzles, no mazes, no randomness (the engine has none).
-## 4. Fair clueing
+## 5. Fair clueing
A puzzle is fair when an attentive player could solve it from what the game
has shown them. The test: could you write the hint for it by quoting the
@@ -137,7 +174,7 @@ game's own text?
- Reflect state changes with text variants (`when`) in room and object descriptions (the door now stands open, the drawer is empty).
-## 5. Rules and state
+## 6. Rules and state
Rules are the heart of a pack. Read section 10 of the spec ("Turn processing")
once carefully; most logic bugs come from forgetting that rules *replace* the
@@ -153,7 +190,7 @@ default behaviour and that only the *first* matching command rule fires.
- Counters changed by `turn` rules must be bounded by their `when`. Prefer flags over counters.
-## 6. Characters and dialogue
+## 7. Characters and dialogue
Dialogue-heavy games (interrogations, negotiations) live from the feeling that
conversations *progress* as the player learns more. In LexVM that is done with
@@ -168,7 +205,7 @@ options that appear when the player holds a clue.
- Node `say` †300 characters, option text †80. Options are the player's words; narration belongs in `say` or `do`.
-## 7. Clues, deductions and the notebook
+## 8. Clues, deductions and the notebook
The notebook is LexVM's answer to "where do I keep what I learned?". Clues are
objects that live in the notebook part of the inventory. Because they are
@@ -184,7 +221,7 @@ deduce something, or *show* a clue to a character to confront them.
- Interrogations and confrontations use clues as evidence (see dialogue).
-## 8. Hints
+## 9. Hints
Every LexVM game has a hint button. A good hint system means nobody has to
search the web for a walkthrough, and nobody gets the answer before they want
@@ -197,22 +234,23 @@ it.
- The first hint whose `when` holds and whose `until` does not is shown, so order hints in the usual solving order, and make sure some hint applies at every point until the ending.
-## 9. Text for phone screens
+## 10. Text for phone screens
LexVM is read on a phone held in portrait mode, in a book-like layout. Long
paragraphs become walls of text; references (`{id}`) become tappable words.
## Text for phone screens
-- Budgets: room descriptions †600 characters, object descriptions †400, dialogue lines †300, option texts †80, names †24. Aim well below.
-- Short paragraphs of 1â3 sentences. The first sentence says what matters; atmosphere second.
+- Budgets: room descriptions †600 characters, object descriptions †400, dialogue lines †300 (`pacing: narrative`: 1,000, 600 and 600); option texts †80, names †24 for every pacing. The player scrolls like a book; a long text needs paragraphs, not cuts.
+- Paragraphs of 1â4 sentences, separated by a blank line. In descriptions the first sentence says what matters; atmosphere second.
+- First visits get the full scene; return visits to a room get one or two sentences (a text variant with `visited`).
- Mention exits naturally in the room description ("The library lies to the west.").
- Every interactable object appears as `{id}` (or `{id|inflected text}`) in its room's description or in its own `roomText`. Portable objects without `roomText` are listed automatically.
- Names are short, without articles, and distinct: "brass key", not "the small brass key".
-- Rule messages (`say`) are 1â2 sentences.
+- Rule messages (`say`) are 1â3 sentences; the response that solves a puzzle or reveals a clue may be a short scene.
-## 10. Language conventions
+## 11. Language conventions
Ids are always ASCII `lower_snake_case`; English ids are fine for every pack
language and make diagnostics easier to read. Everything the player sees is in
@@ -226,7 +264,7 @@ the pack's `language`.
- Pack verbs need a `label` in the pack language and parser `synonyms` (German: imperative and infinitive, e.g. `[lies, lese, lesen]`).
-## 11. YAML pitfalls
+## 12. YAML pitfalls
YAML is friendly until it is not. Almost every pack that fails to load does so
because of one of the following.
@@ -245,7 +283,7 @@ because of one of the following.
- Indent with two spaces, never tabs.
-## 12. The walkthrough
+## 13. The walkthrough
The walkthrough is the pack's proof of solvability. `lexvm check` replays it
from a new game, so it has to be exact.
@@ -259,7 +297,7 @@ from a new game, so it has to be exact.
- Write it last, after all rooms, objects, rules and dialogues exist.
-## 13. Checklist of common mistakes
+## 14. Checklist of common mistakes
Run through this list before you run `lexvm check` â and run `lexvm check`
anyway. The LLM prompts ask the model to go through the same list.
@@ -281,7 +319,7 @@ anyway. The LLM prompts ask the model to go through the same list.
14. **Score.** Each point is awarded once; `maxScore` equals the walkthrough's total.
-## 14. Reviewing a pack (human or generated)
+## 15. Reviewing a pack (human or generated)
`lexvm check` proves that a pack is *correct*. Whether it is *good* is up to
you. Before you publish, play it on a phone and ask:
@@ -290,13 +328,19 @@ you. Before you publish, play it on a phone and ask:
- When stuck, are there always other things to try (look at the chart)?
- Is every puzzle solvable from the text alone, without the hints?
- Do characters react to the evidence you show them?
-- Is the text tight? Does it read well on a small screen, in the chosen
- narrative voice, with consistent quotes?
+- Read the transcript (`lexvm transcript `) from start to end: could a
+ reader retell what happened, who wanted what, and why the player went where
+ they went? Is there a moment where something happens without a reason?
+- Does the text read well on a small screen, in the chosen narrative voice,
+ with consistent quotes? Does the rhythm vary, or is it a chain of fragments?
- Are there plausible actions that get a bland default answer where a custom
response would be better?
- Does the ending pay off what the player found out?
-LLM-generated packs in particular tend to be wordy, to over-use atmosphere
-adjectives, and to forget custom responses for wrong attempts. A careful edit
-pass is part of the job; see [pipeline.md](pipeline.md) for provenance and
+LLM-generated packs fail in two opposite directions: wordy description with
+too many atmosphere adjectives, or, under tight length budgets, a telegram
+style that keeps the story in the model's head and gives the player only the
+facts a puzzle needs. Both get caught by reading the transcript. LLMs also
+tend to forget custom responses for wrong attempts. A careful edit pass is
+part of the job; see [pipeline.md](pipeline.md) for provenance and
licensing.
diff --git a/docs/authoring/pipeline.md b/docs/authoring/pipeline.md
index 4b27494..5a48e97 100644
--- a/docs/authoring/pipeline.md
+++ b/docs/authoring/pipeline.md
@@ -13,7 +13,7 @@ and the same verification ([ADR 0007](../adr/0007-llm-pipeline-byo-prompt-kit-an
Neither flow replaces playtesting. Verification proves that a pack is
*winnable without dead ends*; whether it is *good* is decided by people. See
-the [authoring guide](guide.md) for what "good" means, and section 14 there
+the [authoring guide](guide.md) for what "good" means, and section 15 there
for reviewing a pack.
## The prompt kit
@@ -39,11 +39,13 @@ The stages:
| Stage | Template | Asks the model for |
|---|---|---|
| `oneshot` | `oneshot.md` | A short design (concept, puzzle dependency chart), one complete `pack.yaml`, a self-check against the checklist. |
-| `concept` | `concept.md` | `design/concept.md`: title, voice, premise, cast, chapters, locations, key items and clues. |
+| `concept` | `concept.md` | `design/concept.md`: title, voice, pacing, premise, cast, chapters, locations, key items and clues. |
+| `story` | `story.md` | `design/story.md`: the truth with every motive, the through-line, a scene plan (arrival, turn, way out), a revelation map and the key scenes in prose. |
| `puzzles` | `puzzles.md` | `design/puzzles.md`: a Mermaid puzzle dependency chart and, per puzzle, signposting, solution, wrong attempts, hints, score. |
| `world` | `world.md` | `pack.yaml` (metadata, start, verbs, flags), `rooms.yaml`, `objects.yaml`. |
| `logic` | `logic.md` | `rules.yaml`, `dialogues.yaml`, `solution.yaml` (endings, hints, walkthrough last), plus any earlier file that must change. |
| `repair` | `repair.md` | Only the changed files, complete, given the diagnostics and the current files. |
+| `review` | `review.md` | An editorial pass: given the walkthrough transcript, the story and the files, only the files whose text it improved. |
The staged prompts share one system prompt (`system.md`: the guide, the
checklist, the spec and the example). It contains nothing run-specific, so
@@ -54,22 +56,46 @@ the API can cache it across all calls of a run.
Generated packs should roughly hit their target length, so every prompt
gives the model a size budget up front. The budget comes from
`budgetForMinutes` in the engine, the inverse of the play time estimate
-(spec section 17): for a target length and language it gives a range of
-walkthrough steps and of player-visible words, plus the typical proportions
-(about a quarter of the steps are dialogue choices, about 60% of the words
-appear along the walkthrough).
-
-- The stage prompts (`concept`, `puzzles`, `world`, `logic`) contain the
- budget for `--minutes` (`{{BUDGET}}`); without `--lang` they list it for
- German and English packs.
+(spec section 17): for a target length, language and pacing it gives a range
+of walkthrough steps and of player-visible words, plus the typical
+proportions (about a quarter of the steps are dialogue choices, about 60% of
+the words appear along the walkthrough).
+
+The pacing decides how the minutes are spent ([ADR 0012](../adr/0012-narrative-pacing.md)):
+`narrative` about 60% reading, `balanced` 45% (the default), `puzzle` 30%. A
+45-minute German pack is budgeted at about 70â90 walkthrough steps and
+4,200â5,350 words when balanced, and at about 50â65 steps and 5,600â7,100
+words when narrative: fewer puzzles, more story.
+
+- The stage prompts (`concept`, `story`, `puzzles`, `world`, `logic`,
+ `review`) contain the budget for `--minutes` and `--pacing` (`{{BUDGET}}`);
+ without `--lang` they list it for German and English packs.
- The generic one-shot prompt contains a table for 15, 30, 45 and 60 minutes
- (`{{BUDGET_TABLE}}`, plus the `--minutes` value if it is another one) and
- tells the model to pick the row matching the requested length, 30 minutes
- if the idea names none.
+ and every pacing (`{{BUDGET_TABLE}}`, plus the `--minutes` value if it is
+ another one) and tells the model to choose the pacing from the idea and
+ pick the matching row, 30 minutes if the idea names none.
- `lexvm check` prints the estimate, and warns (`playtime.too-short`,
`playtime.too-long`) when it misses `playtime` by more than 25%, with
concrete numbers: how many puzzles, walkthrough commands or words to add or
- cut. Paste these warnings back like any other diagnostic.
+ cut. When the pack declares a `pacing`, it also warns (`playtime.pacing`)
+ when the reading share is more than 10 points off. Paste these warnings
+ back like any other diagnostic.
+
+### Reading the story: `lexvm transcript`
+
+Verification proves a pack can be won; it cannot tell whether a reader can
+follow it. `lexvm transcript ` replays the walkthrough and prints
+everything the player reads along it as Markdown (room titles as headings,
+commands as quotes; `--out ` writes it to a file). Read it from start to
+end, or have it reviewed:
+
+```sh
+npm run lexvm -- prompt --stage review --pack packs/ --out review.md
+```
+
+The review prompt contains the transcript, the story document and the pack
+files, and asks the model, as a story editor, to improve the text without
+touching the mechanics. Check the result like any repair.
## Flow A: bring your own LLM
@@ -155,9 +181,11 @@ to any file.
| `--out ` | â | Output directory. Its name is the pack id (kebab-case). |
| `--lang de\|en` | language of the idea | Pack language. |
| `--minutes ` | 30 | Target play time: written to `playtime`, sizes the budget in the prompts, checked by the play time estimate. |
+| `--pacing ` | `balanced` | `narrative`, `balanced` or `puzzle`: written to `pacing`, splits the budget between reading and interaction, checked by the estimate. |
+| `--no-review` | off | Skip the editorial review round after the pack passes. |
| `--model ` | `LEXVM_MODEL` | Claude model id (required). |
| `--max-repairs ` | 6 | Repair rounds after the first check. |
-| `--from-stage ` | `concept` | Resume at `concept`, `puzzles`, `world`, `logic` or `verify`. |
+| `--from-stage ` | `concept` | Resume at `concept`, `story`, `puzzles`, `world`, `logic` or `verify`. |
| `--max-states ` | 200000 | State limit of the exploration gate. |
| `--max-tokens ` | 64000 | Output token limit per request. |
| `--effort ` | model default | `low`, `medium`, `high`, `xhigh` or `max`. |
@@ -177,13 +205,15 @@ packs//
rules.yaml dialogues.yaml solution.yaml # logic stage
design/
concept.md # concept stage
+ story.md # story stage
puzzles.md # puzzles stage
run.json # log of every run
```
-Each stage's prompt contains the outputs of the previous stages: the puzzle
-designer sees the concept, the world builder sees concept and puzzles, the
-logic writer sees both documents and the world files. Progress is printed per
+Each stage's prompt contains the outputs of the previous stages: the story
+writer sees the concept, the puzzle designer concept and story, the world
+builder all three documents, the logic writer the documents and the world
+files. Repair rounds see the story too. Progress is printed per
stage to stderr. Every artifact is written as soon as it exists.
The model returns files as fenced code blocks whose info string names the
@@ -232,11 +262,18 @@ twice in the same way (an engine bug, not a pack problem), the loop stops
early.
The length is the one warning the loop acts on by itself: when a pack passes
-every gate but its estimated play time misses the target by more than 25%
-(`playtime.too-short` / `playtime.too-long`), the pipeline spends one more
-repair round on the length, if `--max-repairs` leaves one. If that round
-breaks the pack and the remaining rounds cannot fix it, the last passing
-version is restored, so a length repair never costs a working pack.
+every gate but its estimated play time misses the target by more than 25%,
+or its reading share misses the pacing (`playtime.too-short`,
+`playtime.too-long`, `playtime.pacing`), the pipeline spends one more repair
+round on the length, if `--max-repairs` leaves one.
+
+Then, unless `--no-review` is given, the pipeline runs one **editorial
+review** round: the model gets the walkthrough transcript, the story and the
+files and returns the files whose text it improved. The result is verified
+like a repair and may take further repair rounds. Both extra rounds count
+against `--max-repairs`. If either breaks the pack and the remaining rounds
+cannot fix it, the last passing version is restored, so neither ever costs a
+working pack.
On failure, look at the remaining diagnostics (`npm run lexvm -- check
packs/`), fix what you can by hand, and continue with
@@ -249,12 +286,13 @@ the artifacts of the earlier stages from disk:
| Stage | Needs on disk |
|---|---|
-| `puzzles` | `design/concept.md` |
-| `world` | `design/concept.md`, `design/puzzles.md` (the world stage replaces all existing `*.yaml` files) |
+| `story` | `design/concept.md` |
+| `puzzles` | `design/concept.md`, `design/story.md` |
+| `world` | the three design documents (the world stage replaces all existing `*.yaml` files) |
| `logic` | the design documents and `pack.yaml` |
| `verify` | the pack files |
-The idea, language, play time, author and license are taken from
+The idea, language, play time, pacing, review setting, author and license are taken from
`design/run.json` unless given again on the command line. This makes a
human-in-the-loop workflow easy: generate, read `design/puzzles.md`, improve
the chart by hand, then `--from-stage world`. Without `--from-stage`, the
@@ -278,7 +316,7 @@ the pull request if you want to.
### Time and cost
-A run makes four stage calls plus one call per repair round. Every call
+A run makes five stage calls, one review call and one call per repair round. Every call
sends the shared system prompt (the spec, guide and example â cached after
the first call, which makes later calls cheaper) and the artifacts of the
previous stages; repair rounds resend all pack files. Most of the output, and
diff --git a/docs/spec/content-pack.md b/docs/spec/content-pack.md
index e29b3c1..9bcb454 100644
--- a/docs/spec/content-pack.md
+++ b/docs/spec/content-pack.md
@@ -65,6 +65,7 @@ which is what the player loads. The player can also import `.yaml` and
| `policy` | `"forgiving"` | no | Default and currently the only policy: no losing endings, no dead ends. |
| `generator` | `{pipeline?, notes?}` | no | Provenance, free text. |
| `playtime` | int (minutes) | no | Target play time. `lexvm check` compares its play time estimate against it (section 17). |
+| `pacing` | `"narrative"` \| `"balanced"` \| `"puzzle"` | no | How the play time divides between reading and interaction (about 60%, 45% or 30% reading). Sizes the text budgets (section 4) and, when declared, is checked by the play time estimate (section 17). |
| `maxScore` | int | no | Enables the score display. |
| `start` | `{room, intro?}` | yes | Starting room and intro text. |
| `verbs` | map id â Verb | no | Pack verbs and overrides for core verbs. |
@@ -100,9 +101,12 @@ Inside strings:
- A blank line separates paragraphs; a single newline is a line break.
- Nothing else is markup. Text is never interpreted as HTML.
-Keep texts short for phone screens: room descriptions †600 characters,
+Keep texts readable on phone screens: room descriptions †600 characters,
object descriptions †400, dialogue lines †300, option texts †80, names †24.
-Longer texts produce warnings.
+A pack with `pacing: narrative` tells its scenes in full and gets room
+descriptions †1000, object descriptions †600 and dialogue lines †600; option
+texts and names keep their limits, because they are buttons. Longer texts
+produce warnings (`text.too-long`).
## 5. Rooms and exits
@@ -522,7 +526,7 @@ in `@lexvm/engine`.
| `t_cmd` | 10 s | `secondsPerCommand` | Per command: perceive the scene, tap the object, pick the verb. |
| `t_choice` | 6 s | `secondsPerChoice` | Per dialogue choice. |
| `c` | 0.6 | `coverage` | Share of the optional content a typical player sees. |
-| `f` | 0.5 | `failedAttemptsPerCommand` | Unproductive attempts per productive command. |
+| `f` | 1 | `failedAttemptsPerCommand` | Unproductive attempts per productive command. |
| tolerance | 0.25 | `tolerance` | Allowed relative deviation from the target. |
| target | `playtime` | `targetMinutes`; CLI `--target-minutes` | The length the pack should have. |
@@ -535,12 +539,33 @@ per minute in German and 1234 in English; German words are longer, so German
gets fewer words per minute. The defaults are deliberately below the lab
values: the text is read on a phone screen, in a game, and partly re-read.
+The attempt rate `f` comes from the playtests of
+`packs/letzte-nacht-der-reichsmark` (74 walkthrough steps, 47 of them
+commands): a tap-only player made 180 commands, an adventure veteran 226.
+After the optional looks and dialogue options the model counts separately,
+that leaves about 0.9 and 1.8 unproductive attempts per productive command;
+`f = 1` is the cautious end. Earlier versions used 0.5, which underestimated
+the interaction time of real players and therefore pushed packs to cut text
+to meet their target ([ADR 0012](../adr/0012-narrative-pacing.md)).
+
+**Reading share and pacing.** `reading = (W_path + c · W_optional) / wpm` is
+the part of `minutes_expected` spent reading; the reading share is
+`reading / minutes_expected`. A pack declares how it means to divide its time
+with `pacing`: `narrative` 0.6, `balanced` 0.45, `puzzle` 0.3. When `pacing` is
+declared and the share is more than 0.1 away from its value, `lexvm check`
+warns (`playtime.pacing`): a narrative pack whose story is told too thinly for
+its mechanics, or a pack that reads much more than it plays. A pack without
+`pacing` is never warned and is sized as `balanced`.
+
**Diagnostics** (path `playtime`; Appendix A):
- `playtime.estimate` (info, always): "â 34 min expected (speedrun 21 min);
target 35 min", followed by the counts the estimate is based on.
- `playtime.no-target` (info): the pack has no `playtime`; suggests the
rounded expected time.
+- `playtime.pacing` (warning, only when `pacing` is declared): the reading
+ share is outside the pacing's band; the message says how many words of scene
+ prose are missing, or what to trim.
- `playtime.too-short` / `playtime.too-long` (warning): `|expected / target â 1|`
is greater than the tolerance. The message gives concrete numbers derived
from the pack's own proportions, e.g. "â 12 min short: add 1-2 puzzles, or â
@@ -548,20 +573,25 @@ values: the text is read on a phone screen, in a game, and partly re-read.
"â 4 min too long: trim â 1,100 words or â 20 commands". They are left out
while the walkthrough does not reach a winning ending.
-**Budget.** `budgetForMinutes(minutes, language)` inverts the model for a
-target length with typical ratios of a pack: `W_optional â 0.6 · W_path`,
-`D_path â 0.25 ·` all walkthrough steps, `W_path â 20 · C_path` (words of new
-text per productive command), `L_unseen â 0.5 · C_path` and
-`O_unchosen â 0.25 · D_path`. The ratios are calibrated against the reference
-pack `packs/locked-study` (English) and the German test fixture
-`packages/engine/test/fixtures/runtime/hafen.yaml`, pooled over both
-walkthroughs: measured 0.34, 0.28, 20.7, 0.56 and 0.14. The optional-word
-ratio is set higher than measured because these two packs are tiny, and a
-full-length game carries more side content (custom responses to wrong
-attempts, dialogue branches); the unchosen-option ratio is rounded up for the
-same reason. The budget gives ranges of walkthrough steps and player-visible
-words of ±tolerance/2 around the target, so a pack that stays within both
-ranges lands within the tolerance under the model's assumptions.
+**Budget.** `budgetForMinutes(minutes, language, { pacing })` inverts the
+model for a target length. The reading share of the pacing (default
+`balanced`) splits the minutes: the interaction part sizes the walkthrough
+(steps Ă interaction minutes per step, with tapping, wrong attempts, side looks
+and unchosen options), the reading part sizes the text
+(`W_path + c · W_optional = reading minutes · wpm`). The other ratios are
+typical of a pack: `W_optional â 0.6 · W_path`, `D_path â 0.25 ·` all
+walkthrough steps, `L_unseen â 0.5 · C_path` and `O_unchosen â 0.25 · D_path`.
+They are calibrated against the reference pack `packs/locked-study` (English)
+and the German test fixture `packages/engine/test/fixtures/runtime/hafen.yaml`,
+pooled over both walkthroughs: measured 0.34, 0.28, 0.56 and 0.14. The
+optional-word ratio is set higher than measured because these two packs are
+tiny, and a full-length game carries more side content (custom responses to
+wrong attempts, dialogue branches); the unchosen-option ratio is rounded up
+for the same reason. Earlier versions fixed the words per command at 20 instead
+of deriving them from a reading share; that implied a reading share of about
+30% for every pack. The budget gives ranges of walkthrough steps and
+player-visible words of ±tolerance/2 around the target, so a pack that stays
+within both ranges lands within the tolerance under the model's assumptions.
**Where it is used.**
@@ -572,15 +602,16 @@ ranges lands within the tolerance under the model's assumptions.
catalog entry in `index.json` when the walkthrough reaches a win. The
player's library shows `playtime` and falls back to `estimatedMinutes`;
imported packs keep the estimate computed at import.
-- `lexvm generate --minutes ` writes the target to `playtime` in the
- metadata (world) stage and keeps it there, puts the budget into the stage
- prompts, and checks the estimate in its verification gate. Play time
- warnings come right after the errors in repair prompts. A pack that passes
- every gate but misses the target gets one more repair round for its length
- (if `--max-repairs` allows); if that round breaks the pack and the
- remaining rounds cannot fix it, the last passing version is restored. The
- generic one-shot prompt contains a budget table for 15, 30, 45 and 60
- minutes.
+- `lexvm generate --minutes --pacing ` writes the target to
+ `playtime` and the pacing to `pacing` in the metadata (world) stage and
+ keeps them there, puts the budget into the stage prompts, and checks the
+ estimate in its verification gate. Play time warnings come right after the
+ errors in repair prompts. A pack that passes every gate but misses the
+ target or its pacing gets one more repair round for its length (if
+ `--max-repairs` allows); if that round breaks the pack and the remaining
+ rounds cannot fix it, the last passing version is restored. The generic
+ one-shot prompt contains a budget table for 15, 30, 45 and 60 minutes and
+ every pacing.
## Appendix A. Diagnostic codes
@@ -696,6 +727,7 @@ walkthrough, play time and exploration results.
| `playtime.estimate` | info | The estimate and what it is based on. |
| `playtime.no-target` | info | No `playtime`; suggests a value. |
| `playtime.too-short`, `playtime.too-long` | warning | The expected time misses the target by more than the tolerance, with concrete advice. |
+| `playtime.pacing` | warning | The reading share misses the declared `pacing` by more than 0.1. |
**Tools**
diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts
index 3ce3097..5b5b612 100644
--- a/packages/cli/src/commands/check.ts
+++ b/packages/cli/src/commands/check.ts
@@ -184,7 +184,7 @@ function printReport(report: CheckReport, baseDir: string): void {
target = off ? color.yellow(text) : text;
}
out(
- ` playtime â ${expected} min expected, speedrun ${speedrun} min, ${target}; ${p.words.path + p.words.optional} words, ${p.wordsPerMinute} wpm`,
+ ` playtime â ${expected} min expected, speedrun ${speedrun} min, ${target}; ${p.words.path + p.words.optional} words, ${p.wordsPerMinute} wpm, reading ${Math.round(p.readingShare * 100)}%${p.pacing === null ? "" : ` (pacing ${p.pacing})`}`,
);
}
const x = report.explore;
diff --git a/packages/cli/src/commands/transcript.ts b/packages/cli/src/commands/transcript.ts
new file mode 100644
index 0000000..9e1df67
--- /dev/null
+++ b/packages/cli/src/commands/transcript.ts
@@ -0,0 +1,45 @@
+import { writeFileSync } from "node:fs";
+import { walkthroughTranscript } from "@lexvm/engine";
+import { flag, parseArgs, stringOption, UsageError } from "../args.ts";
+import { compileSource, readPackSource } from "../sources.ts";
+import { clean, err, formatDiagnostic } from "../term.ts";
+
+export const TRANSCRIPT_HELP = `Usage: lexvm transcript [options]
+
+Replay the pack's walkthrough and print everything a player reads along it,
+as Markdown: room titles as headings, the player's commands as quotes. This is
+the text to read (or give to an editor) when reviewing the story: can a reader
+follow what happens, and why?
+
+Options:
+ --out Write the transcript to this file instead of stdout
+ -h, --help Show this help
+
+Exit codes: 0 the walkthrough reaches a winning ending, 1 it does not or the
+pack is invalid, 2 usage error.`;
+
+export function runTranscript(argv: string[]): number {
+ const args = parseArgs(argv, {
+ out: { type: "string", short: "o" },
+ help: { type: "boolean", short: "h" },
+ });
+ if (flag(args, "help")) {
+ process.stdout.write(`${TRANSCRIPT_HELP}\n`);
+ return 0;
+ }
+ if (args.positionals.length !== 1) throw new UsageError("transcript needs exactly one pack");
+ const target = args.positionals[0]!;
+ const source = readPackSource(target);
+ const result = compileSource(source);
+ if (result.pack === null) {
+ for (const d of result.diagnostics) if (d.severity === "error") err(formatDiagnostic(d, source.baseDir, target));
+ err(clean(`${target} is not a valid pack; run "lexvm validate ${target}" for details.`));
+ return 1;
+ }
+ const transcript = walkthroughTranscript(result.pack);
+ const outPath = stringOption(args, "out");
+ if (outPath === undefined) process.stdout.write(clean(transcript.markdown));
+ else writeFileSync(outPath, transcript.markdown);
+ if (!transcript.ok) err(`${target}: the walkthrough does not reach a winning ending; the transcript is partial.`);
+ return transcript.ok ? 0 : 1;
+}
diff --git a/packages/cli/src/generate/assemble.ts b/packages/cli/src/generate/assemble.ts
index 0e367a5..ff33637 100644
--- a/packages/cli/src/generate/assemble.ts
+++ b/packages/cli/src/generate/assemble.ts
@@ -3,14 +3,22 @@
* an LLM. Used by `lexvm prompt` (copy-paste prompts for any LLM) and by
* `lexvm generate` (staged API pipeline), so both always use the same words.
*/
-import { budgetForMinutes, PLAYTIME_DEFAULTS, type PlaytimeBudget } from "@lexvm/engine";
+import {
+ budgetForMinutes,
+ DEFAULT_PACING,
+ PACING_READING_SHARE,
+ type Pacing,
+ PLAYTIME_DEFAULTS,
+ type PlaytimeBudget,
+} from "@lexvm/engine";
import { fenceFile } from "./fenced.ts";
import { type PromptKit, renderTemplate } from "./kit.ts";
-export const PROMPT_STAGES = ["oneshot", "concept", "puzzles", "world", "logic", "repair"] as const;
+export const PROMPT_STAGES = ["oneshot", "concept", "story", "puzzles", "world", "logic", "repair", "review"] as const;
export type PromptStage = (typeof PROMPT_STAGES)[number];
export const PACK_LANGUAGES = ["de", "en"] as const;
+export const PACINGS = ["narrative", "balanced", "puzzle"] as const satisfies readonly Pacing[];
export type PackLanguage = (typeof PACK_LANGUAGES)[number];
export const DEFAULT_MINUTES = 30;
@@ -30,6 +38,8 @@ export interface PromptInputs {
/** The user's idea; null renders the "write your idea here" instruction (generic prompt). */
idea: string | null;
minutes: number;
+ /** Pacing of the pack; null or undefined = the default (balanced), or the model's choice in the one-shot prompt. */
+ pacing?: Pacing | null;
/** Pack id (kebab-case), when the output directory already fixes it. */
packId?: string | null;
/** Author for pack metadata (API pipeline); null = ask the model to use the user's name. */
@@ -41,8 +51,12 @@ export interface PromptInputs {
staged?: boolean;
/** design/concept.md, if available. */
concept?: string | null;
+ /** design/story.md, if available. */
+ story?: string | null;
/** design/puzzles.md, if available. */
puzzles?: string | null;
+ /** The walkthrough transcript (lexvm transcript), for the review stage. */
+ transcript?: string | null;
/** Current pack files (YAML), if available. */
files?: NamedText[] | null;
/** Diagnostics text for the repair stage. */
@@ -102,6 +116,13 @@ function renderFiles(files: NamedText[] | null | undefined): string {
return files.map((f) => fenceFile(f.name, f.content)).join("\n\n");
}
+function renderTranscript(text: string | null | undefined): string {
+ if (text === null || text === undefined || text.trim() === "") {
+ return "(Paste the output of `npm run lexvm -- transcript ` here.)";
+ }
+ return fence(text.trim(), "markdown");
+}
+
function renderDiagnostics(text: string | null | undefined): string {
if (text === null || text === undefined || text.trim() === "") {
return "(Paste the output of `npm run lexvm -- check ` or the diagnostics shown by the LexVM app here.)";
@@ -116,50 +137,65 @@ function range(r: { min: number; max: number }): string {
return `${fmt(r.min)}â${fmt(r.max)}`;
}
-function budgetIntro(minutes: number): string {
+function budgetIntro(minutes: number, pacing: Pacing): string {
return (
- `Size budget for about ${minutes} minutes. LexVM estimates the play time from the walkthrough and the texts; ` +
- `\`lexvm check\` warns when the estimate misses \`playtime\` by more than ${TOLERANCE_PERCENT}%. Stay within these ranges:`
+ `Size budget for about ${minutes} minutes with pacing \`${pacing}\` (about ${Math.round(PACING_READING_SHARE[pacing] * 100)}% of the time is reading). ` +
+ "LexVM estimates the play time from the walkthrough and the texts; " +
+ `\`lexvm check\` warns when the estimate misses \`playtime\` by more than ${TOLERANCE_PERCENT}%, and when the reading share misses the pacing. Stay within these ranges:`
);
}
/** The size budget for one target length, as Markdown (stage prompts). */
-export function renderBudget(minutes: number, lang: PackLanguage | null): string {
+export function renderBudget(minutes: number, lang: PackLanguage | null, pacing: Pacing = DEFAULT_PACING): string {
if (lang !== null) {
- return [budgetIntro(minutes), ...budgetForMinutes(minutes, lang).notes.map((n) => `- ${n}`)].join("\n");
+ return [
+ budgetIntro(minutes, pacing),
+ ...budgetForMinutes(minutes, lang, { pacing }).notes.map((n) => `- ${n}`),
+ ].join("\n");
}
const lines = PACK_LANGUAGES.map((l) => {
- const b = budgetForMinutes(minutes, l);
+ const b = budgetForMinutes(minutes, l, { pacing });
return `- ${LANGUAGE_NAMES[l]} pack (\`${l}\`): ${range(b.walkthroughSteps)} walkthrough steps and ${range(b.words)} player-visible words in the whole pack.`;
});
return [
- budgetIntro(minutes),
+ budgetIntro(minutes, pacing),
...lines,
'- About a quarter of the steps are dialogue choices; about 60% of the words appear along the walkthrough, the rest in optional descriptions, dialogue branches and custom responses (see "Length budget" in the guide).',
].join("\n");
}
-/** The size budget table for 15/30/45/60 minutes (and the requested length), as Markdown (one-shot prompt). */
-export function renderBudgetTable(minutes: number, lang: PackLanguage | null): string {
+/**
+ * The size budget table for 15/30/45/60 minutes (and the requested length) and every pacing (or the given
+ * one), as Markdown (one-shot prompt).
+ */
+export function renderBudgetTable(minutes: number, lang: PackLanguage | null, pacing: Pacing | null = null): string {
const rows = [...new Set([...BUDGET_TABLE_MINUTES, minutes])].sort((a, b) => a - b);
const langs = lang === null ? [...PACK_LANGUAGES] : [lang];
- const budgets = (m: number): PlaytimeBudget[] => langs.map((l) => budgetForMinutes(m, l));
+ const pacings: readonly Pacing[] = pacing === null ? PACINGS : [pacing];
+ const budgets = (m: number, p: Pacing): PlaytimeBudget[] => langs.map((l) => budgetForMinutes(m, l, { pacing: p }));
const head =
langs.length === 1
- ? ["| Play time | Walkthrough steps | Words of text |", "|---|---|---|"]
+ ? ["| Play time | Pacing | Walkthrough steps | Words of text |", "|---|---|---|---|"]
: [
- `| Play time | ${langs.map((l) => `\`${l}\`: walkthrough steps | \`${l}\`: words of text`).join(" | ")} |`,
- `|---|${langs.map(() => "---|---|").join("")}`,
+ `| Play time | Pacing | ${langs.map((l) => `\`${l}\`: walkthrough steps | \`${l}\`: words of text`).join(" | ")} |`,
+ `|---|---|${langs.map(() => "---|---|").join("")}`,
];
- const body = rows.map(
- (m) =>
- `| ${m} min | ${budgets(m)
- .map((b) => `${range(b.walkthroughSteps)} | ${range(b.words)}`)
- .join(" | ")} |`,
+ const body = rows.flatMap((m) =>
+ pacings.map(
+ (p) =>
+ `| ${m} min | ${p} | ${budgets(m, p)
+ .map((b) => `${range(b.walkthroughSteps)} | ${range(b.words)}`)
+ .join(" | ")} |`,
+ ),
);
return [...head, ...body].join("\n");
}
+function describePacing(pacing: Pacing | null | undefined): string {
+ const p = pacing ?? DEFAULT_PACING;
+ return `\`${p}\` (about ${Math.round(PACING_READING_SHARE[p] * 100)}% of the play time is reading)`;
+}
+
function provenance(inputs: PromptInputs): { AUTHOR: string; LICENSE: string; GENERATOR: string } {
const license = inputs.license ?? DEFAULT_LICENSE;
const author =
@@ -191,14 +227,18 @@ export function promptVars(kit: PromptKit, inputs: PromptInputs): Record 0 ? renderBudget(inputs.minutes, inputs.lang) : "",
- BUDGET_TABLE: inputs.minutes > 0 ? renderBudgetTable(inputs.minutes, inputs.lang) : "",
+ PACING: describePacing(inputs.pacing),
+ PACING_ID: inputs.pacing ?? DEFAULT_PACING,
+ BUDGET: inputs.minutes > 0 ? renderBudget(inputs.minutes, inputs.lang, inputs.pacing ?? DEFAULT_PACING) : "",
+ BUDGET_TABLE: inputs.minutes > 0 ? renderBudgetTable(inputs.minutes, inputs.lang, inputs.pacing ?? null) : "",
IDEA: renderIdea(inputs.idea),
PACK_ID: inputs.packId
? `\`${inputs.packId}\``
: "a short kebab-case id derived from the title (e.g. `hamburg-1948`)",
CONCEPT: renderDoc("concept.md", inputs.concept, "concept"),
+ STORY: renderDoc("story.md", inputs.story, "story"),
PUZZLES: renderDoc("puzzles.md", inputs.puzzles, "puzzle design"),
+ TRANSCRIPT: renderTranscript(inputs.transcript),
FILES: renderFiles(inputs.files),
DIAGNOSTICS: renderDiagnostics(inputs.diagnostics),
...provenance(inputs),
diff --git a/packages/cli/src/generate/index.ts b/packages/cli/src/generate/index.ts
index ba5a8e6..0f64b99 100644
--- a/packages/cli/src/generate/index.ts
+++ b/packages/cli/src/generate/index.ts
@@ -11,8 +11,9 @@
import { readFile } from "node:fs/promises";
import { basename, resolve } from "node:path";
import { parseArgs } from "node:util";
+import { DEFAULT_PACING, type Pacing } from "@lexvm/engine";
import { clean } from "../term.ts";
-import { DEFAULT_LICENSE, DEFAULT_MINUTES, PACK_LANGUAGES, type PackLanguage } from "./assemble.ts";
+import { DEFAULT_LICENSE, DEFAULT_MINUTES, PACINGS, PACK_LANGUAGES, type PackLanguage } from "./assemble.ts";
import { loadPromptKit, type PromptKit } from "./kit.ts";
import { type CompleteFn, createAnthropicComplete, EFFORTS, type Effort, LlmError } from "./llm.ts";
import {
@@ -31,8 +32,9 @@ export const DEFAULT_MAX_TOKENS = 64_000;
export const GENERATE_USAGE = `Usage: lexvm generate --idea "" --out packs/ [options]
-Generates a content pack with the Anthropic API in stages (concept, puzzles,
-world, logic) and repairs it until it passes all verification gates.
+Generates a content pack with the Anthropic API in stages (concept, story,
+puzzles, world, logic), repairs it until it passes all verification gates,
+then runs one editorial review round on the walkthrough transcript.
Required:
--idea The story idea, in any language (or --idea-file )
@@ -42,9 +44,12 @@ Options:
--lang Pack language (default: the language of the idea)
--minutes Target play time in minutes (default ${DEFAULT_MINUTES}); becomes the pack's playtime,
sizes the prompts' budget and is checked by the play time estimate
+ --pacing ${PACINGS.join("|")} (default ${DEFAULT_PACING}): share of the time spent reading
+ (about 60/45/30%); becomes the pack's pacing and sizes the budget
+ --no-review Skip the editorial review round after the pack passes
--model Claude model id (or set LEXVM_MODEL)
--max-repairs Repair rounds after the first check (default ${DEFAULT_MAX_REPAIRS})
- --from-stage Resume at concept|puzzles|world|logic|verify, reusing earlier artifacts
+ --from-stage Resume at concept|story|puzzles|world|logic|verify, reusing earlier artifacts
--max-states State limit for the exploration gate (default ${DEFAULT_MAX_STATES})
--max-tokens Output token limit per request (default ${DEFAULT_MAX_TOKENS})
--effort Effort level: ${EFFORTS.join("|")} (default: the model's default)
@@ -132,6 +137,11 @@ export async function runGenerate(argv: string[], deps: GenerateCliDeps = {}): P
}
const lang = values.lang !== undefined ? parseLang(values.lang) : (previous?.params.lang ?? null);
const minutes = int(values.minutes, "minutes", previous?.params.minutes ?? DEFAULT_MINUTES, 5, 240);
+ if (values.pacing !== undefined && !(PACINGS as readonly string[]).includes(values.pacing)) {
+ throw new UsageError(`--pacing must be one of: ${PACINGS.join(", ")}`);
+ }
+ const pacing = (values.pacing as Pacing | undefined) ?? previous?.params.pacing ?? DEFAULT_PACING;
+ const review = values["no-review"] ? false : (previous?.params.review ?? true);
const maxRepairs = int(values["max-repairs"], "max-repairs", DEFAULT_MAX_REPAIRS, 0, 50);
const maxStates = int(values["max-states"], "max-states", DEFAULT_MAX_STATES, 100, 50_000_000);
const maxTokens = int(values["max-tokens"], "max-tokens", DEFAULT_MAX_TOKENS, 1024, 1_000_000);
@@ -171,10 +181,10 @@ export async function runGenerate(argv: string[], deps: GenerateCliDeps = {}): P
const kit = deps.kit ?? (await loadPromptKit());
log(
- `lexvm generate: ${values.out} (language: ${lang ?? "from the idea"}, about ${minutes} min, from stage ${fromStage})`,
+ `lexvm generate: ${values.out} (language: ${lang ?? "from the idea"}, about ${minutes} min, pacing ${pacing}, from stage ${fromStage})`,
);
const result = await generatePack(
- { idea, lang, minutes, outDir, packId, author, license, maxRepairs, maxStates, fromStage },
+ { idea, lang, minutes, pacing, review, outDir, packId, author, license, maxRepairs, maxStates, fromStage },
{ kit, complete, verify: deps.verify ?? engineVerify, log, ...(deps.now ? { now: deps.now } : {}) },
);
if (result.ok) {
@@ -216,6 +226,8 @@ function parse(argv: string[]) {
"idea-file": { type: "string" },
lang: { type: "string" },
minutes: { type: "string" },
+ pacing: { type: "string" },
+ "no-review": { type: "boolean" },
out: { type: "string" },
model: { type: "string" },
"max-repairs": { type: "string" },
diff --git a/packages/cli/src/generate/kit.ts b/packages/cli/src/generate/kit.ts
index 4ff295d..69c0f66 100644
--- a/packages/cli/src/generate/kit.ts
+++ b/packages/cli/src/generate/kit.ts
@@ -11,7 +11,17 @@ import { fileURLToPath } from "node:url";
/** Repository root, derived from this file's location (packages/cli/src/generate). */
export const REPO_ROOT = resolve(fileURLToPath(new URL("../../../../", import.meta.url)));
-export const TEMPLATE_NAMES = ["oneshot", "system", "concept", "puzzles", "world", "logic", "repair"] as const;
+export const TEMPLATE_NAMES = [
+ "oneshot",
+ "system",
+ "concept",
+ "story",
+ "puzzles",
+ "world",
+ "logic",
+ "repair",
+ "review",
+] as const;
export type TemplateName = (typeof TEMPLATE_NAMES)[number];
export interface PromptKit {
diff --git a/packages/cli/src/generate/pipeline.ts b/packages/cli/src/generate/pipeline.ts
index 9499fa2..9c95428 100644
--- a/packages/cli/src/generate/pipeline.ts
+++ b/packages/cli/src/generate/pipeline.ts
@@ -1,7 +1,13 @@
/**
* The staged generation pipeline behind `lexvm generate`:
*
- * concept -> puzzles -> world -> logic -> verify/repair loop
+ * concept -> story -> puzzles -> world -> logic -> verify/repair loop -> review
+ *
+ * The story stage writes the narrative backbone (design/story.md) before any
+ * puzzle exists, so the later stages derive their texts from scenes instead of
+ * inventing them field by field. Once the pack passes every gate, one
+ * editorial review round reads the walkthrough transcript and improves the
+ * text; the result is verified again like any repair (ADR 0012).
*
* Every stage's prompt includes the outputs of the previous stages, every
* artifact is written to the output directory as soon as it exists, and
@@ -14,7 +20,7 @@
*/
import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { join, relative, resolve, sep } from "node:path";
-import type { Diagnostic, SourceFile } from "@lexvm/engine";
+import type { Diagnostic, Pacing, SourceFile } from "@lexvm/engine";
import {
buildStagePrompt,
buildSystemPrompt,
@@ -33,7 +39,7 @@ import {
type VerifyFn,
} from "./verify.ts";
-export const STAGES = ["concept", "puzzles", "world", "logic", "verify"] as const;
+export const STAGES = ["concept", "story", "puzzles", "world", "logic", "verify"] as const;
export type Stage = (typeof STAGES)[number];
export const DESIGN_DIR = "design";
@@ -47,7 +53,15 @@ export const DEFAULT_MAX_REPAIRS = 6;
* remaining rounds cannot fix it, the last passing files are restored.
*/
export const LENGTH_REPAIRS = 1;
-const LENGTH_CODES: ReadonlySet = new Set(["playtime.too-short", "playtime.too-long"]);
+/** Play time warnings the length round acts on: the length, and the reading share of the pacing. */
+const LENGTH_CODES: ReadonlySet = new Set(["playtime.too-short", "playtime.too-long", "playtime.pacing"]);
+/**
+ * Editorial review rounds: once the pack passes every gate (and the length
+ * round is spent), the model reads the walkthrough transcript and improves the
+ * text. Counted against --max-repairs; if it breaks the pack and the
+ * remaining rounds cannot fix it, the last passing files are restored.
+ */
+export const REVIEW_ROUNDS = 1;
/** Files each file-producing stage is asked for. */
export const STAGE_FILES = {
@@ -60,6 +74,10 @@ export interface GenerateParams {
idea: string;
lang: PackLanguage | null;
minutes: number;
+ /** How the play time divides between reading and acting; written to pack.yaml like playtime. */
+ pacing: Pacing;
+ /** Run the editorial review round on the transcript once the pack passes. */
+ review: boolean;
/** Output directory (packs/). */
outDir: string;
packId: string;
@@ -100,7 +118,7 @@ export class PipelineError extends Error {
// ---------------------------------------------------------------------------
export interface RunEvent {
- stage: Exclude | "verify" | "repair";
+ stage: Exclude | "verify" | "repair" | "review";
round?: number;
startedAt: string;
finishedAt: string;
@@ -121,6 +139,9 @@ export interface RunLog {
idea: string;
lang: PackLanguage | null;
minutes: number;
+ /** Missing in run logs written before pacing existed. */
+ pacing?: Pacing;
+ review?: boolean;
author: string | null;
license: string;
maxRepairs: number;
@@ -229,12 +250,26 @@ export function withPlaytime(yaml: string, minutes: number): string {
return `${line}\n${yaml}`;
}
-/** Make pack.yaml carry the --minutes target as `playtime`. Returns true when the file changed. */
-export async function ensurePlaytime(outDir: string, minutes: number): Promise {
+/** Set the top-level `pacing` of a pack.yaml text, replacing an existing value or adding it after `playtime`. */
+export function withPacing(yaml: string, pacing: Pacing): string {
+ const line = `pacing: ${pacing}`;
+ const existing = /^pacing:[^\n]*$/m;
+ if (existing.test(yaml)) return yaml.replace(existing, line);
+ const m = /^playtime:[^\n]*$/m.exec(yaml);
+ if (m) {
+ const end = m.index + m[0].length;
+ return `${yaml.slice(0, end)}\n${line}${yaml.slice(end)}`;
+ }
+ return `${line}\n${yaml}`;
+}
+
+/** Make pack.yaml carry the --minutes target as `playtime` and the --pacing. Returns true when the file changed. */
+export async function ensurePlaytime(outDir: string, minutes: number, pacing?: Pacing): Promise {
const path = join(outDir, "pack.yaml");
const text = await readOptional(path);
if (text === null) return false;
- const updated = withPlaytime(text, minutes);
+ const timed = withPlaytime(text, minutes);
+ const updated = pacing === undefined ? timed : withPacing(timed, pacing);
if (updated === text) return false;
await writeFile(path, updated, "utf8");
return true;
@@ -278,6 +313,8 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
idea: params.idea,
lang: params.lang,
minutes: params.minutes,
+ pacing: params.pacing,
+ review: params.review,
author: params.author,
license: params.license,
maxRepairs: params.maxRepairs,
@@ -293,6 +330,8 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
idea: params.idea || runLog.params.idea,
lang: params.lang,
minutes: params.minutes,
+ pacing: params.pacing,
+ review: params.review,
author: params.author,
license: params.license,
maxRepairs: params.maxRepairs,
@@ -313,6 +352,7 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
lang: params.lang,
idea: params.idea,
minutes: params.minutes,
+ pacing: params.pacing,
packId: params.packId,
author: params.author,
license: params.license,
@@ -370,7 +410,7 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
};
/** A stage whose answer is a Markdown document. */
- const documentStage = async (stage: "concept" | "puzzles", label: string, prompt: string, name: string) => {
+ const documentStage = async (stage: "concept" | "story" | "puzzles", label: string, prompt: string, name: string) => {
for (let attempt = 0; attempt < 2; attempt++) {
const retryNote =
attempt === 0 ? "" : "\n\nYour previous answer was empty. Answer with the complete Markdown document.\n";
@@ -446,10 +486,10 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
const total = STAGES.length;
const tag = (stage: Stage) => `[${STAGES.indexOf(stage) + 1}/${total}] ${stage}`;
const runs = (stage: Stage) => STAGES.indexOf(stage) >= startIndex;
- /** The --minutes target is the pack's playtime: written in the metadata (world) stage, kept through repairs. */
+ /** The --minutes target is the pack's playtime and --pacing its pacing: written in the world stage, kept through repairs. */
const syncPlaytime = async () => {
- if (await ensurePlaytime(outDir, params.minutes))
- log(` set playtime: ${params.minutes} in pack.yaml (the --minutes target)`);
+ if (await ensurePlaytime(outDir, params.minutes, params.pacing))
+ log(` set playtime: ${params.minutes} and pacing: ${params.pacing} in pack.yaml (--minutes, --pacing)`);
};
try {
@@ -461,15 +501,22 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
"concept.md",
);
}
+ if (runs("story")) {
+ const concept = await requireDoc("concept.md", "story");
+ const prompt = buildStagePrompt(deps.kit, "story", { ...inputs(), concept });
+ await documentStage("story", `${tag("story")} âŠ`, prompt, "story.md");
+ }
if (runs("puzzles")) {
const concept = await requireDoc("concept.md", "puzzles");
- const prompt = buildStagePrompt(deps.kit, "puzzles", { ...inputs(), concept });
+ const story = await requireDoc("story.md", "puzzles");
+ const prompt = buildStagePrompt(deps.kit, "puzzles", { ...inputs(), concept, story });
await documentStage("puzzles", `${tag("puzzles")} âŠ`, prompt, "puzzles.md");
}
if (runs("world")) {
const concept = await requireDoc("concept.md", "world");
+ const story = await requireDoc("story.md", "world");
const puzzles = await requireDoc("puzzles.md", "world");
- const prompt = buildStagePrompt(deps.kit, "world", { ...inputs(), concept, puzzles });
+ const prompt = buildStagePrompt(deps.kit, "world", { ...inputs(), concept, story, puzzles });
await filesStage("world", `${tag("world")} âŠ`, prompt, {
expected: STAGE_FILES.world,
allowed: ["yaml"],
@@ -480,12 +527,19 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
}
if (runs("logic")) {
const concept = await requireDoc("concept.md", "logic");
+ const story = await requireDoc("story.md", "logic");
const puzzles = await requireDoc("puzzles.md", "logic");
const files = await readPackFiles(outDir);
if (!files.some((f) => f.name === "pack.yaml")) {
throw new PipelineError("stage 'logic' needs pack.yaml; run the world stage first (--from-stage world)");
}
- const prompt = buildStagePrompt(deps.kit, "logic", { ...inputs(), concept, puzzles, files: asNamed(files) });
+ const prompt = buildStagePrompt(deps.kit, "logic", {
+ ...inputs(),
+ concept,
+ story,
+ puzzles,
+ files: asNamed(files),
+ });
await filesStage("logic", `${tag("logic")} âŠ`, prompt, {
expected: STAGE_FILES.logic,
allowed: ["yaml"],
@@ -499,10 +553,14 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
throw new PipelineError(`no pack files in ${outDir}; run an earlier stage first (--from-stage world)`);
}
const concept = await readDoc("concept.md");
+ const story = await readDoc("story.md");
const puzzles = await readDoc("puzzles.md");
let round = 0;
let lastCrash = "";
let lengthRounds = 0;
+ let reviewRounds = 0;
+ let next: "repair" | "review" = "repair";
+ let transcript = "";
/** The last version that passed every gate, kept while a length round tries to improve it. */
let passing: {
files: SourceFile[];
@@ -537,14 +595,24 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
if (report.ok) {
const length = report.diagnostics.find((d) => LENGTH_CODES.has(d.code));
- if (!length || lengthRounds >= LENGTH_REPAIRS || round >= params.maxRepairs) {
+ const roundsLeft = round < params.maxRepairs;
+ if (length && lengthRounds < LENGTH_REPAIRS && roundsLeft) {
+ // Passing, but the wrong length: one more round on the length, keeping this version as a fallback.
+ passing = { files, diagnostics: report.diagnostics, counts: pick(counts) };
+ lengthRounds++;
+ next = "repair";
+ log(` ${formatDiagnostic(length)}`);
+ } else if (params.review && reviewRounds < REVIEW_ROUNDS && roundsLeft && report.transcript !== undefined) {
+ // Passing: one editorial round on the transcript, keeping this version as a fallback.
+ passing = { files, diagnostics: report.diagnostics, counts: pick(counts) };
+ reviewRounds++;
+ next = "review";
+ transcript = report.transcript;
+ } else {
return await succeed(report.diagnostics, counts);
}
- // Passing, but the wrong length: one more round on the length, keeping this version as a fallback.
- passing = { files, diagnostics: report.diagnostics, counts: pick(counts) };
- lengthRounds++;
- log(` ${formatDiagnostic(length)}`);
} else {
+ next = "repair";
for (const d of report.diagnostics.filter((x) => x.severity === "error").slice(0, 5)) {
log(` ${formatDiagnostic(d)}`);
}
@@ -560,7 +628,7 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
if (round >= params.maxRepairs) {
if (passing) {
await restorePackFiles(outDir, passing.files);
- log(" the length repair broke the pack; restored the last passing version");
+ log(" the length or review round broke the pack; restored the last passing version");
runLog.events.push({
stage: "verify",
round,
@@ -568,7 +636,7 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
finishedAt: now().toISOString(),
durationMs: 0,
diagnostics: countSeverities(passing.diagnostics),
- notes: ["restored the last passing version after an unsuccessful length repair"],
+ notes: ["restored the last passing version after an unsuccessful length or review round"],
});
return await succeed(passing.diagnostics, passing.counts);
}
@@ -584,9 +652,20 @@ export async function generatePack(params: GenerateParams, deps: PipelineDeps):
}
}
round++;
+ if (next === "review") {
+ const prompt = buildStagePrompt(deps.kit, "review", { ...inputs(), story, files: asNamed(files), transcript });
+ await filesStage("review", ` review (round ${round}/${params.maxRepairs}) âŠ`, prompt, {
+ expected: [],
+ allowed: ["yaml"],
+ required: false,
+ round,
+ });
+ continue;
+ }
const prompt = buildStagePrompt(deps.kit, "repair", {
...inputs(),
concept,
+ story,
puzzles,
files: asNamed(files),
diagnostics: formatDiagnosticsForPrompt(report.diagnostics),
diff --git a/packages/cli/src/generate/prompt.ts b/packages/cli/src/generate/prompt.ts
index b9a1159..42eb724 100644
--- a/packages/cli/src/generate/prompt.ts
+++ b/packages/cli/src/generate/prompt.ts
@@ -2,8 +2,9 @@
* `lexvm prompt`: assemble the prompt kit (spec + guide + example) for
* copy-paste use with any LLM. Owned by the pipeline workstream.
*
- * lexvm prompt [--stage oneshot|concept|puzzles|world|logic|repair] [--lang de|en]
- * [--idea "..."] [--minutes 30] [--pack ] [--diagnostics ] [--out ]
+ * lexvm prompt [--stage oneshot|concept|story|puzzles|world|logic|repair|review] [--lang de|en]
+ * [--idea "..."] [--minutes 30] [--pacing narrative|balanced|puzzle] [--pack ]
+ * [--diagnostics ] [--out ]
*
* `npm run prompts` runs `--stage oneshot --out prompts/oneshot.md`, the
* generic prompt bundled by the web app.
@@ -11,11 +12,13 @@
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import { parseArgs } from "node:util";
+import { compile, type Pacing, walkthroughTranscript } from "@lexvm/engine";
import { clean } from "../term.ts";
import {
assemblePrompt,
DEFAULT_MINUTES,
type NamedText,
+ PACINGS,
PACK_LANGUAGES,
type PackLanguage,
PROMPT_STAGES,
@@ -36,8 +39,12 @@ Options:
--lang Pack language (default: the language of the idea)
--idea The story idea (or --idea-file ); omitted = generic prompt
--minutes Target play time in minutes (default ${DEFAULT_MINUTES}); sizes the budget in the prompt
- --pack Existing pack directory or YAML file to include (later stages, repair)
+ --pacing ${PACINGS.join("|")}: how the time divides between reading and acting
+ (default: the pack's pacing, else balanced; the one-shot prompt lets the model choose)
+ --pack Existing pack directory or YAML file to include (later stages, repair, review)
--diagnostics Diagnostics to include in a repair prompt (default: run the checks on --pack)
+
+The review stage includes the walkthrough transcript of --pack (lexvm transcript).
--out Write to a file instead of stdout
`;
@@ -53,9 +60,11 @@ class UsageError extends Error {}
interface PackInputs {
concept: string | null;
+ story: string | null;
puzzles: string | null;
files: NamedText[];
language: string | null;
+ pacing: Pacing | null;
}
async function readPack(path: string): Promise {
@@ -73,19 +82,33 @@ async function readPack(path: string): Promise {
const pack = files.find((f) => f.name === "pack.yaml");
return {
concept: await read("concept.md"),
+ story: await read("story.md"),
puzzles: await read("puzzles.md"),
files,
language: pack ? languageOf(pack.content) : null,
+ pacing: pack ? pacingOf(pack.content) : null,
};
}
const content = await readFile(path, "utf8");
- return { concept: null, puzzles: null, files: [{ name: basename(path), content }], language: languageOf(content) };
+ return {
+ concept: null,
+ story: null,
+ puzzles: null,
+ files: [{ name: basename(path), content }],
+ language: languageOf(content),
+ pacing: pacingOf(content),
+ };
}
function languageOf(yaml: string): string | null {
return /^language:\s*["']?([a-z]{2,3})\b/m.exec(yaml)?.[1] ?? null;
}
+function pacingOf(yaml: string): Pacing | null {
+ const value = /^pacing:\s*["']?([a-z]+)\b/m.exec(yaml)?.[1];
+ return (PACINGS as readonly string[]).includes(value ?? "") ? (value as Pacing) : null;
+}
+
export async function runPrompt(argv: string[], deps: PromptCliDeps = {}): Promise {
// A pack's text is untrusted: no control characters reach a terminal (a file or pipe gets the prompt as is).
const log = deps.log ?? ((line: string) => process.stderr.write(`${clean(line)}\n`));
@@ -123,13 +146,28 @@ export async function runPrompt(argv: string[], deps: PromptCliDeps = {}): Promi
let idea: string | null = values.idea ?? null;
if (values["idea-file"]) idea = await readFile(resolve(cwd, values["idea-file"]), "utf8");
- const inputs: PromptInputs = { lang: (values.lang as PackLanguage | undefined) ?? null, idea, minutes };
+ if (values.pacing !== undefined && !(PACINGS as readonly string[]).includes(values.pacing)) {
+ throw new UsageError(`--pacing must be one of: ${PACINGS.join(", ")}`);
+ }
+ const inputs: PromptInputs = {
+ lang: (values.lang as PackLanguage | undefined) ?? null,
+ idea,
+ minutes,
+ pacing: (values.pacing as Pacing | undefined) ?? null,
+ };
if (values.pack) {
const packPath = resolve(cwd, values.pack);
const pack = await readPack(packPath);
inputs.concept = pack.concept;
+ inputs.story = pack.story;
inputs.puzzles = pack.puzzles;
inputs.files = pack.files;
+ if (inputs.pacing === null) inputs.pacing = pack.pacing;
+ if (stage === "review") {
+ const compiled = compile(pack.files.map((f) => ({ name: f.name, text: f.content })));
+ if (compiled.pack === null) log("lexvm prompt: the pack does not compile; paste the transcript by hand.");
+ else inputs.transcript = walkthroughTranscript(compiled.pack).markdown;
+ }
if (inputs.lang === null && (pack.language === "de" || pack.language === "en")) inputs.lang = pack.language;
const dirName = basename(packPath);
if ((await stat(packPath)).isDirectory() && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(dirName)) inputs.packId = dirName;
@@ -183,6 +221,7 @@ function parse(argv: string[]) {
idea: { type: "string" },
"idea-file": { type: "string" },
minutes: { type: "string" },
+ pacing: { type: "string" },
pack: { type: "string" },
diagnostics: { type: "string" },
out: { type: "string" },
diff --git a/packages/cli/src/generate/verify.ts b/packages/cli/src/generate/verify.ts
index 7140a77..5917bab 100644
--- a/packages/cli/src/generate/verify.ts
+++ b/packages/cli/src/generate/verify.ts
@@ -5,7 +5,15 @@
* first gate with errors, so a repair round focuses on the earliest problems
* (as `lexvm check` does).
*/
-import { analyze, compile, type Diagnostic, estimatePlaytime, runWalkthrough, type SourceFile } from "@lexvm/engine";
+import {
+ analyze,
+ compile,
+ type Diagnostic,
+ estimatePlaytime,
+ runWalkthrough,
+ type SourceFile,
+ walkthroughTranscript,
+} from "@lexvm/engine";
import { verifyExploration } from "../exploration.ts";
import { walkthroughFallbacks } from "../fallbacks.ts";
@@ -25,6 +33,8 @@ export interface VerifyReport {
ok: boolean;
diagnostics: Diagnostic[];
gates: GateResult[];
+ /** The walkthrough as the player reads it (lexvm transcript), once the walkthrough gate passed. */
+ transcript?: string;
}
export interface VerifyOptions {
@@ -106,6 +116,7 @@ export const engineVerify: VerifyFn = (files, options) => {
}
// Gate 2: walkthrough replay, then the play time estimate (it replays the walkthrough as well).
+ let transcript: string | undefined;
try {
const report = runWalkthrough(pack);
diags = [...report.diagnostics, ...walkthroughFallbacks(pack, report, all)];
@@ -115,6 +126,7 @@ export const engineVerify: VerifyFn = (files, options) => {
options.targetMinutes === undefined ? {} : { targetMinutes: options.targetMinutes },
);
diags.push(...estimate.diagnostics);
+ transcript = walkthroughTranscript(pack).markdown;
}
} catch (err) {
diags = [crash("walkthrough", err)];
@@ -134,7 +146,12 @@ export const engineVerify: VerifyFn = (files, options) => {
}
all.push(...diags);
gates.push(gateResult("exploration", diags));
- return { ok: count(all, "error") === 0, diagnostics: all, gates };
+ return {
+ ok: count(all, "error") === 0,
+ diagnostics: all,
+ gates,
+ ...(transcript === undefined ? {} : { transcript }),
+ };
};
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 48db9b1..8710b4d 100755
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -10,6 +10,7 @@ import { runCheck } from "./commands/check.ts";
import { runNew } from "./commands/new.ts";
import { runPlay } from "./commands/play.ts";
import { runSchema } from "./commands/schema.ts";
+import { runTranscript } from "./commands/transcript.ts";
import { runValidate } from "./commands/validate.ts";
import { err, out } from "./term.ts";
@@ -22,6 +23,7 @@ Commands:
build Compile content packs to .lexpack.json plus index.json
check validate + walkthrough replay + state-space exploration
play Play a content pack in the terminal
+ transcript Print the walkthrough as a reader sees it (for story review)
new Scaffold a new content pack
schema Write the JSON Schema of the content pack format
prompt Assemble the prompt kit for any LLM
@@ -43,6 +45,7 @@ const COMMANDS: Record = {
build: runBuild,
check: runCheck,
play: runPlay,
+ transcript: runTranscript,
new: runNew,
schema: runSchema,
// Owned by the generation pipeline; loaded lazily so the other commands never need the API client.
diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.ts
index bbaeed4..ae08112 100644
--- a/packages/cli/test/cli.test.ts
+++ b/packages/cli/test/cli.test.ts
@@ -210,7 +210,7 @@ describe("lexvm build", () => {
packs: Array<{ id: string; playtime?: number; estimatedMinutes?: number }>;
};
const entry = index.packs.find((p) => p.id === "locked-study")!;
- expect(entry.playtime).toBe(5);
+ expect(entry.playtime).toBe(7);
expect(Number.isInteger(entry.estimatedMinutes)).toBe(true);
expect(entry.estimatedMinutes).toBeGreaterThanOrEqual(4);
expect(entry.estimatedMinutes).toBeLessThanOrEqual(8);
@@ -273,6 +273,23 @@ describe("lexvm schema", () => {
);
});
+describe("lexvm transcript", () => {
+ it(
+ "prints the walkthrough as Markdown and writes it to a file",
+ () => {
+ const r = lexvm(["transcript", LOCKED_STUDY]);
+ expect(r.code).toBe(0);
+ expect(r.stdout).toMatch(/^# The Locked Study\n/);
+ expect(r.stdout).toContain("## Entrance Hall");
+ expect(r.stdout).toContain("> Talk to Graves");
+ const file = join(tmp, "transcript.md");
+ expect(lexvm(["transcript", LOCKED_STUDY, "--out", file]).code).toBe(0);
+ expect(readFileSync(file, "utf8")).toBe(r.stdout);
+ },
+ TIMEOUT,
+ );
+});
+
describe("lexvm play", () => {
it.skipIf(!runtimeReady)(
"replays canonical commands and prints the transcript",
@@ -458,7 +475,9 @@ describe("lexvm check", () => {
() => {
const r = lexvm(["check", "--no-explore", "packs/locked-study"]);
expect(r.code, r.stdout + r.stderr).toBe(0);
- expect(r.stdout).toMatch(/ {2}playtime {6}â \d+ min expected, speedrun \d+ min, target 5 min \([+-]\d+%\)/);
+ expect(r.stdout).toMatch(
+ / {2}playtime {6}â \d+ min expected, speedrun \d+ min, target 7 min \([+-]\d+%\); \d+ words, \d+ wpm, reading \d+%/,
+ );
expect(r.stdout).toContain("playtime.estimate");
expect(r.stdout).not.toContain("playtime.too-");
diff --git a/packages/cli/test/generate-playtime.test.ts b/packages/cli/test/generate-playtime.test.ts
index 46909d4..f9760ca 100644
--- a/packages/cli/test/generate-playtime.test.ts
+++ b/packages/cli/test/generate-playtime.test.ts
@@ -47,6 +47,7 @@ function fakeLlm() {
const calls: Array<{ stage: string; prompt: string }> = [];
const answers: Record string> = {
concept: () => "# The Locked Study\n\nA concept.",
+ story: () => "# Story\n\nThe truth.",
puzzles: () => "# Puzzles\n\nA chart.",
world: () => block("pack.yaml", example.replace(/^playtime: \d+\n/m, "")),
logic: () => block("notes.yaml", "# nothing to add\n"),
@@ -111,7 +112,7 @@ describe("lexvm generate: play time", () => {
expect(seen).toHaveLength(1);
expect(seen[0]!.options).toMatchObject({ targetMinutes: 12 });
expect(seen[0]!.pack).toContain("playtime: 12");
- expect(logs.join("\n")).toContain("set playtime: 12 in pack.yaml");
+ expect(logs.join("\n")).toContain("set playtime: 12 and pacing: balanced in pack.yaml");
// The stage prompts carry the budget for the target.
expect(llm.calls.find((c) => c.stage === "world")!.prompt).toContain("Size budget for about 12 minutes");
});
@@ -188,7 +189,9 @@ describe("lexvm generate: play time", () => {
expect(await readFile(join(dir, "notes.yaml"), "utf8")).toBe("# nothing to add\n");
const run = JSON.parse(await readFile(join(dir, "design/run.json"), "utf8")) as RunLog;
expect(run.runs[0]!.result).toMatchObject({ ok: true, warnings: 1 });
- expect(run.events.at(-1)!.notes).toEqual(["restored the last passing version after an unsuccessful length repair"]);
+ expect(run.events.at(-1)!.notes).toEqual([
+ "restored the last passing version after an unsuccessful length or review round",
+ ]);
});
});
diff --git a/packages/cli/test/generate.test.ts b/packages/cli/test/generate.test.ts
index 5fde2fc..6fe5f1c 100644
--- a/packages/cli/test/generate.test.ts
+++ b/packages/cli/test/generate.test.ts
@@ -55,6 +55,7 @@ function fakeLlm(overrides: Partial string>>
const calls: Call[] = [];
const answers: Record string> = {
concept: () => "# The Locked Study\n\nCONCEPT_MARKER: an uncle, a butler, a locked door.",
+ story: () => "# Story\n\nSTORY_MARKER: the uncle hid in the cellar.",
puzzles: () =>
[
"Here is the puzzle design.",
@@ -185,7 +186,8 @@ beforeAll(async () => {
root = await mkdtemp(join(tmpdir(), "lexvm-generate-"));
const example = await readFile(join(REPO_ROOT, "packs/locked-study/pack.yaml"), "utf8");
blocks = splitTopLevel(example);
- topKeys = [...blocks.keys()];
+ // The pipeline adds pacing to pack.yaml (the example declares none).
+ topKeys = [...blocks.keys(), "pacing"];
});
afterAll(async () => {
@@ -206,7 +208,7 @@ describe("lexvm generate", () => {
expect(code, log).toBe(0);
// Stages ran in order; the repair loop ran once and terminated.
- expect(llm.calls.map((c) => c.stage)).toEqual(["concept", "puzzles", "world", "logic", "repair"]);
+ expect(llm.calls.map((c) => c.stage)).toEqual(["concept", "story", "puzzles", "world", "logic", "repair"]);
expect(verifier.seen).toHaveLength(2);
expect(verifier.seen[0]).toEqual([
"pack.yaml",
@@ -218,8 +220,10 @@ describe("lexvm generate", () => {
]);
// Every stage sees the outputs of the previous stages; the system prompt is shared (cacheable).
- const [concept, puzzles, world, logic, repair] = llm.calls;
+ const [concept, story, puzzles, world, logic, repair] = llm.calls;
expect(concept!.prompt).toContain(IDEA);
+ expect(story!.prompt).toContain("CONCEPT_MARKER");
+ for (const call of [puzzles, world, logic, repair]) expect(call!.prompt).toContain("STORY_MARKER");
expect(concept!.prompt).toContain("`locked-study`");
expect(puzzles!.prompt).toContain("CONCEPT_MARKER");
expect(world!.prompt).toContain("CONCEPT_MARKER");
@@ -257,6 +261,7 @@ describe("lexvm generate", () => {
expect(run.params.idea).toBe(IDEA);
expect(run.events.map((e) => (e.round === undefined ? e.stage : `${e.stage}#${e.round}`))).toEqual([
"concept",
+ "story",
"puzzles",
"world",
"logic",
@@ -264,17 +269,19 @@ describe("lexvm generate", () => {
"repair#1",
"verify#1",
]);
- expect(run.events[2]!.files).toEqual(["pack.yaml", "rooms.yaml", "objects.yaml"]);
- expect(run.events[4]!.diagnostics).toEqual({ errors: 1, warnings: 1, infos: 0 });
- expect(run.events[6]!.gates?.every((g) => g.status === "passed")).toBe(true);
- expect(run.totals.outputTokens).toBe(5 * 500);
+ expect(run.events[3]!.files).toEqual(["pack.yaml", "rooms.yaml", "objects.yaml"]);
+ expect(run.events[5]!.diagnostics).toEqual({ errors: 1, warnings: 1, infos: 0 });
+ expect(run.events[7]!.gates?.every((g) => g.status === "passed")).toBe(true);
+ expect(run.totals.outputTokens).toBe(6 * 500);
+ expect(await readFile(join(dir, "pack.yaml"), "utf8")).toMatch(/^pacing: balanced$/m);
+ expect(run.params.pacing).toBe("balanced");
expect(run.runs).toHaveLength(1);
expect(run.runs[0]!.result).toMatchObject({ ok: true, repairs: 1, errors: 0, warnings: 1 });
expect(run.events[0]!.durationMs).toBeGreaterThan(0);
// Progress went to the log; no secrets or model ids anywhere.
- expect(log).toContain("[1/5] concept");
- expect(log).toContain("[5/5] verify");
+ expect(log).toContain("[1/6] concept");
+ expect(log).toContain("[6/6] verify");
expect(log).toContain("12k characters received");
expect(log).toContain("OK:");
const written = await allText(dir);
@@ -306,6 +313,67 @@ describe("lexvm generate", () => {
expect(run.runs[0]!.result).toMatchObject({ ok: false, repairs: 2, errors: 1 });
});
+ it("runs one editorial review round on the transcript once the pack passes, unless --no-review", async () => {
+ const reviewed = (files: { name: string; text: string }[]) =>
+ files.find((f) => f.name === "rules.yaml")!.text.includes("# reviewed");
+ const passing = (): { verify: VerifyFn; seen: number } => {
+ const state = { seen: 0 };
+ const verify: VerifyFn = (files) => {
+ state.seen++;
+ return {
+ ok: true,
+ diagnostics: [],
+ gates: [{ gate: "compile", status: "passed", errors: 0, warnings: 0 }],
+ transcript: reviewed(files) ? "# after review" : "# Locked Study\n\nTRANSCRIPT_MARKER",
+ };
+ };
+ return {
+ verify,
+ get seen() {
+ return state.seen;
+ },
+ };
+ };
+ const review = (prompt: string) => {
+ expect(prompt).toContain("TRANSCRIPT_MARKER");
+ expect(prompt).toContain("STORY_MARKER");
+ return fileBlock("rules.yaml", `# reviewed\n${blocks.get("rules")!}`);
+ };
+
+ const dir = join(root, "case-review", "reviewed-pack");
+ const llm = fakeLlm({ review });
+ const v = passing();
+ const code = await runGenerate(["--idea", IDEA, "--out", dir, "--pacing", "narrative"], {
+ complete: llm.complete,
+ verify: v.verify,
+ env: ENV,
+ log: () => {},
+ kit,
+ });
+ expect(code).toBe(0);
+ expect(llm.calls.map((c) => c.stage)).toEqual(["concept", "story", "puzzles", "world", "logic", "review"]);
+ expect(v.seen).toBe(2);
+ expect(await readFile(join(dir, "rules.yaml"), "utf8")).toMatch(/^# reviewed/);
+ expect(await readFile(join(dir, "pack.yaml"), "utf8")).toMatch(/^pacing: narrative$/m);
+ expect(llm.calls[1]!.prompt).toContain("pacing: `narrative`");
+ const run = JSON.parse(await readFile(join(dir, "design/run.json"), "utf8")) as RunLog;
+ expect(run.events.map((e) => e.stage).slice(-3)).toEqual(["verify", "review", "verify"]);
+ expect(run.params).toMatchObject({ pacing: "narrative", review: true });
+
+ const skipDir = join(root, "case-review", "unreviewed-pack");
+ const skip = fakeLlm({ review });
+ expect(
+ await runGenerate(["--idea", IDEA, "--out", skipDir, "--no-review"], {
+ complete: skip.complete,
+ verify: passing().verify,
+ env: ENV,
+ log: () => {},
+ kit,
+ }),
+ ).toBe(0);
+ expect(skip.calls.map((c) => c.stage)).not.toContain("review");
+ });
+
it("resumes from a stage, reusing earlier artifacts and the stored idea", async () => {
const dir = join(root, "case-3", "resumed-pack");
const first = fakeLlm();
@@ -381,8 +449,8 @@ describe("lexvm generate", () => {
kit,
});
expect(code).toBe(1);
- expect(llm.calls.map((c) => c.stage)).toEqual(["concept", "puzzles", "world", "world"]);
- expect(llm.calls[3]!.prompt).toContain("no usable file blocks");
+ expect(llm.calls.map((c) => c.stage)).toEqual(["concept", "story", "puzzles", "world", "world"]);
+ expect(llm.calls[4]!.prompt).toContain("no usable file blocks");
expect(logs.join("\n")).toContain("produced no files");
const run = JSON.parse(await readFile(join(dir, "design/run.json"), "utf8")) as RunLog;
expect(run.runs[0]!.result?.failure).toContain("produced no files");
diff --git a/packages/cli/test/prompt.test.ts b/packages/cli/test/prompt.test.ts
index e99bb64..1a3dc44 100644
--- a/packages/cli/test/prompt.test.ts
+++ b/packages/cli/test/prompt.test.ts
@@ -7,6 +7,7 @@ import {
assemblePrompt,
BUDGET_TABLE_MINUTES,
buildSystemPrompt,
+ PACINGS,
PROMPT_STAGES,
type PromptInputs,
renderBudget,
@@ -50,6 +51,8 @@ const fullInputs: PromptInputs = {
license: "CC-BY-4.0",
pipeline: true,
concept: "# Concept\n\nNoir.",
+ story: "# Story\n\nSTORY_MARKER: the truth.",
+ transcript: "# Hamburg 1948\n\n## Kai\n\nTRANSCRIPT_MARKER",
puzzles: "# Puzzles\n\n```mermaid\nflowchart TD\n a --> b\n```",
files: [{ name: "pack.yaml", content: "format: lexvm-pack/1\n" }],
diagnostics: "[error] ref.unknown-object @ rules[0]: unknown object 'x'",
@@ -148,19 +151,26 @@ describe("assemblePrompt", () => {
it("gives the one-shot prompt a budget table for 15/30/45/60 minutes and both languages", () => {
const text = assemblePrompt(kit, "oneshot", { lang: null, idea: null, minutes: 30 });
- expect(text).toContain("Pick the row that matches the requested length (no length requested: 30 minutes");
- expect(text).toContain("| Play time | `de`: walkthrough steps | `de`: words of text | `en`: walkthrough steps |");
+ expect(text).toContain(
+ "Pick the row that matches the requested length and the pacing (no length requested: 30 minutes",
+ );
+ expect(text).toContain(
+ "| Play time | Pacing | `de`: walkthrough steps | `de`: words of text | `en`: walkthrough steps |",
+ );
for (const minutes of BUDGET_TABLE_MINUTES) {
- const de = budgetForMinutes(minutes, "de");
- const en = budgetForMinutes(minutes, "en");
- const row = text.split("\n").find((l) => l.startsWith(`| ${minutes} min |`));
- expect(row, `${minutes} min`).toBeDefined();
- expect(row).toContain(`${de.walkthroughSteps.min}â${de.walkthroughSteps.max}`);
- expect(row).toContain(`${en.walkthroughSteps.min}â${en.walkthroughSteps.max}`);
+ for (const pacing of PACINGS) {
+ const de = budgetForMinutes(minutes, "de", { pacing });
+ const en = budgetForMinutes(minutes, "en", { pacing });
+ const row = text.split("\n").find((l) => l.startsWith(`| ${minutes} min | ${pacing} |`));
+ expect(row, `${minutes} min ${pacing}`).toBeDefined();
+ expect(row).toContain(`${de.walkthroughSteps.min}â${de.walkthroughSteps.max}`);
+ expect(row).toContain(`${en.walkthroughSteps.min}â${en.walkthroughSteps.max}`);
+ }
}
- // A requested length outside the standard rows gets its own row; a known language gets one column pair.
+ // A requested length outside the standard rows gets its own rows; a known language gets one column pair.
const table = renderBudgetTable(40, "en");
- expect(table.split("\n")).toHaveLength(2 + 5);
+ expect(table.split("\n")).toHaveLength(2 + 5 * PACINGS.length);
+ expect(renderBudgetTable(40, "en", "narrative").split("\n")).toHaveLength(2 + 5);
expect(table).toContain("| 40 min |");
expect(table).not.toContain("`de`");
// The shared system prompt has no run-specific budget.
@@ -168,8 +178,8 @@ describe("assemblePrompt", () => {
});
it("puts the budget for --minutes into the stage prompts", () => {
- const b = budgetForMinutes(40, "de");
- for (const stage of ["concept", "puzzles", "world", "logic"] as const) {
+ const b = budgetForMinutes(40, "de", { pacing: "balanced" });
+ for (const stage of ["concept", "story", "puzzles", "world", "logic", "review"] as const) {
const text = assemblePrompt(kit, stage, fullInputs);
expect(text, stage).toContain("Size budget for about 40 minutes");
expect(text, stage).toContain(`${b.walkthroughSteps.min}â${b.walkthroughSteps.max} steps`);
@@ -179,9 +189,28 @@ describe("assemblePrompt", () => {
expect(both).toContain("German pack (`de`)");
expect(both).toContain("English pack (`en`)");
expect(assemblePrompt(kit, "world", fullInputs)).toContain("`playtime: 40` (the target play time; keep it)");
+ expect(assemblePrompt(kit, "world", fullInputs)).toContain("`pacing: balanced`");
+ const narrative = assemblePrompt(kit, "story", { ...fullInputs, pacing: "narrative" });
+ expect(narrative).toContain("pacing: `narrative` (about 60% of the play time is reading)");
+ expect(narrative).toContain(budgetForMinutes(40, "de", { pacing: "narrative" }).notes[1]!);
expect(assemblePrompt(kit, "repair", fullInputs)).toContain("`playtime.too-short`");
});
+ it("gives the story and review stages their inputs", () => {
+ const review = assemblePrompt(kit, "review", fullInputs);
+ expect(review).toContain("TRANSCRIPT_MARKER");
+ expect(review).toContain("STORY_MARKER");
+ expect(review).toContain("```yaml file=pack.yaml");
+ expect(review).toContain("story editor");
+ for (const stage of ["puzzles", "world", "logic", "repair"] as const) {
+ expect(assemblePrompt(kit, stage, fullInputs), stage).toContain("STORY_MARKER");
+ }
+ const story = assemblePrompt(kit, "story", fullInputs);
+ expect(story).toContain("Revelation map");
+ expect(story).toContain("# Concept\n\n");
+ expect(assemblePrompt(kit, "review", { ...fullInputs, transcript: null })).toContain("lexvm -- transcript");
+ });
+
it("contains no model identifiers", () => {
for (const stage of PROMPT_STAGES) {
expect(assemblePrompt(kit, stage, fullInputs)).not.toMatch(MODEL_ID);
@@ -220,7 +249,7 @@ describe("runPrompt", () => {
let out = "";
const logs: string[] = [];
expect(await runPrompt(["--stage", "concept", "--idea", "A lighthouse"], { stdout: (t) => (out += t) })).toBe(0);
- expect(out).toContain("# Stage 1 of 4: concept");
+ expect(out).toContain("# Stage 1 of 5: concept");
expect(out).toContain("> A lighthouse");
const target = join(tmp, "nested", "oneshot.md");
expect(await runPrompt(["--out", target, "--lang", "en"], { log: (l) => logs.push(l) })).toBe(0);
diff --git a/packages/engine/src/analyze-text.ts b/packages/engine/src/analyze-text.ts
index c4e708a..162a915 100644
--- a/packages/engine/src/analyze-text.ts
+++ b/packages/engine/src/analyze-text.ts
@@ -4,9 +4,9 @@
*/
import { markupRefs, type PackIndex, renderedText, textStrings, walkPack } from "./analyze-walk.ts";
import type { DiagnosticList } from "./diagnostics.ts";
-import type { Id, Text } from "./schema.ts";
+import type { Id, Pacing, Text } from "./schema.ts";
-/** Character budgets from spec section 4. */
+/** Character budgets from spec section 4 (packs with pacing 'balanced' or 'puzzle', or none). */
export const TEXT_LIMITS = {
roomDescription: 600,
objectDescription: 400,
@@ -15,6 +15,24 @@ export const TEXT_LIMITS = {
name: 24,
} as const;
+/**
+ * A narrative pack tells its scenes in full: a first arrival, a confession, a
+ * turning point need more room than one phone screen of 300 characters. The
+ * player scrolls like a book; options and names stay short for the buttons.
+ */
+const NARRATIVE_LIMITS: Record = {
+ roomDescription: 1000,
+ objectDescription: 600,
+ dialogueSay: 600,
+ optionText: 80,
+ name: 24,
+};
+
+/** The character budgets for a pack's pacing (spec section 4). */
+export function textLimits(pacing: Pacing | undefined): Readonly> {
+ return pacing === "narrative" ? NARRATIVE_LIMITS : TEXT_LIMITS;
+}
+
function length(text: string, ix: PackIndex): number {
return [...renderedText(text, ix.pack)].length;
}
@@ -44,27 +62,28 @@ function checkLength(
function checkLengths(ix: PackIndex, out: DiagnosticList): void {
const { pack } = ix;
+ const limits = textLimits(pack.pacing);
for (const [id, room] of Object.entries(pack.rooms)) {
- checkLength(ix, out, room.name, `rooms.${id}.name`, "Room name", TEXT_LIMITS.name);
- checkLength(ix, out, room.description, `rooms.${id}.description`, "Room description", TEXT_LIMITS.roomDescription);
+ checkLength(ix, out, room.name, `rooms.${id}.name`, "Room name", limits.name);
+ checkLength(ix, out, room.description, `rooms.${id}.description`, "Room description", limits.roomDescription);
}
for (const [id, object] of Object.entries(pack.objects)) {
- checkLength(ix, out, object.name, `objects.${id}.name`, "Object name", TEXT_LIMITS.name);
+ checkLength(ix, out, object.name, `objects.${id}.name`, "Object name", limits.name);
checkLength(
ix,
out,
object.description,
`objects.${id}.description`,
"Object description",
- TEXT_LIMITS.objectDescription,
+ limits.objectDescription,
);
}
for (const [id, dialogue] of Object.entries(pack.dialogues)) {
for (const [nodeId, node] of Object.entries(dialogue.nodes)) {
const p = `dialogues.${id}.nodes.${nodeId}`;
- checkLength(ix, out, node.say, `${p}.say`, "Dialogue line", TEXT_LIMITS.dialogueSay);
+ checkLength(ix, out, node.say, `${p}.say`, "Dialogue line", limits.dialogueSay);
(node.options ?? []).forEach((option, i) => {
- checkLength(ix, out, option.text, `${p}.options[${i}].text`, "Option text", TEXT_LIMITS.optionText);
+ checkLength(ix, out, option.text, `${p}.options[${i}].text`, "Option text", limits.optionText);
});
}
}
diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts
index a09584f..6474387 100644
--- a/packages/engine/src/index.ts
+++ b/packages/engine/src/index.ts
@@ -7,16 +7,27 @@
*/
export { analyze } from "./analyze.ts";
+export { TEXT_LIMITS, textLimits } from "./analyze-text.ts";
export { commandLabel, formatCommand, parseCanonical } from "./commands.ts";
export { compile } from "./compile.ts";
export { explore } from "./explore.ts";
export { packHash, stateKey } from "./hash.ts";
export { loadPack, PackError } from "./load.ts";
export { parseCommand } from "./parser.ts";
-export { BUDGET_DEFAULTS, budgetForMinutes, countWords, estimatePlaytime, PLAYTIME_DEFAULTS } from "./playtime.ts";
+export {
+ BUDGET_DEFAULTS,
+ budgetForMinutes,
+ countWords,
+ DEFAULT_PACING,
+ estimatePlaytime,
+ PACING_BAND,
+ PACING_READING_SHARE,
+ PLAYTIME_DEFAULTS,
+} from "./playtime.ts";
export { hint, newGame, step, view } from "./runtime.ts";
export * from "./schema.ts";
export { objectDescription, plainText, renderPlain } from "./text.ts";
+export { type Transcript, walkthroughTranscript } from "./transcript.ts";
export * from "./types.ts";
export { validateState } from "./validate-state.ts";
export { runWalkthrough } from "./walkthrough.ts";
diff --git a/packages/engine/src/playtime.ts b/packages/engine/src/playtime.ts
index 97727fc..ea56892 100644
--- a/packages/engine/src/playtime.ts
+++ b/packages/engine/src/playtime.ts
@@ -20,7 +20,8 @@
* (`look