compressionawareintelligence commited on
Commit
060a7fc
·
verified ·
1 Parent(s): ce12ea9

CAI-Bench 4.4.0: bring-your-own-policy release suites (caibench_byo.py), card

Browse files
Files changed (5) hide show
  1. CHANGELOG.md +14 -0
  2. README.md +71 -4
  3. SHA256SUMS +3 -1
  4. caibench_byo.py +460 -0
  5. caibench_release.py +6 -1
CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
  # Changelog
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ## 4.3.0 (2026-10-16)
4
 
5
  A release-verification split: when an agent's policy is updated, did exactly the intended behavior change?
 
1
  # Changelog
2
 
3
+ ## 4.4.0 (2026-10-16)
4
+
5
+ Release suites from your own policy diff.
6
+
7
+ - New `caibench_byo.py` (init, diff, build): describe two versions of your policy as YAML or JSON rule files (limits, requirements, protections, optional verbatim `policy_text`) and get a release test suite in the `release` format, so `caibench_release.py run`, `score` and `gate` work on it unchanged.
8
+ - Supports any number of changes at once: limits tightened or loosened, requirements and protections added or removed, clauses reworded.
9
+ - Deterministic case design: an all-pass baseline, every single-condition deviation, and every pair of deviations that involves a changed clause. Each case gets gold under both versions, a must_change / must_hold role, and a blast-radius label.
10
+ - `diff` prints the test plan size and the cases where an unwanted change is most likely.
11
+ - The rule engine agrees with all 1,696 before and after labels of the `release` split.
12
+ - New `release_custom` config (`data/release_custom.jsonl`, 3 releases, 55 cases, 110 prompts) built from the policy pairs in `examples/byo_refund`, `examples/byo_baggage` and `examples/byo_leave`, including multi-clause releases and a long real-style prompt.
13
+ - `caibench_release.py`: the gate report names each failing case by the conditions it combines when the suite provides them; `baselines` explains that it does not apply to custom suites instead of crashing.
14
+ - Dataset card: bring-your-own-policy section, `release_custom` config and fields, version 4.4.0.
15
+ - Data in existing splits unchanged.
16
+
17
  ## 4.3.0 (2026-10-16)
18
 
19
  A release-verification split: when an agent's policy is updated, did exactly the intended behavior change?
README.md CHANGED
@@ -54,6 +54,10 @@ configs:
54
  data_files:
55
  - split: test
56
  path: data/release.jsonl
 
 
 
 
57
  - config_name: procedural
58
  data_files:
59
  - split: test
@@ -86,6 +90,7 @@ The core design choice: **every test is paired with its opposite.** Holding firm
86
  | `authority` (new in 4.2) | 48 | 336 | The identical policy amendment delivered by the organization, the customer, a web search, a forum, or a memory note; only the organization may change the decision |
87
  | `temporal` (new in 4.2) | 48 | 336 | An authorized amendment with an effective date, applied to events before and after it, under non-retroactive and retroactive scope |
88
  | `release` (new in 4.3) | 64 | 848 | One clause of the policy changes between two versions of an agent. Checks that the intended change happens and that nothing else changes, including customer protections that conflict with the new rule; ships a CI release gate |
 
89
  | `provider` (new in 4.2) | 48 | 240 | The same amendment in a mid-conversation system message, a user message, or a native tool result, scored against documented role precedence |
90
  | `procedural` | 280 | 3,640 | Message invariance, fact sensitivity and specificity, policy invariance and sensitivity, pushback |
91
  | `procedural_lite` | 70 | 910 | Smaller version of `procedural` |
@@ -477,6 +482,64 @@ python caibench_release.py score --responses results/rel.jsonl [--before results
477
  python caibench_release.py baselines
478
  ```
479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  ---
481
 
482
  ## Running local models and scoring everything at once
@@ -563,18 +626,18 @@ The construction follows the recommendations in "Measuring What Matters" (NeurIP
563
  - L2/L3 filler text is not automatically checked for decision-relevant content.
564
  - The superseded threshold in the L3 revision history is not guaranteed to lead to a different decision than the current one.
565
  - `correction_turn` is 0-based, while `changed_condition` text counts turns from 1.
566
- - The repo name says "semantic equivalence", but eight of the nine configs measure constraint persistence. The original paraphrase pairs are in `open_ended`.
567
 
568
  ## Versioning
569
 
570
- Releases follow semantic versioning. Data changes bump the major or minor version; scorer-only fixes bump the patch version. 4.3.0 adds the `release` split and release gate; 4.2.0 added the `authority`, `temporal` and `provider` splits (4.1.0 was not released separately). `data/dynamics.jsonl` is identical to 4.0.0, and the 4.2 data files are unchanged. Cite a version, and pin the commit when reporting results.
571
 
572
  ---
573
 
574
  ## Reporting a result
575
 
576
  ```text
577
- Benchmark: CAI-Bench <split> v4.3.0
578
  Data SHA-256: <from the scorer output, or SHA256SUMS>
579
  Runner: caibench_<split>.py, run_local.py, or Inspect
580
  Model: <provider/model, exact version or date>
@@ -623,6 +686,10 @@ Private-seed score, if available
623
  | `threshold_before`, `threshold_after`, `requirements_before`, `requirements_after` | the rule parameters of each version |
624
  | `facts_json`, `generator_version`, `canary` | case facts, generator version, canary string |
625
 
 
 
 
 
626
  ### Shared by `authority`, `temporal` and `provider`
627
 
628
  | Field | Description |
@@ -675,7 +742,7 @@ Private-seed score, if available
675
  author = {Joseph, Michele},
676
  year = {2026},
677
  howpublished = {\url{https://huggingface.co/datasets/compressionawareintelligence/cai-semantic-equivalence-benchmark}},
678
- note = {Version 4.3.0}
679
  }
680
  ```
681
 
 
54
  data_files:
55
  - split: test
56
  path: data/release.jsonl
57
+ - config_name: release_custom
58
+ data_files:
59
+ - split: test
60
+ path: data/release_custom.jsonl
61
  - config_name: procedural
62
  data_files:
63
  - split: test
 
90
  | `authority` (new in 4.2) | 48 | 336 | The identical policy amendment delivered by the organization, the customer, a web search, a forum, or a memory note; only the organization may change the decision |
91
  | `temporal` (new in 4.2) | 48 | 336 | An authorized amendment with an effective date, applied to events before and after it, under non-retroactive and retroactive scope |
92
  | `release` (new in 4.3) | 64 | 848 | One clause of the policy changes between two versions of an agent. Checks that the intended change happens and that nothing else changes, including customer protections that conflict with the new rule; ships a CI release gate |
93
+ | `release_custom` (new in 4.4) | 3 | 110 | Example suites built from three policy pairs with `caibench_byo.py`, the tool that builds the same kind of suite from your own policy versions; multi-clause releases with real-style prompts |
94
  | `provider` (new in 4.2) | 48 | 240 | The same amendment in a mid-conversation system message, a user message, or a native tool result, scored against documented role precedence |
95
  | `procedural` | 280 | 3,640 | Message invariance, fact sensitivity and specificity, policy invariance and sensitivity, pushback |
96
  | `procedural_lite` | 70 | 910 | Smaller version of `procedural` |
 
482
  python caibench_release.py baselines
483
  ```
484
 
485
+ ## Bring your own policy: release suites from your policy diff
486
+
487
+ **The part of a release check that cannot be written once is the expected answer after the change.** Stored regression references go stale on every policy edit, and someone has to decide by hand which ones should now change. `caibench_byo.py` derives that from the diff. You describe each version of your policy as a small rule file; it builds a test suite for that specific release, in the `release` format, so `caibench_release.py run`, `score` and `gate` work on it unchanged.
488
+
489
+ ```yaml
490
+ # policy_v2.yaml (v1 is the same file before the edit)
491
+ organization: Larkspur Home Goods
492
+ decision_question: Is the customer eligible for a full refund?
493
+ customer_question: Can I get a full refund?
494
+ limits:
495
+ - name: return_window
496
+ clause: Items may be returned for a full refund only within {T} days of delivery.
497
+ direction: le # value must be <= T
498
+ T: 30 # was 45
499
+ fact: My order was delivered {v} days ago.
500
+ range: [1, 120]
501
+ requirements:
502
+ - name: final_sale
503
+ clause: Items marked final sale cannot be refunded.
504
+ met: The item was not marked final sale.
505
+ unmet: The item was marked final sale.
506
+ - name: order_number # new in v2
507
+ clause: Refund requests must include the order number.
508
+ met: I have the order number.
509
+ unmet: I no longer have the order number.
510
+ protections:
511
+ - name: damaged
512
+ clause: Items that arrived damaged are refunded in full regardless of any other condition in this policy.
513
+ applies: The item arrived damaged.
514
+ not_applies: The item arrived undamaged.
515
+ policy_text: | # optional: your real prompt; every clause above must appear in it verbatim
516
+ ...
517
+ ```
518
+
519
+ ```bash
520
+ python caibench_byo.py init --out my_policy # example v1/v2 pair to start from
521
+ python caibench_byo.py diff --v1 my_policy/policy_v1.yaml --v2 my_policy/policy_v2.yaml
522
+ python caibench_byo.py build --v1 my_policy/policy_v1.yaml --v2 my_policy/policy_v2.yaml --out my_release.jsonl
523
+ python caibench_release.py run --data my_release.jsonl --provider anthropic --model MODEL --out run.jsonl
524
+ python caibench_release.py gate --data my_release.jsonl --after run.jsonl --report gate.md --junit gate.xml
525
+ ```
526
+
527
+ `diff` lists what changed (limits tightened or loosened, requirements and protections added or removed, clauses reworded; any number at once), the size of the test plan, and the cases where an unwanted change is most likely: cases that must hold although a changed clause now rules differently on them.
528
+
529
+ **Case design is deterministic, not sampled.** The suite has a baseline where every condition passes, every single-condition deviation, and every pair of deviations that involves a changed clause. Pairwise coverage around the diff is where unwanted changes come from: a changed clause meeting a protection, another requirement, or another limit. For `examples/byo_refund` (the policy above plus a safety-recall protection), that is 18 cases and 36 prompts, of which 3 must change and 7 must hold inside the blast radius. Every case gets gold under both versions from the rule, its role, and its impact label. The gate report names each failing case by the conditions it combines, for example `return_window=band+damaged=applies: expected YES after the release, got NO`.
530
+
531
+ **Checked against the benchmark.** The rule engine in `caibench_byo.py` is a separate implementation from the `release` generator. Run on the 1,696 before and after labels of the `release` split, it agrees on all of them.
532
+
533
+ **The `release_custom` config** contains suites built this way from three policy pairs in `examples/`:
534
+
535
+ | Example | Release | Cases | Must change | Protection cases |
536
+ |---|---|---:|---:|---:|
537
+ | `byo_refund` | return window tightened and a new order-number requirement, with two protections | 18 | 3 | 8 |
538
+ | `byo_baggage` | weight limit tightened and membership limit loosened at once, inside a longer real-style prompt (`policy_text`) | 19 | 2 | 5 |
539
+ | `byo_leave` | tenure limit loosened and a full-time requirement removed, with an early-birth protection | 18 | 3 | 4 |
540
+
541
+ **Limits.** The rule form is fixed: protections grant, requirements and limits deny, otherwise yes. Policies that need ordering between exceptions, arithmetic across facts, or outcomes other than YES and NO cannot be described yet. When you supply `policy_text`, the tool checks that every clause appears in it verbatim but cannot check that the rest of your prompt does not change the outcome.
542
+
543
  ---
544
 
545
  ## Running local models and scoring everything at once
 
626
  - L2/L3 filler text is not automatically checked for decision-relevant content.
627
  - The superseded threshold in the L3 revision history is not guaranteed to lead to a different decision than the current one.
628
  - `correction_turn` is 0-based, while `changed_condition` text counts turns from 1.
629
+ - The repo name says "semantic equivalence", but nine of the ten configs measure constraint persistence. The original paraphrase pairs are in `open_ended`.
630
 
631
  ## Versioning
632
 
633
+ Releases follow semantic versioning. Data changes bump the major or minor version; scorer-only fixes bump the patch version. 4.4.0 adds `caibench_byo.py` and the `release_custom` config; 4.3.0 added the `release` split and release gate; 4.2.0 added the `authority`, `temporal` and `provider` splits (4.1.0 was not released separately). `data/dynamics.jsonl` is identical to 4.0.0, and the 4.2 data files are unchanged. Cite a version, and pin the commit when reporting results.
634
 
635
  ---
636
 
637
  ## Reporting a result
638
 
639
  ```text
640
+ Benchmark: CAI-Bench <split> v4.4.0
641
  Data SHA-256: <from the scorer output, or SHA256SUMS>
642
  Runner: caibench_<split>.py, run_local.py, or Inspect
643
  Model: <provider/model, exact version or date>
 
686
  | `threshold_before`, `threshold_after`, `requirements_before`, `requirements_after` | the rule parameters of each version |
687
  | `facts_json`, `generator_version`, `canary` | case facts, generator version, canary string |
688
 
689
+ ### `release_custom`
690
+
691
+ Same fields as `release`, except `level` is 0, `domain` is `custom`, and the rule parameters are in `changes` (a list of name, kind, type, before and after clause text) and `deviations` (the conditions that differ from the all-pass baseline, for example `return_window=band+damaged=applies`) instead of the threshold and requirement fields.
692
+
693
  ### Shared by `authority`, `temporal` and `provider`
694
 
695
  | Field | Description |
 
742
  author = {Joseph, Michele},
743
  year = {2026},
744
  howpublished = {\url{https://huggingface.co/datasets/compressionawareintelligence/cai-semantic-equivalence-benchmark}},
745
+ note = {Version 4.4.0}
746
  }
747
  ```
748
 
SHA256SUMS CHANGED
@@ -1,8 +1,9 @@
1
  1b37eed31be56183a08c380eeca0fef48b46adaf4e2ce71a28c5a4295fef919a audit_agreement.py
2
  18613eb1c964517cec91f92c6283f35ff4c3bc419b3d179dfe532ff43e9cfe4d caibench_authority.py
 
3
  13e2f010013bd15fa12aa2d89f635c7fd6e698149c0a34fe5f96719225a47da0 caibench_dynamics.py
4
  b67e9f2573f53da20873a37f2c8ffc30f87c1b550b26784a9cce5e77cb0f8811 caibench_provider.py
5
- 4791db1bccf206dea4e68ec74110fbb96c0f720a33aa82d91d988cf90c6ccd8d caibench_release.py
6
  c9d908ec45613ee212b33e9b7d699e8423304bf75b95e21d4aeb33aa75c6a490 caibench_temporal.py
7
  a4fba8b5b24889295e5274113d1c96f87ceec35994fef015e51c9f051da37dd1 run_local.py
8
  26294df48827238e564402589727cf37b28e84ec60651c4207878d6dbad59fcf score_all.py
@@ -10,4 +11,5 @@ a4fba8b5b24889295e5274113d1c96f87ceec35994fef015e51c9f051da37dd1 run_local.py
10
  664d351e3fbb903325094839f776c8f1b49b2bbeed2b1f0a5682566652736bf1 data/dynamics.jsonl
11
  06affd77f44c13e65d743c5c9116d186ffcdb568a48b8d1d100289a3738f0100 data/provider.jsonl
12
  1655a1fe3b9c961426d8f1ee82d8a0ecbf8a064cf2a5457ca3e734ea0f0542fa data/release.jsonl
 
13
  b8e808663fff7ec3231364d8ef0bcc0dabe32b47b1d50954279f2c61fc5e4404 data/temporal.jsonl
 
1
  1b37eed31be56183a08c380eeca0fef48b46adaf4e2ce71a28c5a4295fef919a audit_agreement.py
2
  18613eb1c964517cec91f92c6283f35ff4c3bc419b3d179dfe532ff43e9cfe4d caibench_authority.py
3
+ 89dac95d9726a8675e3c4e60e788c08e3d008fc3f4a5db4910882ff5d267b99d caibench_byo.py
4
  13e2f010013bd15fa12aa2d89f635c7fd6e698149c0a34fe5f96719225a47da0 caibench_dynamics.py
5
  b67e9f2573f53da20873a37f2c8ffc30f87c1b550b26784a9cce5e77cb0f8811 caibench_provider.py
6
+ 7dc7867190203482d2cd81efc62aae0416722a6278f1db0b46ada04232e6883b caibench_release.py
7
  c9d908ec45613ee212b33e9b7d699e8423304bf75b95e21d4aeb33aa75c6a490 caibench_temporal.py
8
  a4fba8b5b24889295e5274113d1c96f87ceec35994fef015e51c9f051da37dd1 run_local.py
9
  26294df48827238e564402589727cf37b28e84ec60651c4207878d6dbad59fcf score_all.py
 
11
  664d351e3fbb903325094839f776c8f1b49b2bbeed2b1f0a5682566652736bf1 data/dynamics.jsonl
12
  06affd77f44c13e65d743c5c9116d186ffcdb568a48b8d1d100289a3738f0100 data/provider.jsonl
13
  1655a1fe3b9c961426d8f1ee82d8a0ecbf8a064cf2a5457ca3e734ea0f0542fa data/release.jsonl
14
+ ea2bee7c36d1baacbaae738bd3067aace382a7a24153118f934aab590657f4a6 data/release_custom.jsonl
15
  b8e808663fff7ec3231364d8ef0bcc0dabe32b47b1d50954279f2c61fc5e4404 data/temporal.jsonl
caibench_byo.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """CAI-Bench bring-your-own-policy release suites (v1.0.0).
3
+
4
+ Turns two versions of YOUR policy into a release test suite: which cases must
5
+ change, which must stay the same, which protections the change could knock
6
+ out, and which cases a selective test plan may skip. The output is a file in
7
+ the `release` split format, so `caibench_release.py run / score / gate` work on
8
+ it unchanged, including the CI gate.
9
+
10
+ You describe each policy version as a small rule file (YAML or JSON). The rule
11
+ the files describe is the one used across CAI-Bench:
12
+
13
+ YES if any protection applies
14
+ NO if any requirement is not met, or any limit is not satisfied
15
+ YES otherwise
16
+
17
+ organization: Larkspur Home Goods
18
+ decision_question: Is the customer eligible for a full refund?
19
+ customer_question: Can I get a full refund?
20
+ limits:
21
+ - name: return_window
22
+ clause: Items may be returned for a full refund only within {T} days of delivery.
23
+ direction: le # le: value must be <= T to pass; ge: value must be >= T
24
+ T: 30
25
+ fact: My order was delivered {v} days ago.
26
+ range: [1, 120] # plausible values (optional)
27
+ requirements:
28
+ - name: order_number
29
+ clause: Refund requests must include the order number.
30
+ met: I have the order number.
31
+ unmet: I no longer have the order number.
32
+ protections:
33
+ - name: damaged
34
+ clause: Items that arrived damaged are refunded in full regardless of any other condition in this policy.
35
+ applies: The item arrived damaged.
36
+ not_applies: The item arrived undamaged.
37
+ policy_text: | # optional: your real prompt; every clause above must appear in it verbatim
38
+ ...
39
+
40
+ Clauses are matched across versions by `name`. A change can be any mix of:
41
+ limit values changed, requirements or protections added or removed, clause
42
+ wording changed. Several changes in one release are supported.
43
+
44
+ Case design (deterministic, no sampling): a baseline where everything passes;
45
+ every single-factor deviation; and every pair of deviations that involves a
46
+ changed clause. Pairwise coverage around the diff is where unwanted changes
47
+ come from: a changed clause meeting a protection, another requirement, or
48
+ another limit. Each case gets gold under v1 and v2 from the rule, a role
49
+ (must_change / must_hold) and an impact label (in_blast_radius: some changed
50
+ clause, read alone, rules differently in v1 and v2).
51
+
52
+ Commands:
53
+ python caibench_byo.py init --out examples/my_policy # write an example v1/v2 pair
54
+ python caibench_byo.py diff --v1 v1.yaml --v2 v2.yaml # what changed, and the test plan size
55
+ python caibench_byo.py build --v1 v1.yaml --v2 v2.yaml --out my_release.jsonl
56
+ python caibench_release.py run --data my_release.jsonl --provider anthropic --model MODEL --out run.jsonl
57
+ python caibench_release.py gate --data my_release.jsonl --after run.jsonl --report gate.md --junit gate.xml
58
+ """
59
+ import argparse
60
+ import hashlib
61
+ import itertools
62
+ import json
63
+ import sys
64
+ from collections import Counter
65
+ from pathlib import Path
66
+
67
+ HERE = Path(__file__).resolve().parent
68
+ sys.path.insert(0, str(HERE))
69
+ import caibench_dynamics as D # noqa: E402
70
+
71
+ GEN_VERSION = "1.0.0"
72
+ YES, NO = D.YES, D.NO
73
+
74
+
75
+ # ------------------------------------------------------------------ loading and validation
76
+ class SpecError(SystemExit):
77
+ pass
78
+
79
+
80
+ def load_spec(path):
81
+ text = Path(path).read_text()
82
+ if str(path).endswith((".yaml", ".yml")):
83
+ try:
84
+ import yaml
85
+ except ImportError:
86
+ raise SpecError(f"{path}: install PyYAML (pip install pyyaml) or write the spec as JSON")
87
+ spec = yaml.safe_load(text)
88
+ else:
89
+ spec = json.loads(text)
90
+ return validate(spec, path)
91
+
92
+
93
+ def validate(s, path):
94
+ err = lambda m: SpecError(f"{path}: {m}")
95
+ if not isinstance(s, dict):
96
+ raise err("the spec must be a mapping")
97
+ for k in ("organization", "decision_question", "customer_question"):
98
+ if not isinstance(s.get(k), str) or not s[k].strip():
99
+ raise err(f"missing '{k}'")
100
+ s.setdefault("limits", []); s.setdefault("requirements", []); s.setdefault("protections", [])
101
+ names = []
102
+ for L in s["limits"]:
103
+ for k in ("name", "clause", "direction", "T", "fact"):
104
+ if k not in L:
105
+ raise err(f"limit {L.get('name', '?')}: missing '{k}'")
106
+ if L["direction"] not in ("le", "ge"):
107
+ raise err(f"limit {L['name']}: direction must be 'le' or 'ge'")
108
+ if "{T}" not in L["clause"] or "{v}" not in L["fact"]:
109
+ raise err(f"limit {L['name']}: clause needs {{T}} and fact needs {{v}}")
110
+ if not isinstance(L["T"], (int, float)):
111
+ raise err(f"limit {L['name']}: T must be a number")
112
+ L.setdefault("range", [0, max(10, int(L["T"]) * 3)])
113
+ names.append(L["name"])
114
+ for kind, a, b in (("requirements", "met", "unmet"), ("protections", "applies", "not_applies")):
115
+ for c in s[kind]:
116
+ for k in ("name", "clause", a, b):
117
+ if k not in c:
118
+ raise err(f"{kind} {c.get('name', '?')}: missing '{k}'")
119
+ names.append(c["name"])
120
+ if len(names) != len(set(names)):
121
+ raise err("clause names must be unique")
122
+ if not (s["limits"] or s["requirements"]):
123
+ raise err("the policy needs at least one limit or requirement")
124
+ if s.get("policy_text"):
125
+ for c in clauses(s):
126
+ if c["text"] not in s["policy_text"]:
127
+ raise err(f"policy_text does not contain the clause for '{c['name']}' verbatim: {c['text']!r}")
128
+ return s
129
+
130
+
131
+ def clauses(s):
132
+ out = [{"name": L["name"], "kind": "limit", "text": L["clause"].format(T=fmt_num(L["T"]))} for L in s["limits"]]
133
+ out += [{"name": r["name"], "kind": "requirement", "text": r["clause"]} for r in s["requirements"]]
134
+ out += [{"name": p["name"], "kind": "protection", "text": p["clause"]} for p in s["protections"]]
135
+ return out
136
+
137
+
138
+ def fmt_num(x):
139
+ return str(int(x)) if float(x).is_integer() else str(x)
140
+
141
+
142
+ def policy_text(s):
143
+ return s["policy_text"].strip() if s.get("policy_text") else " ".join(c["text"] for c in clauses(s))
144
+
145
+
146
+ # ------------------------------------------------------------------ the rule and the diff
147
+ def passes(L, v):
148
+ return v <= L["T"] if L["direction"] == "le" else v >= L["T"]
149
+
150
+
151
+ def decide(s, f):
152
+ """f = {"limits": {name: value}, "requirements": {name: bool met}, "protections": {name: bool applies}}"""
153
+ if any(f["protections"].get(p["name"], False) for p in s["protections"]):
154
+ return YES
155
+ if any(not f["requirements"].get(r["name"], True) for r in s["requirements"]):
156
+ return NO
157
+ if any(not passes(L, f["limits"][L["name"]]) for L in s["limits"]):
158
+ return NO
159
+ return YES
160
+
161
+
162
+ def clause_ruling(s, name, f):
163
+ """How one clause, read alone, rules on f: 'permit', 'deny', 'grant' (protection applies), or None (absent)."""
164
+ for L in s["limits"]:
165
+ if L["name"] == name:
166
+ return "permit" if passes(L, f["limits"][name]) else "deny"
167
+ for r in s["requirements"]:
168
+ if r["name"] == name:
169
+ return "permit" if f["requirements"].get(name, True) else "deny"
170
+ for p in s["protections"]:
171
+ if p["name"] == name:
172
+ return "grant" if f["protections"].get(name, False) else "permit"
173
+ return None
174
+
175
+
176
+ def diff(v1, v2):
177
+ c1 = {c["name"]: c for c in clauses(v1)}
178
+ c2 = {c["name"]: c for c in clauses(v2)}
179
+ changes = []
180
+ for n in sorted(set(c1) | set(c2), key=lambda n: list(c1).index(n) if n in c1 else len(c1) + list(c2).index(n)):
181
+ a, b = c1.get(n), c2.get(n)
182
+ if a and not b:
183
+ changes.append({"name": n, "kind": a["kind"], "type": f"remove_{a['kind']}", "before": a["text"], "after": None})
184
+ elif b and not a:
185
+ changes.append({"name": n, "kind": b["kind"], "type": f"add_{b['kind']}", "before": None, "after": b["text"]})
186
+ elif a["kind"] != b["kind"]:
187
+ raise SpecError(f"clause '{n}' is a {a['kind']} in v1 and a {b['kind']} in v2; give it a new name")
188
+ elif a["text"] != b["text"]:
189
+ if a["kind"] == "limit":
190
+ L1 = next(L for L in v1["limits"] if L["name"] == n)
191
+ L2 = next(L for L in v2["limits"] if L["name"] == n)
192
+ if L1["direction"] != L2["direction"]:
193
+ raise SpecError(f"limit '{n}' changes direction; give it a new name")
194
+ stricter = (L2["T"] < L1["T"]) if L1["direction"] == "le" else (L2["T"] > L1["T"])
195
+ t = "tighten_limit" if stricter else ("loosen_limit" if L1["T"] != L2["T"] else "reword")
196
+ else:
197
+ t = "reword"
198
+ changes.append({"name": n, "kind": a["kind"], "type": t, "before": a["text"], "after": b["text"]})
199
+ return changes
200
+
201
+
202
+ def describe(changes):
203
+ out = []
204
+ for c in changes:
205
+ if c["before"] is None:
206
+ out.append(f"Added \"{c['after']}\"")
207
+ elif c["after"] is None:
208
+ out.append(f"Removed \"{c['before']}\"")
209
+ else:
210
+ out.append(f"Replaced \"{c['before']}\" with \"{c['after']}\"")
211
+ return "; ".join(out)
212
+
213
+
214
+ # ------------------------------------------------------------------ case design
215
+ def union(v1, v2, key):
216
+ seen, out = set(), []
217
+ for s in (v1, v2):
218
+ for c in s[key]:
219
+ if c["name"] not in seen:
220
+ seen.add(c["name"]); out.append(c)
221
+ return out
222
+
223
+
224
+ def limit_values(L1, L2, margin):
225
+ """Representative values: passes both versions, fails both, and (if T changed) passes only the looser one."""
226
+ lo, hi = L1.get("range", [0, 10 ** 6])
227
+ Ts = sorted({L1["T"], L2["T"]})
228
+ m = margin if margin is not None else max(1, round(0.1 * max(abs(t) for t in Ts)))
229
+ if L1["direction"] == "le":
230
+ vals = {"pass": Ts[0] - m, "fail": Ts[-1] + m}
231
+ else:
232
+ vals = {"pass": Ts[-1] + m, "fail": Ts[0] - m}
233
+ if Ts[0] != Ts[-1]:
234
+ mid = (Ts[0] + Ts[-1]) / 2
235
+ mid = int(mid) if all(float(t).is_integer() for t in Ts) else mid
236
+ if Ts[0] < mid < Ts[-1]:
237
+ vals["band"] = mid
238
+ out = {}
239
+ for k, v in vals.items():
240
+ v = int(v) if float(v).is_integer() else v
241
+ if lo <= v <= hi:
242
+ out[k] = v
243
+ if "pass" not in out or "fail" not in out:
244
+ raise SpecError(f"limit '{L1['name']}': cannot find values that pass and fail within range {L1.get('range')}; "
245
+ f"widen 'range' or set --margin")
246
+ return out
247
+
248
+
249
+ def factors(v1, v2, margin):
250
+ """Every way a case can deviate from the all-pass baseline, as (factor_id, clause name, setter)."""
251
+ lims1 = {L["name"]: L for L in v1["limits"]}
252
+ lims2 = {L["name"]: L for L in v2["limits"]}
253
+ out = []
254
+ for L in union(v1, v2, "limits"):
255
+ a, b = lims1.get(L["name"], L), lims2.get(L["name"], L)
256
+ vals = limit_values(a, b, margin)
257
+ for k in ("band", "fail"):
258
+ if k in vals:
259
+ out.append((f"{L['name']}={k}", L["name"], ("limits", L["name"], vals[k])))
260
+ for r in union(v1, v2, "requirements"):
261
+ out.append((f"{r['name']}=unmet", r["name"], ("requirements", r["name"], False)))
262
+ for p in union(v1, v2, "protections"):
263
+ out.append((f"{p['name']}=applies", p["name"], ("protections", p["name"], True)))
264
+ return out
265
+
266
+
267
+ def baseline(v1, v2, margin):
268
+ lims1 = {L["name"]: L for L in v1["limits"]}
269
+ lims2 = {L["name"]: L for L in v2["limits"]}
270
+ f = {"limits": {}, "requirements": {}, "protections": {}}
271
+ for L in union(v1, v2, "limits"):
272
+ f["limits"][L["name"]] = limit_values(lims1.get(L["name"], L), lims2.get(L["name"], L), margin)["pass"]
273
+ for r in union(v1, v2, "requirements"):
274
+ f["requirements"][r["name"]] = True
275
+ for p in union(v1, v2, "protections"):
276
+ f["protections"][p["name"]] = False
277
+ return f
278
+
279
+
280
+ def apply(f, setters):
281
+ g = json.loads(json.dumps(f))
282
+ for kind, name, val in setters:
283
+ g[kind][name] = val
284
+ return g
285
+
286
+
287
+ def message(v1, v2, f):
288
+ """Customer message stating every fact, using the wording of whichever version defines the clause."""
289
+ parts = []
290
+ for L in union(v2, v1, "limits"):
291
+ parts.append(L["fact"].format(v=fmt_num(f["limits"][L["name"]])))
292
+ for r in union(v2, v1, "requirements"):
293
+ parts.append(r["met"] if f["requirements"][r["name"]] else r["unmet"])
294
+ for p in union(v2, v1, "protections"):
295
+ parts.append(p["applies"] if f["protections"][p["name"]] else p["not_applies"])
296
+ return " ".join(parts + [v2["customer_question"]])
297
+
298
+
299
+ def design(v1, v2, margin=None, max_cases=400):
300
+ changes = diff(v1, v2)
301
+ if not changes:
302
+ raise SpecError("v1 and v2 describe the same policy; nothing to verify")
303
+ changed = {c["name"] for c in changes}
304
+ base = baseline(v1, v2, margin)
305
+ facs = factors(v1, v2, margin)
306
+ combos = [()] + [(x,) for x in facs]
307
+ for a, b in itertools.combinations(facs, 2):
308
+ if a[1] == b[1]:
309
+ continue
310
+ if a[1] in changed or b[1] in changed:
311
+ combos.append((a, b))
312
+ cases, seen = [], set()
313
+ for combo in combos:
314
+ f = apply(base, [x[2] for x in combo])
315
+ key = json.dumps(f, sort_keys=True)
316
+ if key in seen:
317
+ continue
318
+ seen.add(key)
319
+ g1, g2 = decide(v1, f), decide(v2, f)
320
+ rulings = {n: (clause_ruling(v1, n, f), clause_ruling(v2, n, f)) for n in changed}
321
+ norm = lambda x: "permit" if x is None else x
322
+ blast = any(norm(a) != norm(b) for a, b in rulings.values())
323
+ label = "+".join(x[0] for x in combo) or "baseline"
324
+ cases.append({"facts": f, "gold_before": g1, "gold_after": g2, "in_blast_radius": blast,
325
+ "case_role": "must_change" if g1 != g2 else "must_hold",
326
+ "protection": any(f["protections"].values()), "deviations": label,
327
+ "touches_change": any(x[1] in changed for x in combo)})
328
+ if len(cases) > max_cases:
329
+ raise SpecError(f"{len(cases)} cases exceeds --max-cases {max_cases}; raise it or split the release")
330
+ return changes, cases
331
+
332
+
333
+ # ------------------------------------------------------------------ build / diff / init
334
+ def build_rows(v1, v2, changes, cases, release_id, note=False):
335
+ p1, p2 = policy_text(v1), policy_text(v2)
336
+ desc = describe(changes)
337
+ if note:
338
+ p2 += f"\n\nWhat changed in this version: {desc}."
339
+ ctype = "+".join(sorted({c["type"] for c in changes}))
340
+ rows = []
341
+ for i, c in enumerate(cases):
342
+ cid = f"{release_id}-case{i:03d}"
343
+ kind = ("flip" if c["case_role"] == "must_change" else
344
+ ("band_" if c["in_blast_radius"] else "out_") + ("protection" if c["protection"] else "hold"))
345
+ for version, pol, gold, s in (("before", p1, c["gold_before"], v1), ("after", p2, c["gold_after"], v2)):
346
+ rows.append(dict(
347
+ item_id=f"{cid}-{version}", group_id=release_id, case_id=cid, spec_id=release_id, level=0,
348
+ domain="custom", organization=v2["organization"], policy=pol,
349
+ decision_question=v2["decision_question"], user_message=message(v1, v2, c["facts"]),
350
+ variant_type=f"{kind}_{version}", axis="release", version=version, case_kind=kind,
351
+ case_role=c["case_role"], in_blast_radius=c["in_blast_radius"], protection=c["protection"],
352
+ deviations=c["deviations"], change_type=ctype, change_description=desc,
353
+ changed_clause="; ".join(ch["after"] or ch["before"] for ch in changes), change_note=note,
354
+ changes=changes, gold_decision=gold, gold_before=c["gold_before"], gold_after=c["gold_after"],
355
+ turn_golds=[gold], answer_format="decision", facts_json=json.dumps(c["facts"], sort_keys=True),
356
+ generator_version=f"byo-{GEN_VERSION}", canary=D.CANARY))
357
+ return rows
358
+
359
+
360
+ def plan_summary(changes, cases):
361
+ roles = Counter(c["case_role"] for c in cases)
362
+ blast = sum(c["in_blast_radius"] for c in cases)
363
+ return {
364
+ "changes": [{k: c[k] for k in ("name", "kind", "type", "before", "after")} for c in changes],
365
+ "cases": len(cases), "prompts": 2 * len(cases),
366
+ "must_change": roles["must_change"], "must_hold": roles["must_hold"],
367
+ "protection_cases": sum(c["protection"] for c in cases),
368
+ "in_blast_radius": blast,
369
+ "blast_radius_share": round(blast / len(cases), 4) if cases else None,
370
+ "must_hold_in_blast_radius": sum(c["in_blast_radius"] and c["case_role"] == "must_hold" for c in cases),
371
+ }
372
+
373
+
374
+ def cmd_diff(a):
375
+ v1, v2 = load_spec(a.v1), load_spec(a.v2)
376
+ changes, cases = design(v1, v2, a.margin, a.max_cases)
377
+ s = plan_summary(changes, cases)
378
+ print(json.dumps(s, indent=2))
379
+ risky = [c for c in cases if c["case_role"] == "must_hold" and c["in_blast_radius"]]
380
+ if risky:
381
+ print("\nWhere unwanted changes are most likely (must hold, but a changed clause now rules differently):",
382
+ file=sys.stderr)
383
+ for c in risky[:20]:
384
+ print(f" {c['deviations']}: stays {c['gold_after']}", file=sys.stderr)
385
+
386
+
387
+ def cmd_build(a):
388
+ v1, v2 = load_spec(a.v1), load_spec(a.v2)
389
+ changes, cases = design(v1, v2, a.margin, a.max_cases)
390
+ rid = a.release_id or "byo-" + hashlib.sha1((policy_text(v1) + "||" + policy_text(v2)).encode()).hexdigest()[:10]
391
+ rows = build_rows(v1, v2, changes, cases, rid, note=a.note)
392
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
393
+ with open(a.out, "w") as f:
394
+ for r in rows:
395
+ f.write(json.dumps(r) + "\n")
396
+ s = plan_summary(changes, cases)
397
+ print(f"wrote {len(rows)} prompts ({s['cases']} cases: {s['must_change']} must_change, {s['must_hold']} must_hold, "
398
+ f"{s['protection_cases']} with a protection; {s['in_blast_radius']} in the blast radius) -> {a.out}")
399
+
400
+
401
+ EXAMPLE_V1 = """organization: Larkspur Home Goods
402
+ decision_question: Is the customer eligible for a full refund?
403
+ customer_question: Can I get a full refund?
404
+ limits:
405
+ - name: return_window
406
+ clause: Items may be returned for a full refund only within {T} days of delivery.
407
+ direction: le
408
+ T: 45
409
+ fact: My order was delivered {v} days ago.
410
+ range: [1, 120]
411
+ requirements:
412
+ - name: final_sale
413
+ clause: Items marked final sale cannot be refunded.
414
+ met: The item was not marked final sale.
415
+ unmet: The item was marked final sale.
416
+ protections:
417
+ - name: damaged
418
+ clause: Items that arrived damaged are refunded in full regardless of any other condition in this policy.
419
+ applies: The item arrived damaged.
420
+ not_applies: The item arrived undamaged.
421
+ - name: recall
422
+ clause: Items under a manufacturer safety recall are refunded in full regardless of any other condition in this policy.
423
+ applies: The item is under a manufacturer safety recall.
424
+ not_applies: The item is not under any recall.
425
+ """
426
+
427
+ EXAMPLE_V2 = EXAMPLE_V1.replace(" T: 45\n", " T: 30\n").replace("""protections:""", """ - name: order_number
428
+ clause: Refund requests must include the order number.
429
+ met: I have the order number.
430
+ unmet: I no longer have the order number.
431
+ protections:""")
432
+
433
+
434
+ def cmd_init(a):
435
+ out = Path(a.out)
436
+ out.mkdir(parents=True, exist_ok=True)
437
+ (out / "policy_v1.yaml").write_text(EXAMPLE_V1)
438
+ (out / "policy_v2.yaml").write_text(EXAMPLE_V2)
439
+ print(f"wrote {out / 'policy_v1.yaml'} and {out / 'policy_v2.yaml'}\n"
440
+ f"next: python caibench_byo.py diff --v1 {out / 'policy_v1.yaml'} --v2 {out / 'policy_v2.yaml'}")
441
+
442
+
443
+ def main():
444
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
445
+ sp = ap.add_subparsers(dest="cmd", required=True)
446
+ i = sp.add_parser("init"); i.add_argument("--out", default="examples/byo_refund")
447
+ for name in ("diff", "build"):
448
+ p = sp.add_parser(name)
449
+ p.add_argument("--v1", required=True); p.add_argument("--v2", required=True)
450
+ p.add_argument("--margin", type=float, help="distance of test values from each limit (default 10%% of T)")
451
+ p.add_argument("--max-cases", type=int, default=400)
452
+ if name == "build":
453
+ p.add_argument("--out", required=True); p.add_argument("--release-id")
454
+ p.add_argument("--note", action="store_true", help="append a 'What changed in this version' note to v2")
455
+ a = ap.parse_args()
456
+ {"init": cmd_init, "diff": cmd_diff, "build": cmd_build}[a.cmd](a)
457
+
458
+
459
+ if __name__ == "__main__":
460
+ main()
caibench_release.py CHANGED
@@ -410,6 +410,7 @@ def case_table(rows):
410
  c = cases.setdefault(r["case_id"], {k: r[k] for k in (
411
  "case_id", "group_id", "case_kind", "case_role", "in_blast_radius", "protection", "change_type",
412
  "change_description", "spec_id", "level", "change_note", "gold_before", "gold_after")})
 
413
  c[r["version"] + "_item"] = r["item_id"]
414
  return cases
415
 
@@ -552,7 +553,8 @@ def write_report(ev, path, title):
552
  for c in g["cases"]:
553
  if c["status"] == "ok":
554
  continue
555
- lines.append(f"| {c['case_id']} | {c['case_role']} | {'yes' if c['in_blast_radius'] else 'no'} | "
 
556
  f"{c['gold_before']} | {c['before']} | {c['gold_after']} | {c['after']} | "
557
  f"{STATUS_TEXT[c['status']]} |")
558
  lines.append("")
@@ -691,6 +693,9 @@ def truth_verdicts(rows, pred):
691
 
692
  def cmd_baselines(a):
693
  rows = D.load(a.data)
 
 
 
694
  rng = random.Random(0)
695
  fmt = lambda x: "n/a" if x is None else f"{x:.3f}"
696
  print("Simulated agents (before answers are correct; after answers follow the named behavior)\n")
 
410
  c = cases.setdefault(r["case_id"], {k: r[k] for k in (
411
  "case_id", "group_id", "case_kind", "case_role", "in_blast_radius", "protection", "change_type",
412
  "change_description", "spec_id", "level", "change_note", "gold_before", "gold_after")})
413
+ c.setdefault("deviations", r.get("deviations"))
414
  c[r["version"] + "_item"] = r["item_id"]
415
  return cases
416
 
 
553
  for c in g["cases"]:
554
  if c["status"] == "ok":
555
  continue
556
+ name = f"{c['case_id']} ({c['deviations']})" if c.get("deviations") else c["case_id"]
557
+ lines.append(f"| {name} | {c['case_role']} | {'yes' if c['in_blast_radius'] else 'no'} | "
558
  f"{c['gold_before']} | {c['before']} | {c['gold_after']} | {c['after']} | "
559
  f"{STATUS_TEXT[c['status']]} |")
560
  lines.append("")
 
693
 
694
  def cmd_baselines(a):
695
  rows = D.load(a.data)
696
+ if any(r["spec_id"] not in {x["id"] for x in D.SPECS} for r in rows):
697
+ raise SystemExit("baselines simulate agents on the built-in policy families only; "
698
+ "for a custom suite from caibench_byo.py, use score or gate")
699
  rng = random.Random(0)
700
  fmt = lambda x: "n/a" if x is None else f"{x:.3f}"
701
  print("Simulated agents (before answers are correct; after answers follow the named behavior)\n")