Files
2026-11-25 20:46:42 +08:00

155 lines
9.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Canonicalize harmless provider format variations before strict validation.
This layer never changes caller identity, permission scope, resource identity or
business predicates. Unknown fields/operations still fail the typed contract.
"""
from copy import deepcopy
import json
def normalize_proposal(raw: dict, resources: list[dict]) -> dict:
result = deepcopy(raw)
definitions = {r["id"]: r for r in resources}
assessments = result.get("requested_assessments")
if isinstance(assessments, list):
result["requested_assessments"] = [
f"{entry['resource']}:{entry['rule']}"
if isinstance(entry, dict) and set(entry) == {"resource", "rule"}
and isinstance(entry["resource"], str) and isinstance(entry["rule"], str)
else entry for entry in assessments]
plan = result.get("plan")
if not isinstance(plan, dict):
return result
clarification = result.get('clarification')
if result.get('mode')=='clarify' and clarification is not None:
if isinstance(clarification,dict) and set(clarification)<={'question','options'}:
question=clarification.get('question')
options=clarification.get('options',[])
if isinstance(question,str) and isinstance(options,list) and all(isinstance(v,str) for v in options):
clarification=question+(' 可补充:'+';'.join(options) if options else '')
if isinstance(clarification,str) and plan.get('clarification',clarification)==clarification:
plan['clarification']=clarification
del result['clarification']
if result.get('clarification_context') not in (None,'new','followup'):
# This free-text diagnostic is not an executable context update.
# No reads occur during clarification; confirmed context stays in memory.
result['clarification_context']='followup'
# A misplaced envelope member has the same meaning after relocation.
# Leave conflicting copies in place so strict validation rejects them.
for name in ("focus", "mode", "intent", "reply", "requested_assessments"):
if name in plan and (name not in result or result[name] == plan[name]):
result[name] = plan.pop(name)
focus=result.get('focus')
if isinstance(focus,dict):
for name in ('cleared_context_fields','changed_context_fields'):
if name in focus and (name not in result or result[name]==focus[name]):
result[name]=focus.pop(name)
queries = plan.get("resource_queries", [])
if not isinstance(queries, list):
return result
# A physical date field is an unambiguous alias only when every involved
# resource declares the same date pair. Unknown date semantics still fail.
if isinstance(focus, dict) and focus.get('time_basis'):
raw_basis = focus['time_basis']
aliases = set()
for query in queries:
if not isinstance(query, dict):
continue
for basis, pair in definitions.get(query.get('resource'), {}).get('time_bindings', {}).items():
if pair == [raw_basis + '_from', raw_basis + '_to']:
aliases.add(basis)
if len(aliases) == 1:
focus['time_basis'] = aliases.pop()
if queries and plan.get("scope") in ("mine", "accessible") and all(
isinstance(q, dict) and q.get("scope", plan["scope"]) == plan["scope"] for q in queries):
scope = plan.pop("scope")
for query in queries:
query["scope"] = scope
for query in queries:
if not isinstance(query, dict):
continue
definition = definitions.get(query.get("resource"), {})
analysis=query.get('analysis')
if isinstance(analysis,dict):
for key in ('limit','offset'):
if key in analysis and query.get(key,analysis[key])==analysis[key]:
query[key]=analysis.pop(key)
allowed_filters=definition.get("filters",{})
if query.get('operation')=='detail' and 'record_ids' in query and 'record_ids' not in allowed_filters:
try:
ids=json.loads(query['record_ids']) if isinstance(query['record_ids'],str) else query['record_ids']
if isinstance(ids,list) and len(ids)==1 and isinstance(ids[0],(str,int)) and not isinstance(ids[0],bool):
record_id=str(ids[0])
if query.get('record_id',record_id)==record_id:
query['record_id']=record_id
del query['record_ids']
except (ValueError,TypeError):
pass # Leave malformed/conflicting IDs for strict validation.
filters=query.get('filters',{})
focus=result.get('focus',{})
if isinstance(filters,dict):
for name, fixed in definition.get('fixed_predicates',{}).items():
if name not in allowed_filters and name in filters and str(filters[name])==str(fixed):
# Repeating a server-owned predicate is redundant. A different
# value remains invalid, rather than silently changing intent.
del filters[name]
if isinstance(filters,dict) and isinstance(focus,dict) and 'id' in filters and 'id' not in allowed_filters:
selected=focus.get('selected_source_id') if focus.get('subject_action')=='select' else None
# The compiler reauthorizes this exact selected record and supplies its ID.
# Only remove a redundant identical predicate; a conflict must still fail.
if selected==str(query.get('resource'))+':'+str(filters['id']):
del filters['id']
for name in ("summary","group_by","sort_by","sort_direction","record_ids"):
if name not in query or name not in allowed_filters:continue
filters=query.setdefault("filters",{})
if isinstance(filters,dict) and (name not in filters or filters[name]==query[name]):filters[name]=query.pop(name)
for alias in ("operations", "read_modes", "read_mode"):
value = query.get(alias)
operation = value[0] if isinstance(value, list) and len(value) == 1 else value if isinstance(value, str) else None
if alias in query and operation in definition.get("operations", []):
if "operation" not in query:
query["operation"] = operation
del query[alias]
elif query["operation"] == operation:
del query[alias]
for alias in ("relations", "expand"):
relations = query.get(alias)
allowed = definition.get("relations", {})
if alias in query and isinstance(relations, dict) and set(relations) <= allowed.keys() and all(
isinstance(value, dict)
and set(value) <= {"target", "resource", "filters"}
and value.get("target", allowed[key].get("target")) == allowed[key].get("target")
and value.get("resource", allowed[key].get("target")) == allowed[key].get("target")
# Registered relation predicates are already applied by Java. A distinct
# predicate cannot be discarded, even when the relation name is valid.
and value.get("filters", allowed[key].get("filters", {})) == allowed[key].get("filters", {})
for key, value in relations.items()):
if "include" not in query:
query["include"] = list(relations)
del query[alias]
elif isinstance(query["include"], list) and set(query["include"]) == set(relations):
del query[alias]
if isinstance(query.get("filters"), dict):
for name, value in list(query["filters"].items()):
codes = allowed_filters.get(name, {}).get("values", {})
if isinstance(value, bool):
query["filters"][name] = "true" if value else "false"
elif isinstance(value, (str, int)) and str(value) not in codes:
matches = [key for key, label in codes.items() if label == str(value).strip()]
if len(matches) == 1:
query["filters"][name] = matches[0]
elif isinstance(value,list) and value and all(isinstance(v,(str,int)) and not isinstance(v,bool) for v in value):
values=[str(v) for v in value]
def code(v):
candidates=[key for key,label in codes.items() if label==v]
return candidates[0] if v not in codes and len(candidates)==1 else v
values=[code(v) for v in values]
for target,descriptor in allowed_filters.items():
if descriptor.get("equivalent_filter")==name:
matches=[code for code,group in descriptor.get("groups",{}).items() if isinstance(group,list) and set(map(str,group))==set(values)]
if len(matches)==1 and (target not in query["filters"] or query["filters"][target]==matches[0]):
del query["filters"][name];query["filters"][target]=matches[0];break
if descriptor.get("array_filter")==name and (target not in query["filters"] or query["filters"][target]==json.dumps(values,separators=(',',':'))):
del query["filters"][name];query["filters"][target]=json.dumps(values,separators=(',',':'));break
return result