"""Small, deterministic documentation projections and structured drift checks. These functions do not call an LLM, judge arbitrary prose, or establish runtime truth. The benchmark scorer and task answer labels are deliberately outside this module. """ from __future__ import annotations import json import math import re import unicodedata from collections import Counter from datetime import date MODES = ('full_markdown', 'concise_markdown', 'core_markdown', 'compact_core', 'task_bundle') def normalize(text): """Normalize Unicode and whitespace, without removing qualifiers or punctuation.""" return ' '.join(unicodedata.normalize('NFC', text).split()) def evidence(record): rid = record['id'] spans = { rid + '.source': f"Source: {record['source']['id']} at revision {record['source']['revision']}.", rid + '.status': f"Status: {record['status']}.", rid + '.effective': f"Effective from: {record['effective_from']}.", rid + '.owner': f"Owner: {record['owner']}.", } spans.update({f['id']: f['text'] for f in record['facts']}) spans.update({rid + '.' + key: value for key, value in record['context'].items()}) return spans def render_record(record, mode='full_markdown', kind='decision'): """Compile a public projection. Only kind, never gold fields, controls the view.""" if mode not in MODES: raise ValueError('Unknown projection: ' + mode) rid = record['id'] spans = evidence(record) metadata = [spans[rid + '.' + key] for key in ('source', 'status', 'effective', 'owner')] facts = [fact['text'] for fact in record['facts']] title = f"{rid} — {record['title']}" if mode == 'full_markdown': return '\n\n'.join([ '# ' + title, record['context']['purpose'], '## Responsibility and provenance\n\n' + '\n\n'.join(metadata), '## Decision rules\n\n' + '\n'.join('- ' + fact for fact in facts), '## Why this rule exists\n\n' + record['context']['rationale'], '## Worked example\n\n' + record['context']['example'], ]) if mode in ('concise_markdown', 'core_markdown'): # Equal-fields core Markdown controls for serialization overhead; concise # Markdown is a useful baseline that also retains the rationale. lines = ['# ' + title, *metadata, *('- ' + fact for fact in facts)] if mode == 'concise_markdown': lines.append('Rationale: ' + record['context']['rationale']) return '\n'.join(lines) selected = metadata + facts if mode == 'task_bundle' and kind == 'explanation': selected += [record['context'][k] for k in ('purpose', 'rationale', 'example')] # No shortened operators, token substitutions, or generated paraphrases. return json.dumps({'record': rid, 'title': record['title'], 'evidence': selected}, ensure_ascii=False, separators=(',', ':')) def lexical_tokens(text): return re.findall(r'[\w]+', unicodedata.normalize('NFKC', text).lower(), flags=re.UNICODE) def rank_records(query, records): """BM25 over the same complete source text for every projection (k1=1.2, b=.75).""" documents = [lexical_tokens(render_record(r, 'full_markdown')) for r in records] lengths = [len(tokens) for tokens in documents] average_length = sum(lengths) / len(lengths) counts = [Counter(tokens) for tokens in documents] document_frequency = Counter(token for tokens in documents for token in set(tokens)) query_terms = sorted(set(lexical_tokens(query))) scores = [] for record, tf, length in zip(records, counts, lengths): score = 0.0 for term in query_terms: freq = tf.get(term, 0) if not freq: continue df = document_frequency[term] inverse = math.log(1 + (len(records) - df + .5) / (df + .5)) score += inverse * (freq * 2.2) / (freq + 1.2 * (.25 + .75 * length / average_length)) scores.append((score, record['id'])) return [rid for score, rid in sorted(scores, key=lambda item: (-item[0], item[1]))] def wrap_blocks(blocks): return '\n\n'.join(f'\n{text}' for rid, text in blocks) def pack_records(ranked, records_by_id, mode, kind, count, budget=None, top_k=3): """Ranked first-fit, whole records only; all modes see the same candidate IDs.""" blocks = [] for rid in ranked[:top_k]: candidate = blocks + [(rid, render_record(records_by_id[rid], mode, kind))] if budget is None or count(wrap_blocks(candidate)) <= budget: blocks = candidate return blocks def _canonical(value): """Only schema-typed values are compared, not arbitrary natural-language meaning.""" if isinstance(value, dict): return {key: _canonical(item) for key, item in sorted(value.items())} if isinstance(value, list): return [_canonical(item) for item in value] if isinstance(value, str): return normalize(value) return value def classify_drift(policy, snapshots, as_of, unresolved_prose_change=False): """Compare approved policy with complete, mapped and timely snapshot evidence. ALIGNED means only that declared fields match in a comparable snapshot within the policy's explicit freshness window. Runtime behaviour is never verified. Unknown schema, incomplete extraction and unstructured edits require review. """ def result(status, reason, differences=None): return {'status': status, 'reason': reason, 'differences': differences or []} def iso_date(value): if not isinstance(value, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', value): raise ValueError('Expected an ISO date') return date.fromisoformat(value) def valid_scope(scope): return isinstance(scope, dict) and bool(scope) and all( isinstance(key, str) and key.strip() and isinstance(value, str) and value.strip() for key, value in scope.items()) def valid_fields(fields, require_all=False): allowed = {'operator', 'value', 'unit', 'exceptions'} if not isinstance(fields, dict) or not fields or not set(fields).issubset(allowed): return False if require_all and set(fields) != allowed: return False if 'operator' in fields and fields['operator'] not in ('<', '<=', '>', '>=', '==', '!='): return False if 'value' in fields and (isinstance(fields['value'], bool) or not isinstance(fields['value'], (int, float)) or not math.isfinite(fields['value'])): return False if 'unit' in fields and (not isinstance(fields['unit'], str) or not fields['unit'].strip()): return False if 'exceptions' in fields and (not isinstance(fields['exceptions'], list) or any(not isinstance(item, str) or not item.strip() for item in fields['exceptions'])): return False return True if not isinstance(policy, dict): return result('UNVERIFIED', 'invalid_policy') if not valid_scope(policy.get('scope')): return result('UNVERIFIED', 'missing_policy_scope') if policy.get('schema_version') != '1.0': return result('UNVERIFIED', 'unsupported_policy_schema') if not isinstance(policy.get('revision'), str) or not policy['revision'].strip(): return result('UNVERIFIED', 'missing_policy_revision') if not valid_fields(policy.get('fields'), require_all=True): return result('UNVERIFIED', 'missing_policy_fields') max_age = policy.get('max_evidence_age_days') if isinstance(max_age, bool) or not isinstance(max_age, int) or max_age < 0: return result('UNVERIFIED', 'missing_evidence_freshness_contract') try: current, effective = iso_date(as_of), iso_date(policy.get('effective_from')) except ValueError: return result('UNVERIFIED', 'invalid_policy_or_evaluation_date') if policy.get('status') != 'approved': return result('UNVERIFIED', 'policy_not_approved') if effective > current: return result('NOT_ACTIVE', 'policy_not_yet_effective') if unresolved_prose_change: return result('UNVERIFIED', 'unmapped_prose_change') if snapshots is None or snapshots == []: return result('UNVERIFIED', 'missing_evidence') if isinstance(snapshots, dict): snapshots = [snapshots] if not isinstance(snapshots, list) or any(not isinstance(s, dict) for s in snapshots): return result('UNVERIFIED', 'invalid_evidence') if any(not valid_scope(s.get('scope')) for s in snapshots): return result('UNVERIFIED', 'missing_evidence_scope') comparable = [s for s in snapshots if s['scope'] == policy['scope']] if not comparable: return result('NOT_COMPARABLE', 'scope_mismatch') if any(s.get('schema_version') != '1.0' for s in comparable): return result('UNVERIFIED', 'unsupported_evidence_schema') if any(s.get('policy_revision') != policy['revision'] for s in comparable): return result('UNVERIFIED', 'evidence_targets_another_policy_revision') if any(s.get('coverage') != 'complete' for s in comparable): return result('UNVERIFIED', 'incomplete_snapshot_coverage') if any(not valid_fields(s.get('fields')) for s in comparable): return result('UNVERIFIED', 'missing_structured_fields') try: observed = [iso_date(s.get('observed_at')) for s in comparable] except ValueError: return result('UNVERIFIED', 'invalid_evidence_date') if any(stamp < effective for stamp in observed): return result('UNVERIFIED', 'evidence_predates_policy') if any(stamp > current for stamp in observed): return result('UNVERIFIED', 'evidence_from_the_future') if any((current-stamp).days > max_age for stamp in observed): return result('UNVERIFIED', 'evidence_exceeds_freshness_window') if any(s.get('unmapped_fields') for s in comparable): return result('UNVERIFIED', 'unmapped_configuration_fields') canonical = [json.dumps(_canonical(s['fields']), sort_keys=True) for s in comparable] if len(set(canonical)) > 1: return result('CONFLICT', 'conflicting_comparable_evidence') actual, expected = comparable[0]['fields'], policy['fields'] differences = [key for key in sorted(set(expected) | set(actual)) if key not in expected or key not in actual or json.dumps(_canonical(expected[key]), sort_keys=True) != json.dumps(_canonical(actual[key]), sort_keys=True)] return result('DIVERGED' if differences else 'ALIGNED', 'mapped_field_difference' if differences else 'mapped_fields_equal', differences) def revision_baseline(event): """Common source-revision alarm; coarse by design and named as such.""" return 'ALERT' if event['source_revision_before'] != event['source_revision_after'] else 'NO_ALERT'