Skip to content

Commit 69b4ee3

Browse files
feat(scenarios): --lang zh|en and --prompt short|detailed choose the prompts the agent is given (#34185)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao2uXXmCjR4kVHvAji5B8xgV)_ epic:#33595#1 · os-tesla · session_01L9qibw5wFsyVj9j5sxb8pj Clause-②: yes (widening) — the CLI flags `--lang zh|en` and `--prompt short|detailed` on `objectstack-scenarios run` / `run-scenarios` (`cli.ts`, reached through the bin, not an export entry); through `./runner`: the new exports `PROMPT_LANGS`, `PromptLang`, `PROMPT_LENGTHS`, `PromptLength`, `PromptChoice`, `MissingLanguageError`, `promptLanguageGaps`, `promptLanguageRefusal`, `statedPromptChoice`, `promptChoiceText` (`prompts.ts`) and `samePromptChoice` (`driver.ts`); a new optional trailing `choice` parameter on `buildPrompt`, `iteratePrompt`, `templateIteratePrompt`, `questionPrompt`, `operationPrompt` (`prompts.ts`), `runHalf` (`orchestrate.ts`) and the `RecordingDriver` constructor (`driver.ts`); the new method `RecordedDriver.assertPromptChoice` (`driver.ts`); the new optional fields `RunOptions.promptChoice`, `CardRun.promptChoice` (`orchestrate.ts`), `Recording.promptChoice` (`driver.ts`) and `CardScorecard.promptChoice` (`scorecard.ts`). No export entry moves. Metadata-protocol: none Fixes #33743 ## 维护者速读 - 改了什么:跑分器新增 `--lang zh|en` 与 `--prompt short|detailed`。`--lang` 让卡片里写给模型的所有文字(搭建提示、迭代变更、每个问数和操作的提问)只用指定语言发出,三种模式和 `--ask-repeats` 的每一问都生效;`--prompt` 选择搭建这一轮用卡片的短提示还是详细提示。跑分器自己的外围说明保持英文。 - 为什么改:此前卡片文字一律按「有英文用英文」发出,搭建只用详细提示,评测只量了最有利的输入;客户会用中文、用一句话提需求,M3 给对照卡加中文提示也依赖这个开关。 - 风险与回滚:两个开关都不给时,9 张卡全部提示与 main 逐字节相同(880,752 字节,sha256 一致),记录、评分表、录制文件都不出现新字段。缺语言的卡在第一张卡开跑前就被跳过并列出缺的字段,不会悄悄换语言;回放的语言或提示与录制时不同,开跑前拒绝。回滚即还原本 PR。 - 先看:`packages/qa/scenarios/src/runner/prompts.ts` 的 `text` / `promptLanguageGaps`(语言选择与缺字段判定),`src/runner/cli.ts` 的开跑前跳过,`src/runner/driver.ts` 的 `assertPromptChoice`(回放拒绝)。 - 两分钟验证:`pnpm --filter @objectstack/scenarios exec vitest run --maxWorkers=2 test/runner/orchestrate.test.ts -t 33743`,预期 10 个用例全过。 - 需要你做的:无,席位落地。 ## What changes - **The choice** (`runner/prompts.ts`): `PromptChoice { lang?, prompt? }`. Every card text a prompt renders goes through one `text(t, choice, field)`. With no `lang` it renders `en ?? zh` as before. With a `lang` it renders that language and no other, and a missing text throws `MissingLanguageError` naming the field. `buildPrompt` takes `prompt.short` or `prompt.detailed` by `choice.prompt` (default `detailed`). `iteratePrompt`, `templateIteratePrompt`, `questionPrompt` and `operationPrompt` take the same choice. The iterate prompt always renders `iterate.change`, so `--prompt` changes the build turn only. - **What the language covers** (design point 1): `prompt.short` / `prompt.detailed`, `iterate.change`, and each question's and each operation's `ask`. These are the four `LocalizedText` fields a prompt renders. The runner's own text stays in English: the preamble, the data contract, the naming rule and the answer instructions. So do the card's plain strings it quotes, a persona's `role` and an action's `summary`, which the schema does not localise. The README says so. - **No silent fallback** (design point 2): `promptLanguageGaps(card, choice, modes)` lists every text the run's modes would render that the card lacks in the chosen language. Scratch needs the build prompt `--prompt` names, the iterate change, every question and every operation. Template needs all but the build prompt. Ask needs the questions and operations. The CLI runs this check **before the first card**, before the workspace packages are built and before any scaffold or boot. It prints `skipped CARD: --lang zh sends every card text in zh and no other language, and this card has no zh text for …`, listing each field, and runs the other cards. With none left it exits 2. `runCard` throws the same text for a library caller before any mode runs. - **Defaults** (design point 3): with neither flag, every prompt, record, scorecard and recording is unchanged byte for byte. The choice is written only when a flag is given (`statedPromptChoice`). - **Record and scorecard** (design point 4): `CardRun.promptChoice` and `CardScorecard.promptChoice` carry only the flags given. Both reach the run record (`cardRun`, `scorecard`). `renderScorecard` prints `prompts: language zh · build prompt short` under the packages line, with an unchosen half shown as its default. - **Replay** (design point 5): the recording carries the choice (`Recording.promptChoice`, written by `RecordingDriver` only when a flag is given). `RecordedDriver.assertPromptChoice` refuses a different choice before any card runs. The refusal names both choices and the flags to replay with. `--prompt detailed` is the default's own prompt, so it replays a recording made without flags. `--lang en` counts as a different choice from none and is refused, because on a Chinese-only text the two render differently. - **Every mode** (design point 7): the choice is threaded through `RunOptions.promptChoice` to scratch (build, iterate, both Run halves), template (iterate, Run half) and ask (Run half). Each ask of a repeated question is included. - **Docs**: a README usage line and a **Language and build prompt** entry. The changeset is a patch. ## Tests `test/runner/orchestrate.test.ts`, a new top-level `describe` with 10 tests. `setup()` gains an optional `scenario`, so the fakes can run a variant of the crm card: a bilingual twin whose Chinese texts are the English ones with a marker in front. - **Flags**: `parseArgs` for both flags, unknown values refused (`fr`, `zh-CN`, `long`), a missing value refused, and neither flag set when absent. - **Defaults**: a run with no choice and a run with `{}` in all three modes send the same prompts under the same keys. They write the same record and render the same scorecard, with no `promptChoice` and no `prompts:` line. A recording made with no choice or `{}` carries no `promptChoice`. The build prompt carries `prompt.detailed.en` and a question carries its English ask. The `en ?? zh` fallback on a Chinese-only text is unchanged. - **`--lang zh` in every mode with `--ask-repeats 2`**: the build turn is sent `prompt.detailed.zh`, and both iterates (scratch and template) are sent `iterate.change.zh`. Four Run halves each send 9 × 2 question asks plus 5 operations, each starting with its Chinese ask. No English card text appears as a prompt's text. The record and scorecard state `{ lang: 'zh' }`. - **`--prompt short`**: the build turn equals the default with `prompt.detailed` swapped for `prompt.short`. Every other prompt is byte-identical to the default. The scorecard states it. - **Four combinations**: `buildPrompt` renders `short`/`detailed` × `zh`/`en` to the card's own text. `--lang en` equals the default on a card with English. - **Refusal**: per-mode gaps on the English-only crm card. Only the build prompt that is sent counts. `runCard` rejects with every field named, before any scaffold or prompt. A prompt asked to render a missing text throws `MissingLanguageError`. - **CLI skip**: `main(--only crm --lang zh)` prints the skip line and `no card to run…`, returns 2, writes nothing to `--out` or `--work`, and never opens the replay file. - **Replay**: a recording made under `{ lang: 'zh', prompt: 'short' }` carries it in the saved file. The same choice replays. No choice or a partial choice is refused with the flags to use. A default recording accepts no flag and `--prompt detailed`, and refuses `--lang en`. Through `main` it is refused before any card runs. - **Chinese grading** (design point 6, `score/**` untouched): on `leave_balances`, the Chinese reply `你有 1 个待审批的步骤…来源:approval_step` for `pending_by_approver` as `employee` grades `correct`, `cited`, with no leaks. So does a spaceless `你有1个…` cited with `Source:`. A wrong Chinese figure is not correct. An all-rows question (`annual_days_by_department`) answered in Chinese is correct and cited. On the unanswerable `unpaid_leave_deduction`, a Chinese decline (`无法回答:…没有记录工资`) passes and an invented Chinese figure fails. ## Acceptance notes - The card's "Done when", in order: - `--lang zh|en` picks the language of every prompt (build, iterate, question, operation), with no silent fallback. A card missing a field is reported and not run. - `--prompt short|detailed` picks the build turn's prompt, default `detailed`, unchanged. - The scorecard and run record state both choices. - Tests pin the rendered prompt for each combination on one card, and the refusal. - Design point 6 was checked before anything else was built on it. The grader already reads `来源:`, Chinese measure words, `万`/`亿`, and Chinese declines (`无法`, `未记录`, `没有记录`). No change to `score/**` was needed. - Three control cards (`crm_account_with_contacts`, `invoice_with_line_items`, `project_with_tasks`) have no Chinese text today, so `--lang zh` skips them by name. M3's "control cards gain Chinese prompts" row is what fills them. The other six cards carry both languages in every field. - Off-limits paths are untouched: `src/score/**`, `src/schema.ts`, the card JSONs and `src/export/**`. The cloud#3600 cost ruling and Ruling A on #31999 item 9 are unaffected, because no scoring code changed. `packages/spec` is untouched. - The skip is reported on stderr before the first card, not written as a run record. A card that is not run has no halves to record, and the multi-run summary is M3's row. ## Verification <details><summary>Default parity against main</summary> - Every prompt for every card of the open library (9 cards; build, iterate, template iterate, every question, every operation), rendered by `main`'s `prompts.ts` (`2539ad98`) and by this branch with no choice, with `{}` and with `{ prompt: 'detailed' }`, under `tsx`: 880,752 bytes, sha256 prefix `b3357be8d7eaa6fb` for all four, `identical true`. </details> <details><summary>Ablation</summary> - `node scripts/ablation-replace.mjs` on the committed head. The tests import `src`, so there is no build leg. Each mutation was restored with `git diff HEAD` empty and the blob equal to HEAD. - `runCard` without its language refusal: 1 failed / 9 passed (the no-silent-fallback test). - `text()` ignoring `lang` (always `en ?? zh`): 3 failed / 7 passed (every mode in zh, the four combinations, the refusal). - `assertPromptChoice` always accepting: 1 failed / 9 passed (the replay test). </details> <details><summary>Local gates</summary> - `pnpm --filter '@objectstack/scenarios^...' build` :: exit 0 (lock VERDICT command-exit 0). - `pnpm --filter @objectstack/scenarios typecheck` :: exit 0. - `pnpm --filter @objectstack/scenarios build && pnpm --filter @objectstack/scenarios test` :: exit 0 (lock VERDICT command-exit 0): 34 test files passed (34), 922 tests passed (922), on `78f7e31e`. A first run without the package's own `dist/` failed only the two `test/build/*` files on their prerequisite ("build @objectstack/scenarios first"). After the build, all 34 passed. - `eslint --no-inline-config` on the six touched TS files :: exit 0. - Derived gates (`dispatch-gates --commands --repo objectstack-ai/objectstack` at `78f7e31e`, 8 paths, 66 families), each run with stdin from `/dev/null`: 64 exit 0, and 2 exit 3 (PREREQUISITE NOT MET): - `check-plugin-teardown-shape --self-test` could not read its pinned fixture commit in the shallow clone. After `git fetch origin 621a487…`, a rerun exited 0 ("48 cases pass"). The rerun is recorded on its own line. The first-run record is kept as it was. - `pnpm check:dual-build-cjs-loads` is NOT MEASURED locally, because it needs every package's `dist/`. CI runs it. - `--ran` on the first-run record: "66 derived famil(ies) accounted for — 64 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3)". - Main (`bf594ebd`) was merged once before opening (`78f7e31e`). It touched only `ui/` app-shell, so nothing was rebuilt for it. - 582 changed lines (+547/-35) in 8 files. No governed surface, and `packages/spec` is untouched. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibw5wFsyVj9j5sxb8pj)_ <!-- signed: epic:#33595#1 · os-tesla · session_01L9qibw5wFsyVj9j5sxb8pj --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 661ede2 commit 69b4ee3

8 files changed

Lines changed: 547 additions & 35 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
feat(scenarios): `--lang zh|en` and `--prompt short|detailed` choose the prompts the agent is given
6+
7+
Clause-②: yes (widening) — the CLI flags `--lang zh|en` and `--prompt short|detailed` (the `objectstack-scenarios` bin, `cli.ts`); through `./runner`: the new exports `PROMPT_LANGS`, `PromptLang`, `PROMPT_LENGTHS`, `PromptLength`, `PromptChoice`, `MissingLanguageError`, `promptLanguageGaps`, `promptLanguageRefusal`, `statedPromptChoice` and `promptChoiceText` (`prompts.ts`) and `samePromptChoice` (`driver.ts`); a new optional `choice` parameter on `buildPrompt`, `iteratePrompt`, `templateIteratePrompt`, `questionPrompt`, `operationPrompt` (`prompts.ts`) and `runHalf` (`orchestrate.ts`), and on the `RecordingDriver` constructor (`driver.ts`); the new method `RecordedDriver.assertPromptChoice` (`driver.ts`); the new optional fields `RunOptions.promptChoice`, `CardRun.promptChoice` (`orchestrate.ts`), `Recording.promptChoice` (`driver.ts`) and `CardScorecard.promptChoice` (`scorecard.ts`)
8+
Metadata-protocol: none
9+
10+
Until now every card text reached the agent as `en ?? zh`, so a card with both languages was always given in English, and the build turn was always given `prompt.detailed`: the eval measured only the most favourable input, never the Chinese sentence a customer writes.
11+
12+
`--lang zh|en` renders every card-authored text a prompt carries in that language and no other — the build prompt, the iterate change, and each question's and each operation's ask — in scratch, template and ask modes, at every ask of `--ask-repeats`. The runner's own wrapper text (preamble, data contract, naming rule, answer instructions) stays in English. There is no silent fallback: a card lacking one of the texts the run's modes render in the chosen language is skipped before the first card runs, before any scaffold or boot, with a line naming each missing text, and the other cards run. `--prompt short|detailed` picks the card prompt the build turn is given (default `detailed`); the iterate turn is unchanged.
13+
14+
With either flag the run record states the choice (`promptChoice` on the card's run and on the scorecard) and the scorecard prints `prompts: language zh · build prompt short`. A recording made under a choice carries it, and replaying it (`--driver recorded:F`) under another choice is refused before any card runs, naming the flags to replay it with. With neither flag the prompts, the record, the scorecard and the recording are unchanged byte for byte. The grader already reads a Chinese reply (`来源:` lines, Chinese measure words and declines), so a Chinese turn grades as an English one does; no scoring change.

‎packages/qa/scenarios/README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ pnpm --filter @objectstack/scenarios run-scenarios --model sonnet # t
206206
pnpm --filter @objectstack/scenarios run-scenarios --author-model opus --ask-model haiku # build and persona turns apart
207207
pnpm --filter @objectstack/scenarios run-scenarios --effort medium # the effort every turn asks for (default: the CLI's own)
208208
pnpm --filter @objectstack/scenarios run-scenarios --author-effort high --ask-effort low # build and persona turns apart
209+
pnpm --filter @objectstack/scenarios run-scenarios --lang zh --prompt short # the card's Chinese texts, and its short build prompt (default: en, else zh; detailed)
209210
pnpm --filter @objectstack/scenarios run-scenarios --packages workspace # on this checkout's unreleased packages (default: published)
210211
```
211212

@@ -332,6 +333,27 @@ npx @objectstack/scenarios help # the comma
332333
without repeats still replays. `--ask-repeats` is not a live-only flag: with `--driver recorded:F` it decides how
333334
many recorded asks of each question turn are read (the first N), and an N larger than the recording holds of any
334335
question turn is refused before any card runs, naming the turn and the count found.
336+
- **Language and build prompt** (`prompts.ts`, `orchestrate.ts`, `scorecard.ts`, `driver.ts`): `--lang zh|en` renders
337+
every card-authored text a prompt carries in that language and no other — the build prompt (`prompt.short` or
338+
`prompt.detailed`), the iterate change (`iterate.change`), and each question's and each operation's `ask` — in every
339+
mode (scratch, template and ask) and at every ask of `--ask-repeats`. The runner's own text around it (the preamble,
340+
the data contract, the naming rule, the answer instructions) stays in English, and so do the plain strings it quotes
341+
from the card (a persona's role, an action's summary); a Chinese wrapper is not offered. **No silent fallback**: a
342+
card that lacks one of the texts the run's modes render in that language (scratch: the build prompt `--prompt` names,
343+
the iterate change, every question and operation; template: all but the build prompt; ask: the questions and
344+
operations) is skipped before the first card runs, before any scaffold or boot, with a line naming each missing text
345+
(``skipped crm_account_with_contacts: … no zh text for `prompt.detailed`, `iterate.change`, …``), and the other cards
346+
run; with none left the run exits 2. `--prompt short|detailed` picks the card prompt the build turn is given; the
347+
iterate turn is given `iterate.change` either way. With neither flag nothing changes, byte for byte: each text in
348+
English when the card has it, else in Chinese, the build turn given `prompt.detailed`, and the record, the scorecard
349+
and the recording carry no trace of the choice. With either flag, the run's record states it (`promptChoice` on the
350+
card's run and on the scorecard, only the flags given) and the scorecard says `prompts: language zh · build prompt
351+
short`. A recording made under a choice carries it (`promptChoice`), and `--driver recorded:F` under another choice
352+
is refused before any card runs, naming both and the flags to replay it with: the recorded answers answered the
353+
recorded prompts, and a replay sends none. `--prompt detailed` is the default's own prompt, so it replays a recording
354+
made without flags; `--lang en` is another choice than none, refused alike. The grader reads a reply in either
355+
language (`来源:` and `Source:` lines, Chinese measure words and declines), so a Chinese turn grades as an English
356+
one does.
335357
- **Turn caps** (`driver.ts`): an authoring turn, build and iterate alike, may take `DEFAULT_AUTHOR_MAX_TURNS` by the
336358
card's `tier` — `control` 80, `starter` 300, `delivery` 600 — unless `--author-max-turns N` sets one cap for every
337359
card; a question or operation turn takes 12 unless `--ask-max-turns N` says otherwise. The cap guards a looping turn

‎packages/qa/scenarios/src/runner/cli.ts‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,21 @@
6060
* --ask-effort L the effort for question and operation turns, in place
6161
* of --effort; the record and the scorecard state the
6262
* effort each turn asked for beside its served model
63+
* --lang zh|en render every card text a prompt carries (the build
64+
* prompt, the iterate change, each question's and each
65+
* operation's ask) in this language and no other; a
66+
* card missing one that the run's modes render is
67+
* skipped before the first card runs, naming each
68+
* missing text, and the other cards run. The runner's
69+
* own wrapper text stays in English (default: each
70+
* text in English when the card has it, else Chinese)
71+
* --prompt short|detailed
72+
* the card prompt the build turn is given (default
73+
* detailed); the iterate turn is unchanged. The record
74+
* and the scorecard state both choices when either
75+
* flag is given, a recording carries them, and a
76+
* replay (`recorded:`) under other choices than its
77+
* recording's is refused before any card runs
6378
* --template F a verified build (dist/objectstack.json) for template
6479
* and ask modes
6580
* --no-iterate-run skip the Run half after the iterate (scratch mode)
@@ -92,6 +107,7 @@ import { CAPABILITY_AREAS_DIR, locateLibraryRoot } from './library.js';
92107
import { askModeRefusal, minutesText, runCard, type ProjectOps } from './orchestrate.js';
93108
import { installedSpecVersion, PACKAGES_MODES, prepareWorkspacePackages, settleWorkspaceProject, workspaceScaffolder, type PackageSource, type PackagesMode } from './packages.js';
94109
import { bootDev, os, readArtifact, readNamespace, scaffold } from './project.js';
110+
import { PROMPT_LANGS, PROMPT_LENGTHS, promptChoiceText, promptLanguageRefusal, statedPromptChoice, type PromptChoice, type PromptLang, type PromptLength } from './prompts.js';
95111
import { rebaseScenario } from './run-date.js';
96112
import { cardScorecard, renderScorecard, runRecord } from './scorecard.js';
97113

@@ -141,6 +157,10 @@ export interface CliArgs {
141157
createVersion?: string;
142158
/** `--packages`: where the `@objectstack/*` packages come from. */
143159
packages: PackagesMode;
160+
/** `--lang`: the language every card text a prompt renders is sent in ({@link PromptChoice.lang}); absent ⇒ English, else Chinese, per text. */
161+
lang?: PromptLang;
162+
/** `--prompt`: the card prompt the build turn is given ({@link PromptChoice.prompt}); absent ⇒ `detailed`. */
163+
prompt?: PromptLength;
144164
}
145165

146166
export function parseArgs(argv: readonly string[]): CliArgs {
@@ -198,6 +218,15 @@ export function parseArgs(argv: readonly string[]): CliArgs {
198218
else if (flag === '--effort') a.effort = effort();
199219
else if (flag === '--author-effort') a.authorEffort = effort();
200220
else if (flag === '--ask-effort') a.askEffort = effort();
221+
else if (flag === '--lang') {
222+
const l = val();
223+
if (!(PROMPT_LANGS as readonly string[]).includes(l)) throw new Error(`unknown --lang \`${l}\` (${PROMPT_LANGS.join(', ')})`);
224+
a.lang = l as PromptLang;
225+
} else if (flag === '--prompt') {
226+
const p = val();
227+
if (!(PROMPT_LENGTHS as readonly string[]).includes(p)) throw new Error(`unknown --prompt \`${p}\` (${PROMPT_LENGTHS.join(', ')})`);
228+
a.prompt = p as PromptLength;
229+
}
201230
else if (flag === '--out') a.out = val();
202231
else if (flag === '--work') a.work = val();
203232
else if (flag === '--create-version') a.createVersion = val();
@@ -215,6 +244,11 @@ export function parseArgs(argv: readonly string[]): CliArgs {
215244
return a;
216245
}
217246

247+
/** The prompt choice `--lang` and `--prompt` set ({@link PromptChoice}), or `undefined` when neither is given: the default prompts. */
248+
export function promptChoiceOf(args: Pick<CliArgs, 'lang' | 'prompt'>): PromptChoice | undefined {
249+
return statedPromptChoice({ ...(args.lang !== undefined ? { lang: args.lang } : {}), ...(args.prompt !== undefined ? { prompt: args.prompt } : {}) });
250+
}
251+
218252
/** The live driver's limits a run may set: `--author-timeout`, `--author-max-turns`, `--ask-max-turns`. */
219253
export type DriverLimits = Pick<CliArgs, 'authorTimeoutMin' | 'authorMaxTurns' | 'askMaxTurns'>;
220254

@@ -311,16 +345,29 @@ export async function main(argv: readonly string[]): Promise<number> {
311345
library: libraryOf(cardsDir, repo),
312346
});
313347
for (const r of refusals) console.error(formatRefusal(r));
314-
const chosen = args.only ? cards.filter((c) => args.only!.includes(c.card.id)) : cards;
315-
if (chosen.length === 0) {
348+
const picked = args.only ? cards.filter((c) => args.only!.includes(c.card.id)) : cards;
349+
if (picked.length === 0) {
316350
console.error(`no card to run under ${cardsDir}${args.only ? ` matching ${args.only.join(',')}` : ''}`);
317351
return 2;
318352
}
353+
const promptChoice = promptChoiceOf(args);
354+
// A card that lacks a text the run would render in the chosen language is skipped here, before any scaffold or boot; the others run.
355+
const chosen = picked.filter((c) => {
356+
const refusal = promptLanguageRefusal(c.card, promptChoice, args.modes);
357+
if (refusal) console.error(`skipped ${c.card.id}: ${refusal}`);
358+
return refusal === undefined;
359+
});
360+
if (chosen.length === 0) {
361+
console.error(`no card to run: every card chosen lacks a text the run would send in ${args.lang}`);
362+
return 2;
363+
}
319364

320365
const live = makeDriver(args.driver, args);
321366
// A replay reads the first N asks of each question turn: refused here, before any card runs, when it holds fewer.
322367
if (args.askRepeats !== undefined && live instanceof RecordedDriver) live.assertAskRepeats(args.askRepeats, chosen.map((c) => c.card));
323-
const driver = args.record ? new RecordingDriver(live) : live;
368+
// A replay under other prompts than its recording's would grade one choice's answers as another's: refused here, before any card runs.
369+
if (live instanceof RecordedDriver) live.assertPromptChoice(promptChoice);
370+
const driver = args.record ? new RecordingDriver(live, promptChoice) : live;
324371
const info = driver.info();
325372
console.log(
326373
`driver: ${info.driver} ${info.version ?? ''} · login: ${info.authMethod ?? 'n/a'} · API-billed: no` +
@@ -333,6 +380,7 @@ export async function main(argv: readonly string[]): Promise<number> {
333380
(info.askEffort ? ` · ask effort: ${info.askEffort}` : ''),
334381
);
335382
if (args.askRepeats !== undefined && args.askRepeats > 1) console.log(`ask repeats: each question turn asked ${args.askRepeats} times, operations once`);
383+
if (promptChoice) console.log(`prompts: ${promptChoiceText(promptChoice)}`);
336384

337385
// Built and packed once, before the first card: every scaffold of this run installs the same tarballs.
338386
const workspace = args.packages === 'workspace' ? await prepareWorkspacePackages(repo, join(work, 'workspace-packages')) : undefined;
@@ -380,7 +428,7 @@ export async function main(argv: readonly string[]): Promise<number> {
380428
console.log(`dates: the card's ${loaded.card.asOf} is run as ${scenario.card.asOf}, every card date moved by the same days`);
381429
}
382430
publishedVersions = new Set();
383-
const cardRun = await runCard(scenario, driver, ops, { modes: args.modes, iterateRun: args.iterateRun, admin: ADMIN, ...(template ? { templateArtifact: template } : {}), ...(args.askRepeats !== undefined ? { askRepeats: args.askRepeats } : {}) });
431+
const cardRun = await runCard(scenario, driver, ops, { modes: args.modes, iterateRun: args.iterateRun, admin: ADMIN, ...(template ? { templateArtifact: template } : {}), ...(args.askRepeats !== undefined ? { askRepeats: args.askRepeats } : {}), ...(promptChoice ? { promptChoice } : {}) });
384432
const packages: PackageSource = workspace ? workspace.source : { source: 'published', versions: [...publishedVersions].sort() };
385433
const record = runRecord({ run: `${date}-scenario-${scenario.card.id}`, date, ...(framework ? { framework } : {}), packages, driver: info, runner: 'scenario-runner', evidenceDir: work }, cardRun);
386434
const file = join(outDir, `${date}-scenario-${scenario.card.id}.json`);

‎packages/qa/scenarios/src/runner/driver.ts‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import { flowRefusalOf } from '../score/scenario-run-grade.js';
4444
import type { ToolAnswer } from './app.js';
4545
import { noResult, runTurnProcess } from './drivers/process.js';
4646
import { WRITE_TOOLS } from './observe.js';
47+
import { promptChoiceText, statedPromptChoice, type PromptChoice } from './prompts.js';
4748
import { parseStreamJson, refusalCodeOf, type ParsedTurn, type RunnerToolCall } from './transcript.js';
4849

4950
/** Which run step a turn belongs to; the replay key is built from it. */
@@ -481,6 +482,22 @@ export interface Recording {
481482
turns: Record<string, ParsedTurn>;
482483
/** Authoring turns' resulting project sources, keyed like `turns`. */
483484
files: Record<string, Record<string, string>>;
485+
/**
486+
* The prompt choice the recorded turns were sent (`--lang`, `--prompt`),
487+
* when a flag set one; absent ⇒ the default prompts. A replay under
488+
* another choice is refused before any card runs
489+
* ({@link RecordedDriver.assertPromptChoice}).
490+
*/
491+
promptChoice?: PromptChoice;
492+
}
493+
494+
/**
495+
* Two prompt choices send the same prompts: the same language (no choice is
496+
* its own: English, else Chinese, per card text) and the same build prompt
497+
* (no choice is `detailed`).
498+
*/
499+
export function samePromptChoice(a: PromptChoice | undefined, b: PromptChoice | undefined): boolean {
500+
return a?.lang === b?.lang && (a?.prompt ?? 'detailed') === (b?.prompt ?? 'detailed');
484501
}
485502

486503
export class MissingRecordingError extends Error {
@@ -611,6 +628,23 @@ export class RecordedDriver implements AgentDriver {
611628
throw new Error(`--ask-repeats ${repeats} replays ${repeats} asks of each question turn, but the recording ${this.source} holds fewer of ${short.length}: ${shown}`);
612629
}
613630

631+
/**
632+
* Refuse a replay under another prompt choice than the recording was made
633+
* with ({@link samePromptChoice}), before any card runs: the recorded turns
634+
* answered the prompts the recording was sent, and a replay never sends a
635+
* prompt, so the run would grade one choice's answers as another's.
636+
*/
637+
assertPromptChoice(choice: PromptChoice | undefined): void {
638+
const made = this.recording.promptChoice;
639+
if (samePromptChoice(made, choice)) return;
640+
const flags = (c: PromptChoice | undefined) =>
641+
[c?.lang !== undefined ? `--lang ${c.lang}` : '', c?.prompt !== undefined ? `--prompt ${c.prompt}` : ''].filter(Boolean).join(' ') || 'neither flag';
642+
throw new Error(
643+
`the recording ${this.source} was sent ${promptChoiceText(made ?? {})}, and this run asks for ${promptChoiceText(choice ?? {})}: ` +
644+
`a replay re-reads the answers to the prompts that were recorded, so replay it with ${flags(made)}`,
645+
);
646+
}
647+
614648
info(): DriverInfo {
615649
const made = this.recording.driver;
616650
// A recording of a replay names the agent of the run it replayed, not the replay.
@@ -682,8 +716,18 @@ export class RecordedDriver implements AgentDriver {
682716
export class RecordingDriver implements AgentDriver {
683717
readonly recording: Recording;
684718

685-
constructor(private readonly inner: AgentDriver) {
686-
this.recording = { driver: inner.info(), turns: {}, files: {} };
719+
/** `choice`: the prompt choice the run sends, stated on the recording when a flag set one ({@link Recording.promptChoice}). */
720+
constructor(
721+
private readonly inner: AgentDriver,
722+
choice?: PromptChoice,
723+
) {
724+
const stated = statedPromptChoice(choice);
725+
this.recording = {
726+
driver: inner.info(),
727+
turns: {},
728+
files: {},
729+
...(stated !== undefined ? { promptChoice: stated } : {}),
730+
};
687731
}
688732

689733
info(): DriverInfo {

0 commit comments

Comments
 (0)