mobiusguard-eval 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (76) hide show
  1. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/PKG-INFO +23 -3
  2. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/README.md +18 -0
  3. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/pyproject.toml +7 -2
  4. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/__init__.py +1 -1
  5. mobiusguard_eval-0.3.0/src/mobiusguard_eval/augment.py +251 -0
  6. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/cli.py +220 -13
  7. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/detectors/__init__.py +16 -3
  8. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/detectors/hf.py +28 -5
  9. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/detectors/proxy.py +25 -6
  10. mobiusguard_eval-0.3.0/src/mobiusguard_eval/dev_texts.py +31 -0
  11. mobiusguard_eval-0.3.0/src/mobiusguard_eval/distill.py +135 -0
  12. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/export.py +48 -2
  13. mobiusguard_eval-0.3.0/src/mobiusguard_eval/gate.py +238 -0
  14. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/items.py +7 -0
  15. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/judge.py +18 -2
  16. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/ledger.py +5 -0
  17. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/metrics.py +38 -0
  18. mobiusguard_eval-0.3.0/src/mobiusguard_eval/model_meta.py +101 -0
  19. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/obfuscate.py +2 -2
  20. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/__init__.py +2 -0
  21. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/adaptive.py +355 -0
  22. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/adaptive_pyrit.py +122 -0
  23. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/cache.py +91 -0
  24. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/cli.py +181 -0
  25. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/findings.py +170 -0
  26. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/garak_export.py +179 -0
  27. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/gate.py +83 -0
  28. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/holdout.py +105 -0
  29. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/mutate.py +107 -0
  30. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/pyrit_converters.py +102 -0
  31. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/run.py +224 -0
  32. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/seeds.py +115 -0
  33. mobiusguard_eval-0.3.0/src/mobiusguard_eval/redteam/targets.py +300 -0
  34. mobiusguard_eval-0.3.0/src/mobiusguard_eval/roles.py +157 -0
  35. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/run.py +8 -3
  36. mobiusguard_eval-0.3.0/src/mobiusguard_eval/screening.py +63 -0
  37. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/sources.py +198 -3
  38. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/train.py +108 -14
  39. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/train_data.py +13 -2
  40. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/train_sources.py +498 -3
  41. mobiusguard_eval-0.3.0/tests/test_augment.py +325 -0
  42. mobiusguard_eval-0.3.0/tests/test_distill.py +113 -0
  43. mobiusguard_eval-0.3.0/tests/test_export.py +63 -0
  44. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_judge.py +24 -0
  45. mobiusguard_eval-0.3.0/tests/test_local_views.py +37 -0
  46. mobiusguard_eval-0.3.0/tests/test_model_meta.py +90 -0
  47. mobiusguard_eval-0.3.0/tests/test_phase1_sources.py +136 -0
  48. mobiusguard_eval-0.3.0/tests/test_redteam_adaptive.py +333 -0
  49. mobiusguard_eval-0.3.0/tests/test_redteam_findings.py +91 -0
  50. mobiusguard_eval-0.3.0/tests/test_redteam_holdout_gate.py +146 -0
  51. mobiusguard_eval-0.3.0/tests/test_redteam_run.py +192 -0
  52. mobiusguard_eval-0.3.0/tests/test_redteam_seeds.py +197 -0
  53. mobiusguard_eval-0.3.0/tests/test_redteam_targets.py +194 -0
  54. mobiusguard_eval-0.3.0/tests/test_roles.py +105 -0
  55. mobiusguard_eval-0.3.0/tests/test_screening.py +41 -0
  56. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_train_data.py +33 -1
  57. mobiusguard_eval-0.3.0/tests/test_train_sources_dev.py +282 -0
  58. mobiusguard_eval-0.3.0/tests/test_unit_interval.py +42 -0
  59. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/.gitignore +0 -0
  60. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/LICENSE +0 -0
  61. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/NOTICE +0 -0
  62. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/checkpoint.py +0 -0
  63. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/dedup.py +0 -0
  64. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/detectors/keyword.py +0 -0
  65. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/detectors/tfidf.py +0 -0
  66. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/fetch.py +0 -0
  67. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/latency.py +0 -0
  68. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/py.typed +0 -0
  69. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/redaction.py +0 -0
  70. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/src/mobiusguard_eval/suite.py +0 -0
  71. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_checkpoint.py +0 -0
  72. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_core.py +0 -0
  73. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_import.py +0 -0
  74. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_run.py +0 -0
  75. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_suite.py +0 -0
  76. {mobiusguard_eval-0.2.0 → mobiusguard_eval-0.3.0}/tests/test_train_sources_v2.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mobiusguard-eval
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Honest evaluation harness for LLM guardrails: prompt-injection detectors scored on held-out attack families at a fixed false-positive rate, with pinned datasets, a provenance ledger and CPU latency; trains and exports small ONNX classifiers.
5
5
  Project-URL: Homepage, https://github.com/gantrly/mobius-guard
6
6
  Project-URL: Documentation, https://github.com/gantrly/mobius-guard/tree/main/docs
@@ -29,8 +29,8 @@ Classifier: Topic :: Security
29
29
  Classifier: Typing :: Typed
30
30
  Requires-Python: >=3.11
31
31
  Requires-Dist: huggingface-hub>=0.26
32
- Requires-Dist: mobiusguard-redact<0.3,>=0.2.0
33
- Requires-Dist: mobiusguard<0.3,>=0.2.0
32
+ Requires-Dist: mobiusguard-redact<0.4,>=0.3.0
33
+ Requires-Dist: mobiusguard<0.4,>=0.3.0
34
34
  Requires-Dist: numpy>=2.0
35
35
  Requires-Dist: pyarrow>=18
36
36
  Provides-Extra: hf
@@ -38,6 +38,8 @@ Requires-Dist: torch>=2.5; extra == 'hf'
38
38
  Requires-Dist: transformers>=4.46; extra == 'hf'
39
39
  Provides-Extra: judge
40
40
  Requires-Dist: boto3>=1.40; extra == 'judge'
41
+ Provides-Extra: pyrit
42
+ Requires-Dist: pyrit==1.1.0; extra == 'pyrit'
41
43
  Provides-Extra: sklearn
42
44
  Requires-Dist: scikit-learn>=1.5; extra == 'sklearn'
43
45
  Provides-Extra: train
@@ -96,6 +98,24 @@ in the ledger with its licence, and any source of the evaluation suite is refuse
96
98
  <img src="https://raw.githubusercontent.com/gantrly/mobius-guard/main/docs/assets/fortress-recall.png" alt="Recall at 1% false positives per attack family for Fortress-XS, PIGuard, ProtectAI v2 and keyword rules" width="760">
97
99
  </p>
98
100
 
101
+ ## Red-team a configuration
102
+
103
+ Attack a Mobius Guard configuration with garak's prompt-injection probes, each in 26
104
+ mutated forms and delivered both as a message and as a tool result, then see what got
105
+ through and check that a fix does not block more harmless text:
106
+
107
+ ```sh
108
+ mobiusguard-eval redteam run --seeds seeds.jsonl --config mobiusguard.toml --out runs/rt
109
+ mobiusguard-eval redteam seal --seeds seeds.jsonl --out runs/holdout # before tuning
110
+ mobiusguard-eval redteam findings --out runs/rt --seeds seeds.jsonl \
111
+ --holdout runs/holdout/holdout.json --report runs/findings
112
+ mobiusguard-eval redteam gate --suite runs/suite --base mobiusguard.toml --patched new.toml \
113
+ --report runs/gate
114
+ ```
115
+
116
+ Runs resume after a crash and store no attack text. See the
117
+ [red-team guide](https://github.com/gantrly/mobius-guard/blob/main/docs/red-team.md).
118
+
99
119
  ## What makes the numbers honest
100
120
 
101
121
  - **A provenance ledger.** Every dataset is pinned to a commit or a SHA-256, with its
@@ -46,6 +46,24 @@ in the ledger with its licence, and any source of the evaluation suite is refuse
46
46
  <img src="https://raw.githubusercontent.com/gantrly/mobius-guard/main/docs/assets/fortress-recall.png" alt="Recall at 1% false positives per attack family for Fortress-XS, PIGuard, ProtectAI v2 and keyword rules" width="760">
47
47
  </p>
48
48
 
49
+ ## Red-team a configuration
50
+
51
+ Attack a Mobius Guard configuration with garak's prompt-injection probes, each in 26
52
+ mutated forms and delivered both as a message and as a tool result, then see what got
53
+ through and check that a fix does not block more harmless text:
54
+
55
+ ```sh
56
+ mobiusguard-eval redteam run --seeds seeds.jsonl --config mobiusguard.toml --out runs/rt
57
+ mobiusguard-eval redteam seal --seeds seeds.jsonl --out runs/holdout # before tuning
58
+ mobiusguard-eval redteam findings --out runs/rt --seeds seeds.jsonl \
59
+ --holdout runs/holdout/holdout.json --report runs/findings
60
+ mobiusguard-eval redteam gate --suite runs/suite --base mobiusguard.toml --patched new.toml \
61
+ --report runs/gate
62
+ ```
63
+
64
+ Runs resume after a crash and store no attack text. See the
65
+ [red-team guide](https://github.com/gantrly/mobius-guard/blob/main/docs/red-team.md).
66
+
49
67
  ## What makes the numbers honest
50
68
 
51
69
  - **A provenance ledger.** Every dataset is pinned to a commit or a SHA-256, with its
@@ -23,8 +23,8 @@ classifiers = [
23
23
  ]
24
24
  dependencies = [
25
25
  "huggingface-hub>=0.26",
26
- "mobiusguard>=0.2.0,<0.3",
27
- "mobiusguard-redact>=0.2.0,<0.3",
26
+ "mobiusguard>=0.3.0,<0.4",
27
+ "mobiusguard-redact>=0.3.0,<0.4",
28
28
  "numpy>=2.0",
29
29
  "pyarrow>=18",
30
30
  ]
@@ -60,6 +60,11 @@ train = [
60
60
  "onnxruntime>=1.20",
61
61
  "onnxscript>=0.2",
62
62
  ]
63
+ # The red-team runner's PyRIT converters and attackers (decision 0014). garak is not an
64
+ # extra: it pins transformers below what `hf`/`train` need, so it runs in its own environment.
65
+ pyrit = [
66
+ "pyrit==1.1.0",
67
+ ]
63
68
  # The label-cleaning judges (Amazon Bedrock).
64
69
  judge = [
65
70
  "boto3>=1.40",
@@ -4,4 +4,4 @@ Held-out attack families, false-positive sets, recall at a fixed false-positive
4
4
  rate, and CPU latency.
5
5
  """
6
6
 
7
- __version__ = "0.2.0"
7
+ __version__ = "0.3.0"
@@ -0,0 +1,251 @@
1
+ """Disguised training copies that carry no label, and the harmless test sets that check it.
2
+
3
+ Fortress v1 caught 99.5% of the suite's spaced-out attacks, but only 53% of the same
4
+ attacks in plain text, and it blocks 94% of harmless messages once they are spaced out: it
5
+ had learned "spaced letters = attack", because the only spaced texts it trained on were 36
6
+ attacks. v2 added 99 harmless spaced messages (wildchat_dev) and learned the opposite. A
7
+ disguise must tell the model nothing, so here the same share of attack and harmless items
8
+ gets a disguised copy, and the model can only score a disguised text by what it says.
9
+
10
+ Rules:
11
+
12
+ - Each item gets at most one copy, chosen by a hash of its ID; each disguise takes
13
+ ``RATE`` of the eligible items, whatever their label.
14
+ - Only texts of at most ``MAX_CHARS`` characters are copied: a disguise multiplies the
15
+ token count, and a cut copy could lose the part that made it an attack.
16
+ - A copy keeps its original's label, split and cluster, so no copy sits in ``val`` while
17
+ its original is in ``train``.
18
+ - The disguises are training variants, not the suite's (``obfuscate.py``): other
19
+ separators, partial spacing, a larger leetspeak map, other invisible characters. Look-
20
+ alike letters are not used at all, so the suite's ``obf:homoglyph`` stays a disguise the
21
+ model never saw: the honest check that it reads through disguises in general.
22
+
23
+ Group weight: the harmless developer and tool-call sources added for v2 (``DEV_GROUP``)
24
+ hold 33k items and pulled everything they share with attacks towards harmless. Their loss
25
+ weight makes the group count as one source at the build's per-source cap (``CAP``).
26
+
27
+ ``extend_suite`` adds harmless test items to a copy of the suite: the calibration source's
28
+ test messages disguised with the suite's own transforms, and the developer check's eight
29
+ messages. The calibration half is unchanged, so thresholds are too.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import hashlib
35
+ import json
36
+ import random
37
+ from collections import Counter
38
+ from collections.abc import Callable, Sequence
39
+ from dataclasses import replace
40
+ from pathlib import Path
41
+ from typing import Any
42
+
43
+ from .items import Item, read_jsonl, write_jsonl
44
+ from .obfuscate import TRANSFORMS as SUITE_TRANSFORMS
45
+ from .obfuscate import item_rng as suite_rng
46
+ from .train_data import CAP
47
+
48
+ RATE = 0.04 # per disguise, of the eligible items
49
+ MAX_CHARS = 450
50
+ DEV_GROUP = frozenset({
51
+ "toucan", "glaive_fc", "wildchat_dev", "dev_secrets", "when2call", "toolace", "hermes_fc",
52
+ "magicoder", "self_oss", "opencodeinstruct", "codefeedback",
53
+ }) # fmt: skip
54
+ HELD_OUT = "homoglyph" # never used in training: the suite's check of an unseen disguise
55
+ # Recipe R2 (2026-11-26): harmless prompts that sound harmful. The teacher blocked 59% of
56
+ # OR-Bench hard's harmless prompts (v1 49.5%); these sources teach the harmful output that
57
+ # topic alone is not harm, so R2 gives their harmless items more weight.
58
+ HARD_BENIGN = frozenset({"phtest", "coconot", "aegis2", "wildjailbreak_benign", "jbb_benign"})
59
+
60
+ _LEET = {"a": "4@", "e": "3", "i": "1!", "o": "0", "s": "5$", "t": "7", "g": "9", "b": "8",
61
+ "l": "1", "z": "2"} # fmt: skip
62
+ _INVISIBLE = ("​", "‌", "‍", "⁠", "")
63
+
64
+
65
+ def seeded(key: str) -> random.Random:
66
+ seed = int.from_bytes(hashlib.sha256(f"augment:{key}".encode()).digest()[:8], "big")
67
+ return random.Random(seed) # noqa: S311 - reproducible training data, not security
68
+
69
+
70
+ def _unit(key: str) -> float:
71
+ return (
72
+ int.from_bytes(hashlib.sha256(f"augment-pick:{key}".encode()).digest()[:8], "big") / 2**64
73
+ )
74
+
75
+
76
+ def spaced(text: str, rng: random.Random) -> str:
77
+ """Letters apart, three styles: all words, hyphen or dot joined, or about half the words."""
78
+ style = rng.randrange(3)
79
+ words = text.split(" ")
80
+ if style == 0:
81
+ return rng.choice((" ", " ")).join(" ".join(w) for w in words)
82
+ if style == 1:
83
+ sep = rng.choice("-.")
84
+ return " ".join(sep.join(w) for w in words)
85
+ return " ".join(" ".join(w) if rng.random() < 0.5 else w for w in words)
86
+
87
+
88
+ def leetspeak(text: str, rng: random.Random) -> str:
89
+ """Swap some of the swappable letters (a share drawn per text) for digits or symbols."""
90
+ p = rng.uniform(0.5, 1.0)
91
+ out: list[str] = []
92
+ for c in text:
93
+ subs = _LEET.get(c.lower())
94
+ out.append(rng.choice(subs) if subs and rng.random() < p else c)
95
+ return "".join(out)
96
+
97
+
98
+ def zero_width(text: str, rng: random.Random) -> str:
99
+ """Invisible characters after a share of the letters (drawn per text), some after spaces."""
100
+ p = rng.uniform(0.1, 0.5)
101
+ out: list[str] = []
102
+ for c in text:
103
+ out.append(c)
104
+ if (c.isalpha() and rng.random() < p) or (c == " " and rng.random() < p / 2):
105
+ out.append(rng.choice(_INVISIBLE))
106
+ return "".join(out)
107
+
108
+
109
+ TRAIN_TRANSFORMS: dict[str, Callable[[str, random.Random], str]] = {
110
+ "spaced": spaced,
111
+ "leetspeak": leetspeak,
112
+ "zero_width": zero_width,
113
+ }
114
+ assert HELD_OUT not in TRAIN_TRANSFORMS # noqa: S101 - a design rule, checked at import
115
+
116
+
117
+ def pick(it: Item) -> str | None:
118
+ """The disguise this item's copy gets, or None for no copy."""
119
+ if len(it.text) > MAX_CHARS or it.meta.get("augmented"):
120
+ return None
121
+ u = _unit(it.id)
122
+ names = list(TRAIN_TRANSFORMS)
123
+ k = int(u / RATE)
124
+ return names[k] if k < len(names) else None
125
+
126
+
127
+ def disguise(it: Item, name: str) -> Item:
128
+ text = TRAIN_TRANSFORMS[name](it.text, seeded(f"{it.id}|{name}"))
129
+ return replace(it, id=f"{it.id}~aug:{name}", text=text,
130
+ meta={**it.meta, "augmented": name, "original": it.id}) # fmt: skip
131
+
132
+
133
+ def group_weight(items: Sequence[Item]) -> float:
134
+ n = sum(it.source in DEV_GROUP for it in items)
135
+ return min(1.0, CAP / n) if n else 1.0
136
+
137
+
138
+ def weigh(it: Item, w: float) -> Item:
139
+ if it.source not in DEV_GROUP or w >= 1.0:
140
+ return it
141
+ return replace(it, meta={**it.meta, "weight": f"{w:.4f}"})
142
+
143
+
144
+ def hard_benign(it: Item) -> bool:
145
+ return it.source in HARD_BENIGN and it.label == 0 and it.meta.get("harmful") == "0"
146
+
147
+
148
+ def extra_spaced(it: Item, rate: float) -> bool:
149
+ """Recipe R2: an extra spaced copy for a share of the harmless items that got none."""
150
+ return (rate > 0 and it.label == 0 and len(it.text) <= MAX_CHARS
151
+ and not it.meta.get("augmented") and pick(it) is None
152
+ and _unit(f"extra-spaced:{it.id}") < rate) # fmt: skip
153
+
154
+
155
+ def augment(data: Path, out: Path, *, exclude: Sequence[str] = (),
156
+ weight: float | None = None, hard_benign_weight: float = 1.0,
157
+ extra_benign_spaced: float = 0.0) -> dict[str, Any]: # fmt: skip
158
+ """Write ``out/{train,val}.jsonl`` and ``summary.json``: the items of ``data`` with
159
+ their group weights, plus one disguised copy for the picked items.
160
+
161
+ ``exclude`` leaves sources out (to find which ones move a result); ``weight`` fixes the
162
+ group weight instead of computing it, so leaving sources out changes nothing else.
163
+ Recipe R2: ``hard_benign_weight`` multiplies the loss weight of harmless items from
164
+ ``HARD_BENIGN``; ``extra_benign_spaced`` gives that share of the harmless items that
165
+ got no copy an extra spaced one. Both labels no longer get the same share of spaced
166
+ copies, on purpose: the gate's spaced-attack check shows whether that costs recall."""
167
+ parts = {p: [it for it in read_jsonl(data / f"{p}.jsonl") if it.source not in exclude]
168
+ for p in ("train", "val")} # fmt: skip
169
+ w = weight if weight is not None else group_weight([it for v in parts.values() for it in v])
170
+ out.mkdir(parents=True, exist_ok=True)
171
+ counts: Counter[str] = Counter()
172
+ ids: list[str] = []
173
+ for part, items in parts.items():
174
+ result: list[Item] = []
175
+ for it in items:
176
+ it = weigh(it, w)
177
+ if hard_benign_weight != 1.0 and hard_benign(it):
178
+ base_w = float(it.meta.get("weight", "1"))
179
+ it = replace(it, meta={**it.meta, "weight": f"{base_w * hard_benign_weight:.4f}"})
180
+ counts[f"hard_benign_weighted/{part}"] += 1
181
+ result.append(it)
182
+ if name := pick(it):
183
+ result.append(disguise(it, name))
184
+ counts[f"{name}/{'attack' if it.label else 'benign'}/{part}"] += 1
185
+ elif extra_spaced(it, extra_benign_spaced):
186
+ result.append(disguise(it, "spaced"))
187
+ counts[f"extra_spaced/benign/{part}"] += 1
188
+ write_jsonl(out / f"{part}.jsonl", result)
189
+ ids += [f"{it.id}\t{it.meta.get('weight', '1')}" for it in result]
190
+ counts[f"items/{part}"] = len(result)
191
+ base = json.loads((data / "summary.json").read_text())
192
+ summary: dict[str, Any] = {
193
+ **{k: base[k] for k in ("from_build", "suite_ids_sha256", "judges", "rule") if k in base},
194
+ "from_data": str(data),
195
+ "from_ids_sha256": base.get("ids_sha256"),
196
+ "augment": {
197
+ "rate": RATE,
198
+ "max_chars": MAX_CHARS,
199
+ "transforms": sorted(TRAIN_TRANSFORMS),
200
+ "held_out": HELD_OUT,
201
+ "dev_group": sorted(DEV_GROUP),
202
+ "dev_group_weight": round(w, 4),
203
+ "excluded": sorted(exclude),
204
+ "hard_benign": sorted(HARD_BENIGN),
205
+ "hard_benign_weight": hard_benign_weight,
206
+ "extra_benign_spaced": extra_benign_spaced,
207
+ },
208
+ "counts": dict(sorted(counts.items())),
209
+ # IDs and weights: two sets with the same items but other weights are other data.
210
+ "ids_sha256": hashlib.sha256("\n".join(sorted(ids)).encode()).hexdigest(),
211
+ }
212
+ (out / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
213
+ return summary
214
+
215
+
216
+ EXTRA_PER_DISGUISE = 1_000
217
+ BENIGN_DISGUISES = ("spaced", "leetspeak", "homoglyph", "zero_width") # base64 adds an order
218
+
219
+
220
+ def extend_suite(suite: Path, out: Path, calibration_source: str = "oasst") -> dict[str, Any]:
221
+ """A copy of the suite plus harmless test items: disguised calibration-source test
222
+ messages (``obf-benign:<name>``, the suite's own transforms) and the developer check's
223
+ eight messages (``dev_check``). Thresholds come from the unchanged calibration half."""
224
+ from .dev_texts import TEXTS
225
+
226
+ items = list(read_jsonl(suite / "items.jsonl"))
227
+ pool = [it for it in items if it.source == calibration_source and it.split == "test"
228
+ and it.label == 0 and len(it.text) >= 40] # fmt: skip
229
+ pool.sort(key=lambda it: hashlib.sha256(f"benign-obf:{it.id}".encode()).hexdigest())
230
+ chosen = pool[:EXTRA_PER_DISGUISE]
231
+ extra: list[Item] = []
232
+ for name in BENIGN_DISGUISES:
233
+ for it in chosen:
234
+ fam = f"obf-benign:{name}"
235
+ extra.append(replace(it, id=f"{it.id}~benign:{name}", source=fam, family=fam,
236
+ text=SUITE_TRANSFORMS[name](it.text, suite_rng(it.id, name)),
237
+ meta={**it.meta, "original": it.id})) # fmt: skip
238
+ for i, (name, text) in enumerate(TEXTS):
239
+ extra.append(Item(id=f"dev_check:{i}", text=text, label=0, source="dev_check",
240
+ family="dev_check", lang="en", split="test", cluster=f"dev_check:{i}",
241
+ meta={"name": name})) # fmt: skip
242
+ out.mkdir(parents=True, exist_ok=True)
243
+ write_jsonl(out / "items.jsonl", sorted(items + extra, key=lambda it: it.id))
244
+ manifest = {
245
+ "from_suite": str(suite),
246
+ "from_ids_sha256": hashlib.sha256("\n".join(it.id for it in items).encode()).hexdigest(),
247
+ "added": dict(Counter(it.source for it in extra)),
248
+ "items": len(items) + len(extra),
249
+ }
250
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
251
+ return manifest