Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/34878-scenario-thrown-turn-skill-case.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@objectstack/scenarios': patch
---

fix(scenarios): a live turn that throws is recorded and replays as the same failure, and a skill file spelled otherwise than `SKILL.md` is refused by name

Clause-②: yes (widening: published @objectstack/scenarios ./runner types ThrownTurn, RecordedTurn and RecordedThrowError, plus one optional field on Recording.turns)
Metadata-protocol: none

- **A thrown turn is recorded.** When a live question, dataset question, operation, confirmation or authoring turn threw, the recording held nothing for it, so a replay met a missing turn. A dataset question or a confirmation turn reads a missing turn as not measured, so a row that showed 4/5 live could show 4/4 on replay. The recording now holds such a turn as an empty turn with `thrown: { name, message }`, and the live error is still thrown exactly as before. A replay throws an error with the same name and message again, writes no recorded file and re-sends no write, so the runner counts it exactly as it counted the live throw. A recording made before this change has no such turns and replays exactly as it did. A throw that is itself a replay's verdict (a missing or unfaithful recorded turn, when a replay is recorded) is still left unrecorded.
- **`--ask-skills` matches the skill file by its exact spelling.** The runner checked for `SKILL.md` with `existsSync`, which a case-insensitive filesystem answers true for `skill.md`. The run then crashed with `Cannot read properties of undefined (reading 'toString')`, and on a case-sensitive filesystem the skill was skipped without a word. The directory listing now decides. A skill directory whose file is spelled `skill.md`, `Skill.md` or any other case of `SKILL.md` is refused before any turn runs, with a sentence that names the file found and says to rename it to `SKILL.md`. This happens on every filesystem.
52 changes: 42 additions & 10 deletions packages/qa/scenarios/src/runner/ask-skills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,25 +149,57 @@ export function skillVersionOf(skillMd: string): string | undefined {
return m ? m[1]!.trim() : undefined;
}

/**
* The skill file `dir` holds, read off its listing by exact spelling:
* `SKILL.md` when it holds that file; else the name of a file spelled
* otherwise (`skill.md`, `Skill.md`); else `undefined`. Never `existsSync`: a
* case-insensitive filesystem answers it true for `skill.md`, while the listing
* names each file as it is spelled on every filesystem.
*/
function skillFileOf(dir: string): string | undefined {
const names = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name);
if (names.includes(SKILL_FILE)) return SKILL_FILE;
return names.find((n) => n.toLowerCase() === SKILL_FILE.toLowerCase());
}

/**
* Read a skills directory: either one skill (a directory holding `SKILL.md`,
* named after the directory) or a directory of skills (each subdirectory that
* holds `SKILL.md`, the layout of a `.claude/skills/` directory). Refused, with
* the reason, when the path is no directory or holds no skill: an option that
* gave the client nothing must not run as if it had. Refused too when any
* SKILL.md of a skill carries a front-matter key outside the ask turn's closed
* set ({@link frontMatterRefusal}): a skill must not widen the turn beyond the
* app's tools and `Skill`.
* gave the client nothing must not run as if it had. Refused when a skill file
* is spelled otherwise than `SKILL.md` ({@link skillFileOf}), naming it: a
* session reads such a file on one filesystem and misses it on another, so the
* turn would be given a skill on one machine and none on the next. Refused too
* when any SKILL.md of a skill carries a front-matter key outside the ask
* turn's closed set ({@link frontMatterRefusal}): a skill must not widen the
* turn beyond the app's tools and `Skill`.
*/
export function readAskSkills(dirArg: string): AskSkillsBundle {
const dir = resolve(dirArg);
if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new Error(`--ask-skills names \`${dirArg}\`, which is no directory`);
const skillDirs: Array<[string, string]> = existsSync(join(dir, SKILL_FILE))
? [[basename(dir), dir]]
: readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory() && existsSync(join(dir, e.name, SKILL_FILE)))
.map((e) => [e.name, join(dir, e.name)] as [string, string])
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
const misspelt = (shown: string) =>
new Error(
`--ask-skills names \`${dirArg}\`, which holds \`${shown}\`: a skill file is spelled \`${SKILL_FILE}\` exactly, ` +
`or a session reads it on one filesystem and misses it on another; rename it to \`${SKILL_FILE}\``,
);
const skillDirs: Array<[string, string]> = [];
const top = skillFileOf(dir);
if (top !== undefined) {
if (top !== SKILL_FILE) throw misspelt(top);
skillDirs.push([basename(dir), dir]);
} else {
const subdirs = readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory())
.map((e) => e.name)
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
for (const name of subdirs) {
const found = skillFileOf(join(dir, name));
if (found === undefined) continue;
if (found !== SKILL_FILE) throw misspelt(`${name}/${found}`);
skillDirs.push([name, join(dir, name)]);
}
}
if (skillDirs.length === 0) {
throw new Error(`--ask-skills names \`${dirArg}\`, which holds no skill: give a directory holding ${SKILL_FILE}, or a directory of skill directories that each hold one`);
}
Expand Down
77 changes: 72 additions & 5 deletions packages/qa/scenarios/src/runner/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
* what the recorded run wrote.
*
* {@link RecordingDriver} wraps a live driver and writes every turn it sees to
* a recording the replay driver reads back.
* a recording the replay driver reads back. A turn that threw is recorded as
* one ({@link RecordedTurn.thrown}), and its replay throws it again.
*/

import { spawnSync } from 'node:child_process';
Expand Down Expand Up @@ -514,10 +515,28 @@ export class ClaudeCodeDriver implements AgentDriver {

// ── Replay ──────────────────────────────────────────────────────────────────

/**
* A live turn that threw instead of answering ({@link RecordingDriver}): the
* error's `name` and `message`, as the run counted it. Its turn is empty.
*/
export interface ThrownTurn {
name: string;
message: string;
}

/**
* A recorded turn: what the driver answered, or, with {@link thrown}, an empty
* turn standing for an ask or authoring turn that threw. Absent ⇒ the turn
* answered, as every turn of a recording made before throws were recorded.
*/
export interface RecordedTurn extends ParsedTurn {
thrown?: ThrownTurn;
}

/** A recording: every turn of a run, keyed by {@link stepKey}. */
export interface Recording {
driver: DriverInfo;
turns: Record<string, ParsedTurn>;
turns: Record<string, RecordedTurn>;
/** Authoring turns' resulting project sources, keyed like `turns`. */
files: Record<string, Record<string, string>>;
/**
Expand Down Expand Up @@ -545,6 +564,33 @@ export class MissingRecordingError extends Error {
}
}

/**
* A replayed turn that threw in the recorded run ({@link RecordedTurn.thrown}),
* thrown again with the recorded `name` and `message`: the runner counts it
* exactly as it counted the live throw (an error, never a missing turn, which a
* dataset question or a confirmation turn reads as not measured).
*/
export class RecordedThrowError extends Error {
constructor(
readonly key: string,
thrown: ThrownTurn,
) {
super(thrown.message);
this.name = thrown.name;
}
}

/**
* The turn recorded for a live call that threw `e`, or `undefined` for a throw
* that is itself a replay's verdict on a missing or unfaithful turn: those are
* left unrecorded, as before, so a replay of the recording meets the same gap.
*/
function thrownTurn(e: unknown): RecordedTurn | undefined {
if (e instanceof MissingRecordingError || e instanceof ReplayNotFaithfulError) return undefined;
const thrown: ThrownTurn = e instanceof Error ? { name: e.name, message: e.message } : { name: 'Error', message: String(e) };
return { replyText: '', toolCalls: [], meta: {}, thrown };
}

/**
* A replayed turn whose recorded writes the booted app did not answer as it
* answered the recorded run, or that the recording cannot re-send faithfully.
Expand Down Expand Up @@ -596,7 +642,8 @@ function remapIds(value: unknown, ids: ReadonlyMap<string, string>): unknown {
}

/**
* Replays a {@link Recording}. A step it has no turn for is a loud error, never an empty turn.
* Replays a {@link Recording}. A step it has no turn for is a loud error, never an empty turn;
* a step whose live turn threw throws again ({@link RecordedThrowError}), with nothing re-sent.
* Each ask of a repeated question turn is read by its own key ({@link stepKey});
* how many asks are read is the run's `--ask-repeats`, checked against what the
* recording holds before any card runs ({@link RecordedDriver.assertAskRepeats}).
Expand Down Expand Up @@ -702,6 +749,7 @@ export class RecordedDriver implements AgentDriver {
const key = stepKey(task);
const turn = this.recording.turns[key];
if (!turn) throw new MissingRecordingError(key);
if (turn.thrown) throw new RecordedThrowError(key, turn.thrown);
const files = this.recording.files[key] ?? {};
const root = resolve(task.cwd);
for (const [rel, content] of Object.entries(files)) {
Expand All @@ -717,6 +765,7 @@ export class RecordedDriver implements AgentDriver {
const key = stepKey(task);
const turn = this.recording.turns[key];
if (!turn) throw new MissingRecordingError(key);
if (turn.thrown) throw new RecordedThrowError(key, turn.thrown);
const writes = recordedWrites(turn);
if (writes.length === 0 || task.callTool === undefined) return turn;
const unanswered = writes.filter((c) => c.output === undefined);
Expand Down Expand Up @@ -775,18 +824,36 @@ export class RecordingDriver implements AgentDriver {
}

async author(task: AuthorTask): Promise<AuthorResult> {
const r = await this.inner.author(task);
let r: AuthorResult;
try {
r = await this.inner.author(task);
} catch (e) {
this.recordThrow(task, e);
throw e;
}
this.recording.turns[stepKey(task)] = r.turn;
if (r.files) this.recording.files[stepKey(task)] = r.files;
return r;
}

async ask(task: AskTask): Promise<ParsedTurn> {
const t = await this.inner.ask(task);
let t: ParsedTurn;
try {
t = await this.inner.ask(task);
} catch (e) {
this.recordThrow(task, e);
throw e;
}
this.recording.turns[stepKey(task)] = t;
return t;
}

/** A turn that threw is recorded as one ({@link RecordedTurn.thrown}), so its replay throws it again and counts as the run did. */
private recordThrow(task: StepRef, e: unknown): void {
const turn = thrownTurn(e);
if (turn) this.recording.turns[stepKey(task)] = turn;
}

save(path: string): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(this.recording, null, 2));
Expand Down
58 changes: 58 additions & 0 deletions packages/qa/scenarios/test/runner/ask-skills.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ import { ClaudeCodeDriver, RecordedDriver, RecordingDriver, type AgentDriver, ty
import { renderSummaryTable, summaryTables, type SummaryRecord } from '../../src/runner/summary.js';
import type { ParsedTurn } from '../../src/runner/transcript.js';

/**
* A case-insensitive filesystem (macOS, Windows), stood in for on any host:
* while `on`, `existsSync` answers a path true when its directory holds the
* name in any case, as such a filesystem does. Off, `node:fs` answers as ever.
*/
const caseInsensitive = vi.hoisted(() => ({ on: false }));
vi.mock('node:fs', async (importOriginal) => {
const fs = await importOriginal<typeof import('node:fs')>();
const { basename, dirname } = await import('node:path');
const anyCase = (p: string) => {
if (fs.existsSync(p)) return true;
const d = dirname(p);
return fs.existsSync(d) && fs.statSync(d).isDirectory() && fs.readdirSync(d).some((n) => n.toLowerCase() === basename(p).toLowerCase());
};
return { ...fs, existsSync: (p: import('node:fs').PathLike) => (caseInsensitive.on ? anyCase(String(p)) : fs.existsSync(p)) };
});

const SKILL_MD = '---\nname: ask-data\ndescription: Answer business questions through the governed datasets.\nmetadata:\n version: 1.2.0\n---\n\nCall list_datasets first.\n';

const root = mkdtempSync(join(tmpdir(), 'scenario-ask-skills-'));
Expand Down Expand Up @@ -118,6 +135,47 @@ describe('readAskSkills — the directory read once, as the record states it', (
});
});

describe('readAskSkills — a skill file is matched by its exact spelling, on every filesystem', () => {
afterEach(() => {
caseInsensitive.on = false;
});
const onBoth = (check: () => void) => {
for (const on of [true, false]) {
caseInsensitive.on = on;
check();
}
};

it('⛔ a skill directory whose file is spelled `skill.md` is refused, naming the file found and the spelling required', () => {
const dir = mkdtempSync(join(root, 'lower-'));
writeFileSync(join(dir, 'skill.md'), SKILL_MD);
onBoth(() =>
expect(() => readAskSkills(dir)).toThrow(
`--ask-skills names \`${dir}\`, which holds \`skill.md\`: a skill file is spelled \`SKILL.md\` exactly, ` +
'or a session reads it on one filesystem and misses it on another; rename it to `SKILL.md`',
),
);
});

it('⛔ in a directory of skills, one spelled `Skill.md` is refused by its path, never skipped while the others load', () => {
const dir = skillsDir();
mkdirSync(join(dir, 'mixed'));
writeFileSync(join(dir, 'mixed', 'Skill.md'), '---\nname: mixed\n---\n');
onBoth(() => expect(() => readAskSkills(dir)).toThrow(`--ask-skills names \`${dir}\`, which holds \`mixed/Skill.md\`: a skill file is spelled \`SKILL.md\` exactly`));
});

it('a skill file spelled `SKILL.md` loads as before, on both filesystems', () => {
const dir = skillsDir();
onBoth(() => {
expect(readAskSkills(dir).info.skills.map((s) => [s.name, s.version])).toEqual([
['ask-data', '1.2.0'],
['fallback', '0.1'],
]);
expect(readAskSkills(join(dir, 'ask-data')).info.skills.map((s) => s.name)).toEqual(['ask-data']);
});
});
});

/**
* A stand-in `claude`: `--version` and `auth status` as a subscription login
* answers them; a turn answers its argument list and the skill files its
Expand Down
Loading
Loading