dsh-project-dept 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1344 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """project-dept evals runner — schema check, deterministic keyword grading, A/B compare.
4
+
5
+ The eval cases in ``evals/evals.json`` are frozen judge criteria (prompt + expected_output)
6
+ plus machine-checkable assertions. This runner never calls a model: it checks the assertions
7
+ file itself, prints a ready-to-paste grading brief for a judge sub-agent, and scores an answer
8
+ deterministically so the same answer always gets the same verdict.
9
+
10
+ Modes
11
+ -----
12
+ static (default)
13
+ Validate ``evals/evals.json`` against the v2 schema (fields present, ids unique,
14
+ assertions non-empty and not tautological, must_include literally derivable from
15
+ expected_output, must_exclude not present in expected_output, axes real, steps real,
16
+ budgets positive). On success print, for every case, a complete grading brief that can
17
+ be pasted verbatim to a judge sub-agent, plus the case's token budget.
18
+
19
+ grade --case <id> --answer <path>
20
+ DEPRECATED as an acceptance criterion. Deterministic keyword grading: every
21
+ must_include must appear verbatim; any must_exclude appearing is an immediate FAIL.
22
+ Reason: verbatim matching rejects answers that state the right point in different
23
+ words; measured on 12 real answers it produced 12/12 false FAILs (backlog P-15-8).
24
+ Use ``judge`` + ``tally`` instead. The mode still prints its per-assertion
25
+ ``[ok]``/``[x]`` report and last line ``CASE <id> PASS`` or ``CASE <id> FAIL`` with
26
+ unchanged exit codes.
27
+
28
+ compare --with <dir> --without <dir>
29
+ Run grade over the answer files of two directories and print an A/B table (per-case
30
+ verdict, total passes, naive difference) with an explicit small-sample warning.
31
+
32
+ judge --answers <dir> --out <dir> [--seed 7] [--case <id>]
33
+ Blind-judge harness. Scan ``<case>-<arm>-r<rep>.txt`` answer files (arm is one of
34
+ with/without, rep a positive integer); any other file in the directory is a hard error.
35
+ For every case, shuffle the answers with a reproducible seed, replace identities by
36
+ A/B/C..., and write three files:
37
+ * ``judge_prompt_<case>.md`` - grading instructions + 4 rubric items + the
38
+ anonymised answer texts. Safe to hand to a judge: no arm name and no arm-revealing
39
+ hint appears anywhere in it.
40
+ * ``scores_template_<case>.json`` - the case id, the 4 rubric items, and a
41
+ null-filled 0/1 slot per anonymous answer for the judge to fill in.
42
+ * ``map_<case>.json`` - anonymous label -> real answer key
43
+ (``with-r1`` / ``without-r1`` ...). FOR STATISTICS ONLY; never give it to a judge.
44
+ Rubric source: the case's optional ``rubric`` field (a list of exactly 4 strings) when
45
+ present; otherwise 4 groups split evenly out of ``assertions.must_include``. The
46
+ expected_output text is never injected into the rubric.
47
+
48
+ tally --out <dir> [--json]
49
+ Read ``scores_*.json`` + ``map_*.json`` pairs written by judge, then print: per-case
50
+ two-arm totals and full marks (items x reps), per-rubric two-arm hit counts, paired
51
+ ``(case, rep)`` with-better / worse / tie counts, the paired win rate with a Wilson 95%
52
+ confidence interval (with a directional-only warning for small n), and the grand total
53
+ row. Any null score, unequal arm counts, an answer missing from one arm or an unpaired
54
+ file is a hard error (exit 2), never a silent skip. ``--json`` makes stdout a single
55
+ JSON document (payload keys: cases, items, pairs, per_arm, wilson, warnings).
56
+
57
+ Exit codes
58
+ ----------
59
+ static : 0 valid | 2 invalid
60
+ grade : 0 PASS | 1 FAIL | 2 cannot execute (bad args, case missing, answer unreadable)
61
+ compare: 0 both sides graded (NOT "both passed") | 1 a case FAILed on the --with side |
62
+ 2 evals invalid or a directory unreadable
63
+ judge : 0 prompt/template/map written | 2 cannot execute (bad answer naming, unequal arms)
64
+ tally : 0 statistics printed | 2 cannot execute (null score, mismatch, missing pair)
65
+
66
+ Why the deprecation: keyword matching rejects answers that state the right point in
67
+ different words. Measured on 12 real answers it produced 12/12 false FAILs, so it is not
68
+ an acceptance criterion (backlog P-15-8); use judge + tally for verdicts.
69
+
70
+ Standard library only. Paths resolve relative to this script, never to the user's cwd.
71
+ """
72
+
73
+ from __future__ import annotations
74
+
75
+ import argparse
76
+ import hashlib
77
+ import json
78
+ import math
79
+ import os
80
+ import random
81
+ import re
82
+ import sys
83
+
84
+ HERE = os.path.dirname(os.path.abspath(__file__))
85
+ SKILL_ROOT = os.path.dirname(HERE)
86
+ DEFAULT_EVALS = os.path.join(SKILL_ROOT, "evals", "evals.json")
87
+ MANIFEST_PATH = os.path.join(SKILL_ROOT, "manifest.yaml")
88
+ WORKFLOW_PATH = os.path.join(SKILL_ROOT, "static", "core", "workflow.md")
89
+ RUNS_HINT_DIR = os.path.join("evals", "runs")
90
+
91
+ EXIT_PASS = 0
92
+ EXIT_FAIL = 1
93
+ EXIT_CANNOT = 2
94
+
95
+ # A string that any answer would contain proves nothing. must_include may not be one of these.
96
+ TRUE_STRINGS = frozenset({u"的", u"是", u"了", u"和", u"与", u"在", u"一个",
97
+ u"a", u"the", u"and"})
98
+ MIN_INCLUDE = 5
99
+ MIN_EXCLUDE = 2
100
+
101
+ # Slugs are derived from static/core/workflow.md headings; the label is what the heading says.
102
+ STEP_VOCAB = {
103
+ "0-gate": u"Step 0 \u2014 Run the gate",
104
+ "1-read-base": u"Step 1 \u2014 Read the base",
105
+ "2-scope": u"Step 2 \u2014 Scope the package (\u7acb\u9879)",
106
+ "3-split": u"Step 3 \u2014 Break into tasks",
107
+ "4-staff": u"Step 4 \u2014 Staff it",
108
+ "5-run-loop": u"Step 5 \u2014 Run the loop",
109
+ "6-closeout": u"Step 6 \u2014 Close and archive",
110
+ }
111
+
112
+ for _stream in (sys.stdout, sys.stderr):
113
+ try:
114
+ _stream.reconfigure(encoding="utf-8", errors="replace")
115
+ except Exception: # noqa: BLE001 (older Python / redirected streams)
116
+ pass
117
+
118
+
119
+ class EvalError(Exception):
120
+ """A condition that makes the requested mode impossible to execute (exit 2)."""
121
+
122
+
123
+ # --------------------------------------------------------------------------- #
124
+ # loading / small utilities
125
+ # --------------------------------------------------------------------------- #
126
+ def read_bytes(path):
127
+ try:
128
+ with open(path, "rb") as fh:
129
+ return fh.read()
130
+ except OSError as exc:
131
+ raise EvalError("读不到 %s:%s" % (path, exc)) from exc
132
+
133
+
134
+ def load_json_file(path, label="evals.json"):
135
+ raw = read_bytes(path)
136
+ if raw.startswith(b"\xef\xbb\xbf"):
137
+ raise EvalError(
138
+ "%s 带 UTF-8 BOM(EF BB BF);本项目踩过这个坑:必须保存为 UTF-8 无 BOM 再跑 json.load"
139
+ % label)
140
+ try:
141
+ text = raw.decode("utf-8")
142
+ except UnicodeDecodeError as exc:
143
+ raise EvalError("%s 不是合法 UTF-8:%s" % (label, exc)) from exc
144
+ try:
145
+ return json.loads(text)
146
+ except json.JSONDecodeError as exc:
147
+ raise EvalError("%s 不是合法 JSON:第 %d 行第 %d 列:%s"
148
+ % (label, exc.lineno, exc.colno, exc.msg)) from exc
149
+
150
+
151
+ def load_manifest_axes(path=MANIFEST_PATH):
152
+ """Extract {axis: [values...]} from manifest.yaml without a YAML dependency.
153
+
154
+ The manifest is written in a fixed shape (``axes:`` at indent 2, ``values:`` at indent 4,
155
+ ``key: fragment`` at indent 6), so a tiny indentation-aware reader is enough and keeps the
156
+ runner standard-library only.
157
+ """
158
+ raw = read_bytes(path)
159
+ try:
160
+ text = raw.decode("utf-8-sig")
161
+ except UnicodeDecodeError as exc:
162
+ raise EvalError("manifest.yaml 不是合法 UTF-8:%s" % exc) from exc
163
+ axes = {}
164
+ current = None
165
+ in_values = False
166
+ for line in text.splitlines():
167
+ stripped = line.strip()
168
+ if not stripped or stripped.startswith("#"):
169
+ continue
170
+ indent = len(line) - len(line.lstrip(" "))
171
+ if indent == 2 and stripped.endswith(":") and not stripped.startswith("-"):
172
+ current = stripped[:-1].strip()
173
+ axes[current] = []
174
+ in_values = False
175
+ elif indent == 4 and stripped == "values:":
176
+ in_values = True
177
+ elif in_values and indent == 6 and ":" in stripped:
178
+ key = stripped.split(":", 1)[0].strip()
179
+ if key:
180
+ axes[current].append(key)
181
+ elif indent <= 4:
182
+ in_values = False
183
+ axes = {k: v for k, v in axes.items() if v}
184
+ for required in ("deliverable", "rigor"):
185
+ if required not in axes:
186
+ raise EvalError("manifest.yaml 里读不到 axes.%s 的 values(声明缺失或格式变了)" % required)
187
+ return axes
188
+
189
+
190
+ def load_workflow_headings(path=WORKFLOW_PATH):
191
+ """Return {step_number: heading_title} parsed from workflow.md; empty dict if unreadable."""
192
+ try:
193
+ text = read_bytes(path).decode("utf-8-sig")
194
+ except (EvalError, UnicodeDecodeError):
195
+ return {}
196
+ headings = {}
197
+ for line in text.splitlines():
198
+ m = re.match(r"^##\s*Step\s*(\d+)\s*[\u2014\u2013-]\s*(.+?)\s*$", line)
199
+ if m:
200
+ headings[int(m.group(1))] = m.group(2).strip()
201
+ return headings
202
+
203
+
204
+ def load_and_validate(evals_path):
205
+ """Load evals.json + manifest, validate, return (data, axes, warnings)."""
206
+ data = load_json_file(evals_path)
207
+ axes = load_manifest_axes()
208
+ errors, warnings = validate(data, axes)
209
+ if errors:
210
+ raise ValidationFailed(errors)
211
+ return data, axes, warnings
212
+
213
+
214
+ class ValidationFailed(EvalError):
215
+ def __init__(self, errors):
216
+ super().__init__("evals.json 不合法")
217
+ self.errors = errors
218
+
219
+
220
+ def _is_nonempty_str(value):
221
+ return isinstance(value, str) and bool(value.strip())
222
+
223
+
224
+ def _dedupe_report(items):
225
+ seen = set()
226
+ dupes = []
227
+ for item in items:
228
+ if item in seen and item not in dupes:
229
+ dupes.append(item)
230
+ seen.add(item)
231
+ return dupes
232
+
233
+
234
+ def validate(data, axes):
235
+ """Check the v2 schema. Returns (errors, warnings); errors are human-readable Chinese."""
236
+ errors = []
237
+ warnings = []
238
+
239
+ if not isinstance(data, dict):
240
+ return ["顶层必须是 JSON 对象"], warnings
241
+
242
+ if not _is_nonempty_str(data.get("skill_name")):
243
+ errors.append("skill_name 必须是非空字符串")
244
+ if data.get("schema_version") != 2:
245
+ errors.append("schema_version 必须是整数 2(当前 %r)" % (data.get("schema_version"),))
246
+ if not _is_nonempty_str(data.get("eval_mode")):
247
+ errors.append("eval_mode 必须是非空字符串(如 static+manual-judge)")
248
+
249
+ cases = data.get("evals")
250
+ if not isinstance(cases, list) or not cases:
251
+ errors.append("evals 必须是非空数组")
252
+ return errors, warnings
253
+
254
+ seen_ids = set()
255
+ for index, case in enumerate(cases):
256
+ where = "evals[%d]" % index
257
+ if not isinstance(case, dict):
258
+ errors.append("%s 必须是对象" % where)
259
+ continue
260
+
261
+ cid = case.get("id")
262
+ if not _is_nonempty_str(cid):
263
+ errors.append("%s.id 必须是非空字符串" % where)
264
+ label = where
265
+ else:
266
+ label = cid
267
+ if cid in seen_ids:
268
+ errors.append("case '%s': id 重复(id 必须唯一)" % cid)
269
+ seen_ids.add(cid)
270
+
271
+ def err(message):
272
+ errors.append("case '%s': %s" % (label, message))
273
+
274
+ expected = case.get("expected_output")
275
+ if not _is_nonempty_str(case.get("prompt")):
276
+ err("缺 prompt 或不是非空字符串")
277
+ if not _is_nonempty_str(expected):
278
+ err("缺 expected_output 或不是非空字符串")
279
+
280
+ assertions = case.get("assertions")
281
+ if not isinstance(assertions, dict):
282
+ err("缺 assertions 或不是对象")
283
+ continue
284
+
285
+ include = assertions.get("must_include")
286
+ include_valid = isinstance(include, list)
287
+ if not include_valid:
288
+ err("assertions.must_include 必须是数组")
289
+ include = []
290
+ elif len(include) < MIN_INCLUDE:
291
+ err("assertions.must_include 至少 %d 条(当前 %d)" % (MIN_INCLUDE, len(include)))
292
+ seen_include = []
293
+ for pos, item in enumerate(include, 1):
294
+ if not _is_nonempty_str(item):
295
+ err("must_include 第 %d 条必须是非空字符串" % pos)
296
+ continue
297
+ seen_include.append(item)
298
+ if item.strip() in TRUE_STRINGS:
299
+ err("must_include 含恒真串 '%s'(黑名单:%s),换有鉴别力的短串"
300
+ % (item, "/".join(sorted(TRUE_STRINGS))))
301
+ elif _is_nonempty_str(expected) and item not in expected:
302
+ err("must_include '%s' 在 expected_output 里找不到(断言必须从判据原文提取,"
303
+ "不许凭空造)" % item)
304
+ for dupe in _dedupe_report(seen_include):
305
+ err("must_include 重复:'%s'" % dupe)
306
+
307
+ exclude = assertions.get("must_exclude")
308
+ exclude_valid = isinstance(exclude, list)
309
+ if not exclude_valid:
310
+ err("assertions.must_exclude 必须是数组")
311
+ exclude = []
312
+ elif len(exclude) < MIN_EXCLUDE:
313
+ err("assertions.must_exclude 至少 %d 条(当前 %d)" % (MIN_EXCLUDE, len(exclude)))
314
+ seen_exclude = []
315
+ for pos, item in enumerate(exclude, 1):
316
+ if not _is_nonempty_str(item):
317
+ err("must_exclude 第 %d 条必须是非空字符串" % pos)
318
+ continue
319
+ seen_exclude.append(item)
320
+ if item.strip() in TRUE_STRINGS:
321
+ err("must_exclude 含恒真串 '%s'" % item)
322
+ if _is_nonempty_str(expected) and item in expected:
323
+ err("must_exclude '%s' 出现在 expected_output 里:正确回答会判自己 FAIL" % item)
324
+ for inc_item in seen_include:
325
+ if item in inc_item:
326
+ err("must_exclude '%s' 是 must_include '%s' 的子串:判分会自相矛盾"
327
+ % (item, inc_item))
328
+ if item != item.strip():
329
+ warnings.append("case '%s': must_exclude '%s' 首尾有空白,逐字匹配会漏判"
330
+ % (label, item))
331
+ for dupe in _dedupe_report(seen_exclude):
332
+ err("must_exclude 重复:'%s'" % dupe)
333
+
334
+ ax = assertions.get("axes")
335
+ if not isinstance(ax, dict):
336
+ err("assertions.axes 必须是对象 {deliverable, rigor}")
337
+ else:
338
+ for key in ("deliverable", "rigor"):
339
+ if key not in ax:
340
+ err("assertions.axes 缺 %s" % key)
341
+ continue
342
+ value = ax[key]
343
+ allowed = axes.get(key, [])
344
+ if not _is_nonempty_str(value):
345
+ err("assertions.axes.%s 必须是非空字符串" % key)
346
+ elif allowed and value not in allowed:
347
+ err("assertions.axes.%s='%s' 不是 manifest.yaml 的真实轴值 %s"
348
+ % (key, value, sorted(allowed)))
349
+ for extra in sorted(set(ax) - {"deliverable", "rigor"}):
350
+ err("assertions.axes 有未知轴 '%s'(只允许 deliverable/rigor)" % extra)
351
+
352
+ steps = assertions.get("steps")
353
+ if not isinstance(steps, list):
354
+ err("assertions.steps 必须是数组")
355
+ else:
356
+ if not steps:
357
+ warnings.append("case '%s': steps 为空(仅当该 case 明确不进入流程时允许)" % label)
358
+ for step in steps:
359
+ if not _is_nonempty_str(step):
360
+ err("steps 里每条都必须是非空字符串")
361
+ elif step not in STEP_VOCAB:
362
+ err("steps 里的 '%s' 不是六步编号(可选:%s)"
363
+ % (step, " / ".join(sorted(STEP_VOCAB))))
364
+ for dupe in _dedupe_report([s for s in steps if _is_nonempty_str(s)]):
365
+ err("steps 重复:'%s'" % dupe)
366
+
367
+ rubric = case.get("rubric")
368
+ if rubric is not None:
369
+ if not isinstance(rubric, list):
370
+ err("rubric 必须是数组(%d 条语义要点)" % RUBRIC_SIZE)
371
+ elif len(rubric) != RUBRIC_SIZE:
372
+ err("rubric 必须恰好 %d 条(当前 %d)" % (RUBRIC_SIZE, len(rubric)))
373
+ else:
374
+ expected_text = case.get("expected_output") or ""
375
+ for pos, item in enumerate(rubric, 1):
376
+ if not _is_nonempty_str(item):
377
+ err("rubric 第 %d 条必须是非空字符串" % pos)
378
+ continue
379
+ value = item.strip()
380
+ if len(value) < 8:
381
+ err("rubric 第 %d 条太短(<8 字),当不了判分要点" % pos)
382
+ elif value and value in expected_text:
383
+ err("rubric 第 %d 条是从 expected_output 里逐字抄的(%r)—— "
384
+ "rubric 要写「怎样算做到」,不能变成参考答案" % (pos, value[:24]))
385
+
386
+ budget = case.get("budget_hint")
387
+ if not isinstance(budget, dict):
388
+ err("缺 budget_hint 或不是对象 {max_tokens, max_minutes}")
389
+ else:
390
+ for key in ("max_tokens", "max_minutes"):
391
+ value = budget.get(key)
392
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
393
+ err("budget_hint.%s 必须是正整数" % key)
394
+
395
+ return errors, warnings
396
+
397
+
398
+ # --------------------------------------------------------------------------- #
399
+ # static mode
400
+ # --------------------------------------------------------------------------- #
401
+ def judge_brief(case, axes):
402
+ """Build the ready-to-paste grading brief for one case."""
403
+ assertions = case["assertions"]
404
+ budget = case["budget_hint"]
405
+ cid = case["id"]
406
+ answer_dir = os.path.join(RUNS_HINT_DIR, cid)
407
+ answer_path = os.path.join(answer_dir, "answer.md")
408
+
409
+ lines = []
410
+ lines.append("=" * 78)
411
+ lines.append("CASE: %s [deliverable=%s, rigor=%s]"
412
+ % (cid, assertions["axes"]["deliverable"], assertions["axes"]["rigor"]))
413
+ lines.append("=" * 78)
414
+ lines.append("")
415
+ lines.append(u"\u3010case prompt\u3011")
416
+ lines.append(case["prompt"])
417
+ lines.append("")
418
+ lines.append(u"\u3010expected_output\uff08\u5224\u636e\u539f\u6587\uff0c\u51bb\u7ed3\uff0c\u4e0d\u5f97\u6539\u5199\uff09\u3011")
419
+ lines.append(case["expected_output"])
420
+ lines.append("")
421
+ lines.append(u"\u3010must_include\uff08\u9010\u5b57\u547d\u4e2d\uff0c\u5c11\u4e00\u6761\u5373 FAIL\uff09\u3011")
422
+ for pos, item in enumerate(assertions["must_include"], 1):
423
+ lines.append(" %d. %s" % (pos, item))
424
+ lines.append("")
425
+ lines.append(u"\u3010must_exclude\uff08\u4efb\u4e00\u547d\u4e2d\u5373 FAIL\uff09\u3011")
426
+ for item in assertions["must_exclude"]:
427
+ lines.append(" - %s" % item)
428
+ lines.append("")
429
+ lines.append(u"\u3010\u6d41\u7a0b\u6b65\u9aa4\u3011" +
430
+ (u" \u2192 ".join(assertions["steps"]) if assertions["steps"]
431
+ else u"\uff08\u8be5 case \u660e\u786e\u4e0d\u8fdb\u5165\u6d41\u7a0b\uff09"))
432
+ lines.append(u"\u3010token \u9884\u7b97\u63d0\u793a\u3011max_tokens=%d, max_minutes=%d"
433
+ % (budget["max_tokens"], budget["max_minutes"]))
434
+ lines.append(u"\u3010\u8f93\u51fa\u53bb\u5411\u5efa\u8bae\u3011\u628a judge \u5b50\u667a\u80fd\u4f53\u7684\u56de\u7b54\u5b58\u6210 "
435
+ "%s\uff0c\u7136\u540e\u8fd0\u884c\uff1a" % answer_path.replace(os.sep, "/"))
436
+ lines.append(" python scripts/run_evals.py --mode grade --case %s --answer %s"
437
+ % (cid, answer_path.replace(os.sep, "/")))
438
+ lines.append("")
439
+ lines.append(u"\u3010\u7ed9 judge \u7684\u8bc4\u5206\u8981\u6c42\uff08\u4e0a\u9762\u6574\u6bb5\u76f4\u63a5\u7c98\u7ed9\u5b50\u667a\u80fd\u4f53\uff09\u3011")
440
+ lines.append(u"\u4f60\u662f\u72ec\u7acb\u8bc4\u5206\u5458\u3002\u53ea\u4f9d\u636e\u4e0a\u9762\u7684\u65ad\u8a00\u5224\u5206\uff0c"
441
+ u"\u4e0d\u5f97\u6539\u5199\u5224\u636e\u3001\u4e0d\u5f97\u81ea\u884c\u53d1\u6325\uff1a")
442
+ lines.append(u" 1. must_include \u6bcf\u4e00\u6761\u90fd\u5fc5\u987b\u5728\u56de\u7b54\u91cc\u9010\u5b57\u51fa\u73b0\uff0c"
443
+ u"\u5c11\u4e00\u6761\u5373\u5224 FAIL\uff1b")
444
+ lines.append(u" 2. must_exclude \u4efb\u4e00\u6761\u51fa\u73b0\u5373\u5224 FAIL\uff1b")
445
+ lines.append(u" 3. \u9010\u6761\u8f93\u51fa [ok]/[x]\uff0c\u6700\u540e\u4e00\u884c\u53ea\u5199\uff1a"
446
+ u"CASE %s PASS \u6216 CASE %s FAIL\u3002" % (cid, cid))
447
+ lines.append("")
448
+ return "\n".join(lines)
449
+
450
+
451
+ def cmd_static(args):
452
+ evals_path = args.evals or DEFAULT_EVALS
453
+ try:
454
+ data, axes, warnings = load_and_validate(evals_path)
455
+ except ValidationFailed as exc:
456
+ for message in exc.errors:
457
+ print("[x] %s" % message)
458
+ print("[x] \u5171 %d \u6761\u9519\u8bef\uff1aevals \u4e0d\u5408\u6cd5\uff08exit 2\uff09" % len(exc.errors))
459
+ return EXIT_CANNOT
460
+ except EvalError as exc:
461
+ print("[x] %s" % exc)
462
+ print("[x] static \u6821\u9a8c\u65e0\u6cd5\u6267\u884c\uff08exit 2\uff09")
463
+ return EXIT_CANNOT
464
+
465
+ for message in warnings:
466
+ print("[warn] %s" % message)
467
+
468
+ headings = load_workflow_headings()
469
+ used_steps = set()
470
+ for case in data["evals"]:
471
+ used_steps.update(case["assertions"]["steps"])
472
+ for slug in sorted(used_steps, key=lambda s: (int(s.split("-")[0]), s)):
473
+ number = int(slug.split("-")[0])
474
+ expected_title = STEP_VOCAB[slug].split(u"\u2014", 1)[-1].strip()
475
+ if headings and number not in headings:
476
+ print("[warn] %s: workflow.md \u91cc\u627e\u4e0d\u5230 Step %d\uff08\u6b65\u9aa4\u7f16\u53f7\u5df2\u53d8\uff1f\uff09"
477
+ % (slug, number))
478
+ elif headings and expected_title not in headings[number]:
479
+ print("[warn] %s: workflow.md \u6807\u9898\u4e0e\u9884\u671f\u4e0d\u4e00\u81f4\uff08%s vs %s\uff09"
480
+ % (slug, expected_title, headings[number]))
481
+
482
+ cases = data["evals"]
483
+ print("project-dept evals \u00b7 static \u6821\u9a8c\u901a\u8fc7")
484
+ print(" skill_name : %s" % data["skill_name"])
485
+ print(" schema : v%s" % data["schema_version"])
486
+ print(" eval_mode : %s" % data["eval_mode"])
487
+ print(" cases : %d" % len(cases))
488
+ print(" axes : deliverable=%s rigor=%s"
489
+ % ("/".join(axes["deliverable"]), "/".join(axes["rigor"])))
490
+ print(" steps vocab : %s" % " / ".join(sorted(STEP_VOCAB)))
491
+ print("")
492
+
493
+ for index, case in enumerate(cases, 1):
494
+ print(judge_brief(case, axes))
495
+ if index != len(cases):
496
+ print("")
497
+
498
+ total_tokens = sum(c["budget_hint"]["max_tokens"] for c in cases)
499
+ print("-" * 78)
500
+ print("\u5168\u90e8 %d \u4e2a case \u7684\u8bc4\u5206\u63d0\u793a\u5df2\u6253\u5370\uff1b"
501
+ "\u9884\u7b97\u5408\u8ba1 \u2264%d tokens\u3002" % (len(cases), total_tokens))
502
+ print("\u63d0\u793a\uff1akeyword \u5224\u5206\u53ea\u80fd\u505a\u786e\u5b9a\u6027\u56de\u5f52\uff0c"
503
+ "\u5f62\u5f0f\u5bf9\u4e0d\u4ee3\u8868\u610f\u601d\u5bf9\uff1b\u4e24\u4e2a\u76ee\u5f55\u7684\u5bf9\u7167"
504
+ "\u4e5f\u4e0d\u662f\u7b49\u4ef7\u6027\u8bc1\u660e\u3002")
505
+ return EXIT_PASS
506
+
507
+
508
+ # --------------------------------------------------------------------------- #
509
+ # grading
510
+ # --------------------------------------------------------------------------- #
511
+ def find_case(data, case_id):
512
+ for case in data["evals"]:
513
+ if case["id"] == case_id:
514
+ return case
515
+ return None
516
+
517
+
518
+ def grade_text(case, text):
519
+ """Deterministically grade one answer string against one case."""
520
+ assertions = case["assertions"]
521
+ include_rows = [(item, item in text) for item in assertions["must_include"]]
522
+ exclude_rows = [(item, item in text) for item in assertions["must_exclude"]]
523
+ include_ok = sum(1 for _, ok in include_rows if ok)
524
+ exclude_hit = sum(1 for _, hit in exclude_rows if hit)
525
+ passed = include_ok == len(include_rows) and exclude_hit == 0
526
+ return {
527
+ "passed": passed,
528
+ "include_rows": include_rows,
529
+ "exclude_rows": exclude_rows,
530
+ "include_ok": include_ok,
531
+ "include_total": len(include_rows),
532
+ "exclude_hit": exclude_hit,
533
+ "exclude_total": len(exclude_rows),
534
+ }
535
+
536
+
537
+ def read_answer(path):
538
+ if not os.path.exists(path):
539
+ raise EvalError("\u7b54\u6848\u6587\u4ef6\u4e0d\u5b58\u5728\uff1a%s" % path)
540
+ if not os.path.isfile(path):
541
+ raise EvalError("\u7b54\u6848\u8def\u5f84\u4e0d\u662f\u6587\u4ef6\uff1a%s" % path)
542
+ raw = read_bytes(path)
543
+ for encoding in ("utf-8-sig", "utf-8", "gb18030"):
544
+ try:
545
+ return raw.decode(encoding)
546
+ except UnicodeDecodeError:
547
+ continue
548
+ raise EvalError("\u7b54\u6848\u6587\u4ef6\u65e0\u6cd5\u6309 UTF-8 / GB18030 \u89e3\u7801\uff1a%s" % path)
549
+
550
+
551
+ def print_grade_report(case_id, result):
552
+ for item, ok in result["include_rows"]:
553
+ if ok:
554
+ print("[ok] must_include %s" % item)
555
+ else:
556
+ print("[x] must_include %s \uff08\u672a\u51fa\u73b0\uff09" % item)
557
+ for item, hit in result["exclude_rows"]:
558
+ if hit:
559
+ print("[x] must_exclude %s \uff08\u51fa\u73b0\uff0c\u76f4\u63a5 FAIL\uff09" % item)
560
+ else:
561
+ print("[ok] must_exclude %s \uff08\u672a\u51fa\u73b0\uff0c\u6b63\u786e\uff09" % item)
562
+ print("include %d/%d\uff0cexclude \u547d\u4e2d %d \u6761 \u2192 %s"
563
+ % (result["include_ok"], result["include_total"], result["exclude_hit"],
564
+ "PASS" if result["passed"] else "FAIL"))
565
+ print("CASE %s %s" % (case_id, "PASS" if result["passed"] else "FAIL"))
566
+
567
+
568
+ def cmd_grade(args):
569
+ print(DEPRECATED_GRADE)
570
+ if not args.case:
571
+ print("[x] --mode grade \u9700\u8981 --case <id>")
572
+ return EXIT_CANNOT
573
+ if not args.answer:
574
+ print("[x] --mode grade \u9700\u8981 --answer <path>")
575
+ return EXIT_CANNOT
576
+ evals_path = args.evals or DEFAULT_EVALS
577
+ try:
578
+ data, _axes, _warnings = load_and_validate(evals_path)
579
+ case = find_case(data, args.case)
580
+ if case is None:
581
+ raise EvalError("case '%s' \u4e0d\u5b58\u5728\uff1b\u53ef\u7528\uff1a%s"
582
+ % (args.case, ", ".join(c["id"] for c in data["evals"])))
583
+ text = read_answer(args.answer)
584
+ except ValidationFailed as exc:
585
+ for message in exc.errors:
586
+ print("[x] %s" % message)
587
+ print("[x] evals \u4e0d\u5408\u6cd5\uff0c\u65e0\u6cd5\u5224\u5206\uff08exit 2\uff09")
588
+ return EXIT_CANNOT
589
+ except EvalError as exc:
590
+ print("[x] %s" % exc)
591
+ return EXIT_CANNOT
592
+
593
+ print("case: %s answer: %s chars: %d" % (case["id"], args.answer, len(text)))
594
+ if not text.strip():
595
+ print("[warn] \u7b54\u6848\u6587\u4ef6\u4e3a\u7a7a\uff0c\u6240\u6709 must_include \u90fd\u4f1a\u7b97\u672a\u547d\u4e2d")
596
+ result = grade_text(case, text)
597
+ print_grade_report(case["id"], result)
598
+ return EXIT_PASS if result["passed"] else EXIT_FAIL
599
+
600
+
601
+ # --------------------------------------------------------------------------- #
602
+ # judge / tally modes: blind judging + paired statistics (backlog P-15-8)
603
+ # --------------------------------------------------------------------------- #
604
+ ARMS = ("with", "without")
605
+ RUBRIC_SIZE = 4
606
+ SMALL_N = 10
607
+ Z_95 = 1.96
608
+ JUDGE_SALT = "project-dept-judge-v1"
609
+
610
+ # Printed by grade mode on every run. Exact wording matters: P-15-8 says keyword grading
611
+ # must not be used as an acceptance criterion.
612
+ DEPRECATED_GRADE = (
613
+ "[!] DEPRECATED: 关键词逐字判分不可作为验收判据(见 P-15-8)——请用 judge + tally"
614
+ )
615
+
616
+ ANSWER_NAME_RE = re.compile(
617
+ r"^(?P<case>.+)-(?P<arm>with|without)-r(?P<rep>[1-9][0-9]*)\.txt$")
618
+ MAP_VALUE_RE = re.compile(r"^(?P<arm>with|without)-r(?P<rep>[1-9][0-9]*)$")
619
+ SCORES_NAME_RE = re.compile(r"^scores_(?P<template>template_)?(?P<case>.+)\.json$")
620
+ MAP_NAME_RE = re.compile(r"^map_(?P<case>.+)\.json$")
621
+
622
+
623
+ def label_for(index):
624
+ """0 -> A ... 25 -> Z, 26 -> A1, 27 -> B1 ... Stable and collision-free."""
625
+ if index < 26:
626
+ return chr(ord("A") + index)
627
+ return "%s%d" % (chr(ord("A") + index % 26), index // 26)
628
+
629
+
630
+ def write_text_file(path, text):
631
+ try:
632
+ with open(path, "w", encoding="utf-8", newline="\n") as handle:
633
+ handle.write(text)
634
+ except OSError as exc:
635
+ raise EvalError("写不进 %s:%s" % (path, exc)) from exc
636
+
637
+
638
+ def write_json_file(path, payload):
639
+ write_text_file(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
640
+
641
+
642
+ def resolve_case_selector(cases, token):
643
+ """Resolve a case selector to a full case id: exact id first, then a unique prefix.
644
+
645
+ Answer files may use short labels (e.g. ``base`` for ``baseline-is-wrong``); an
646
+ ambiguous prefix must fail loudly instead of silently picking one case.
647
+ """
648
+ ids = [case["id"] for case in cases]
649
+ for case_id in ids:
650
+ if case_id == token:
651
+ return case_id
652
+ matches = [case_id for case_id in ids if case_id.startswith(token)]
653
+ if len(matches) == 1:
654
+ return matches[0]
655
+ if not matches:
656
+ raise EvalError("case '%s' 不存在;可用:%s" % (token, ", ".join(ids)))
657
+ raise EvalError("case '%s' 是多个 case 的前缀(%s),请写完整 id"
658
+ % (token, ", ".join(matches)))
659
+
660
+
661
+ def build_rubric(case):
662
+ """Return exactly RUBRIC_SIZE rubric strings for one case.
663
+
664
+ Prefer the case's optional ``rubric`` field (must be 4 non-empty strings). Otherwise
665
+ split ``assertions.must_include`` evenly into 4 groups; every group is phrased as
666
+ "要点:a、b、c" plus an explicit hit threshold. expected_output is never used: copying
667
+ the model answer into the rubric would turn the rubric into a reference answer.
668
+ """
669
+ explicit = case.get("rubric")
670
+ if explicit is not None:
671
+ if (not isinstance(explicit, (list, tuple)) or len(explicit) != RUBRIC_SIZE
672
+ or not all(_is_nonempty_str(item) for item in explicit)):
673
+ raise EvalError("case '%s' 的 rubric 必须是 %d 条非空字符串"
674
+ % (case.get("id", "?"), RUBRIC_SIZE))
675
+ return [item.strip() for item in explicit]
676
+ assertions = case.get("assertions") or {}
677
+ must_include = assertions.get("must_include") or []
678
+ if (not isinstance(must_include, (list, tuple))
679
+ or not must_include
680
+ or not all(_is_nonempty_str(item) for item in must_include)):
681
+ raise EvalError("case '%s' 缺少可用的 assertions.must_include,无法派生 rubric"
682
+ % case.get("id", "?"))
683
+ total = len(must_include)
684
+ if total < RUBRIC_SIZE:
685
+ raise EvalError("case '%s' 只有 %d 条 must_include,无法均分成 %d 条 rubric"
686
+ % (case.get("id", "?"), total, RUBRIC_SIZE))
687
+ base, remainder = divmod(total, RUBRIC_SIZE)
688
+ groups = []
689
+ start = 0
690
+ for index in range(RUBRIC_SIZE):
691
+ size = base + (1 if index < remainder else 0)
692
+ groups.append(must_include[start:start + size])
693
+ start += size
694
+ rubric = []
695
+ for group in groups:
696
+ need = len(group) // 2 + 1
697
+ rubric.append("要点:%s(命中该组多数,至少 %d/%d 个要点给 1)"
698
+ % ("、".join(group), need, len(group)))
699
+ return rubric
700
+
701
+
702
+ def scan_answer_files(answers_dir):
703
+ """Scan ``<case>-<arm>-r<rep>.txt`` files; any other entry is a hard error."""
704
+ if not os.path.isdir(answers_dir):
705
+ raise EvalError("答案目录不存在或不是目录:%s" % answers_dir)
706
+ try:
707
+ names = sorted(os.listdir(answers_dir))
708
+ except OSError as exc:
709
+ raise EvalError("读不到答案目录 %s:%s" % (answers_dir, exc)) from exc
710
+ records = []
711
+ for name in names:
712
+ path = os.path.join(answers_dir, name)
713
+ match = ANSWER_NAME_RE.match(name)
714
+ if match is None or not os.path.isfile(path):
715
+ raise EvalError(
716
+ "答案目录里有不符合 <case>-<with|without>-r<正整数>.txt 命名的条目:%s"
717
+ % path)
718
+ records.append({
719
+ "name": name,
720
+ "path": path,
721
+ "case": match.group("case"),
722
+ "arm": match.group("arm"),
723
+ "rep": int(match.group("rep")),
724
+ })
725
+ if not records:
726
+ raise EvalError("答案目录里没有任何答案文件:%s" % answers_dir)
727
+ return records
728
+
729
+
730
+ def group_answers(records, cases):
731
+ """Map real case id -> answer records, rejecting duplicate (case, arm, rep)."""
732
+ grouped = {}
733
+ seen = {}
734
+ for record in records:
735
+ case_id = resolve_case_selector(cases, record["case"])
736
+ key = (case_id, record["arm"], record["rep"])
737
+ if key in seen:
738
+ raise EvalError("同一 case/臂/rep 出现两次:%s 与 %s"
739
+ % (seen[key], record["name"]))
740
+ seen[key] = record["name"]
741
+ record["case_id"] = case_id
742
+ grouped.setdefault(case_id, []).append(record)
743
+ return grouped
744
+
745
+
746
+ def check_arm_balance(case_id, records):
747
+ """Both arms must exist and cover exactly the same rep numbers."""
748
+ by_arm = {arm: [] for arm in ARMS}
749
+ for record in records:
750
+ by_arm[record["arm"]].append(record)
751
+ for arm in ARMS:
752
+ if not by_arm[arm]:
753
+ raise EvalError("case '%s' 缺少 %s 臂的答案" % (case_id, arm))
754
+ reps = {arm: sorted(record["rep"] for record in by_arm[arm]) for arm in ARMS}
755
+ if reps["with"] != reps["without"]:
756
+ raise EvalError("case '%s' 两臂答案数/rep 不一致:with=%s without=%s"
757
+ % (case_id, ", ".join(str(n) for n in reps["with"]) or "-",
758
+ ", ".join(str(n) for n in reps["without"]) or "-"))
759
+ return by_arm, reps["with"]
760
+
761
+
762
+ def plan_judge_case(case_id, records, seed):
763
+ """Shuffle one case's answers reproducibly and return (entries, label -> key, reps)."""
764
+ _by_arm, reps = check_arm_balance(case_id, records)
765
+ ordered = sorted(records, key=lambda record: (record["arm"], record["rep"]))
766
+ digest = hashlib.sha256(
767
+ ("%s|%d|%s" % (JUDGE_SALT, seed, case_id)).encode("utf-8")).hexdigest()
768
+ random.Random(int(digest[:16], 16)).shuffle(ordered)
769
+ entries = []
770
+ mapping = {}
771
+ for index, record in enumerate(ordered):
772
+ label = label_for(index)
773
+ mapping[label] = "%s-r%d" % (record["arm"], record["rep"])
774
+ entries.append((label, record))
775
+ return entries, mapping, len(reps)
776
+
777
+
778
+ def render_judge_prompt(case_id, rubric, entries):
779
+ """Render the blind-judge prompt. Never mention an arm name or any arm-revealing hint."""
780
+ lines = [
781
+ "# 盲判任务单:%s" % case_id,
782
+ "",
783
+ "## 判分说明",
784
+ "",
785
+ "你是独立判官。只依据下面的 %d 条评分要点,对每一份答复独立打分。" % RUBRIC_SIZE,
786
+ "- 每条要点满分 1 分:命中给 1,未命中给 0;不接受 0.5 或其它分数。",
787
+ "- 各份答复彼此独立,不要相互比较,也不要推测答复的来源或版本。",
788
+ "- 不要逐字比对:意思到了就算命中,措辞不同不影响判定。",
789
+ "- 把结果填进同目录的 `scores_template_%s.json`:`scores` 下每个字母对应"
790
+ "一行 %d 个 0/1。" % (case_id, RUBRIC_SIZE),
791
+ "",
792
+ "## 评分要点(%d 条)" % RUBRIC_SIZE,
793
+ "",
794
+ ]
795
+ for index, text in enumerate(rubric):
796
+ lines.append("R%d. %s" % (index + 1, text))
797
+ lines.extend(["", "## 待判答复(匿名为 A、B、C…,顺序已打乱)", ""])
798
+ for label, record in entries:
799
+ lines.append("===== 答复 %s 开始 =====" % label)
800
+ lines.append(read_answer(record["path"]).rstrip("\n"))
801
+ lines.append("===== 答复 %s 结束 =====" % label)
802
+ lines.append("")
803
+ return "\n".join(lines).rstrip("\n") + "\n"
804
+
805
+
806
+ def render_scores_template(case_id, items, labels):
807
+ return {
808
+ "case": case_id,
809
+ "items": [{"id": "R%d" % (index + 1), "text": text}
810
+ for index, text in enumerate(items)],
811
+ "scores": {label: [None] * len(items) for label in labels},
812
+ }
813
+
814
+
815
+ def cmd_judge(args):
816
+ if not args.answers:
817
+ print("[x] --mode judge 需要 --answers <答案目录>")
818
+ return EXIT_CANNOT
819
+ if not args.out:
820
+ print("[x] --mode judge 需要 --out <输出目录>")
821
+ return EXIT_CANNOT
822
+ evals_path = args.evals or DEFAULT_EVALS
823
+ try:
824
+ data = load_json_file(evals_path)
825
+ cases = data.get("evals") if isinstance(data, dict) else None
826
+ if not isinstance(cases, list) or not cases:
827
+ raise EvalError("%s 里没有非空的 evals 列表" % evals_path)
828
+ records = scan_answer_files(args.answers)
829
+ grouped = group_answers(records, cases)
830
+ selected = cases
831
+ if args.case:
832
+ wanted = resolve_case_selector(cases, args.case)
833
+ if wanted not in grouped:
834
+ raise EvalError("答案目录里没有 case '%s' 的答案" % wanted)
835
+ selected = [case for case in cases if case["id"] == wanted]
836
+ else:
837
+ selected = [case for case in cases if case["id"] in grouped]
838
+ if not selected:
839
+ raise EvalError("答案目录里没有可判的 case(目录里只有:%s)"
840
+ % ", ".join(sorted(grouped)))
841
+ os.makedirs(args.out, exist_ok=True)
842
+ answers_per_case = {}
843
+ # Plan every case first: a bad case must not leave a half-written output directory.
844
+ plans = []
845
+ for case in selected:
846
+ case_id = case["id"]
847
+ entries, mapping, reps = plan_judge_case(case_id, grouped[case_id], args.seed)
848
+ plans.append((case_id, entries, mapping, reps, build_rubric(case)))
849
+ for case_id, entries, mapping, reps, items in plans:
850
+ write_text_file(os.path.join(args.out, "judge_prompt_%s.md" % case_id),
851
+ render_judge_prompt(case_id, items, entries))
852
+ write_json_file(
853
+ os.path.join(args.out, "scores_template_%s.json" % case_id),
854
+ render_scores_template(case_id, items, [label for label, _ in entries]))
855
+ write_json_file(os.path.join(args.out, "map_%s.json" % case_id), mapping)
856
+ answers_per_case[case_id] = reps
857
+ except EvalError as exc:
858
+ print("[x] %s" % exc)
859
+ return EXIT_CANNOT
860
+ print("judge: 写出 %d 个 case / 每 case %s 份答案 / seed=%d → %s"
861
+ % (len(answers_per_case),
862
+ "/".join(str(answers_per_case[cid]) for cid in sorted(answers_per_case)),
863
+ args.seed, args.out))
864
+ return EXIT_PASS
865
+
866
+
867
+ def wilson_interval(successes, trials, z=Z_95):
868
+ """Wilson score interval for a binomial proportion (clamped to [0, 1])."""
869
+ if trials <= 0:
870
+ return {"p": None, "n": 0, "lower": None, "upper": None, "z": z}
871
+ p = successes / trials
872
+ denominator = 1.0 + z * z / trials
873
+ centre = p + z * z / (2.0 * trials)
874
+ margin = z * math.sqrt(p * (1.0 - p) / trials + z * z / (4.0 * trials * trials))
875
+ return {
876
+ "p": p,
877
+ "n": trials,
878
+ "lower": max(0.0, (centre - margin) / denominator),
879
+ "upper": min(1.0, (centre + margin) / denominator),
880
+ "z": z,
881
+ }
882
+
883
+
884
+ def scan_tally_files(out_dir):
885
+ """Return ({case: 'scores_*.json' meta}, {case: 'map_*.json' path}) with pairing checks."""
886
+ if not os.path.isdir(out_dir):
887
+ raise EvalError("judge 输出目录不存在或不是目录:%s" % out_dir)
888
+ try:
889
+ names = sorted(os.listdir(out_dir))
890
+ except OSError as exc:
891
+ raise EvalError("读不到 judge 输出目录 %s:%s" % (out_dir, exc)) from exc
892
+ scores = {}
893
+ maps = {}
894
+ for name in names:
895
+ path = os.path.join(out_dir, name)
896
+ if not os.path.isfile(path):
897
+ continue
898
+ match = SCORES_NAME_RE.match(name)
899
+ if match:
900
+ case_key = match.group("case")
901
+ candidate = {"path": path, "template": bool(match.group("template"))}
902
+ previous = scores.get(case_key)
903
+ # A filled scores_<case>.json wins over the untouched scores_template_<case>.json.
904
+ if previous is None or (previous["template"] and not candidate["template"]):
905
+ scores[case_key] = candidate
906
+ continue
907
+ match = MAP_NAME_RE.match(name)
908
+ if match:
909
+ case_key = match.group("case")
910
+ if case_key in maps:
911
+ raise EvalError("同一个 case 有两份 map:%s 与 %s"
912
+ % (maps[case_key], name))
913
+ maps[case_key] = path
914
+ if not scores and not maps:
915
+ raise EvalError("目录里没有 scores_*.json 或 map_*.json:%s" % out_dir)
916
+ for case_key in sorted(set(scores) | set(maps)):
917
+ if case_key not in maps:
918
+ raise EvalError("case '%s' 有 scores 但没有对应 map_%s.json(配对缺失)"
919
+ % (case_key, case_key))
920
+ if case_key not in scores:
921
+ raise EvalError("case '%s' 有 map 但没有对应 scores_*.json(配对缺失)"
922
+ % case_key)
923
+ return scores, maps
924
+
925
+
926
+ def load_tally_pair(case_key, scores_meta, map_path):
927
+ """Validate one scores/map pair; return (case summary, per-item rows, pair rows)."""
928
+ scores_payload = load_json_file(scores_meta["path"],
929
+ label=os.path.basename(scores_meta["path"]))
930
+ mapping = load_json_file(map_path, label=os.path.basename(map_path))
931
+ if not isinstance(scores_payload, dict):
932
+ raise EvalError("%s 顶层必须是 JSON 对象" % scores_meta["path"])
933
+ case_id = scores_payload.get("case")
934
+ if not _is_nonempty_str(case_id):
935
+ raise EvalError("%s 缺少 case 字段" % scores_meta["path"])
936
+ if case_id != case_key:
937
+ raise EvalError("%s 里 case='%s' 与文件名里的 '%s' 不一致"
938
+ % (scores_meta["path"], case_id, case_key))
939
+ items = scores_payload.get("items")
940
+ if not isinstance(items, list) or not items:
941
+ raise EvalError("case '%s' 的 items 必须是非空数组" % case_id)
942
+ item_ids = []
943
+ for index, item in enumerate(items):
944
+ if isinstance(item, dict):
945
+ item_id, item_text = item.get("id"), item.get("text")
946
+ elif isinstance(item, str):
947
+ item_id, item_text = "R%d" % (index + 1), item
948
+ else:
949
+ raise EvalError("case '%s' 的 items[%d] 既不是对象也不是字符串"
950
+ % (case_id, index))
951
+ if not _is_nonempty_str(item_id) or not _is_nonempty_str(item_text):
952
+ raise EvalError("case '%s' 的 items[%d] 缺少 id/text" % (case_id, index))
953
+ if item_id in item_ids:
954
+ raise EvalError("case '%s' 的 item id 重复:%s" % (case_id, item_id))
955
+ item_ids.append(item_id)
956
+ rows = scores_payload.get("scores")
957
+ if not isinstance(rows, dict) or not rows:
958
+ raise EvalError("case '%s' 的 scores 必须是非空对象" % case_id)
959
+ if not isinstance(mapping, dict) or not mapping:
960
+ raise EvalError("case '%s' 的 map 必须是非空对象" % case_id)
961
+ if set(rows) != set(mapping):
962
+ only_scores = sorted(set(rows) - set(mapping))
963
+ only_map = sorted(set(mapping) - set(rows))
964
+ raise EvalError("case '%s' 的 scores 标签与 map 不一致:scores 多 %s,map 多 %s"
965
+ % (case_id, only_scores or "-", only_map or "-"))
966
+ parsed = {}
967
+ seen_keys = {}
968
+ for label in sorted(mapping):
969
+ value = mapping[label]
970
+ if not isinstance(value, str):
971
+ raise EvalError("case '%s' 的 map['%s'] 不是字符串:%r" % (case_id, label, value))
972
+ match = MAP_VALUE_RE.match(value)
973
+ if match is None:
974
+ raise EvalError("case '%s' 的 map['%s']='%s' 不符合 with|without-r<正整数>"
975
+ % (case_id, label, value))
976
+ key = (match.group("arm"), int(match.group("rep")))
977
+ if key in seen_keys:
978
+ raise EvalError("case '%s' 的 map 里 %s 出现两次(%s 与 %s)"
979
+ % (case_id, value, seen_keys[key], label))
980
+ seen_keys[key] = label
981
+ parsed[label] = key
982
+ missing = []
983
+ matrix = {}
984
+ for label in sorted(rows):
985
+ row = rows[label]
986
+ if not isinstance(row, list):
987
+ raise EvalError("case '%s' 标签 %s 的分数必须是数组" % (case_id, label))
988
+ if len(row) != len(item_ids):
989
+ raise EvalError("case '%s' 标签 %s 有 %d 格分数,但 rubric 是 %d 条"
990
+ % (case_id, label, len(row), len(item_ids)))
991
+ for index, score in enumerate(row):
992
+ if score is None:
993
+ missing.append((case_id, item_ids[index], label, mapping[label]))
994
+ continue
995
+ if isinstance(score, bool) or not isinstance(score, int) or score not in (0, 1):
996
+ raise EvalError("case '%s' 标签 %s / %s 的分数非法:%r(只接受 0/1 整数)"
997
+ % (case_id, label, item_ids[index], score))
998
+ matrix[label] = list(row)
999
+ if missing:
1000
+ detail = ";".join("%s 的 %s / 标签 %s(原答案 %s)" % cell for cell in missing)
1001
+ raise EvalError("有 %d 个格子还没打分(null),判官未填完:%s"
1002
+ % (len(missing), detail))
1003
+ by_arm = {arm: {} for arm in ARMS}
1004
+ for label, (arm, rep) in parsed.items():
1005
+ by_arm[arm][rep] = label
1006
+ for arm in ARMS:
1007
+ if not by_arm[arm]:
1008
+ raise EvalError("case '%s' 缺少 %s 臂的分数(某臂缺答案)" % (case_id, arm))
1009
+ if sorted(by_arm["with"]) != sorted(by_arm["without"]):
1010
+ raise EvalError("case '%s' 两臂 rep 不一致:with=%s without=%s"
1011
+ % (case_id, sorted(by_arm["with"]), sorted(by_arm["without"])))
1012
+ reps = sorted(by_arm["with"])
1013
+ pairs = []
1014
+ for rep in reps:
1015
+ with_total = sum(matrix[by_arm["with"][rep]])
1016
+ without_total = sum(matrix[by_arm["without"][rep]])
1017
+ if with_total > without_total:
1018
+ winner = "with"
1019
+ elif with_total < without_total:
1020
+ winner = "without"
1021
+ else:
1022
+ winner = "tie"
1023
+ pairs.append({"case": case_id, "rep": rep, "with": with_total,
1024
+ "without": without_total, "winner": winner})
1025
+ item_rows = []
1026
+ for index, item_id in enumerate(item_ids):
1027
+ item_rows.append({
1028
+ "case": case_id,
1029
+ "item": item_id,
1030
+ "with": sum(matrix[by_arm["with"][rep]][index] for rep in reps),
1031
+ "without": sum(matrix[by_arm["without"][rep]][index] for rep in reps),
1032
+ "max": len(reps),
1033
+ })
1034
+ case_row = {
1035
+ "case": case_id,
1036
+ "items": len(item_ids),
1037
+ "reps": len(reps),
1038
+ "max": len(item_ids) * len(reps),
1039
+ "with": sum(pair["with"] for pair in pairs),
1040
+ "without": sum(pair["without"] for pair in pairs),
1041
+ }
1042
+ return case_row, item_rows, pairs
1043
+
1044
+
1045
+ def tally_statistics(case_rows, item_rows, pair_rows):
1046
+ trial_count = len(pair_rows)
1047
+ with_better = sum(1 for pair in pair_rows if pair["winner"] == "with")
1048
+ without_better = sum(1 for pair in pair_rows if pair["winner"] == "without")
1049
+ ties = trial_count - with_better - without_better
1050
+ win_rate = (with_better / trial_count) if trial_count else None
1051
+ warnings = []
1052
+ warnings.append("平局计入配对胜率分母(胜率 = with 更好的对数 / 全部配对数)")
1053
+ if ties:
1054
+ warnings.append("有 %d 对两臂同分,计入分母但不算 with 更好" % ties)
1055
+ if trial_count < SMALL_N:
1056
+ warnings.append("配对数 n=%d < %d:Wilson 95%% 区间只能当方向性参考,不能当显著性"
1057
+ "或通过判据" % (trial_count, SMALL_N))
1058
+ return {
1059
+ "cases": case_rows,
1060
+ "items": item_rows,
1061
+ "pairs": pair_rows,
1062
+ "per_arm": {
1063
+ "with": sum(row["with"] for row in case_rows),
1064
+ "without": sum(row["without"] for row in case_rows),
1065
+ "max": sum(row["max"] for row in case_rows),
1066
+ "pairs": {
1067
+ "n": trial_count,
1068
+ "with_better": with_better,
1069
+ "without_better": without_better,
1070
+ "tie": ties,
1071
+ "win_rate": win_rate,
1072
+ },
1073
+ },
1074
+ "wilson": wilson_interval(with_better, trial_count),
1075
+ "warnings": warnings,
1076
+ }
1077
+
1078
+
1079
+ def print_tally_report(stats):
1080
+ print("=== 每 case 两臂总分 ===")
1081
+ print("%-30s %8s %8s %8s" % ("case", "with", "without", "满分"))
1082
+ for row in stats["cases"]:
1083
+ print("%-30s %8d %8d %8d" % (row["case"], row["with"], row["without"], row["max"]))
1084
+ print("")
1085
+ print("=== 每条 rubric 两臂命中数 ===")
1086
+ print("%-30s %6s %8s %8s %6s" % ("case", "item", "with", "without", "满分"))
1087
+ for row in stats["items"]:
1088
+ print("%-30s %6s %8d %8d %6d"
1089
+ % (row["case"], row["item"], row["with"], row["without"], row["max"]))
1090
+ print("")
1091
+ pairs = stats["per_arm"]["pairs"]
1092
+ print("=== 配对比较(单位 = case × rep)===")
1093
+ print("配对数 n=%d:with 更好 %d / 更差 %d / 平 %d"
1094
+ % (pairs["n"], pairs["with_better"], pairs["without_better"], pairs["tie"]))
1095
+ print("配对胜率 = %s"
1096
+ % ("-" if pairs["win_rate"] is None else "%.4f" % pairs["win_rate"]))
1097
+ wilson = stats["wilson"]
1098
+ if wilson["n"]:
1099
+ print("Wilson 95%% CI = [%.4f, %.4f](z=%.2f)"
1100
+ % (wilson["lower"], wilson["upper"], wilson["z"]))
1101
+ else:
1102
+ print("Wilson 95%% CI = 无配对,无法计算")
1103
+ print("")
1104
+ print("=== 总分 ===")
1105
+ print("with %d / %d without %d / %d"
1106
+ % (stats["per_arm"]["with"], stats["per_arm"]["max"],
1107
+ stats["per_arm"]["without"], stats["per_arm"]["max"]))
1108
+ for warning in stats["warnings"]:
1109
+ print("[warn] %s" % warning)
1110
+
1111
+
1112
+ def precheck_blank_scores(scores_meta):
1113
+ """一次性收集所有 case 的空格,避免只报排序第一个 case。"""
1114
+ report = []
1115
+ for case_key in sorted(scores_meta):
1116
+ path = scores_meta[case_key]["path"]
1117
+ payload = load_json_file(path, label=os.path.basename(path))
1118
+ if not isinstance(payload, dict):
1119
+ continue
1120
+ rows = payload.get("scores")
1121
+ if not isinstance(rows, dict):
1122
+ continue
1123
+ item_ids = []
1124
+ for index, item in enumerate(payload.get("items") or []):
1125
+ if isinstance(item, dict):
1126
+ item_ids.append(str(item.get("id") or ("R%d" % (index + 1))))
1127
+ else:
1128
+ item_ids.append("R%d" % (index + 1))
1129
+ cells = []
1130
+ for label in sorted(rows):
1131
+ row = rows[label]
1132
+ if not isinstance(row, list):
1133
+ continue
1134
+ for index, score in enumerate(row):
1135
+ if score is None:
1136
+ item_id = item_ids[index] if index < len(item_ids) else "第%d条" % (index + 1)
1137
+ cells.append((label, item_id))
1138
+ if cells:
1139
+ report.append((case_key, cells))
1140
+ return report
1141
+
1142
+
1143
+ def cmd_tally(args):
1144
+ if not args.out:
1145
+ sys.stderr.write("[x] --mode tally 需要 --out <judge 输出目录>\n")
1146
+ return EXIT_CANNOT
1147
+ try:
1148
+ scores_meta, map_paths = scan_tally_files(args.out)
1149
+ blanks = precheck_blank_scores(scores_meta)
1150
+ if blanks:
1151
+ parts = []
1152
+ total = 0
1153
+ for case_key, cells in blanks:
1154
+ total += len(cells)
1155
+ sample = "、".join(
1156
+ "%s / 标签 %s(null)" % (item_id, label)
1157
+ for label, item_id in cells[:6]
1158
+ )
1159
+ more = " 等" if len(cells) > 6 else ""
1160
+ parts.append("case '%s' 空 %d 格(%s%s)"
1161
+ % (case_key, len(cells), sample, more))
1162
+ raise EvalError("判官没填完(null),共 %d 个 case 有空格、合计 %d 格:%s"
1163
+ % (len(blanks), total, ";".join(parts)))
1164
+ case_rows, item_rows, pair_rows = [], [], []
1165
+ for case_key in sorted(scores_meta):
1166
+ case_row, item_row, pair_row = load_tally_pair(
1167
+ case_key, scores_meta[case_key], map_paths[case_key])
1168
+ case_rows.append(case_row)
1169
+ item_rows.extend(item_row)
1170
+ pair_rows.extend(pair_row)
1171
+ stats = tally_statistics(case_rows, item_rows, pair_rows)
1172
+ except EvalError as exc:
1173
+ sys.stderr.write("[x] %s\n" % exc)
1174
+ return EXIT_CANNOT
1175
+ if args.json_out:
1176
+ print(json.dumps(stats, ensure_ascii=False, sort_keys=True))
1177
+ else:
1178
+ print_tally_report(stats)
1179
+ return EXIT_PASS
1180
+
1181
+
1182
+ # --------------------------------------------------------------------------- #
1183
+ # compare mode
1184
+ # --------------------------------------------------------------------------- #
1185
+ def resolve_answer_path(root, case_id, case_count):
1186
+ """Find the answer file for one case inside one run directory."""
1187
+ candidates = [
1188
+ os.path.join(root, case_id, "answer.md"),
1189
+ os.path.join(root, case_id + ".md"),
1190
+ os.path.join(root, case_id, "answer.txt"),
1191
+ os.path.join(root, "answer_" + case_id + ".md"),
1192
+ os.path.join(root, case_id + "_answer.md"),
1193
+ ]
1194
+ if case_count == 1:
1195
+ candidates.append(os.path.join(root, "answer.md"))
1196
+ for path in candidates:
1197
+ if os.path.isfile(path):
1198
+ return path
1199
+ # "or any .md": a single top-level markdown file is unambiguous only for a one-case eval set.
1200
+ if case_count == 1 and os.path.isdir(root):
1201
+ mds = sorted(name for name in os.listdir(root)
1202
+ if name.lower().endswith(".md") and os.path.isfile(os.path.join(root, name)))
1203
+ if len(mds) == 1:
1204
+ return os.path.join(root, mds[0])
1205
+ return None
1206
+
1207
+
1208
+ def side_verdict(data, root):
1209
+ """Return {case_id: (status, detail)} for one directory."""
1210
+ cases = data["evals"]
1211
+ verdicts = {}
1212
+ for case in cases:
1213
+ cid = case["id"]
1214
+ path = resolve_answer_path(root, cid, len(cases))
1215
+ if path is None:
1216
+ verdicts[cid] = ("MISSING", u"\u627e\u4e0d\u5230\u7b54\u6848\u6587\u4ef6")
1217
+ continue
1218
+ try:
1219
+ text = read_answer(path)
1220
+ except EvalError as exc:
1221
+ verdicts[cid] = ("ERROR", str(exc))
1222
+ continue
1223
+ result = grade_text(case, text)
1224
+ verdicts[cid] = ("PASS" if result["passed"] else "FAIL", result)
1225
+ return verdicts
1226
+
1227
+
1228
+ def cmd_compare(args):
1229
+ if not args.with_dir or not args.without_dir:
1230
+ print("[x] --mode compare \u9700\u8981 --with <dir> --without <dir>")
1231
+ return EXIT_CANNOT
1232
+ for label, path in (("--with", args.with_dir), ("--without", args.without_dir)):
1233
+ if not os.path.isdir(path):
1234
+ print("[x] %s \u76ee\u5f55\u4e0d\u53ef\u8bfb\uff1a%s" % (label, path))
1235
+ return EXIT_CANNOT
1236
+ evals_path = args.evals or DEFAULT_EVALS
1237
+ try:
1238
+ data, _axes, _warnings = load_and_validate(evals_path)
1239
+ except ValidationFailed as exc:
1240
+ for message in exc.errors:
1241
+ print("[x] %s" % message)
1242
+ print("[x] evals \u4e0d\u5408\u6cd5\uff0c\u65e0\u6cd5\u5bf9\u6bd4\uff08exit 2\uff09")
1243
+ return EXIT_CANNOT
1244
+ except EvalError as exc:
1245
+ print("[x] %s" % exc)
1246
+ return EXIT_CANNOT
1247
+
1248
+ with_side = side_verdict(data, args.with_dir)
1249
+ without_side = side_verdict(data, args.without_dir)
1250
+
1251
+ print("A/B compare with: %s without: %s" % (args.with_dir, args.without_dir))
1252
+ print("%-28s %-10s %-10s" % ("CASE", "WITH", "WITHOUT"))
1253
+ print("-" * 50)
1254
+ with_pass = without_pass = 0
1255
+ with_fail = False
1256
+ for case in data["evals"]:
1257
+ cid = case["id"]
1258
+ w_status = with_side[cid][0]
1259
+ wo_status = without_side[cid][0]
1260
+ if w_status == "PASS":
1261
+ with_pass += 1
1262
+ else:
1263
+ with_fail = True
1264
+ if wo_status == "PASS":
1265
+ without_pass += 1
1266
+ print("%-28s %-10s %-10s" % (cid, w_status, wo_status))
1267
+
1268
+ total = len(data["evals"])
1269
+ print("-" * 50)
1270
+ print("%-28s %-10s %-10s" % ("TOTAL PASS", "%d/%d" % (with_pass, total),
1271
+ "%d/%d" % (without_pass, total)))
1272
+ print("%-28s %+d" % ("\u5dee\u503c\uff08with - without\uff09", with_pass - without_pass))
1273
+ for case in data["evals"]:
1274
+ cid = case["id"]
1275
+ for label, side in (("with", with_side), ("without", without_side)):
1276
+ status, detail = side[cid]
1277
+ if status in ("MISSING", "ERROR"):
1278
+ print("[warn] %s \u4fa7 case '%s'\uff1a%s%s"
1279
+ % (label, cid, status,
1280
+ ("\uff1a" + detail) if isinstance(detail, str) else ""))
1281
+ print("")
1282
+ print("[warn] \u6837\u672c\u91cf\u5c0f\uff08%d \u4e2a case\uff0c\u6bcf\u4e2a case \u5355\u6b21\u5224\u5206\uff09\uff1a"
1283
+ "\u8fd9\u662f\u65b9\u5411\u6027\u5bf9\u7167\uff0c\u4ec5\u4f9b\u53c2\u8003\uff0c"
1284
+ "\u4e0d\u80fd\u5f53\u7b49\u4ef7\u6027\u8bc1\u660e\u3002" % total)
1285
+ return EXIT_FAIL if with_fail else EXIT_PASS
1286
+
1287
+
1288
+ # --------------------------------------------------------------------------- #
1289
+ # entry point
1290
+ # --------------------------------------------------------------------------- #
1291
+ def build_parser():
1292
+ parser = argparse.ArgumentParser(
1293
+ prog="run_evals.py",
1294
+ description=(
1295
+ "project-dept evals runner. Modes: static (default) = validate evals/evals.json "
1296
+ "schema; grade = DEPRECATED verbatim keyword grading (rejects answers that make "
1297
+ "the right point in different words; 12/12 false FAILs on 12 real answers, "
1298
+ "backlog P-15-8); compare = grade two answer directories A/B; judge = anonymise "
1299
+ "<case>-<arm>-r<rep>.txt answers into blind-judge prompts + score templates + arm "
1300
+ "map; tally = paired per-rubric statistics with a Wilson 95% CI."),
1301
+ epilog=(
1302
+ "Keyword grading is not an acceptance criterion: it rejects correct answers that "
1303
+ "use different wording (measured 12/12 false FAILs on real answers, P-15-8). "
1304
+ "Use --mode judge to produce anonymous grading material, then --mode tally to "
1305
+ "compute paired per-rubric statistics."))
1306
+ parser.add_argument("--mode", choices=("static", "grade", "compare", "judge", "tally"),
1307
+ default="static",
1308
+ help="static (default) | grade (deprecated) | compare | judge | tally")
1309
+ parser.add_argument("--evals", default=None,
1310
+ help="path to evals.json (default: <skill>/evals/evals.json)")
1311
+ parser.add_argument("--case", default=None,
1312
+ help="case id (grade mode) or case selector (judge mode, id or unique prefix)")
1313
+ parser.add_argument("--answer", default=None, help="answer/transcript text file (grade mode)")
1314
+ parser.add_argument("--with", dest="with_dir", default=None, help="run directory of the with-skill answers")
1315
+ parser.add_argument("--without", dest="without_dir", default=None, help="run directory of the without-skill answers")
1316
+ parser.add_argument("--answers", default=None,
1317
+ help="answer directory of <case>-<with|without>-r<rep>.txt files (judge mode)")
1318
+ parser.add_argument("--out", default=None,
1319
+ help="output directory (judge mode) / judge output directory (tally mode)")
1320
+ parser.add_argument("--seed", type=int, default=7,
1321
+ help="shuffle seed for reproducible anonymisation (judge mode, default 7)")
1322
+ parser.add_argument("--json", dest="json_out", action="store_true",
1323
+ help="print the tally result as a single JSON document on stdout")
1324
+ return parser
1325
+
1326
+
1327
+ def main(argv=None):
1328
+ args = build_parser().parse_args(argv)
1329
+ if args.mode == "static":
1330
+ return cmd_static(args)
1331
+ if args.mode == "grade":
1332
+ return cmd_grade(args)
1333
+ if args.mode == "compare":
1334
+ return cmd_compare(args)
1335
+ if args.mode == "judge":
1336
+ return cmd_judge(args)
1337
+ if args.mode == "tally":
1338
+ return cmd_tally(args)
1339
+ print("[x] 未知 mode:%s" % args.mode)
1340
+ return EXIT_CANNOT
1341
+
1342
+
1343
+ if __name__ == "__main__":
1344
+ sys.exit(main())