File size: 7,598 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Source subtype gate for explicit bathroom furniture requirements.

Call after existing native admission and asset/record pin intersections. Enrich
pool candidates with native source_semantic_evidence first. This helper verifies
the exact source CSV row; it neither grants native admission nor installs assets.
No candidates, entity inventory, dimensions, receipts or source files are changed.

API: filter_bath_furniture_candidates(candidates, *, requested_function,
                                     read_bytes=None) -> audit dict.
Functions: washroom_vanity / wash_storage (strict washroom vanity), or the
separate bathroom_storage requirement. No automatic substitution is performed.
An empty vanity domain remains unfulfilled; fallback_requirement is a proposal
for a separate explicit storage entity and must pass its own native gates.
"""
from __future__ import annotations

import copy
import csv
import hashlib
import html
import io
from pathlib import Path
import re


def _text(value):
    return ' '.join(html.unescape(str(value or '')).lower().replace('_', ' ').split())


def _source_row(candidate, loader, cache):
    envelope = candidate['source_semantic_evidence']
    if envelope.get('qualification_error') or envelope['asset_id'] != candidate['asset_id']:
        raise ValueError('source_semantic_identity_unqualified')
    for field, source in [('source_sha256', 'asset_sha256'), ('runtime_sha256', 'runtime_sha256')]:
        value = candidate[source]
        if not isinstance(value, str) or not re.fullmatch('[0-9a-f]{64}', value) or envelope.get(field) != value:
            raise ValueError('source_runtime_identity_mismatch')
    matrix = candidate['canonical_transform']
    if not isinstance(matrix, (list, tuple)) or len(matrix) != 16 or envelope.get('canonical_transform') != matrix:
        raise ValueError('source_frame_identity_mismatch')
    authored = envelope['authored_source']
    row_id = authored['source_row_id']
    if not isinstance(row_id, str) or not row_id:
        raise ValueError('missing_source_row_identity')
    if candidate['asset_id'].startswith('hssd:') and candidate['asset_id'].rsplit('/', 1)[-1] != row_id:
        raise ValueError('source_row_asset_identity_mismatch')
    ref = envelope['evidence_references']['authored_semantic_csv']
    uri, digest = ref['uri'], ref['sha256']
    if (not isinstance(uri, str) or not uri or not isinstance(digest, str)
            or not re.fullmatch('[0-9a-f]{64}', digest)
            or ref.get('scope') != 'exact_source_row_id:' + row_id):
        raise ValueError('source_reference_scope_or_identity_invalid')
    key = uri, digest
    if key not in cache:
        raw = loader(uri)
        if not isinstance(raw, bytes) or hashlib.sha256(raw).hexdigest() != digest:
            raise ValueError('source_semantics_hash_mismatch')
        index = {}
        for row in csv.DictReader(io.StringIO(raw.decode('utf-8-sig'))):
            index.setdefault(row.get('id'), []).append(row)
        cache[key] = index
    rows = cache[key].get(row_id, [])
    if len(rows) != 1:
        raise ValueError('source_row_missing_or_ambiguous')
    row = rows[0]
    if authored.get('source_name') and _text(authored['source_name']) != _text(row.get('name')):
        raise ValueError('authored_name_conflicts_with_verified_csv')
    return row, dict(source_uri=uri, source_sha256=digest, source_row_id=row_id,
                     source_name=row.get('name'), wordnet_synset=row.get('wnsynsetkey'),
                     main_category=row.get('main_category'))


def _subtype(row, function):
    name = _text(row.get('name'))
    classes = ' '.join(_text(row.get(k)) for k in ('wnsynsetkey', 'main_wnsynsetkey', 'main_category'))
    text = name + ' ' + classes
    if re.search(r'\b(?:dressing table|work table|worktable|workbench|writing table|desk|makeup table|make up table)\b', text):
        return 'reject', 'source_is_work_or_dressing_table'
    if re.search(r'\b(?:lamp|lamps|light|lights|lighting|bench|stool|chair|mirror)\b', classes):
        return 'reject', 'source_is_accessory_not_washroom_cabinet'
    if re.search(r'\b(?:washbasin|wash basin|sink stand|basin|sink)\.n\.', classes):
        return 'reject', 'source_is_basin_or_stand_not_vanity_storage'
    # Source class has priority over a product-name mention of "vanity".
    if re.search(r'\b(?:mirror|lamp|lighting|shelf)\b', name) and not re.search(r'\bcabinet\b', name):
        return 'reject', 'source_is_accessory_not_washroom_cabinet'
    real_vanity = bool(re.search(r'\bsink cabinet\.n\.', classes)
        or re.search(r'\bbathroom vanity (?:unit|set|cabinet)\b', name)
        or (re.search(r'\b(?:vanity unit|washstand)\b', name)
            and re.search(r'\b(?:basin|sink)\b', name)
            and re.search(r'\b(?:unit|cabinet|door|drawers?)\b', name)))
    storage = bool(re.search(r'\bbathroom (?:wall |mirror |storage )?cabinet\b', name))
    if real_vanity or (function == 'bathroom_storage' and storage):
        return 'accept', 'verified_washroom_storage_subtype' if function == 'bathroom_storage' else 'verified_washroom_vanity_subtype'
    if storage:
        return 'reject', 'bathroom_storage_does_not_satisfy_washroom_vanity'
    return 'unknown', 'washroom_function_subtype_unproven'


def filter_bath_furniture_candidates(candidates, *, requested_function, read_bytes=None):
    """Return copied survivors and source decisions; preserve every input pin.

    Accepted means source subtype only. Source mesh eligibility, real support,
    plumbing/mounting, saved geometry and physical function remain native work.
    Missing/stale/conflicting source evidence cannot satisfy the requirement.
    """
    if requested_function not in {'washroom_vanity', 'wash_storage', 'bathroom_storage'}:
        raise ValueError('Explicit supported bathroom function required')
    loader = read_bytes or (lambda uri: Path(uri).read_bytes())
    cache, accepted, decisions = {}, [], []
    for candidate in candidates:
        decision = dict(asset_id=candidate.get('asset_id'),
                        record_id=candidate.get('pool_candidate_key') or candidate.get('record_id'),
                        status='unknown')
        try:
            row, evidence = _source_row(candidate, loader, cache)
            status, reason = _subtype(row, requested_function)
            decision.update(status=status, reason=reason, evidence=evidence)
            if status == 'accept':
                accepted.append(copy.deepcopy(candidate))
        except (KeyError, TypeError, ValueError, OSError, UnicodeError) as error:
            decision['reason'] = str(error)
        decisions.append(decision)
    strict = requested_function != 'bathroom_storage'
    return dict(schema='rhg.bath-furniture-source-policy.v1', requested_function=requested_function,
                accepted=accepted, decisions=decisions, rejected=[d for d in decisions if d['status'] != 'accept'],
                source_subtype_candidate_count=len(accepted), counts_as_vanity=False,
                source_subtype_is_washroom_vanity=strict and bool(accepted),
                requirement_status='pending_native_and_installation_verification' if accepted else 'unfulfilled',
                requirement_fulfilled=False, native_admission_granted=False, installation_qualified=False,
                physical_function_verified=False,
                fallback_requirement=(dict(function='bathroom_storage', counts_as_vanity=False,
                    status='requires_separate_explicit_entity_and_native_domain') if strict and not accepted else None))