Skip to content

Commit f012183

Browse files
feat(scenarios): skill-evals runs the published skills' eval cases on a with-skill and a no-skill arm (#34841)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ repo:objectstack#3 · os-support-ai · session_01WGufzg1NmbJpZhtiWQkTir Part of #34764 — this PR is the runner. The eval lane's charter line is the seat's own PR, after this one lands. Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:`@objectstack/scenarios` 里新增 `skill-evals` 运行器,只从仓库检出运行,不进发布的 bin 或 exports。它用订阅登录的 Claude Code 把已发布技能现成的 209 个评测用例逐条发给模型,每条跑两次,一次装上技能、一次不装,再按用例自带的 must_contain / must_not_contain 机械打分,写出每次的 JSON 记录和汇总。 - **为什么改**:#34691 S2 裁定 A:技能评测每周跑一轮,带一个不装技能的对照臂。在此之前,这些用例从没被送进过模型。 - **风险与回滚**:不进 CI,不拦合并。dist 里查不到该运行器的符号(已实测)。回滚就是 revert 本 PR。唯一的外部影响是一轮会用掉订阅额度:本轮让七日用量从 0.45 涨到 0.56,用量到 0.9 时运行器自己停下。 - **先看**:① `src/skill-evals/run.ts` 的 `verdictOf`,判断两臂是否装对、怎么打分;② `src/skill-evals/arms.ts`,两臂的 argv 和临时目录(技能的 `evals/` 不拷进去);③ `src/skill-evals/cli.ts`,登录守卫排在读取任何东西之前,以及 `--regrade`:修复轮 2 起,每条记录带用例哈希,用例改过的不重新打分、单列在通过率之外(`run.ts` 的 `regradeRecords`)。 - **两分钟验证**:`pnpm --filter '@objectstack/scenarios^...' build && pnpm --filter @objectstack/scenarios skill-evals --dry-run`。预期输出 11 个 bundle 和 `209 case(s) × 2 arms × 1 repeat(s) = 418 turn(s)`,外加一行 argv,不调用模型。 - **需要你做的**:无,席位落地。 ## What changes - **`packages/qa/scenarios/src/skill-evals/`** (new, unpublished). `pnpm --filter @objectstack/scenarios skill-evals` adds one `scripts` entry. The tsup entries, `bin` and `exports` are unchanged. - `cases.ts` reads `skills/BUNDLE/evals/*.json` strictly. A case that does not parse, uses the wrong types or asserts nothing is a located refusal, never a pass. It also reads which bundles set `user-invocable: false`. - `grade.ts`: pass = every `must_contain` present and no `must_not_contain`, as literal case-sensitive substrings of the answer (the result line's text). - `arms.ts`: one fresh temp dir per turn. The with-skill arm gets `.claude/skills/BUNDLE/` copied **without `evals/`**, and the no-skill arm gets nothing. Both arms run `--setting-sources project --tools Read,Glob,Grep,Skill --allowedTools Skill`, an empty `--mcp-config` with `--strict-mcp-config`, and `--no-session-persistence`. - `run.ts`: the preflight **imports** `subscriptionOnlyEnv` / `assertSubscriptionLogin` / `effortLevelsFromHelp` from `runner/driver.ts`, `runTurnProcess` and `parseStreamJson` (none copied). It also judges each turn: `pass` / `fail` / `invalid` (wrong arm) / `error` (no answer). The round stops on the rate-limit window (`--max-utilization`, default 0.9, exit 3). - `summary.ts`: per bundle, each arm's pass rate, the with-skill failures and the cases where no-skill ≥ with-skill. Per case, both arms. Written as `round.json`, `summary.md` and `summary.github.md` (angle brackets spelled out for a GitHub body). - `self-test.ts`: 21 table rows with a pinned roster, a floor and a verdict handshake, per AGENTS.md "Writing a `--self-test`". - `cli.ts`: `--skills a,b`, `--skills-from workspace|VERSION` (packs `@objectstack/skills@VERSION` from npm), `--repeats`, `--concurrency`, `--max-turns`, `--case-timeout`, `--max-utilization`, `--model`, `--effort`, `--bin`, `--out` (default under the git-ignored `docs/qa/platform-checklist/runs/`), `--dry-run`, `--regrade DIR`, `--self-test`. - `runner/driver.ts` and `runner/cli.ts` are not edited. - README section "Running the published skills' eval cases": login, arms, grading, records, quota, and cost and time from this PR's round. - Changeset: `@objectstack/scenarios` patch. The README is in `files[]`, so its text ships. Nothing else a consumer installs changes. ## Tests - `test/skill-evals/skill-evals.test.ts`, 26 tests. No model and no network; a turn is an injected function or a stand-in `claude` script. - A round refuses to start with `ANTHROPIC_API_KEY` set: from the preflight, and from the command line, where the stand-in is never asked a turn and no `--out` is created. `ANTHROPIC_AUTH_TOKEN`, an `api_key` login and no login are refused too. - The grader passes and fails, and a case-only difference is a fail. - `--self-test` passes with the real grader. It reds and never reaches its verdict when given a broken grader that passes everything, or an empty catalog. - The arms' argv. Each turn sees its arm's directory (bundle without `evals/`, or empty), the prompt on stdin, and no `ANTHROPIC_API_KEY` or `CLAUDE_CODE_EFFORT_LEVEL` in its environment. Its directory is removed afterwards. - The rate-limit stop, the summary arithmetic, the `user-invocable: false` handling, and `--regrade`. <details><summary>Readings at head 9de1cbd</summary> - `pnpm --filter @objectstack/scenarios typecheck && pnpm --filter @objectstack/scenarios exec vitest run --maxWorkers=2`, under `os-verify-lock`: `Test Files 36 passed (36)`, `Tests 1013 passed (1013)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/scenarios skill-evals --self-test`: `✓ skill-evals self-test: 20 rows pass.` - `skill-evals --dry-run`: 11 bundles, `209 case(s) × 2 arms × 1 repeat(s) = 418 turn(s)`. - Ablation (committed fix first, `scripts/ablation-replace.mjs`). The live preflight call in `cli.ts` was replaced with a constant login. Anchor x1 → x0, blob `8017e60d` → `e1b6bbe8`. The CLI refusal test went red (`1 failed | 18 passed (19)`). Restored to blob `8017e60d` = HEAD, and `git diff HEAD` is empty. </details> ## Acceptance notes - **Live round** on this container's subscription login. 209 cases × 2 arms × 1 rep = 418 turns, `--concurrency 4`, 56.1 min, all 418 ran, served `claude-opus-5-5` on every turn. Notional cost 71.24 USD; seven-day utilization 0.45 → 0.56. Result: with-skill 144/209 (69%), no-skill 20/209 (10%). 65 cases fail on the with-skill arm. The full per-bundle and per-case scores are in the `eval-run` record linked from #34764. - **Measured during the round, and fixed here.** `objectui` sets `user-invocable: false`. Claude Code 2.1.326 leaves such a skill out of the init line's `skills` list, but the model can still launch it. The first arm check therefore read all 34 `objectui` with-skill turns as `invalid`, although 33 of them launched `objectui`. The check now grades them and records `armEvidence` (`launched` / `not-shown`). `--regrade` re-drew those 34 verdicts from the recorded answers, asking no model. The turns ran at `adf4081a`, and `arms.ts`, `grade.ts` and the turn-running lines are byte-identical at head. - `no-skill ≥ with-skill` counts cases where both arms fail as well. This round: 2 cases where no-skill > with-skill, 18 where both pass, 63 where both fail. - 144 permission denials across 111 turns, a tool call refused for a missing permission (such as a read outside the turn's directory). This round's records keep only the count. The runner now also records the refused tool's name. - Measured, and reflected in the arms: a user skill under `~/.claude/skills/` is absent from a turn's init line under `--setting-sources project`. A read outside the turn's directory is refused in `-p` (`requested permissions to read … but you haven't granted it yet`). The published `@objectstack/skills@18.5.0` ships `dist/skills/BUNDLE/evals/` (29 tarball entries match `evals/`), so `--skills-from VERSION` reads that version's cases too. ## Verification - Derived gate families (`node scripts/pm/dispatch-gates.mjs --commands`, 75 commands at head) were all run locally. `dispatch-gates --ran`: `75 derived famil(ies) accounted for — 74 run, 1 NOT-MEASURED`. The one is `node scripts/check-plugin-teardown-shape.mjs --self-test` (exit 3, PREREQUISITE NOT MET: its fixture needs an unshallowed clone; it is a checker self-test and does not read this diff). - Publish surface: after `pnpm --filter @objectstack/scenarios build`, `gradeAnswer` is in 0 files under `dist/` (control: `assertSubscriptionLogin` is in 8). - `node scripts/pm/overlap-check.mjs` before each push: `VERDICT clean exit 0` (origin/main, #34808, #33849). - CI check-runs: in progress when this was opened. ## Fix round 2 (L1 S1, note N1) - **S1: `--regrade` grades an old answer only against the case that ran.** - Every run record now carries `caseHash`: a sha256 of the case's prompt and both token lists, as the turn ran them. `expected_output` is left out because it is neither sent nor graded. - On `--regrade`, each record's hash is compared with the case now (`caseDrift`: `same` / `changed` / `unhashed`). `regradeRecords` in `run.ts` then sorts the cases: - A case **changed** since the round, or **removed** from the catalog, is set apart. It is not regraded and its record files are left byte-for-byte as they are. It is left out of the summary's pass rates, and the summary header names it: `M case(s) changed since the round, set apart: not regraded and out of every pass rate below: KEYS`. `regradeRecord` itself also refuses a changed case. - A case **added** since the round is left out. Before this, it was counted as not run. - A record with **no hash** (one written before this round, such as the 2026-11-17 round) is regraded against the case as it is now. It is counted as `unhashed`, and the header says nothing shows those cases are the ones that ran. - `round.json` `regraded` gains `unhashed`, `setApart: { changed, removed }` and `added`. The planned set survives a second regrade. - **Why set apart rather than refuse.** Refusing the whole regrade would make every round recorded before a reword impossible to regrade, and #34789 rewords cases across the catalog. Regrading the changed case would mix week-N answers with week-N+1 assertions. Setting it apart keeps the rule regrade for the unchanged cases and keeps the changed ones visible outside the rates. - **N1.** The census prose in `scripts/pm/dispatch-gates.data.mjs` was re-measured at `e2c2b8c2` with `compoundAnchorDecls` over `git ls-files` (bare declarations counted by renaming `selfTest` to a probe name the anchor still matches): 330 matches, 294 bare, 36 compound over 29 spellings, 21 under `ui/`. The compound half matches the table (36 rows). The prose is comment-only. - README: one paragraph on `caseHash` and the set-apart rule, under Grading. The changeset is unchanged, since its sentence still describes the README. <details><summary>Readings at head bd40928</summary> - `pnpm --filter @objectstack/scenarios typecheck` and `vitest run --maxWorkers=2 test/skill-evals/skill-evals.test.ts`, under `os-verify-lock`: `Tests 26 passed (26)`, `VERDICT command-exit 0`. The whole package after `pnpm --filter @objectstack/scenarios build`: `Test Files 36 passed (36)`, `Tests 1017 passed (1017)`, `VERDICT command-exit 0`. - `skill-evals --self-test`: `✓ skill-evals self-test: 21 rows pass.` The new row is `regrade: a case changed since the round → SET APART, never graded against the new text`. - New pins: every record carries its case hash (and `expected_output` does not move it). An unchanged case regrades normally, a changed one is set apart and refused by `regradeRecord`, and an unhashed record is regraded and counted. A removed case is set apart and an added one is left out. The command runs on a fixture round: the reworded case's record bytes are unchanged, the summary names it, and it is out of the totals. - Ablation (fix committed first, `scripts/ablation-replace.mjs`). `caseDrift`'s comparison `return rec.caseHash === hashCase(c) ? 'same' : 'changed';` was replaced with `return 'same';`. Anchor x1 → x0, blob `b48c9627` → `10e64fff`. The result was `Tests 4 failed | 22 passed (26)`: both regrade pins, the self-test row, and the empty-catalog self-test count. Restored to blob `b48c9627` = HEAD, and `git diff HEAD` is empty. - `--regrade` on a scratch copy of the 2026-11-17 regraded round, with no model asked: `418 record(s) carry no case hash … regraded against the cases as they are now`. The setApart and added lists are empty, and the summary is identical to the recorded one (with-skill 144/209, no-skill 20/209). - `pnpm check:pm-dispatch-gates` (because the ledger file was touched): `EXIT=0`, `✓ every compound self-test NAME the anchor matches is classified in COMPOUND_ANCHOR_LEDGER`, and the fast tier `2217 cases pass`. The slow tier is deferred to CI. - `node scripts/check-nul-bytes.mjs`: OK. `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0` (origin/main, #34882, #33849). - Local scope was narrowed to the dispatch's list. The derived `--commands` set (121 over the whole PR change set) is left to CI. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzg1NmbJpZhtiWQkTir)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzg1NmbJpZhtiWQkTir --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c41b6ca commit f012183

12 files changed

Lines changed: 2139 additions & 8 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
docs(scenarios): the README documents the skill-evals runner
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The package README gains a section on `skill-evals`, a command run from an ObjectStack checkout (`pnpm --filter @objectstack/scenarios skill-evals`). It runs the published skills' existing eval cases (`skills/BUNDLE/evals/*.json`) through the local Claude Code subscription login, each case once with its skill bundle installed and once without, and grades each answer by the case's own `must_contain` / `must_not_contain` tokens. The runner is not in the published `bin` or `exports`, so nothing a consumer installs changes beyond the README text and a `scripts` entry in `package.json`.

‎packages/qa/scenarios/README.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,3 +729,61 @@ the directory you run from. For anything more, write a wrapper script.
729729
**WorkBuddy** (checked 2026-11-07): Tencent's WorkBuddy is a desktop app; no headless mode with structured output
730730
and an MCP client was found for it, so it is not wired here. A tool that has both rides `--driver external:` with a
731731
wrapper, with no change to the runner.
732+
733+
## Running the published skills' eval cases — `skill-evals`
734+
735+
Every published skill bundle carries eval cases (`skills/BUNDLE/evals/*.json`: a `prompt`, an `expected_output` and
736+
`assertions.must_contain` / `must_not_contain`). `skill-evals` sends each case to the local Claude Code login twice,
737+
once with the bundle installed and once without, and grades each answer by the case's own tokens. It runs from this
738+
checkout only. It is not part of the published `bin` or `exports`, not a CI job and not a merge gate. The cases are
739+
the skill authors' and the runner never edits them.
740+
741+
```bash
742+
unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN
743+
claude auth status # oauth_token
744+
pnpm install && pnpm --filter '@objectstack/scenarios^...' build # the runner reads its dependencies' dist/
745+
pnpm --filter @objectstack/scenarios skill-evals --dry-run # the plan and the argv; no login read, no model call
746+
pnpm --filter @objectstack/scenarios skill-evals # every case × 2 arms
747+
pnpm --filter @objectstack/scenarios skill-evals --skills objectstack-query --repeats 3 # a touched skill
748+
pnpm --filter @objectstack/scenarios skill-evals --skills-from 18.5.0 # a published @objectstack/skills version's bundles and cases
749+
pnpm --filter @objectstack/scenarios skill-evals --regrade DIR # re-draw a recorded round's verdicts from its records; no model call
750+
pnpm --filter @objectstack/scenarios skill-evals --self-test # the runner's own fixtures; no model call
751+
```
752+
753+
- **Login**: the scenario runner's guard, imported from `src/runner/driver.ts`. A round refuses to start while
754+
`ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` is set, or when `claude auth status` reports no login or an API-key
755+
login. Every turn is spawned without those two variables. Never an API-billed key.
756+
- **The arms**: each turn is one `claude -p` in a fresh temporary directory. The prompt goes on stdin. The two arms
757+
differ only in the bundle. The with-skill arm copies it into `.claude/skills/BUNDLE/` without its `evals/`, so the
758+
turn cannot read the assertions it is graded on. The no-skill arm's directory is empty. Both arms take the same
759+
flags: `--setting-sources project` (the user's own skills, plugins and hooks stay out),
760+
`--tools Read,Glob,Grep,Skill`, no MCP server (`--strict-mcp-config` over an empty config) and
761+
`--no-session-persistence`. A read outside the directory needs a permission no turn is given, and `-p` denies it.
762+
The skills built into Claude Code are present in both arms.
763+
- **Grading**: the answer is the result line's text, the reply a user reads. It passes when every `must_contain` token
764+
is in it and no `must_not_contain` token is. Tokens match as literal, case-sensitive substrings, and no model judges
765+
an answer. A turn whose init line shows the wrong arm is `invalid`: the with-skill arm does not list the bundle, or
766+
the no-skill arm lists one or launches one. A bundle whose `SKILL.md` sets `user-invocable: false` (`objectui`) is
767+
never in the init line's `skills` list, though the model can launch it. Its with-skill turns are graded, and each
768+
record's `armEvidence` says whether the turn launched the bundle (`launched`) or nothing in the stream shows it
769+
(`not-shown`). A turn with no answer is `error`: the process failed or timed out, or the result line is not
770+
`success` (`error_max_turns` included). Both kinds are counted and named, and neither is in a denominator.
771+
`--regrade DIR` applies the current rules to a recorded round's answers and arm facts. A changed record keeps the
772+
verdict its turn was first given as `regradedFrom`. Each record carries `caseHash`, a hash of its case's prompt and
773+
token lists as the turn ran them. A case changed or removed since the round is set apart: it is not regraded, its
774+
records are left as they are, and the summary names it outside every pass rate. A record with no hash predates the
775+
hash; it is regraded against the case as it is now, and the summary counts it as unhashed.
776+
- **Records**: by default the round goes to `docs/qa/platform-checklist/runs/skill-evals/ROUND/` (git-ignored), or to
777+
`--out`. It holds one `runs/*.json` per turn (verdict, missing and forbidden tokens, the answer, the skills listed
778+
and launched, the served model, the CLI's notional cost and the rate-limit reading), `round.json` (environment,
779+
scope and the full per-case scores on both arms) and `summary.md`. The summary has one row per bundle (each arm's
780+
pass rate, the with-skill failing cases, and the cases where the no-skill arm scored at least as high) and then
781+
every case. `summary.github.md` is the same text with angle brackets spelled `(lt)` / `(gt)` for a GitHub body.
782+
- **Quota**: every turn reports the subscription's rate-limit window. The round stops scheduling turns once a window
783+
reports `rejected` or a utilization at or above `--max-utilization` (default 0.9). The turns not run are recorded
784+
as not run, and the command exits 3.
785+
- **Cost and time**: the CLI's cost figure is notional under a subscription login, and nothing is billed per token.
786+
One whole round took 56 min in a Claude Code cloud container: 209 cases × 2 arms, `--concurrency 4`, Claude Code
787+
2.1.326, the login's default model. The CLI reported 71 USD notional for it, 49 for the with-skill arm and 22 for
788+
the no-skill arm. The median turn took 30 s with the skill and 24 s without. The round moved the login's seven-day
789+
utilization from 0.45 to 0.56.

‎packages/qa/scenarios/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@
6767
"typecheck": "tsc --noEmit",
6868
"run-scenarios": "tsx src/runner/cli.ts",
6969
"export-gallery": "tsx src/export/cli.ts",
70-
"gallery-refresh": "tsx src/export/refresh-cli.ts"
70+
"gallery-refresh": "tsx src/export/refresh-cli.ts",
71+
"skill-evals": "tsx src/skill-evals/cli.ts"
7172
},
7273
"dependencies": {
7374
"@objectstack/core": "workspace:*",
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The two arms one case runs under, as the directory a `claude -p` turn starts
5+
* in and the argv it is given. The arms differ in exactly one thing — whether
6+
* the case's bundle sits in the turn's project skills
7+
* (`.claude/skills/BUNDLE/`) — and share everything else:
8+
*
9+
* - a fresh temporary directory as the working directory, so nothing of this
10+
* checkout is in reach (a read outside the working directory needs a
11+
* permission no turn is granted, and `-p` denies it);
12+
* - `--setting-sources project`: the user's own settings, skills, plugins and
13+
* hooks stay out (measured on Claude Code 2.1.326: a user skill under
14+
* `~/.claude/skills/` is absent from the init line's `skills`, while a
15+
* bundle under the directory's `.claude/skills/` is listed); the skills
16+
* built into Claude Code stay in, in both arms alike;
17+
* - `--tools Read,Glob,Grep,Skill`: the bundle's `rules/` and `references/`
18+
* files are readable, nothing runs a command, nothing fetches the web;
19+
* - `--allowedTools Skill`, so a skill launch needs no prompt;
20+
* - no MCP server: `--strict-mcp-config` over an empty `--mcp-config`;
21+
* - `--no-session-persistence`, so a round leaves no session behind.
22+
*
23+
* The bundle is copied WITHOUT its `evals/` directory: the cases' expected
24+
* outputs and assertions must not be readable by the turn being graded on them.
25+
*/
26+
27+
import { cpSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
28+
import { tmpdir } from 'node:os';
29+
import { join, sep } from 'node:path';
30+
31+
export const ARMS = ['with-skill', 'no-skill'] as const;
32+
export type Arm = (typeof ARMS)[number];
33+
34+
/** The built-in tools both arms are given. */
35+
export const ARM_TOOLS = ['Read', 'Glob', 'Grep', 'Skill'] as const;
36+
37+
/** The directory under the bundle never copied into a turn's project. */
38+
export const WITHHELD_BUNDLE_DIR = 'evals';
39+
40+
export interface ArmTurnOptions {
41+
/** `--max-turns` for one case. */
42+
maxTurns: number;
43+
/** `--model`; absent ⇒ the login's default. */
44+
model?: string;
45+
/** `--effort`; absent ⇒ the CLI's default effort. */
46+
effort?: string;
47+
}
48+
49+
/** The argv of one turn, prompt excluded (it travels on stdin). Pure over its inputs. */
50+
export function armArgs(mcpConfigPath: string, opts: ArmTurnOptions): string[] {
51+
const a = [
52+
'-p',
53+
'--output-format', 'stream-json',
54+
'--verbose',
55+
'--max-turns', String(opts.maxTurns),
56+
'--setting-sources', 'project',
57+
'--tools', ARM_TOOLS.join(','),
58+
'--allowedTools', 'Skill',
59+
'--mcp-config', mcpConfigPath,
60+
'--strict-mcp-config',
61+
'--no-session-persistence',
62+
];
63+
if (opts.model) a.push('--model', opts.model);
64+
if (opts.effort) a.push('--effort', opts.effort);
65+
return a;
66+
}
67+
68+
export interface ArmWorkdir {
69+
/** The turn's working directory (fresh, empty but for the arm's skill). */
70+
cwd: string;
71+
/** The empty MCP config the turn is pointed at, outside `cwd`. */
72+
mcpConfigPath: string;
73+
/** Remove everything this made. */
74+
root: string;
75+
}
76+
77+
/**
78+
* Make one turn's directory: `ROOT/project` as the working directory, holding
79+
* `.claude/skills/BUNDLE/` (without `evals/`) on the with-skill arm and
80+
* nothing on the no-skill arm, and `ROOT/mcp.json` beside it.
81+
*/
82+
export function prepareArmWorkdir(arm: Arm, bundle: string, skillsRoot: string, base: string = tmpdir()): ArmWorkdir {
83+
const root = mkdtempSync(join(base, 'skill-eval-'));
84+
const cwd = join(root, 'project');
85+
mkdirSync(cwd);
86+
const mcpConfigPath = join(root, 'mcp.json');
87+
writeFileSync(mcpConfigPath, JSON.stringify({ mcpServers: {} }));
88+
if (arm === 'with-skill') {
89+
const from = join(skillsRoot, bundle);
90+
const withheld = join(from, WITHHELD_BUNDLE_DIR);
91+
cpSync(from, join(cwd, '.claude', 'skills', bundle), {
92+
recursive: true,
93+
// A link into this checkout would hand the turn a path outside its project: copy what it points at.
94+
dereference: true,
95+
filter: (src) => src !== withheld && !src.startsWith(withheld + sep),
96+
});
97+
}
98+
return { cwd, mcpConfigPath, root };
99+
}
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The published skills' eval cases, read from a skills root: the workspace's
5+
* `skills/` tree, or the `dist/skills/` of a packed `@objectstack/skills`
6+
* version. Each bundle is one directory holding a `SKILL.md`; its cases are the
7+
* `evals/*.json` files beside it, in the shape every one of them already uses:
8+
*
9+
* { "skill_name": BUNDLE, "evals": [ { "id", "prompt", "expected_output",
10+
* "files": [], "assertions": { "must_contain": [..], "must_not_contain": [..] } } ] }
11+
*
12+
* The reader is strict, never lenient: a file that does not parse, a case
13+
* whose prompt is not a string, an assertion list that is not a list of
14+
* strings, or a case with no assertion at all is a located refusal — never a
15+
* case graded as a pass because nothing was asked of it. The cases themselves
16+
* are not this runner's to edit.
17+
*/
18+
19+
import { createHash } from 'node:crypto';
20+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
21+
import { join } from 'node:path';
22+
23+
/** One eval case, located. */
24+
export interface SkillEvalCase {
25+
/** The bundle directory name (`objectstack-query`). */
26+
bundle: string;
27+
/** The eval file's name inside `evals/` (`filters-pagination-search.json`). */
28+
file: string;
29+
/** The case's own `id` inside its file. */
30+
id: number | string;
31+
/** `BUNDLE/FILE_STEM#ID` — unique across a catalog. */
32+
key: string;
33+
prompt: string;
34+
expectedOutput?: string;
35+
mustContain: string[];
36+
mustNotContain: string[];
37+
}
38+
39+
/** A file or case the reader refused, with where. */
40+
export interface SkillEvalRefusal {
41+
path: string;
42+
message: string;
43+
}
44+
45+
export interface SkillEvalCatalog {
46+
root: string;
47+
/** Every bundle directory under the root (a `SKILL.md` beside it), sorted. */
48+
bundles: string[];
49+
/**
50+
* Bundles whose `SKILL.md` frontmatter says `user-invocable: false`. Claude
51+
* Code leaves such a skill out of the init line's `skills` list while the
52+
* model can still launch it (measured on 2.1.326: `objectui`, absent from
53+
* every with-skill init line of a round, launched by 33 of its 34 turns), so
54+
* the init line cannot show that it was installed.
55+
*/
56+
unlistedBundles: string[];
57+
cases: SkillEvalCase[];
58+
refusals: SkillEvalRefusal[];
59+
}
60+
61+
const isStringList = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === 'string');
62+
63+
/** `BUNDLE/FILE_STEM#ID`. */
64+
export const caseKey = (bundle: string, file: string, id: number | string): string => `${bundle}/${file.replace(/\.json$/, '')}#${id}`;
65+
66+
/**
67+
* The case as a turn meets it: a hash of the prompt the turn is asked and the
68+
* two token lists its answer is graded on (`expected_output` is neither sent
69+
* nor graded, so it is left out). Every run record carries it, so `--regrade`
70+
* can tell a case reworded since the round from the case that ran. Pure.
71+
*/
72+
export const hashCase = (c: Pick<SkillEvalCase, 'prompt' | 'mustContain' | 'mustNotContain'>): string =>
73+
`sha256:${createHash('sha256').update(JSON.stringify([c.prompt, c.mustContain, c.mustNotContain])).digest('hex')}`;
74+
75+
/** Read one eval file's text into cases, or refusals. Pure over its inputs. */
76+
export function parseEvalFile(bundle: string, file: string, text: string): { cases: SkillEvalCase[]; refusals: SkillEvalRefusal[] } {
77+
const path = `${bundle}/evals/${file}`;
78+
const cases: SkillEvalCase[] = [];
79+
const refusals: SkillEvalRefusal[] = [];
80+
let doc: unknown;
81+
try {
82+
doc = JSON.parse(text);
83+
} catch (e) {
84+
return { cases, refusals: [{ path, message: `does not parse: ${e instanceof Error ? e.message : String(e)}` }] };
85+
}
86+
const evals = typeof doc === 'object' && doc !== null && !Array.isArray(doc) ? (doc as Record<string, unknown>).evals : undefined;
87+
if (!Array.isArray(evals)) return { cases, refusals: [{ path, message: 'has no `evals` list' }] };
88+
const seen = new Set<string>();
89+
evals.forEach((raw, i) => {
90+
const at = `${path}: evals[${i}]`;
91+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
92+
refusals.push({ path: at, message: 'is not an object' });
93+
return;
94+
}
95+
const e = raw as Record<string, unknown>;
96+
const id = e.id;
97+
if (typeof id !== 'number' && typeof id !== 'string') {
98+
refusals.push({ path: at, message: '`id` is neither a number nor a string' });
99+
return;
100+
}
101+
if (typeof e.prompt !== 'string' || e.prompt.trim() === '') {
102+
refusals.push({ path: at, message: '`prompt` is not a non-empty string' });
103+
return;
104+
}
105+
const a = e.assertions;
106+
if (typeof a !== 'object' || a === null || Array.isArray(a)) {
107+
refusals.push({ path: at, message: '`assertions` is not an object' });
108+
return;
109+
}
110+
const { must_contain: mc = [], must_not_contain: mnc = [] } = a as Record<string, unknown>;
111+
if (!isStringList(mc) || !isStringList(mnc)) {
112+
refusals.push({ path: at, message: '`assertions.must_contain` / `must_not_contain` must each be a list of strings' });
113+
return;
114+
}
115+
if (mc.length + mnc.length === 0) {
116+
refusals.push({ path: at, message: 'asserts nothing: a case with no `must_contain` and no `must_not_contain` would pass every answer' });
117+
return;
118+
}
119+
const key = caseKey(bundle, file, id);
120+
if (seen.has(key)) {
121+
refusals.push({ path: at, message: `repeats the id \`${String(id)}\`` });
122+
return;
123+
}
124+
seen.add(key);
125+
cases.push({
126+
bundle,
127+
file,
128+
id,
129+
key,
130+
prompt: e.prompt,
131+
...(typeof e.expected_output === 'string' ? { expectedOutput: e.expected_output } : {}),
132+
mustContain: mc,
133+
mustNotContain: mnc,
134+
});
135+
});
136+
return { cases, refusals };
137+
}
138+
139+
/** Every bundle under `root` and every case its `evals/*.json` hold. */
140+
export function loadSkillEvalCatalog(root: string): SkillEvalCatalog {
141+
if (!existsSync(root) || !statSync(root).isDirectory()) {
142+
return { root, bundles: [], unlistedBundles: [], cases: [], refusals: [{ path: root, message: 'is not a directory of skill bundles' }] };
143+
}
144+
const bundles = readdirSync(root, { withFileTypes: true })
145+
.filter((d) => d.isDirectory() && existsSync(join(root, d.name, 'SKILL.md')))
146+
.map((d) => d.name)
147+
.sort();
148+
const cases: SkillEvalCase[] = [];
149+
const refusals: SkillEvalRefusal[] = [];
150+
for (const bundle of bundles) {
151+
const dir = join(root, bundle, 'evals');
152+
if (!existsSync(dir)) continue;
153+
const files = readdirSync(dir, { withFileTypes: true })
154+
.filter((d) => d.isFile() && d.name.endsWith('.json'))
155+
.map((d) => d.name)
156+
.sort();
157+
for (const file of files) {
158+
const r = parseEvalFile(bundle, file, readFileSync(join(dir, file), 'utf8'));
159+
cases.push(...r.cases);
160+
refusals.push(...r.refusals);
161+
}
162+
}
163+
const unlistedBundles = bundles.filter((b) => notUserInvocable(readFileSync(join(root, b, 'SKILL.md'), 'utf8')));
164+
return { root, bundles, unlistedBundles, cases, refusals };
165+
}
166+
167+
/** The `SKILL.md` frontmatter sets `user-invocable: false`. Pure over its input. */
168+
export function notUserInvocable(skillMd: string): boolean {
169+
const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(skillMd);
170+
return fm !== null && /^user-invocable:\s*false\s*$/m.test(fm[1]!);
171+
}
172+
173+
/**
174+
* Narrow a catalog to the named bundles (`--skills a,b`). A name that is not a
175+
* bundle of the catalog is refused, never dropped: a misspelt touched skill
176+
* would otherwise run nothing and read as a clean round.
177+
*/
178+
export function selectBundles(catalog: SkillEvalCatalog, names: readonly string[] | undefined): SkillEvalCase[] {
179+
if (!names || names.length === 0) return catalog.cases;
180+
const unknown = names.filter((n) => !catalog.bundles.includes(n));
181+
if (unknown.length) throw new Error(`--skills names ${unknown.map((n) => `\`${n}\``).join(', ')}, not a bundle under ${catalog.root} (bundles: ${catalog.bundles.join(', ')})`);
182+
const noCases = names.filter((n) => !catalog.cases.some((c) => c.bundle === n));
183+
if (noCases.length) throw new Error(`--skills names ${noCases.map((n) => `\`${n}\``).join(', ')}, a bundle with no eval case under ${catalog.root}`);
184+
const set = new Set(names);
185+
return catalog.cases.filter((c) => set.has(c.bundle));
186+
}

0 commit comments

Comments
 (0)