File size: 12,864 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""Tests for the brand rules rubric: schema validation, structural integrity, and content rules."""

from __future__ import annotations

import json
import re
from pathlib import Path

import jsonschema
import pytest

from rubric.loader import load_rubric, Rubric

RUBRIC_DIR = Path(__file__).parent.parent / "rubric"
RULES_FILE = RUBRIC_DIR / "brand_rules.json"
SCHEMA_FILE = RUBRIC_DIR / "schema.json"

REQUIRED_CATEGORIES = {
    "title_slide",
    "section_header",
    "slide_title",
    "confidentiality_statement",
    "bullets",
    "tables_overall",
    "table_title",
    "table_header",
    "table_body",
    "statistics_row",
    "client_row",
    "chart_title",
    "chart_content",
    "chart_source_notes",
    "shapes",
    "footnotes",
    "emphasis_annotations",
    "writing_style",
    "terminology",
    "color_palette",
}

SOURCE_REF_PATTERN = re.compile(
    r"^(brand-guidelines \(2\)\.md:L[0-9]+-[0-9]+|Dev Docs/PRD\.md:L[0-9]+-[0-9]+|internal_qa_policy)$"
)


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture(scope="module")
def rubric() -> Rubric:
    return load_rubric()


@pytest.fixture(scope="module")
def raw_data() -> dict:
    return json.loads(RULES_FILE.read_text(encoding="utf-8"))


@pytest.fixture(scope="module")
def schema() -> dict:
    return json.loads(SCHEMA_FILE.read_text(encoding="utf-8"))


# ---------------------------------------------------------------------------
# Schema validation
# ---------------------------------------------------------------------------


def test_schema_file_exists():
    assert SCHEMA_FILE.exists(), "schema.json must exist"


def test_rules_file_exists():
    assert RULES_FILE.exists(), "brand_rules.json must exist"


def test_rubric_validates_against_schema(raw_data, schema):
    """brand_rules.json must validate against schema.json without errors."""
    jsonschema.validate(instance=raw_data, schema=schema)


def test_load_rubric_returns_rubric_instance(rubric):
    assert isinstance(rubric, Rubric)


# ---------------------------------------------------------------------------
# Required fields on every rule
# ---------------------------------------------------------------------------


def test_every_rule_has_required_fields(rubric):
    for rule in rubric.rules:
        assert rule.id, f"Rule missing id: {rule}"
        assert rule.category, f"Rule {rule.id} missing category"
        assert rule.rule_text, f"Rule {rule.id} missing rule_text"
        assert rule.severity_default in ("high", "medium", "low"), (
            f"Rule {rule.id} has invalid severity_default: {rule.severity_default}"
        )
        assert rule.detection_type in ("deterministic", "ai_judgment", "hybrid"), (
            f"Rule {rule.id} has invalid detection_type: {rule.detection_type}"
        )
        assert rule.source_ref, f"Rule {rule.id} missing source_ref"


def test_every_rule_source_ref_matches_pattern(rubric):
    for rule in rubric.rules:
        assert SOURCE_REF_PATTERN.match(rule.source_ref), (
            f"Rule {rule.id} has invalid source_ref: {rule.source_ref!r}"
        )


def test_rule_ids_are_unique(rubric):
    ids = [rule.id for rule in rubric.rules]
    assert len(ids) == len(set(ids)), f"Duplicate rule ids found: {[i for i in ids if ids.count(i) > 1]}"


# ---------------------------------------------------------------------------
# Every category has at least one rule
# ---------------------------------------------------------------------------


def test_every_category_has_at_least_one_rule(rubric):
    covered = {rule.category for rule in rubric.rules}
    missing = REQUIRED_CATEGORIES - covered
    assert not missing, f"Categories with no rules: {sorted(missing)}"


def test_no_orphan_categories(rubric):
    """No rule should have a category outside the defined enum."""
    for rule in rubric.rules:
        assert rule.category in REQUIRED_CATEGORIES, (
            f"Rule {rule.id} has unknown category: {rule.category}"
        )


# ---------------------------------------------------------------------------
# Mandatory deterministic rules
# ---------------------------------------------------------------------------


def test_title_slide_no_draft_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "title_slide.no_draft"), None)
    assert rule is not None, "Rule title_slide.no_draft must exist"
    assert rule.detection_type == "deterministic"


def test_percentile_label_rule_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "tables_overall.percentile_label"), None)
    assert rule is not None, "Rule tables_overall.percentile_label must exist"
    assert rule.detection_type == "deterministic"
    # Ensure rule text references %ile
    assert "%ile" in rule.rule_text


def test_target_not_tgt_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "terminology.target_not_tgt"), None)
    assert rule is not None, "Rule terminology.target_not_tgt must exist"
    assert rule.detection_type == "deterministic"


def test_executive_not_incumbent_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "table_header.executive_not_incumbent"), None)
    assert rule is not None, "Rule table_header.executive_not_incumbent must exist"
    assert rule.detection_type == "deterministic"


def test_color_palette_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "color_palette.approved_colors_only"), None)
    assert rule is not None, "Rule color_palette.approved_colors_only must exist"
    assert rule.detection_type == "deterministic"


def test_no_ending_punctuation_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "bullets.no_ending_punctuation"), None)
    assert rule is not None, "Rule bullets.no_ending_punctuation must exist"
    assert rule.detection_type == "deterministic"


def test_no_internal_comments_is_deterministic(rubric):
    rule = next((r for r in rubric.rules if r.id == "writing_style.no_internal_comments"), None)
    assert rule is not None, "Rule writing_style.no_internal_comments must exist"
    assert rule.detection_type == "deterministic"


# ---------------------------------------------------------------------------
# Mandatory ai_judgment rules
# ---------------------------------------------------------------------------


def test_takeaway_not_topic_is_ai_judgment(rubric):
    rule = next((r for r in rubric.rules if r.id == "slide_title.takeaway_not_topic"), None)
    assert rule is not None, "Rule slide_title.takeaway_not_topic must exist"
    assert rule.detection_type == "ai_judgment"


def test_bullets_parallel_grammar_is_ai_judgment(rubric):
    rule = next((r for r in rubric.rules if r.id == "bullets.parallel_grammar"), None)
    assert rule is not None, "Rule bullets.parallel_grammar must exist"
    assert rule.detection_type == "ai_judgment"


def test_key_vs_legend_is_ai_judgment(rubric):
    rule = next((r for r in rubric.rules if r.id == "chart_content.key_vs_legend"), None)
    assert rule is not None, "Rule chart_content.key_vs_legend must exist"
    assert rule.detection_type == "ai_judgment"


def test_table_as_image_is_ai_judgment(rubric):
    rule = next((r for r in rubric.rules if r.id == "tables_overall.no_image_table"), None)
    assert rule is not None, "Rule tables_overall.no_image_table must exist"
    assert rule.detection_type == "ai_judgment"


# ---------------------------------------------------------------------------
# confidentiality_statement.present_and_positioned is hybrid
# ---------------------------------------------------------------------------


def test_confidentiality_is_hybrid(rubric):
    rule = next(
        (r for r in rubric.rules if r.id == "confidentiality_statement.present_and_positioned"),
        None,
    )
    assert rule is not None, "Rule confidentiality_statement.present_and_positioned must exist"
    assert rule.detection_type == "hybrid"


def test_confidentiality_has_canonical_text(rubric):
    rule = next(
        (r for r in rubric.rules if r.id == "confidentiality_statement.present_and_positioned"),
        None,
    )
    assert rule is not None
    assert rule.metadata is not None, "confidentiality rule must have metadata"
    assert rule.metadata.canonical_text, "canonical_text must be non-empty"
    assert len(rule.metadata.canonical_text) > 10


# ---------------------------------------------------------------------------
# must_flag_markers
# ---------------------------------------------------------------------------


def test_must_flag_markers_exist(rubric):
    assert rubric.metadata.must_flag_markers, "must_flag_markers must be non-empty"


def test_must_flag_markers_keys(rubric):
    keys = set(rubric.metadata.must_flag_markers.keys())
    assert keys == {"DRAFT", "TW question", "Page to be updated"}, (
        f"must_flag_markers keys mismatch: {keys}"
    )


def test_must_flag_markers_reference_existing_rule_ids(rubric):
    existing_ids = {rule.id for rule in rubric.rules}
    for marker_key, marker in rubric.metadata.must_flag_markers.items():
        assert marker.rule_id in existing_ids, (
            f"must_flag_markers[{marker_key!r}].rule_id={marker.rule_id!r} "
            f"does not resolve to an existing rule"
        )


def test_must_flag_markers_required_fields(rubric):
    for marker_key, marker in rubric.metadata.must_flag_markers.items():
        assert marker.category, f"must_flag_markers[{marker_key!r}] missing category"
        assert marker.severity_default in ("high", "medium", "low"), (
            f"must_flag_markers[{marker_key!r}] invalid severity_default"
        )
        assert marker.title_template, f"must_flag_markers[{marker_key!r}] missing title_template"
        assert marker.rule_id, f"must_flag_markers[{marker_key!r}] missing rule_id"


# ---------------------------------------------------------------------------
# color_palette allowed_hex
# ---------------------------------------------------------------------------


def test_color_palette_has_allowed_hex(rubric):
    rule = next((r for r in rubric.rules if r.id == "color_palette.approved_colors_only"), None)
    assert rule is not None
    assert rule.metadata is not None
    assert rule.metadata.allowed_hex is not None
    assert len(rule.metadata.allowed_hex) > 0


def test_color_palette_allowed_hex_are_deduplicated(rubric):
    rule = next((r for r in rubric.rules if r.id == "color_palette.approved_colors_only"), None)
    assert rule is not None
    hexes = rule.metadata.allowed_hex
    assert len(hexes) == len(set(h.upper() for h in hexes)), (
        "allowed_hex contains duplicate entries"
    )


def test_color_palette_allowed_hex_length_matches_rubric(rubric):
    """Verify the hex count in the rule matches the deduplicated unique hex set in the rubric.

    This test does NOT use a hard-coded constant — it derives the expected count
    from the rubric itself.
    """
    rule = next((r for r in rubric.rules if r.id == "color_palette.approved_colors_only"), None)
    assert rule is not None
    hexes = rule.metadata.allowed_hex
    unique_count = len(set(h.upper() for h in hexes))
    assert len(hexes) == unique_count, (
        f"allowed_hex length {len(hexes)} != unique count {unique_count}"
    )


def test_color_palette_allowed_hex_format(rubric):
    rule = next((r for r in rubric.rules if r.id == "color_palette.approved_colors_only"), None)
    assert rule is not None
    hex_pattern = re.compile(r"^#[0-9A-Fa-f]{6}$")
    for h in rule.metadata.allowed_hex:
        assert hex_pattern.match(h), f"Invalid hex format: {h!r}"


# ---------------------------------------------------------------------------
# Loader error handling
# ---------------------------------------------------------------------------


def test_load_rubric_raises_on_missing_file(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_rubric(rules_path=tmp_path / "nonexistent.json")


def test_load_rubric_raises_on_schema_violation(tmp_path):
    """Loader must raise jsonschema.ValidationError when rubric violates schema."""
    import jsonschema

    bad_rubric = {
        "version": "1.0.0",
        "metadata": {"must_flag_markers": {}},
        "rules": [
            {
                "id": "bad_rule",
                "category": "title_slide",
                # missing required fields: rule_text, severity_default, detection_type, source_ref
            }
        ],
    }
    bad_file = tmp_path / "bad_rules.json"
    bad_file.write_text(json.dumps(bad_rubric), encoding="utf-8")
    with pytest.raises(jsonschema.ValidationError):
        load_rubric(rules_path=bad_file, schema_path=SCHEMA_FILE)