@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.0

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 (135) hide show
  1. package/README.md +20 -2
  2. package/cordis.patch.yml +4 -0
  3. package/icon.svg +4 -0
  4. package/index.js +35 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +37 -4
  8. package/skills/datarc-access-permissions/SKILL.md +30 -0
  9. package/skills/datarc-access-permissions/references/api.md +31 -0
  10. package/skills/datarc-access-permissions/references/write-order.md +16 -0
  11. package/skills/datarc-analysis-report/SKILL.md +125 -0
  12. package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
  13. package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  14. package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
  15. package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  16. package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  17. package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  18. package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
  19. package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
  20. package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
  21. package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  22. package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  23. package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  24. package/skills/datarc-data-search/SKILL.md +243 -0
  25. package/skills/datarc-data-search/scripts/calculate.py +116 -0
  26. package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
  27. package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
  28. package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
  29. package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  30. package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  31. package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  32. package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  33. package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  34. package/skills/datarc-dataseek-search/SKILL.md +96 -0
  35. package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  36. package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  37. package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  38. package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  39. package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  40. package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  41. package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  42. package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  43. package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  44. package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  45. package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  46. package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  47. package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
  48. package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  49. package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  50. package/skills/datarc-datasource/SKILL.md +97 -0
  51. package/skills/datarc-oauth/SKILL.md +47 -0
  52. package/skills/datarc-oauth/scripts/auth.mjs +130 -0
  53. package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
  54. package/skills/datarc-report-add-card/SKILL.md +90 -0
  55. package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
  56. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  57. package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
  58. package/skills/datarc-semantic-alias/SKILL.md +20 -0
  59. package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  60. package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
  61. package/skills/datarc-semantic-calibration/SKILL.md +20 -0
  62. package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  63. package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  64. package/skills/datarc-semantic-core/SKILL.md +12 -0
  65. package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
  66. package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
  67. package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
  68. package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
  69. package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  70. package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  71. package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
  72. package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  73. package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  74. package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  75. package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
  76. package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
  77. package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
  78. package/skills/datarc-semantic-dataset/SKILL.md +20 -0
  79. package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  80. package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  81. package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  82. package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
  83. package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  84. package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  85. package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  86. package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  87. package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  88. package/skills/datarc-semantic-prompt/SKILL.md +20 -0
  89. package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
  90. package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  91. package/skills/datarc-semantic-synonym/SKILL.md +20 -0
  92. package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  93. package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  94. package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
  95. package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  96. package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  97. package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  98. package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  99. package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  100. package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
  101. package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  102. package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  103. package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  104. package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  105. package/skills/datarc-workspace-configuration/SKILL.md +59 -0
  106. package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
  107. package/skills/datarc-workspace-configuration/references/verification.md +20 -0
  108. package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
  109. package/skills/datarc-workspace-context/SKILL.md +43 -0
  110. package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
  111. package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  112. package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
  113. package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  114. package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
  115. package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  116. package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  117. package/skills/datarc-workspace-keywords/SKILL.md +197 -0
  118. package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
  119. package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
  120. package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
  121. package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  122. package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  123. package/skills/datarc-workspace-membership/SKILL.md +29 -0
  124. package/skills/datarc-workspace-membership/references/api.md +19 -0
  125. package/skills/datarc-workspace-modeling/SKILL.md +209 -0
  126. package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
  127. package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
  128. package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
  129. package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
  130. package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  131. package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  132. package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  133. package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  134. package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  135. package/skills-index.json +194 -0
@@ -0,0 +1,2225 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic helpers for the datarc analysis-report agent loop.
3
+
4
+ This module deliberately performs no network calls. The agent owns authenticated
5
+ API calls; these helpers lock down card request payloads, structured drill extraction,
6
+ loop budgets, task polling, report assembly, and round-trip verification.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import copy
13
+ import hashlib
14
+ import json
15
+ import locale
16
+ import os
17
+ import re
18
+ import string
19
+ import sys
20
+ import time
21
+ from collections.abc import Callable, Collection, Iterable, Sequence
22
+ from pathlib import Path
23
+ from typing import Any
24
+ from urllib.parse import parse_qsl, unquote, urlsplit
25
+
26
+ QUERY_DATA_TASK_TYPE = 8
27
+ AUTO_INSIGHTS_TASK_TYPE = 11
28
+ MAX_ROUNDS = 3
29
+ MAX_DATA_CARDS = 24
30
+ MAX_QUESTIONS_PER_ROUND = 8
31
+ MAX_BRANCHES_PER_ROUND = MAX_QUESTIONS_PER_ROUND
32
+ MAX_MODELS_PER_QUESTION = 16
33
+ MAX_MODEL_UID_CHARS = 128
34
+ MAX_QUESTION_CHARS = 4_000
35
+ MAX_JSON_INPUT_BYTES = 4 * 1024 * 1024
36
+ MAX_REPORT_JSON_INPUT_BYTES = 50 * 1024 * 1024
37
+ MIN_CARDS_PER_ANALYSIS_CHAPTER = 2
38
+ DATASEEK_MESSAGE_TIMEOUT_SECONDS = 300.0
39
+ NUMERIC_CARD_HEIGHT = 6
40
+ DEFAULT_CARD_HEIGHT = 12
41
+ CONTRIBUTION_CARD_HEIGHT = 9
42
+ INTERPRETATION_CARD_HEIGHT = 12
43
+ INTERPRETATION_CARD_TYPES = frozenset({1, 3, 7, 12})
44
+ INTERPRETATION_PROMPT_VARIABLES = frozenset(
45
+ {"question", "summary", "workspace_knowledge", "today", "anchor_date", "workspace_name", "workspace_desc", "language"}
46
+ )
47
+ SUPPORTED_OUTPUT_LANGUAGES = frozenset({"zh-CN", "en-US"})
48
+ SUPPORTED_COMPARISON_TYPES = frozenset({"yoy", "ring"})
49
+ SUPPORTED_ANALYSIS_MODES = frozenset(
50
+ {
51
+ "level",
52
+ "trend",
53
+ "comparison",
54
+ "breakdown",
55
+ "validation",
56
+ "contribution",
57
+ "distribution",
58
+ "secondary-axis",
59
+ "anomaly",
60
+ "ranking",
61
+ "concentration",
62
+ "pareto",
63
+ }
64
+ )
65
+ SUPPORTED_TIME_GRAINS = frozenset({"second", "minute", "hour", "day", "week", "month", "quarter", "year"})
66
+ QUESTION_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
67
+ QUESTION_TOKEN_ALLOWED_KEYS = frozenset({"word", "prop", "lock", "start", "end"})
68
+ SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
69
+ SUPPORTED_QUESTION_ROLES = frozenset(
70
+ {
71
+ "LEVEL",
72
+ "TREND",
73
+ "TREND_COMPARE",
74
+ "BREAKDOWN",
75
+ "VALIDATE",
76
+ "CONTRIBUTION",
77
+ "DISTRIBUTION",
78
+ "SECONDARY_AXIS",
79
+ }
80
+ )
81
+ EVIDENCE_ROLES = frozenset({"primary", "comparator", "diagnostic", "validation"})
82
+ SECTION_ROLES = frozenset({"summary", "analysis", "conclusion", "context"})
83
+ COVERAGE_STATUSES = frozenset({"complete", "degraded"})
84
+
85
+ _INSIGHT_PRIORITY = {
86
+ "breakout": 0,
87
+ "ringOutlier": 1,
88
+ "outlier": 2,
89
+ "maximum": 3,
90
+ "minimum": 4,
91
+ }
92
+ _SENSITIVE_LINK_KEYS = {
93
+ "accesskey",
94
+ "accesstoken",
95
+ "apikey",
96
+ "auth",
97
+ "authdata",
98
+ "authorization",
99
+ "credential",
100
+ "jwt",
101
+ "key",
102
+ "password",
103
+ "secret",
104
+ "sig",
105
+ "signature",
106
+ "token",
107
+ }
108
+ _SIGNED_LINK_KEY_PREFIXES = ("xamz", "xgoog")
109
+ _SIGNED_LINK_KEY_SUFFIXES = ("credential", "signature", "securitytoken")
110
+ _JWT_PATTERN = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+")
111
+ _PINBOARD_UID_PATTERN = re.compile(r"[0-9a-fA-F]{32}")
112
+ _CJK_PATTERN = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]")
113
+ _RAW_URL_PATTERN = re.compile(r"(?i)(?:https?://|(?<![A-Za-z0-9_])www\.)\S+")
114
+ _MEASURE_PROP_PATTERN = re.compile(r"m[1-9]\d*")
115
+ _DIMENSION_PROP_PATTERN = re.compile(r"d[1-9]\d*")
116
+ _TIME_DIMENSION_PROP_PATTERN = re.compile(r"t(?:0|[1-9]\d*)")
117
+ _DATASET_PROP_PATTERN = re.compile(r"ds[1-9]\d*")
118
+ _FIELD_LIKE_PROP_PATTERN = re.compile(r"(?:ds|[mdt])\d")
119
+ _EMPTY_WORD_CONTROL_PROPS = frozenset({"proportion_zai"})
120
+
121
+
122
+ class ReportContractError(ValueError):
123
+ """Raised when a payload would violate an analysis-report contract."""
124
+
125
+
126
+ class TaskTimeout(TimeoutError):
127
+ """Raised after bounded polling of one existing task UID."""
128
+
129
+
130
+ class TaskFailed(RuntimeError):
131
+ """Raised when an async task reaches a terminal non-success state."""
132
+
133
+
134
+ class DataSeekTimeout(TimeoutError):
135
+ """Raised when one DataSeek message does not finish within its elapsed-time budget."""
136
+
137
+
138
+ class DataSeekFailed(RuntimeError):
139
+ """Raised when DataSeek reaches an explicit error or a terminal result without answer tokens."""
140
+
141
+
142
+ def resolve_output_language(login_context: dict[str, Any] | str) -> str:
143
+ """Resolve the output language without an explicit user selection.
144
+
145
+ Prefer the persisted frontend login language when present; otherwise fall back
146
+ to the platform/browser system language (no user prompt). Only an explicit
147
+ unsupported login language is rejected.
148
+ """
149
+ if isinstance(login_context, dict):
150
+ data = login_context
151
+ elif isinstance(login_context, str) and login_context:
152
+ try:
153
+ data = json.loads(unquote(login_context))
154
+ except (TypeError, ValueError, json.JSONDecodeError) as exc:
155
+ raise ReportContractError("login context must be a JSON object") from exc
156
+ else:
157
+ data = None
158
+ if not isinstance(data, dict) or not data.get("language"):
159
+ # No login language available: use the platform/system language directly.
160
+ return detect_system_language()
161
+ return _validate_output_language(data.get("language"))
162
+
163
+
164
+ def detect_system_language() -> str:
165
+ """Return the current system language mapped to zh-CN or en-US.
166
+
167
+ Uses the portable OS locale (env locale vars then Python's locale module).
168
+ Never prompts the user and never guesses from the question text.
169
+ """
170
+ for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
171
+ value = (os.environ.get(var) or "").strip().lower().split(".")[0]
172
+ if value.startswith("zh"):
173
+ return "zh-CN"
174
+ try:
175
+ code, _ = locale.getlocale()
176
+ if code and code.lower().split(".")[0].startswith("zh"):
177
+ return "zh-CN"
178
+ except (ValueError, TypeError):
179
+ pass
180
+ return "en-US"
181
+
182
+
183
+ def build_locale_headers(language: str) -> dict[str, str]:
184
+ """Build the non-secret locale header shared by every internal API call."""
185
+ return {"Accept-Language": _validate_output_language(language)}
186
+
187
+
188
+ def rank_workspace_candidates(
189
+ projects: Sequence[dict[str, Any]],
190
+ query: str,
191
+ *,
192
+ current_project_id: int | None = None,
193
+ limit: int = 5,
194
+ ) -> list[dict[str, Any]]:
195
+ """Rank accessible workspace candidates without inventing unavailable metadata."""
196
+ if not isinstance(projects, (list, tuple)) or not isinstance(query, str) or not query.strip() or limit < 1:
197
+ raise ReportContractError("workspace ranking requires projects, a query, and a positive limit")
198
+ normalized_query = query.casefold().strip()
199
+ query_terms = _workspace_query_terms(normalized_query)
200
+ ranked: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
201
+ for ordinal, project in enumerate(projects):
202
+ if not isinstance(project, dict):
203
+ continue
204
+ project_id = project.get("id")
205
+ name = project.get("name")
206
+ if isinstance(project_id, bool) or not isinstance(project_id, int) or not isinstance(name, str) or not name.strip():
207
+ continue
208
+ normalized_name = name.casefold().strip()
209
+ normalized_desc = project.get("desc", "")
210
+ normalized_desc = normalized_desc.casefold() if isinstance(normalized_desc, str) else ""
211
+ name_hits = sum(term in normalized_name for term in query_terms)
212
+ desc_hits = sum(term in normalized_desc for term in query_terms)
213
+ score = (
214
+ int(normalized_query == str(project_id)),
215
+ int(normalized_query == normalized_name),
216
+ int(normalized_query in normalized_name),
217
+ name_hits,
218
+ desc_hits,
219
+ int(project_id == current_project_id),
220
+ str(project.get("updated_at") or project.get("updatedAt") or ""),
221
+ -ordinal,
222
+ )
223
+ ranked.append((score, copy.deepcopy(project)))
224
+ ranked.sort(key=lambda item: item[0], reverse=True)
225
+ return [project for _, project in ranked[:limit]]
226
+
227
+
228
+ def build_sop_search_payload(
229
+ query: str,
230
+ sop_ids: Sequence[int],
231
+ *,
232
+ n_results: int = 5,
233
+ max_distance: float | None = None,
234
+ ) -> dict[str, Any]:
235
+ """Build the workspace SOP semantic-search payload used before planning."""
236
+ if not isinstance(query, str) or not query.strip():
237
+ raise ReportContractError("SOP query must be non-empty")
238
+ if (
239
+ not isinstance(sop_ids, (list, tuple))
240
+ or not sop_ids
241
+ or not all(isinstance(sop_id, int) and not isinstance(sop_id, bool) and sop_id > 0 for sop_id in sop_ids)
242
+ or len(sop_ids) != len(set(sop_ids))
243
+ ):
244
+ raise ReportContractError("SOP ids must be unique positive integers")
245
+ if isinstance(n_results, bool) or not isinstance(n_results, int) or n_results < 1:
246
+ raise ReportContractError("SOP n_results must be a positive integer")
247
+ payload: dict[str, Any] = {"query": query.strip(), "sop_ids": list(sop_ids), "n_results": n_results}
248
+ if max_distance is not None:
249
+ if isinstance(max_distance, bool) or not isinstance(max_distance, (int, float)) or not 0 <= max_distance <= 1:
250
+ raise ReportContractError("SOP max_distance must be between 0 and 1")
251
+ payload["max_distance"] = max_distance
252
+ return payload
253
+
254
+
255
+ def rank_sop_candidates(sops: Sequence[dict[str, Any]], chunks: Sequence[dict[str, Any]], *, limit: int = 3) -> list[dict[str, Any]]:
256
+ """Aggregate semantic chunks into stable SOP candidates for user confirmation."""
257
+ if not isinstance(sops, (list, tuple)) or not isinstance(chunks, (list, tuple)) or limit < 1:
258
+ raise ReportContractError("SOP ranking requires lists and a positive limit")
259
+ sop_by_id = {
260
+ sop["id"]: sop
261
+ for sop in sops
262
+ if isinstance(sop, dict)
263
+ and isinstance(sop.get("id"), int)
264
+ and not isinstance(sop.get("id"), bool)
265
+ and isinstance(sop.get("name"), str)
266
+ and sop["name"].strip()
267
+ }
268
+ stats: dict[int, dict[str, Any]] = {}
269
+ for ordinal, chunk in enumerate(chunks):
270
+ metadata = chunk.get("metadata") if isinstance(chunk, dict) else None
271
+ sop_id = metadata.get("sop_id") if isinstance(metadata, dict) else None
272
+ if sop_id not in sop_by_id:
273
+ continue
274
+ distance = chunk.get("distance")
275
+ numeric_distance = float(distance) if isinstance(distance, (int, float)) and not isinstance(distance, bool) else None
276
+ document = chunk.get("document")
277
+ entry = stats.setdefault(
278
+ sop_id,
279
+ {"hitCount": 0, "bestDistance": None, "firstOrdinal": ordinal, "topExcerpt": ""},
280
+ )
281
+ entry["hitCount"] += 1
282
+ if numeric_distance is not None and (entry["bestDistance"] is None or numeric_distance < entry["bestDistance"]):
283
+ entry["bestDistance"] = numeric_distance
284
+ if not entry["topExcerpt"] and isinstance(document, str):
285
+ entry["topExcerpt"] = document.strip()[:200]
286
+ ranked_ids = sorted(
287
+ stats,
288
+ key=lambda sop_id: (
289
+ -stats[sop_id]["hitCount"],
290
+ stats[sop_id]["bestDistance"] if stats[sop_id]["bestDistance"] is not None else float("inf"),
291
+ stats[sop_id]["firstOrdinal"],
292
+ ),
293
+ )
294
+ result: list[dict[str, Any]] = []
295
+ for sop_id in ranked_ids[:limit]:
296
+ candidate = copy.deepcopy(sop_by_id[sop_id])
297
+ candidate.update({key: value for key, value in stats[sop_id].items() if key != "firstOrdinal"})
298
+ result.append(candidate)
299
+ return result
300
+
301
+
302
+ def build_dataseek_message_payload(project_id: int, message: str) -> dict[str, Any]:
303
+ """Build the message payload used by the report-only DataSeek thread."""
304
+ if isinstance(project_id, bool) or not isinstance(project_id, int) or project_id <= 0:
305
+ raise ReportContractError("project_id must be a positive integer")
306
+ if not isinstance(message, str) or not message.strip():
307
+ raise ReportContractError("DataSeek message must be non-empty")
308
+ return {"project_id": project_id, "message": message.strip()}
309
+
310
+
311
+ def poll_dataseek_message(
312
+ fetch_message: Callable[[str, int], dict[str, Any]],
313
+ thread_uid: str,
314
+ message_id: int,
315
+ *,
316
+ timeout: float = DATASEEK_MESSAGE_TIMEOUT_SECONDS,
317
+ interval: float = 1.0,
318
+ monotonic: Callable[[], float] = time.monotonic,
319
+ wait: Callable[[float], None] = time.sleep,
320
+ ) -> list[dict[str, Any]]:
321
+ """Poll one DataSeek message by elapsed time and return its first answer question."""
322
+ if (
323
+ not isinstance(thread_uid, str)
324
+ or not thread_uid
325
+ or isinstance(message_id, bool)
326
+ or not isinstance(message_id, int)
327
+ or message_id <= 0
328
+ or isinstance(timeout, bool)
329
+ or not isinstance(timeout, (int, float))
330
+ or timeout <= 0
331
+ or isinstance(interval, bool)
332
+ or not isinstance(interval, (int, float))
333
+ or interval <= 0
334
+ ):
335
+ raise ReportContractError("invalid DataSeek polling arguments")
336
+ started_at = monotonic()
337
+ while True:
338
+ response = fetch_message(thread_uid, message_id)
339
+ message = _unwrap_api_data(response)
340
+ current = message.get("current") if isinstance(message, dict) else None
341
+ if not isinstance(current, dict):
342
+ raise DataSeekFailed("DataSeek returned an invalid message")
343
+ if current.get("error"):
344
+ raise DataSeekFailed("DataSeek returned an explicit error")
345
+ result = current.get("result")
346
+ if isinstance(result, list) and result:
347
+ for item in result:
348
+ data = item.get("data") if isinstance(item, dict) and item.get("type") == "answer" else None
349
+ questions = data.get("questions") if isinstance(data, dict) else None
350
+ tokens = questions[0] if isinstance(questions, list) and questions else None
351
+ if isinstance(tokens, list) and tokens:
352
+ normalized_tokens = normalize_question_tokens(tokens)
353
+ _card_question_text(normalized_tokens)
354
+ return normalized_tokens
355
+ raise DataSeekFailed("DataSeek reached a terminal result without answer tokens")
356
+ elapsed = monotonic() - started_at
357
+ if elapsed >= timeout:
358
+ raise DataSeekTimeout(f"DataSeek message exceeded {timeout:g} seconds")
359
+ wait(min(interval, timeout - elapsed))
360
+
361
+
362
+ def plan_digest(plan: dict[str, Any]) -> str:
363
+ """Fingerprint the exact Plan version shown to the user."""
364
+ if not isinstance(plan, dict) or not plan:
365
+ raise ReportContractError("plan must be a non-empty object")
366
+ encoded = json.dumps(plan, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
367
+ return hashlib.sha256(encoded.encode()).hexdigest()
368
+
369
+
370
+ def require_plan_approval(plan: dict[str, Any], approved_digest: str | None) -> str:
371
+ """Reject execution when approval belongs to a missing or stale Plan version."""
372
+ current_digest = plan_digest(plan)
373
+ if approved_digest != current_digest:
374
+ raise ReportContractError("the current Plan has not been approved")
375
+ return current_digest
376
+
377
+
378
+ def validate_execution_plan(plan: Any) -> dict[str, Any]:
379
+ """Validate and normalize the machine-readable contract inside an approved Plan."""
380
+ if not isinstance(plan, dict) or not plan:
381
+ raise ReportContractError("approved Plan must be a non-empty object")
382
+ chapter_evidence_plan = validate_chapter_evidence_plan(plan)
383
+ execution = plan.get("executionContract")
384
+ required = {
385
+ "schemaVersion",
386
+ "projectId",
387
+ "language",
388
+ "scope",
389
+ "initialQuestions",
390
+ "maxRounds",
391
+ "maxQuestionsPerRound",
392
+ "maxDataCards",
393
+ }
394
+ if not isinstance(execution, dict) or set(execution) != required or execution["schemaVersion"] != 2:
395
+ raise ReportContractError("approved Plan must contain the exact executionContract")
396
+ project_id = execution["projectId"]
397
+ if isinstance(project_id, bool) or not isinstance(project_id, int) or project_id <= 0:
398
+ raise ReportContractError("executionContract projectId must be a positive integer")
399
+ if execution["language"] not in SUPPORTED_OUTPUT_LANGUAGES:
400
+ raise ReportContractError("executionContract language must be zh-CN or en-US")
401
+ _validate_analysis_scope(execution["scope"])
402
+ max_rounds = execution["maxRounds"]
403
+ if isinstance(max_rounds, bool) or not isinstance(max_rounds, int) or not 2 <= max_rounds <= MAX_ROUNDS:
404
+ raise ReportContractError(f"executionContract maxRounds must be between 2 and {MAX_ROUNDS}")
405
+ max_questions = execution["maxQuestionsPerRound"]
406
+ if isinstance(max_questions, bool) or not isinstance(max_questions, int) or not 1 <= max_questions <= MAX_QUESTIONS_PER_ROUND:
407
+ raise ReportContractError(f"executionContract maxQuestionsPerRound must be between 1 and {MAX_QUESTIONS_PER_ROUND}")
408
+ if execution["maxDataCards"] != MAX_DATA_CARDS:
409
+ raise ReportContractError(f"executionContract maxDataCards must be {MAX_DATA_CARDS}")
410
+ questions = execution["initialQuestions"]
411
+ if not isinstance(questions, list) or not 1 <= len(questions) <= max_questions:
412
+ raise ReportContractError(f"executionContract initialQuestions must contain one to {max_questions} items")
413
+
414
+ validated = copy.deepcopy(execution)
415
+ seen_ids: set[str] = set()
416
+ seen_signatures: set[tuple[str, tuple[str, ...]]] = set()
417
+ required_question_keys = {
418
+ "id",
419
+ "round",
420
+ "role",
421
+ "question",
422
+ "normalizedTokens",
423
+ "requestTuids",
424
+ "chapterKey",
425
+ "evidenceRole",
426
+ "purpose",
427
+ "expectedEvidence",
428
+ "parentEvidenceRefs",
429
+ }
430
+ for question in validated["initialQuestions"]:
431
+ if not isinstance(question, dict) or set(question) != required_question_keys:
432
+ raise ReportContractError("initialQuestions must use the complete Plan question contract")
433
+ question_id = question["id"]
434
+ if (
435
+ not isinstance(question_id, str)
436
+ or not QUESTION_ID_PATTERN.fullmatch(question_id)
437
+ or not question_id.startswith("r1-")
438
+ or question_id in seen_ids
439
+ ):
440
+ raise ReportContractError("initial question ids must be unique safe r1- identifiers")
441
+ if question["round"] != 1 or question["normalizedTokens"] is not None or question["parentEvidenceRefs"] != []:
442
+ raise ReportContractError("initial Plan questions must be round 1 with null tokens and no parent evidence")
443
+ if not isinstance(question["role"], str) or question["role"] not in SUPPORTED_QUESTION_ROLES:
444
+ raise ReportContractError("initial Plan question role is invalid")
445
+ value = question["question"]
446
+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > MAX_QUESTION_CHARS:
447
+ raise ReportContractError(f"initial question must be non-empty and at most {MAX_QUESTION_CHARS} characters")
448
+ question["question"] = value.strip()
449
+ request_tuids = question["requestTuids"]
450
+ if request_tuids != []:
451
+ raise ReportContractError("initial question requestTuids must be an empty list for automatic model matching")
452
+ if not isinstance(question["chapterKey"], str) or question["chapterKey"] not in chapter_evidence_plan:
453
+ raise ReportContractError("initial Plan question chapterKey must reference chapterEvidencePlan")
454
+ if not isinstance(question["evidenceRole"], str) or question["evidenceRole"] not in EVIDENCE_ROLES:
455
+ raise ReportContractError("initial Plan question evidenceRole is invalid")
456
+ for field in ("purpose", "expectedEvidence"):
457
+ if not isinstance(question[field], str) or not question[field].strip():
458
+ raise ReportContractError(f"initial Plan question {field} must be non-empty")
459
+ signature = (question["question"], tuple(request_tuids))
460
+ if signature in seen_signatures:
461
+ raise ReportContractError("initial Plan questions must be unique")
462
+ seen_ids.add(question_id)
463
+ seen_signatures.add(signature)
464
+ return validated
465
+
466
+
467
+ def project_execution_questions(execution: dict[str, Any]) -> list[dict[str, Any]]:
468
+ """Project approved initial questions onto the exact Runner batch contract."""
469
+ return [{key: copy.deepcopy(question[key]) for key in ("id", "question", "requestTuids")} for question in execution["initialQuestions"]]
470
+
471
+
472
+ def validate_chapter_evidence_plan(plan: Any) -> dict[str, dict[str, Any]]:
473
+ """Validate the user-approved evidence bundle for every analysis chapter."""
474
+ if not isinstance(plan, dict):
475
+ raise ReportContractError("approved Plan must be an object")
476
+ items = plan.get("chapterEvidencePlan")
477
+ if not isinstance(items, list) or not items:
478
+ raise ReportContractError("approved Plan must contain a non-empty chapterEvidencePlan")
479
+ required = {
480
+ "chapterKey",
481
+ "decisionQuestion",
482
+ "requiredEvidenceRoles",
483
+ "minCards",
484
+ "targetCards",
485
+ "fallback",
486
+ }
487
+ validated: dict[str, dict[str, Any]] = {}
488
+ for item in items:
489
+ if not isinstance(item, dict) or set(item) != required:
490
+ raise ReportContractError("chapterEvidencePlan entries must use the exact evidence bundle contract")
491
+ chapter_key = item["chapterKey"]
492
+ if not isinstance(chapter_key, str) or not chapter_key or chapter_key in validated:
493
+ raise ReportContractError("chapterEvidencePlan chapterKey values must be non-empty and unique")
494
+ if not isinstance(item["decisionQuestion"], str) or not item["decisionQuestion"].strip():
495
+ raise ReportContractError("chapterEvidencePlan decisionQuestion must be non-empty")
496
+ roles = item["requiredEvidenceRoles"]
497
+ if (
498
+ not isinstance(roles, list)
499
+ or not 2 <= len(roles) <= len(EVIDENCE_ROLES)
500
+ or len(roles) != len(set(roles))
501
+ or not set(roles).issubset(EVIDENCE_ROLES)
502
+ ):
503
+ raise ReportContractError("chapterEvidencePlan requires two to four unique evidence roles")
504
+ if item["minCards"] != MIN_CARDS_PER_ANALYSIS_CHAPTER:
505
+ raise ReportContractError(f"chapterEvidencePlan minCards must be {MIN_CARDS_PER_ANALYSIS_CHAPTER}")
506
+ target_cards = item["targetCards"]
507
+ if isinstance(target_cards, bool) or not isinstance(target_cards, int) or not 3 <= target_cards <= 6 or target_cards < len(roles):
508
+ raise ReportContractError("chapterEvidencePlan targetCards must be between 3 and 6 and cover every role")
509
+ if item["fallback"] != "degrade-with-limitation":
510
+ raise ReportContractError("chapterEvidencePlan fallback must be degrade-with-limitation")
511
+ validated[chapter_key] = copy.deepcopy(item)
512
+ if sum(item["targetCards"] for item in validated.values()) > MAX_DATA_CARDS:
513
+ raise ReportContractError(f"chapterEvidencePlan targetCards total must not exceed the {MAX_DATA_CARDS}-card report budget")
514
+ return validated
515
+
516
+
517
+ def build_card_payload(question: str | Sequence[dict[str, Any]]) -> dict[str, Any]:
518
+ """Build the single-card payload used by the frontend AI-report flow.
519
+
520
+ Like the frontend SingleCard flow, the server always auto-matches models
521
+ from the question. Restricting the request can fail with 10406
522
+ CARD_NOT_MATCHED_MODEL when a selected model lacks part of the fields.
523
+ """
524
+ card_question: str | list[dict[str, Any]]
525
+ if isinstance(question, str):
526
+ card_question = _card_question_text(question)
527
+ else:
528
+ card_question = normalize_question_tokens(question)
529
+ return {"question": card_question, "params": {"tuids": []}}
530
+
531
+
532
+ def normalize_question_tokens(tokens: Any) -> list[dict[str, Any]]:
533
+ """Project DataSeek tokens onto the safe TokenASiri fields used by report cards."""
534
+ if not isinstance(tokens, (list, tuple)) or not tokens:
535
+ raise ReportContractError("question tokens must be a non-empty list")
536
+ normalized: list[dict[str, Any]] = []
537
+ for token in tokens:
538
+ if (
539
+ not isinstance(token, dict)
540
+ or not isinstance(token.get("prop"), str)
541
+ or not token["prop"]
542
+ or not isinstance(token.get("word"), str)
543
+ or (not token["word"] and token["prop"] not in _EMPTY_WORD_CONTROL_PROPS)
544
+ ):
545
+ raise ReportContractError(
546
+ "question tokens must contain string words and non-empty props; "
547
+ "only approved backend-synthesized control tokens may have an empty word"
548
+ )
549
+ extra_keys = set(token) - QUESTION_TOKEN_ALLOWED_KEYS
550
+ if extra_keys:
551
+ raise ReportContractError(f"question token contains unsupported fields: {', '.join(sorted(extra_keys))}")
552
+ if "lock" in token and not isinstance(token["lock"], bool):
553
+ raise ReportContractError("question token lock must be boolean")
554
+ if any(key in token and (not isinstance(token[key], str) or not token[key] or len(token[key]) > 64) for key in ("start", "end")):
555
+ raise ReportContractError("question token start and end must be non-empty strings of at most 64 characters")
556
+ if ("start" in token) != ("end" in token):
557
+ raise ReportContractError("question token start and end must appear together")
558
+ normalized.append({key: copy.deepcopy(value) for key, value in token.items() if key in QUESTION_TOKEN_ALLOWED_KEYS})
559
+ return normalized
560
+
561
+
562
+ def validate_normalized_tokens_in_scope(
563
+ tokens: Sequence[dict[str, Any]],
564
+ scope: dict[str, Any],
565
+ context: str = "question tokens",
566
+ ) -> None:
567
+ """Validate card-producing parser tokens against one approved field scope."""
568
+ _validate_question_tokens(tokens, context)
569
+ measure_props, dimension_props, time_dimensions = _validate_analysis_scope(scope)
570
+ _validate_tokens_in_analysis_scope(
571
+ tokens,
572
+ measure_props,
573
+ dimension_props,
574
+ time_dimensions,
575
+ context,
576
+ reject_multiple_time_dimensions=True,
577
+ )
578
+
579
+
580
+ def build_auto_insights_payload(card: dict[str, Any]) -> dict[str, Any]:
581
+ """Build the taskType=11 payload from one eligible card without guessing."""
582
+ if not isinstance(card, dict) or not (card.get("configs") or {}).get("hasAutoInsights"):
583
+ raise ReportContractError("card does not support local AutoInsights")
584
+ units = _validated_units(card.get("units"))
585
+ data = card.get("data")
586
+ if not isinstance(data, list) or not data or not isinstance(data[0], dict):
587
+ raise ReportContractError("card has no query data")
588
+ query = data[0].get("data")
589
+ q_key = query.get("qKey") if isinstance(query, dict) else None
590
+ if not isinstance(q_key, str) or not q_key:
591
+ raise ReportContractError("card has no qKey for local AutoInsights")
592
+ tuids = card.get("tuids")
593
+ if tuids is not None and not isinstance(tuids, list):
594
+ raise ReportContractError("card tuids must be a list or null")
595
+ return {
596
+ "taskType": AUTO_INSIGHTS_TASK_TYPE,
597
+ "params": {
598
+ "units": units,
599
+ "tuids": copy.deepcopy(tuids),
600
+ "qKey": q_key,
601
+ },
602
+ }
603
+
604
+
605
+ def flatten_units(units: Sequence[dict[str, Any]]) -> list[dict[str, str]]:
606
+ """Flatten exact structured units into the token shape accepted by ask/card."""
607
+ validated = _validated_units(units)
608
+ return [copy.deepcopy(token) for unit in validated for token in unit["tokens"]]
609
+
610
+
611
+ def drill_signature(evidence_units: Sequence[dict[str, Any]], comparison_type: Any) -> str:
612
+ canonical = json.dumps(
613
+ {"evidenceUnits": evidence_units, "comparisonType": comparison_type},
614
+ ensure_ascii=False,
615
+ sort_keys=True,
616
+ separators=(",", ":"),
617
+ )
618
+ return hashlib.sha256(canonical.encode()).hexdigest()
619
+
620
+
621
+ def extract_drill_candidates(insights: Any, limit: int = MAX_BRANCHES_PER_ROUND) -> list[dict[str, Any]]:
622
+ """Extract exact `anomalies/attribution.units`; never infer from display labels."""
623
+ if limit < 1:
624
+ raise ReportContractError("candidate limit must be positive")
625
+ if isinstance(insights, dict) and isinstance(insights.get("data"), list):
626
+ insights = insights["data"]
627
+ if not isinstance(insights, list):
628
+ return []
629
+
630
+ found: list[tuple[int, int, dict[str, Any]]] = []
631
+ ordinal = 0
632
+ for insight in insights:
633
+ if not isinstance(insight, dict):
634
+ continue
635
+ insight_type = insight.get("type")
636
+ if not isinstance(insight_type, str):
637
+ continue
638
+
639
+ for source, package in _walk_drill_packages(insight.get("data")):
640
+ try:
641
+ units = _validated_units(package.get("units"))
642
+ except ReportContractError:
643
+ continue
644
+ comparison_type = package.get("comparisonType")
645
+ if comparison_type not in SUPPORTED_COMPARISON_TYPES:
646
+ continue
647
+ evidence_units = _evidence_units(units)
648
+ signature = drill_signature(evidence_units, comparison_type)
649
+ candidate = {
650
+ "insightType": insight_type,
651
+ "source": source,
652
+ "units": units,
653
+ "evidenceUnits": evidence_units,
654
+ "comparisonType": comparison_type,
655
+ "signature": signature,
656
+ }
657
+ found.append((_INSIGHT_PRIORITY.get(insight_type, 100), ordinal, candidate))
658
+ ordinal += 1
659
+
660
+ candidates: list[dict[str, Any]] = []
661
+ seen: set[str] = set()
662
+ for _, _, candidate in sorted(found, key=lambda item: (item[0], item[1])):
663
+ if candidate["signature"] in seen:
664
+ continue
665
+ seen.add(candidate["signature"])
666
+ candidates.append(candidate)
667
+ if len(candidates) == limit:
668
+ break
669
+ return candidates
670
+
671
+
672
+ def select_evidence_cards(
673
+ cards: Sequence[dict[str, Any]],
674
+ *,
675
+ current_card_count: int,
676
+ seen_signatures: set[str],
677
+ ) -> dict[str, Any]:
678
+ """Select actual returned cards without crossing the report evidence budget."""
679
+ if current_card_count < 0 or current_card_count > MAX_DATA_CARDS:
680
+ raise ReportContractError(f"current_card_count must be between 0 and {MAX_DATA_CARDS}")
681
+ if not isinstance(cards, (list, tuple)):
682
+ raise ReportContractError("cards must be a sequence")
683
+ remaining = MAX_DATA_CARDS - current_card_count
684
+ selected: list[dict[str, Any]] = []
685
+ signatures: list[str] = []
686
+ dropped: list[dict[str, str]] = []
687
+ seen = set(seen_signatures)
688
+ for card in cards:
689
+ if not isinstance(card, dict):
690
+ raise ReportContractError("every returned card must be an object")
691
+ signature = _evidence_card_signature(card)
692
+ if signature in seen:
693
+ dropped.append({"signature": signature, "reason": "duplicate"})
694
+ continue
695
+ if len(selected) >= remaining:
696
+ dropped.append({"signature": signature, "reason": "card-budget"})
697
+ continue
698
+ seen.add(signature)
699
+ signatures.append(signature)
700
+ selected.append(copy.deepcopy(card))
701
+ return {
702
+ "cards": selected,
703
+ "signatures": signatures,
704
+ "cardCount": current_card_count + len(selected),
705
+ "droppedCount": len(dropped),
706
+ "dropped": dropped,
707
+ }
708
+
709
+
710
+ def identify_added_card(before_report: dict[str, Any], after_report: dict[str, Any], expected_signature: dict[str, Any]) -> dict[str, Any]:
711
+ """Identify one card pin by the exact content-ID delta around a single add call."""
712
+ before_content = before_report.get("content") if isinstance(before_report, dict) else None
713
+ after_content = after_report.get("content") if isinstance(after_report, dict) else None
714
+ if not isinstance(before_content, list) or not isinstance(after_content, list):
715
+ raise ReportContractError("before and after reports must contain content lists")
716
+ before_by_id = _content_by_id(before_content)
717
+ after_by_id = _content_by_id(after_content)
718
+ if not set(before_by_id).issubset(after_by_id):
719
+ raise ReportContractError("single-card add removed an existing pin")
720
+ added_ids = set(after_by_id) - set(before_by_id)
721
+ if len(added_ids) != 1:
722
+ raise ReportContractError("single-card add must create exactly one new pin")
723
+ pin_id = next(iter(added_ids))
724
+ pin = after_by_id[pin_id]
725
+ if pin.get("type") != 2:
726
+ raise ReportContractError("single-card add did not create a card pin")
727
+ _validate_expected_card_signature(expected_signature, pin_id)
728
+ if _card_signature_from_pin(pin) != expected_signature:
729
+ raise ReportContractError("new card pin does not match the expected signature")
730
+ return {"pinId": pin_id, "cardSignature": copy.deepcopy(expected_signature)}
731
+
732
+
733
+ def plan_next_round(
734
+ *,
735
+ completed_round: int,
736
+ card_count: int,
737
+ candidates: Sequence[dict[str, Any]],
738
+ seen_signatures: set[str],
739
+ unresolved_high_value: bool,
740
+ new_analysis_axes: Sequence[str] = (),
741
+ allowed_analysis_axes: Collection[str] = frozenset(),
742
+ used_analysis_axes: Collection[str] = frozenset(),
743
+ ) -> dict[str, Any]:
744
+ """Apply the 2-round default, conditional round 3, and hard budgets."""
745
+ if completed_round < 1:
746
+ raise ReportContractError("completed_round must be at least 1")
747
+ if card_count < 0:
748
+ raise ReportContractError("card_count cannot be negative")
749
+ if completed_round >= MAX_ROUNDS:
750
+ return _stop("round-limit")
751
+ if card_count >= MAX_DATA_CARDS:
752
+ return _stop("card-budget")
753
+ if completed_round == 2 and not unresolved_high_value:
754
+ return _stop("round-2-sufficient")
755
+ axes = list(
756
+ dict.fromkeys(
757
+ item for item in new_analysis_axes if isinstance(item, str) and item and item in allowed_analysis_axes and item not in used_analysis_axes
758
+ )
759
+ )
760
+ if completed_round == 2 and not axes:
761
+ return _stop("no-new-analysis-axis")
762
+
763
+ fresh = [item for item in candidates if isinstance(item.get("signature"), str) and item["signature"] not in seen_signatures]
764
+ if not fresh:
765
+ return _stop("no-new-structured-units")
766
+ remaining_cards = MAX_DATA_CARDS - card_count
767
+ selected = [copy.deepcopy(item) for item in fresh[: min(MAX_BRANCHES_PER_ROUND, remaining_cards)]]
768
+ if not selected:
769
+ return _stop("card-budget")
770
+ return {
771
+ "nextRound": completed_round + 1,
772
+ "candidates": selected,
773
+ "newAnalysisAxes": axes,
774
+ "stopReason": None,
775
+ }
776
+
777
+
778
+ def poll_task(
779
+ fetch_task: Callable[[str], dict[str, Any]],
780
+ task_uid: str,
781
+ *,
782
+ task_type: int,
783
+ max_attempts: int = 30,
784
+ interval: float = 2.0,
785
+ wait: Callable[[float], None] = time.sleep,
786
+ ) -> Any:
787
+ """Poll one task UID. Timeout never creates or retries a POST task."""
788
+ if task_type not in {QUERY_DATA_TASK_TYPE, AUTO_INSIGHTS_TASK_TYPE}:
789
+ raise ReportContractError("task_type must be 8 or 11")
790
+ if not task_uid or max_attempts < 1 or interval < 0:
791
+ raise ReportContractError("invalid polling arguments")
792
+ for attempt in range(max_attempts):
793
+ response = fetch_task(task_uid)
794
+ task = _unwrap_api_data(response)
795
+ if not isinstance(task, dict):
796
+ raise TaskFailed(f"task {task_uid} returned an invalid response")
797
+ status = task.get("status")
798
+ if status == 2:
799
+ result = task.get("result")
800
+ invalid_result = not isinstance(result, dict) or result.get("status") != "SUCCESS" or "data" not in result
801
+ if not invalid_result and task_type == AUTO_INSIGHTS_TASK_TYPE:
802
+ invalid_result = not isinstance(result["data"], list)
803
+ if invalid_result:
804
+ raise TaskFailed(f"task {task_uid} returned a failed or malformed result")
805
+ return copy.deepcopy(result)
806
+ if status in {3, 4, 5}:
807
+ raise TaskFailed(f"task {task_uid} ended with status {status}")
808
+ if status not in {0, 1, None}:
809
+ raise TaskFailed(f"task {task_uid} returned unknown status {status}")
810
+ if attempt + 1 < max_attempts:
811
+ wait(interval)
812
+ raise TaskTimeout(f"task {task_uid} did not finish after {max_attempts} polls")
813
+
814
+
815
+ def build_report_patch(report: dict[str, Any], manifest: dict[str, Any], *, report_origin: str | None = None) -> dict[str, Any]:
816
+ """Merge semantic chapter pins with current cards and rebuild full layouts."""
817
+ report_uid, chapters, allowed_link_origins = _validate_manifest(report, manifest, report_origin)
818
+ current_content = report.get("content") or []
819
+ if not isinstance(current_content, list):
820
+ raise ReportContractError("report content must be a list")
821
+ current_by_id = _content_by_id(current_content)
822
+
823
+ role_ids: dict[str, dict[str, str]] = {}
824
+ generated_ids: set[str] = set()
825
+ for chapter in chapters:
826
+ key = chapter["key"]
827
+ role_ids[key] = {role: _stable_pin_id(report_uid, key, role) for role in ("heading", "purpose", "interpretation")}
828
+ generated_ids.update(role_ids[key].values())
829
+
830
+ claimed_cards: list[str] = []
831
+ for chapter in chapters:
832
+ card_ids = chapter.get("cardIds") or []
833
+ if not isinstance(card_ids, list) or not all(isinstance(item, str) and item for item in card_ids):
834
+ raise ReportContractError("chapter cardIds must be a list of pin ids")
835
+ for card_id in card_ids:
836
+ if card_id in claimed_cards:
837
+ raise ReportContractError(f"card {card_id} is assigned to more than one chapter")
838
+ pin = current_by_id.get(card_id)
839
+ if not pin or pin.get("type") != 2:
840
+ raise ReportContractError(f"chapter references missing card {card_id}")
841
+ claimed_cards.append(card_id)
842
+ if len(claimed_cards) > MAX_DATA_CARDS:
843
+ raise ReportContractError(f"report data-card budget exceeds {MAX_DATA_CARDS}")
844
+ interpretation_pins = _interpretation_pins(manifest, current_by_id)
845
+ generated_ids.update(pin["i"] for pins in interpretation_pins.values() for pin in pins)
846
+ unexpected_pins = set(current_by_id) - generated_ids - set(claimed_cards)
847
+ if unexpected_pins:
848
+ raise ReportContractError("report contains a pin not declared by the manifest")
849
+ _validate_card_signatures(current_by_id, claimed_cards, manifest)
850
+
851
+ content: list[dict[str, Any]] = []
852
+ for chapter in chapters:
853
+ key = chapter["key"]
854
+ ids = role_ids[key]
855
+ title = chapter["title"].strip()
856
+ content.append(_text_pin(ids["heading"], 4, {"ops": [{"insert": f"{title}\n"}]}, allowed_link_origins))
857
+ if purpose := chapter.get("purpose"):
858
+ content.append(_text_pin(ids["purpose"], 3, purpose, allowed_link_origins))
859
+ for card_id in chapter.get("cardIds") or []:
860
+ content.append(copy.deepcopy(current_by_id[card_id]))
861
+ content.extend(interpretation_pins.get(card_id, []))
862
+ if interpretation := chapter.get("interpretation"):
863
+ content.append(_text_pin(ids["interpretation"], 3, interpretation, allowed_link_origins))
864
+
865
+ if sum(pin.get("type") == 2 for pin in content) > MAX_DATA_CARDS:
866
+ raise ReportContractError(f"report contains more than {MAX_DATA_CARDS} data cards")
867
+ for pin in content:
868
+ if pin.get("type") in {3, 4}:
869
+ _validate_delta(pin.get("data"), allowed_link_origins)
870
+
871
+ return {"content": content, "layouts": _build_layouts(content)}
872
+
873
+
874
+ def validate_report(report: dict[str, Any], manifest: dict[str, Any], *, report_origin: str | None = None) -> list[str]:
875
+ """Return structural and security errors found after the final GET."""
876
+ errors: list[str] = []
877
+ try:
878
+ report_uid, chapters, allowed_link_origins = _validate_manifest(report, manifest, report_origin)
879
+ except ReportContractError as exc:
880
+ return [str(exc)]
881
+ content = report.get("content")
882
+ if not isinstance(content, list):
883
+ return ["report content must be a list"]
884
+ ids = [pin.get("i") for pin in content if isinstance(pin, dict)]
885
+ if len(ids) != len(content) or any(not isinstance(item, str) or not item for item in ids):
886
+ errors.append("every content pin must have a non-empty id")
887
+ if len(set(ids)) != len(ids):
888
+ errors.append("content pin ids are not unique")
889
+
890
+ content_by_id: dict[str, dict[str, Any]] = {}
891
+ try:
892
+ content_by_id = _content_by_id(content)
893
+ except ReportContractError as exc:
894
+ errors.append(str(exc))
895
+
896
+ expected: list[tuple[str, int]] = []
897
+ expected_deltas: dict[str, dict[str, Any]] = {}
898
+ interpretation_pins: dict[str, list[dict[str, Any]]] = {}
899
+ try:
900
+ interpretation_pins = _interpretation_pins(manifest, content_by_id)
901
+ except ReportContractError as exc:
902
+ errors.append(str(exc))
903
+ expected_interpretations = {pin["i"]: pin for pins in interpretation_pins.values() for pin in pins}
904
+ claimed_cards: list[str] = []
905
+ for chapter in chapters:
906
+ key = chapter["key"]
907
+ heading_id = _stable_pin_id(report_uid, key, "heading")
908
+ expected.append((heading_id, 4))
909
+ expected_deltas[heading_id] = {"ops": [{"insert": f"{chapter['title'].strip()}\n"}]}
910
+ if chapter.get("purpose"):
911
+ purpose_id = _stable_pin_id(report_uid, key, "purpose")
912
+ expected.append((purpose_id, 3))
913
+ expected_deltas[purpose_id] = chapter["purpose"]
914
+ chapter_card_ids = chapter.get("cardIds") or []
915
+ for card_id in chapter_card_ids:
916
+ expected.append((card_id, 2))
917
+ expected.extend((pin["i"], 5) for pin in interpretation_pins.get(card_id, []))
918
+ claimed_cards.extend(chapter_card_ids)
919
+ if chapter.get("interpretation"):
920
+ interpretation_id = _stable_pin_id(report_uid, key, "interpretation")
921
+ expected.append((interpretation_id, 3))
922
+ expected_deltas[interpretation_id] = chapter["interpretation"]
923
+ expected_ids = [item[0] for item in expected]
924
+ if ids != expected_ids:
925
+ errors.append("report pins do not exactly match manifest order")
926
+ pin_types = {pin.get("i"): pin.get("type") for pin in content if isinstance(pin, dict)}
927
+ for pin_id, expected_type in expected:
928
+ if pin_types.get(pin_id) != expected_type:
929
+ errors.append(f"pin {pin_id} has the wrong type")
930
+ for pin_id, expected_delta in expected_deltas.items():
931
+ if content_by_id.get(pin_id, {}).get("data") != expected_delta:
932
+ errors.append(f"narrative pin {pin_id} does not match manifest")
933
+ for pin_id, expected_pin in expected_interpretations.items():
934
+ actual_pin = copy.deepcopy(content_by_id.get(pin_id, {}))
935
+ actual_pin.pop("configVersion", None)
936
+ if actual_pin != expected_pin:
937
+ errors.append(f"AI interpretation pin {pin_id} does not match manifest; reload its saved configuration")
938
+
939
+ unassigned_cards = [pin_id for pin_id, pin in content_by_id.items() if pin.get("type") == 2 and pin_id not in claimed_cards]
940
+ if unassigned_cards:
941
+ errors.append("report contains an unassigned card")
942
+ if content_by_id:
943
+ try:
944
+ _validate_card_signatures(content_by_id, claimed_cards, manifest)
945
+ except ReportContractError as exc:
946
+ errors.append(f"card signature error: {exc}")
947
+
948
+ content_ids = {item for item in ids if isinstance(item, str)}
949
+ layouts = report.get("layouts") or {}
950
+ for layout_name in ("sm", "xxs"):
951
+ layout = layouts.get(layout_name)
952
+ layout_ids = [item.get("i") for item in layout] if isinstance(layout, list) else []
953
+ if len(layout_ids) != len(set(layout_ids)) or set(layout_ids) != content_ids:
954
+ errors.append(f"{layout_name} layout ids do not match content ids")
955
+ if content_by_id and isinstance(layouts, dict):
956
+ expected_layouts = _build_layouts(content)
957
+ for layout_name in ("sm", "xxs"):
958
+ if layouts.get(layout_name) != expected_layouts[layout_name]:
959
+ errors.append(f"{layout_name} layout geometry or order does not match report content")
960
+
961
+ if sum(pin.get("type") == 2 for pin in content if isinstance(pin, dict)) > MAX_DATA_CARDS:
962
+ errors.append(f"report contains more than {MAX_DATA_CARDS} data cards")
963
+ for pin in content:
964
+ if not isinstance(pin, dict) or pin.get("type") not in {3, 4}:
965
+ continue
966
+ try:
967
+ _validate_delta(pin.get("data"), allowed_link_origins)
968
+ except ReportContractError as exc:
969
+ errors.append(f"unsafe link in pin {pin.get('i')}: {exc}")
970
+ return errors
971
+
972
+
973
+ def build_report_url(endpoint: str, project_id: int, uid: str) -> str:
974
+ """Build a verified private-report route without carrying endpoint secrets."""
975
+ parts = urlsplit(endpoint)
976
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
977
+ raise ReportContractError("DATARC_ENDPOINT must be an http(s) origin")
978
+ if parts.username or parts.password:
979
+ raise ReportContractError("DATARC_ENDPOINT must not contain user info")
980
+ if isinstance(project_id, bool) or not isinstance(project_id, int) or project_id <= 0:
981
+ raise ReportContractError("project_id must be a positive integer")
982
+ if not isinstance(uid, str) or not _PINBOARD_UID_PATTERN.fullmatch(uid):
983
+ raise ReportContractError("pinboard uid must be 32 hexadecimal characters")
984
+ origin = f"{parts.scheme}://{parts.netloc}"
985
+ return f"{origin}/#/pinboard/{uid}?projectId={project_id}"
986
+
987
+
988
+ def main(argv: Sequence[str] | None = None) -> int:
989
+ parser = argparse.ArgumentParser(description="Validate deterministic pieces of a datarc analysis-report loop")
990
+ subparsers = parser.add_subparsers(dest="command", required=True)
991
+
992
+ card_parser = subparsers.add_parser("card-payload", help="build the report-only /card/ payload")
993
+ card_parser.add_argument("question", type=Path, help="JSON string or flat DataSeek token array")
994
+
995
+ plan_parser = subparsers.add_parser("plan-digest", help="fingerprint the exact Plan version shown for approval")
996
+ plan_parser.add_argument("plan", type=Path)
997
+
998
+ extract_parser = subparsers.add_parser("extract-candidates", help="extract exact drill units from taskType=11 output")
999
+ extract_parser.add_argument("input", type=Path)
1000
+ extract_parser.add_argument("--limit", type=int, default=MAX_BRANCHES_PER_ROUND)
1001
+
1002
+ identify_parser = subparsers.add_parser("identify-card", help="identify one newly added report card by content-ID delta")
1003
+ identify_parser.add_argument("before_report", type=Path)
1004
+ identify_parser.add_argument("after_report", type=Path)
1005
+ identify_parser.add_argument("expected_signature", type=Path)
1006
+
1007
+ build_parser = subparsers.add_parser("build-report", help="build a full Pinboard content/layouts PATCH")
1008
+ build_parser.add_argument("report", type=Path)
1009
+ build_parser.add_argument("manifest", type=Path)
1010
+ build_parser.add_argument("--report-origin", help="trusted DATARC_ENDPOINT origin; required only when text links are enabled")
1011
+
1012
+ validate_parser = subparsers.add_parser("validate-report", help="validate the final Pinboard GET response")
1013
+ validate_parser.add_argument("report", type=Path)
1014
+ validate_parser.add_argument("manifest", type=Path)
1015
+ validate_parser.add_argument("--report-origin", help="trusted DATARC_ENDPOINT origin; required only when text links are enabled")
1016
+
1017
+ args = parser.parse_args(argv)
1018
+ if args.command == "card-payload":
1019
+ _write_json(build_card_payload(_read_json(args.question)))
1020
+ return 0
1021
+ if args.command == "plan-digest":
1022
+ _write_json({"digest": plan_digest(_read_json(args.plan))})
1023
+ return 0
1024
+ if args.command == "extract-candidates":
1025
+ result = extract_drill_candidates(_read_json(args.input), limit=args.limit)
1026
+ _write_json(result)
1027
+ return 0
1028
+ if args.command == "identify-card":
1029
+ result = identify_added_card(
1030
+ _read_json(args.before_report, max_bytes=MAX_REPORT_JSON_INPUT_BYTES),
1031
+ _read_json(args.after_report, max_bytes=MAX_REPORT_JSON_INPUT_BYTES),
1032
+ _read_json(args.expected_signature),
1033
+ )
1034
+ _write_json(result)
1035
+ return 0
1036
+ if args.command == "build-report":
1037
+ _write_json(
1038
+ build_report_patch(
1039
+ _read_json(args.report, max_bytes=MAX_REPORT_JSON_INPUT_BYTES),
1040
+ _read_json(args.manifest),
1041
+ report_origin=args.report_origin,
1042
+ )
1043
+ )
1044
+ return 0
1045
+ errors = validate_report(
1046
+ _read_json(args.report, max_bytes=MAX_REPORT_JSON_INPUT_BYTES),
1047
+ _read_json(args.manifest),
1048
+ report_origin=args.report_origin,
1049
+ )
1050
+ _write_json({"valid": not errors, "errors": errors})
1051
+ return 0 if not errors else 1
1052
+
1053
+
1054
+ def _validated_units(units: Any) -> list[dict[str, Any]]:
1055
+ if not isinstance(units, (list, tuple)) or not units:
1056
+ raise ReportContractError("structured units must be a non-empty list")
1057
+ result: list[dict[str, Any]] = []
1058
+ for unit in units:
1059
+ if not isinstance(unit, dict) or not isinstance(unit.get("tokens"), list) or not unit["tokens"]:
1060
+ raise ReportContractError("every unit must contain tokens")
1061
+ tokens: list[dict[str, str]] = []
1062
+ for token in unit["tokens"]:
1063
+ if not isinstance(token, dict) or not isinstance(token.get("word"), str) or not isinstance(token.get("prop"), str):
1064
+ raise ReportContractError("every token must contain string word and prop")
1065
+ tokens.append(copy.deepcopy(token))
1066
+ copied = copy.deepcopy(unit)
1067
+ copied["tokens"] = tokens
1068
+ result.append(copied)
1069
+ return result
1070
+
1071
+
1072
+ def _card_question_text(question: str | Sequence[dict[str, Any]]) -> str:
1073
+ if isinstance(question, str):
1074
+ question_text = question.strip()
1075
+ elif isinstance(question, (list, tuple)) and question:
1076
+ question = normalize_question_tokens(question)
1077
+ words: list[str] = []
1078
+ for token in question:
1079
+ word = token.get("word") if isinstance(token, dict) else None
1080
+ if not isinstance(word, str) or not word.strip():
1081
+ raise ReportContractError("question tokens must contain non-empty words")
1082
+ words.append(word.strip())
1083
+ question_text = " ".join(words)
1084
+ else:
1085
+ raise ReportContractError("question must be a non-empty string or token sequence")
1086
+ if not question_text or len(question_text) > MAX_QUESTION_CHARS:
1087
+ raise ReportContractError(f"question must be non-empty and at most {MAX_QUESTION_CHARS} characters")
1088
+ return question_text
1089
+
1090
+
1091
+ def _workspace_query_terms(query: str) -> tuple[str, ...]:
1092
+ terms: list[str] = []
1093
+ for token in re.findall(r"[\w\u3400-\u9fff]+", query):
1094
+ terms.append(token)
1095
+ if len(token) > 2 and _CJK_PATTERN.search(token):
1096
+ terms.extend(token[index : index + 2] for index in range(len(token) - 1))
1097
+ return tuple(dict.fromkeys(terms))
1098
+
1099
+
1100
+ def _walk_drill_packages(node: Any) -> Iterable[tuple[str, dict[str, Any]]]:
1101
+ if isinstance(node, list):
1102
+ for item in node:
1103
+ yield from _walk_drill_packages(item)
1104
+ return
1105
+ if not isinstance(node, dict):
1106
+ return
1107
+ for source in ("anomalies", "attribution"):
1108
+ package = node.get(source)
1109
+ if isinstance(package, dict):
1110
+ yield source, package
1111
+ for key, value in node.items():
1112
+ if key not in {"anomalies", "attribution"}:
1113
+ yield from _walk_drill_packages(value)
1114
+
1115
+
1116
+ def _evidence_units(units: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
1117
+ """Keep only token words and props needed to recompute a non-sensitive drill signature."""
1118
+ validated = _validated_units(units)
1119
+ return [{"tokens": [{"word": token["word"], "prop": token["prop"]} for token in unit["tokens"]]} for unit in validated]
1120
+
1121
+
1122
+ def _evidence_card_signature(card: dict[str, Any]) -> str:
1123
+ canonical = json.dumps(
1124
+ {
1125
+ "cardType": card.get("card_type", card.get("cardType")),
1126
+ "units": card.get("units"),
1127
+ "tuids": card.get("tuids"),
1128
+ },
1129
+ ensure_ascii=False,
1130
+ sort_keys=True,
1131
+ separators=(",", ":"),
1132
+ )
1133
+ return hashlib.sha256(canonical.encode()).hexdigest()
1134
+
1135
+
1136
+ def _stop(reason: str) -> dict[str, Any]:
1137
+ return {"nextRound": None, "candidates": [], "stopReason": reason}
1138
+
1139
+
1140
+ def _unwrap_api_data(response: Any) -> Any:
1141
+ if isinstance(response, dict) and response.get("status") == "SUCCESS" and "data" in response:
1142
+ return response["data"]
1143
+ return response
1144
+
1145
+
1146
+ def _validate_manifest(
1147
+ report: dict[str, Any], manifest: dict[str, Any], report_origin: str | None
1148
+ ) -> tuple[str, list[dict[str, Any]], frozenset[str]]:
1149
+ if not isinstance(report, dict) or not isinstance(manifest, dict):
1150
+ raise ReportContractError("report and manifest must be objects")
1151
+ required_manifest_keys = {
1152
+ "reportUid",
1153
+ "projectId",
1154
+ "reportName",
1155
+ "reportDesc",
1156
+ "language",
1157
+ "approvedPlan",
1158
+ "approvedPlanDigest",
1159
+ "analysisGoal",
1160
+ "textLinkPolicy",
1161
+ "scope",
1162
+ "interestProfile",
1163
+ "modelResolution",
1164
+ "cardSignatures",
1165
+ "rounds",
1166
+ "stopReason",
1167
+ "chapters",
1168
+ }
1169
+ if set(manifest) - {"aiInterpretations"} != required_manifest_keys:
1170
+ raise ReportContractError("manifest must use the exact analysis-report contract")
1171
+ report_uid = report.get("uid")
1172
+ if not isinstance(report_uid, str) or not report_uid:
1173
+ raise ReportContractError("report has no uid")
1174
+ if manifest.get("reportUid") != report_uid:
1175
+ raise ReportContractError("manifest reportUid does not match report uid")
1176
+ if not isinstance(manifest.get("approvedPlanDigest"), str) or not SHA256_PATTERN.fullmatch(manifest["approvedPlanDigest"]):
1177
+ raise ReportContractError("manifest approvedPlanDigest must be a lowercase SHA-256 digest")
1178
+ approved_plan = manifest.get("approvedPlan")
1179
+ require_plan_approval(approved_plan, manifest["approvedPlanDigest"])
1180
+ execution = validate_execution_plan(approved_plan)
1181
+ chapter_evidence_plan = validate_chapter_evidence_plan(approved_plan)
1182
+ if manifest.get("projectId") != execution["projectId"]:
1183
+ raise ReportContractError("manifest projectId does not match the approved Plan")
1184
+ language = _validate_output_language(manifest.get("language"))
1185
+ if language != execution["language"]:
1186
+ raise ReportContractError("manifest language does not match the approved Plan")
1187
+ signatures = manifest.get("cardSignatures")
1188
+ source_terms = _source_terms_from_signatures(signatures)
1189
+ manifest_scope = manifest.get("scope")
1190
+ measure_props, dimension_props, time_dimensions = _validate_analysis_scope(manifest_scope)
1191
+ if manifest_scope != execution["scope"]:
1192
+ raise ReportContractError("manifest scope does not match the approved Plan execution scope")
1193
+ _validate_report_metadata(report, manifest, language, source_terms)
1194
+ allowed_link_origins = _validate_text_link_policy(manifest.get("textLinkPolicy"), report_origin)
1195
+ _validate_interest_profile(manifest.get("interestProfile"), measure_props, dimension_props)
1196
+ round_card_contracts, claims_by_id = _validate_rounds(
1197
+ manifest,
1198
+ language,
1199
+ source_terms,
1200
+ chapter_evidence_plan=chapter_evidence_plan,
1201
+ measure_props=measure_props,
1202
+ dimension_props=dimension_props,
1203
+ time_dimensions=time_dimensions,
1204
+ max_rounds=execution["maxRounds"],
1205
+ max_questions=execution["maxQuestionsPerRound"],
1206
+ max_cards=execution["maxDataCards"],
1207
+ )
1208
+ if _plan_question_bindings(manifest["rounds"][0]["questions"]) != _plan_question_bindings(execution["initialQuestions"]):
1209
+ raise ReportContractError("manifest round 1 questions do not match the approved Plan")
1210
+ if not isinstance(signatures, dict) or set(signatures) != set(round_card_contracts):
1211
+ raise ReportContractError("cardSignatures must match rounds[].cards exactly")
1212
+ report_model_uids = _validate_model_resolution(
1213
+ manifest.get("modelResolution"),
1214
+ list(round_card_contracts),
1215
+ )
1216
+ for card_id, signature in signatures.items():
1217
+ _validate_expected_card_signature(signature, card_id)
1218
+ _validate_tokens_in_analysis_scope(
1219
+ signature["data"],
1220
+ measure_props,
1221
+ dimension_props,
1222
+ time_dimensions,
1223
+ f"card signature for {card_id}",
1224
+ reject_multiple_time_dimensions=True,
1225
+ )
1226
+ if signature["pinboardTuids"] != report_model_uids:
1227
+ raise ReportContractError(f"card signature for {card_id} does not use the derived report model list")
1228
+ if signature["data"] != round_card_contracts[card_id]["data"]:
1229
+ raise ReportContractError(f"card signature for {card_id} does not match its question tokens")
1230
+ _validate_language_text(signature["chartName"], language, f"card title {card_id}", source_terms, require_zh=False)
1231
+
1232
+ chapters = manifest.get("chapters")
1233
+ if not isinstance(chapters, list) or not chapters:
1234
+ raise ReportContractError("manifest must contain chapters")
1235
+ seen_keys: set[str] = set()
1236
+ chapter_card_ids: list[str] = []
1237
+ referenced_claim_ids: set[str] = set()
1238
+ analysis_chapter_keys: set[str] = set()
1239
+ analysis_claim_refs: dict[str, set[str]] = {}
1240
+ summary_chapters: list[dict[str, Any]] = []
1241
+ conclusion_chapters: list[dict[str, Any]] = []
1242
+ required_chapter_keys = {
1243
+ "key",
1244
+ "title",
1245
+ "kind",
1246
+ "sectionRole",
1247
+ "dependsOnChapterKeys",
1248
+ "cardIds",
1249
+ "cardRoles",
1250
+ "claimRefs",
1251
+ "coverageStatus",
1252
+ "purpose",
1253
+ "interpretation",
1254
+ }
1255
+ for chapter in chapters:
1256
+ if not isinstance(chapter, dict) or set(chapter) != required_chapter_keys:
1257
+ raise ReportContractError("every chapter must use the complete evidence-backed narrative contract")
1258
+ key = chapter.get("key")
1259
+ title = chapter.get("title")
1260
+ if not isinstance(key, str) or not key or key in seen_keys:
1261
+ raise ReportContractError("chapter keys must be non-empty and unique")
1262
+ if not isinstance(title, str) or not title.strip():
1263
+ raise ReportContractError("chapter title must be non-empty")
1264
+ _validate_language_text(title, language, f"chapter title {key}", source_terms)
1265
+ section_role = chapter.get("sectionRole")
1266
+ if section_role not in SECTION_ROLES:
1267
+ raise ReportContractError("chapter sectionRole is invalid")
1268
+ expected_kind = "analysis" if section_role == "analysis" else "narrative"
1269
+ if chapter.get("kind") != expected_kind:
1270
+ raise ReportContractError("chapter kind must match sectionRole")
1271
+ dependencies = chapter.get("dependsOnChapterKeys")
1272
+ if (
1273
+ not isinstance(dependencies, list)
1274
+ or not all(isinstance(item, str) and item for item in dependencies)
1275
+ or len(dependencies) != len(set(dependencies))
1276
+ or not set(dependencies).issubset(seen_keys)
1277
+ ):
1278
+ raise ReportContractError("chapter dependencies must be unique earlier chapter keys")
1279
+ seen_keys.add(key)
1280
+
1281
+ purpose = chapter.get("purpose")
1282
+ interpretation = chapter.get("interpretation")
1283
+ for narrative_role, delta in (("purpose", purpose), ("interpretation", interpretation)):
1284
+ _validate_delta(delta, allowed_link_origins)
1285
+ text = _delta_text(delta)
1286
+ if not text.strip():
1287
+ raise ReportContractError(f"chapter {key} {narrative_role} must be non-empty")
1288
+ _validate_language_text(text, language, f"chapter {key} {narrative_role}", source_terms)
1289
+
1290
+ card_ids = chapter.get("cardIds")
1291
+ if not isinstance(card_ids, list) or not all(isinstance(item, str) and item for item in card_ids) or len(card_ids) != len(set(card_ids)):
1292
+ raise ReportContractError("chapter cardIds must be a list of unique pin ids")
1293
+ if not set(card_ids).issubset(signatures):
1294
+ raise ReportContractError("chapter cardIds must reference declared card signatures")
1295
+ card_roles = chapter.get("cardRoles")
1296
+ if not isinstance(card_roles, dict) or set(card_roles) != set(card_ids):
1297
+ raise ReportContractError("chapter cardRoles must assign one evidence role to every data card")
1298
+ if not all(isinstance(role, str) and role in EVIDENCE_ROLES for role in card_roles.values()):
1299
+ raise ReportContractError("chapter cardRoles contains an unsupported evidence role")
1300
+ for card_id in card_ids:
1301
+ card_contract = round_card_contracts[card_id]
1302
+ if card_contract["chapterKey"] != key:
1303
+ raise ReportContractError("every data card must be assigned to its question's declared chapter")
1304
+ if card_roles[card_id] != card_contract["evidenceRole"]:
1305
+ raise ReportContractError("chapter cardRoles must match each question's declared evidenceRole")
1306
+
1307
+ claim_refs = chapter.get("claimRefs")
1308
+ if (
1309
+ not isinstance(claim_refs, list)
1310
+ or not all(isinstance(item, str) and item for item in claim_refs)
1311
+ or len(claim_refs) != len(set(claim_refs))
1312
+ or not set(claim_refs).issubset(claims_by_id)
1313
+ ):
1314
+ raise ReportContractError("chapter claimRefs must be unique known claim ids")
1315
+ interpretation_text = _delta_text(interpretation)
1316
+ for claim_id in claim_refs:
1317
+ if claims_by_id[claim_id]["text"] not in interpretation_text:
1318
+ raise ReportContractError(f"chapter {key} interpretation must render every referenced claim")
1319
+ referenced_claim_ids.update(claim_refs)
1320
+
1321
+ coverage_status = chapter.get("coverageStatus")
1322
+ if coverage_status not in COVERAGE_STATUSES:
1323
+ raise ReportContractError("chapter coverageStatus must be complete or degraded")
1324
+ if section_role == "analysis":
1325
+ evidence_plan = chapter_evidence_plan.get(key)
1326
+ if evidence_plan is None:
1327
+ raise ReportContractError("analysis chapter has no approved chapterEvidencePlan entry")
1328
+ if len(card_ids) < evidence_plan["minCards"]:
1329
+ raise ReportContractError(f"analysis chapters must contain at least {evidence_plan['minCards']} data cards")
1330
+ claim_kinds = [claims_by_id[claim_id]["kind"] for claim_id in claim_refs]
1331
+ if claim_kinds.count("fact") < 2 or not {"inference", "limitation"}.intersection(claim_kinds):
1332
+ raise ReportContractError("analysis chapters require at least two facts and one inference or limitation")
1333
+ chapter_evidence_refs = {evidence_ref for card_id in card_ids for evidence_ref in round_card_contracts[card_id]["evidenceRefs"]}
1334
+ used_chapter_evidence: set[str] = set()
1335
+ for claim_id in claim_refs:
1336
+ claim = claims_by_id[claim_id]
1337
+ if claim["kind"] == "limitation":
1338
+ continue
1339
+ claim_evidence = set(claim["evidenceRefs"])
1340
+ if not claim_evidence.issubset(chapter_evidence_refs):
1341
+ raise ReportContractError("analysis chapter claims may use evidence only from that chapter's cards and local insights")
1342
+ used_chapter_evidence.update(claim_evidence)
1343
+ if any(not set(round_card_contracts[card_id]["evidenceRefs"]).intersection(used_chapter_evidence) for card_id in card_ids):
1344
+ raise ReportContractError("every analysis card must support at least one claim rendered in its chapter")
1345
+ missing_roles = set(evidence_plan["requiredEvidenceRoles"]) - set(card_roles.values())
1346
+ if coverage_status == "complete" and (len(card_ids) < evidence_plan["targetCards"] or missing_roles):
1347
+ raise ReportContractError("complete analysis chapters must meet their target card and evidence-role coverage")
1348
+ if coverage_status == "degraded" and "limitation" not in claim_kinds:
1349
+ raise ReportContractError("degraded analysis chapters must render an explicit limitation claim")
1350
+ analysis_chapter_keys.add(key)
1351
+ analysis_claim_refs[key] = set(claim_refs)
1352
+ else:
1353
+ if card_ids or card_roles:
1354
+ raise ReportContractError("narrative chapters must not contain data cards or card roles")
1355
+ if coverage_status != "complete":
1356
+ raise ReportContractError("narrative chapters must use complete coverageStatus")
1357
+ if section_role == "summary":
1358
+ if len(claim_refs) < 3:
1359
+ raise ReportContractError("the executive summary must render at least three claims")
1360
+ summary_chapters.append(chapter)
1361
+ elif section_role == "conclusion":
1362
+ claim_kinds = {claims_by_id[claim_id]["kind"] for claim_id in claim_refs}
1363
+ if len(claim_refs) < 3 or not {"recommendation", "limitation"}.issubset(claim_kinds):
1364
+ raise ReportContractError("the conclusion must render at least three claims including a recommendation and limitation")
1365
+ conclusion_chapters.append(chapter)
1366
+ chapter_card_ids.extend(card_ids)
1367
+
1368
+ if analysis_chapter_keys != set(chapter_evidence_plan):
1369
+ raise ReportContractError("analysis chapters must exactly match the approved chapterEvidencePlan")
1370
+ if len(summary_chapters) != 1 or chapters[0] is not summary_chapters[0]:
1371
+ raise ReportContractError("the report must begin with exactly one executive-summary chapter")
1372
+ if len(conclusion_chapters) != 1 or chapters[-1] is not conclusion_chapters[0]:
1373
+ raise ReportContractError("the report must end with exactly one conclusion chapter")
1374
+ conclusion = conclusion_chapters[0]
1375
+ if not analysis_chapter_keys.issubset(conclusion["dependsOnChapterKeys"]):
1376
+ raise ReportContractError("the conclusion must directly depend on every analysis chapter")
1377
+ if any(not refs.intersection(conclusion["claimRefs"]) for refs in analysis_claim_refs.values()):
1378
+ raise ReportContractError("the conclusion must carry forward at least one claim from every analysis chapter")
1379
+ if referenced_claim_ids != set(claims_by_id):
1380
+ raise ReportContractError("every round claim must be rendered by at least one chapter")
1381
+ if len(chapter_card_ids) != len(set(chapter_card_ids)) or set(chapter_card_ids) != set(round_card_contracts):
1382
+ raise ReportContractError("chapter cardIds must assign every round evidence card exactly once")
1383
+ return report_uid, chapters, allowed_link_origins
1384
+
1385
+
1386
+ def _validate_report_metadata(report: dict[str, Any], manifest: dict[str, Any], language: str, source_terms: frozenset[str]) -> None:
1387
+ report_name = manifest.get("reportName")
1388
+ report_desc = manifest.get("reportDesc")
1389
+ analysis_goal = manifest.get("analysisGoal")
1390
+ if report.get("name") != report_name or report.get("desc") != report_desc:
1391
+ raise ReportContractError("report name or description does not match manifest")
1392
+ _validate_language_text(report_name, language, "report name", source_terms)
1393
+ _validate_language_text(report_desc, language, "report description", source_terms)
1394
+ _validate_language_text(analysis_goal, language, "analysis goal", source_terms)
1395
+
1396
+
1397
+ def _validate_analysis_scope(scope: Any) -> tuple[frozenset[str], frozenset[str], frozenset[str]]:
1398
+ required = {"measureProps", "dimensionProps", "timeDimensions"}
1399
+ if not isinstance(scope, dict) or set(scope) != required:
1400
+ raise ReportContractError("scope must contain only confirmed measure, dimension, and time-dimension allowlists")
1401
+ values: dict[str, frozenset[str]] = {}
1402
+ for field in required:
1403
+ items = scope[field]
1404
+ if not isinstance(items, list) or not all(isinstance(item, str) and item for item in items) or len(items) != len(set(items)):
1405
+ raise ReportContractError(f"scope {field} must contain unique non-empty props")
1406
+ values[field] = frozenset(items)
1407
+ if not values["measureProps"]:
1408
+ raise ReportContractError("scope must contain at least one measure prop")
1409
+ if values["measureProps"] & values["dimensionProps"]:
1410
+ raise ReportContractError("scope measure and dimension props must not overlap")
1411
+ if values["measureProps"] & values["timeDimensions"]:
1412
+ raise ReportContractError("scope measure and time-dimension props must not overlap")
1413
+ if values["dimensionProps"] & values["timeDimensions"]:
1414
+ raise ReportContractError("scope dimension and time-dimension props must not overlap")
1415
+ return values["measureProps"], values["dimensionProps"], values["timeDimensions"]
1416
+
1417
+
1418
+ def _validate_model_resolution(
1419
+ resolution: Any,
1420
+ card_ids: Sequence[str],
1421
+ ) -> list[str]:
1422
+ required = {"cards", "reportModelUids"}
1423
+ if not isinstance(resolution, dict) or set(resolution) != required:
1424
+ raise ReportContractError("modelResolution must use the complete resolved-model contract")
1425
+ cards = resolution["cards"]
1426
+ if not isinstance(cards, dict) or set(cards) != set(card_ids):
1427
+ raise ReportContractError("modelResolution cards must exactly match all round evidence cards")
1428
+
1429
+ has_unknown_resolution = False
1430
+ stable_report_models: list[str] = []
1431
+ seen_report_models: set[str] = set()
1432
+ for card_id in card_ids:
1433
+ card_resolution = cards[card_id]
1434
+ if not isinstance(card_resolution, dict) or set(card_resolution) != {"resolvedTuids"}:
1435
+ raise ReportContractError(f"modelResolution card {card_id} must contain only resolvedTuids")
1436
+ resolved_tuids = card_resolution["resolvedTuids"]
1437
+ if resolved_tuids is not None and (
1438
+ not isinstance(resolved_tuids, list)
1439
+ or not 1 <= len(resolved_tuids) <= MAX_MODELS_PER_QUESTION
1440
+ or not all(isinstance(uid, str) and uid and len(uid) <= MAX_MODEL_UID_CHARS for uid in resolved_tuids)
1441
+ or len(resolved_tuids) != len(set(resolved_tuids))
1442
+ ):
1443
+ raise ReportContractError(
1444
+ f"modelResolution card {card_id} resolvedTuids must be null or contain one to {MAX_MODELS_PER_QUESTION} unique model uids"
1445
+ )
1446
+ if resolved_tuids is None:
1447
+ has_unknown_resolution = True
1448
+ continue
1449
+ for uid in resolved_tuids:
1450
+ if uid not in seen_report_models:
1451
+ seen_report_models.add(uid)
1452
+ stable_report_models.append(uid)
1453
+
1454
+ expected_report_models = [] if has_unknown_resolution else stable_report_models
1455
+ if len(expected_report_models) > MAX_MODELS_PER_QUESTION:
1456
+ raise ReportContractError(f"the resolved report model union exceeds {MAX_MODELS_PER_QUESTION}; reduce the number of evidence cards")
1457
+ report_model_uids = resolution["reportModelUids"]
1458
+ if report_model_uids != expected_report_models:
1459
+ raise ReportContractError("modelResolution reportModelUids must be the stable resolved-model union")
1460
+ return expected_report_models
1461
+
1462
+
1463
+ def _validate_interest_profile(profile: Any, measure_props: frozenset[str], dimension_props: frozenset[str]) -> None:
1464
+ required = {"measures", "dimensions", "analysisModes", "timeGrains", "historyWeightCap"}
1465
+ if not isinstance(profile, dict) or set(profile) != required:
1466
+ raise ReportContractError("interestProfile must contain only aggregated preference fields")
1467
+ cap = profile["historyWeightCap"]
1468
+ if isinstance(cap, bool) or not isinstance(cap, (int, float)) or not 0 <= cap <= 0.15:
1469
+ raise ReportContractError("historyWeightCap must be between 0 and 0.15")
1470
+ allowed_props = {"measures": measure_props, "dimensions": dimension_props}
1471
+ for field in ("measures", "dimensions"):
1472
+ items = profile[field]
1473
+ if not isinstance(items, list):
1474
+ raise ReportContractError(f"interestProfile {field} must be a list")
1475
+ seen_props: set[str] = set()
1476
+ for item in items:
1477
+ if not isinstance(item, dict) or set(item) != {"prop", "weight"}:
1478
+ raise ReportContractError(f"interestProfile {field} entries may contain only prop and weight")
1479
+ prop = item["prop"]
1480
+ weight = item["weight"]
1481
+ if not isinstance(prop, str) or not prop or prop in seen_props:
1482
+ raise ReportContractError(f"interestProfile {field} props must be non-empty and unique")
1483
+ if prop not in allowed_props[field]:
1484
+ raise ReportContractError(f"interestProfile {field} prop is outside the current analysis scope")
1485
+ if isinstance(weight, bool) or not isinstance(weight, (int, float)) or not 0 <= weight <= 1:
1486
+ raise ReportContractError(f"interestProfile {field} weights must be between 0 and 1")
1487
+ seen_props.add(prop)
1488
+ supported_values = {"analysisModes": SUPPORTED_ANALYSIS_MODES, "timeGrains": SUPPORTED_TIME_GRAINS}
1489
+ for field in ("analysisModes", "timeGrains"):
1490
+ values = profile[field]
1491
+ if not isinstance(values, list) or not all(isinstance(item, str) and item for item in values) or len(values) != len(set(values)):
1492
+ raise ReportContractError(f"interestProfile {field} must contain unique strings")
1493
+ if not set(values).issubset(supported_values[field]):
1494
+ raise ReportContractError(f"interestProfile {field} contains an unsupported category")
1495
+
1496
+
1497
+ def _validate_rounds(
1498
+ manifest: dict[str, Any],
1499
+ language: str,
1500
+ source_terms: frozenset[str],
1501
+ *,
1502
+ chapter_evidence_plan: dict[str, dict[str, Any]],
1503
+ measure_props: frozenset[str],
1504
+ dimension_props: frozenset[str],
1505
+ time_dimensions: frozenset[str],
1506
+ max_rounds: int,
1507
+ max_questions: int,
1508
+ max_cards: int,
1509
+ ) -> tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]]]:
1510
+ rounds = manifest.get("rounds")
1511
+ if not isinstance(rounds, list) or not 1 <= len(rounds) <= max_rounds:
1512
+ raise ReportContractError(f"manifest rounds must contain one to {max_rounds} completed rounds")
1513
+ known_evidence: set[str] = set()
1514
+ question_ids: set[str] = set()
1515
+ question_signatures: set[str] = set()
1516
+ known_insight_signatures: set[str] = set()
1517
+ card_contracts: dict[str, dict[str, Any]] = {}
1518
+ claims_by_id: dict[str, dict[str, Any]] = {}
1519
+ final_reason = None
1520
+
1521
+ for expected_round, round_data in enumerate(rounds, start=1):
1522
+ if not isinstance(round_data, dict) or round_data.get("round") != expected_round:
1523
+ raise ReportContractError("manifest rounds must be sequential starting at 1")
1524
+ required_round_keys = {"round", "questions", "cards", "insightRefs", "claims", "stopOrNextReason"}
1525
+ if expected_round == 3:
1526
+ required_round_keys |= {"allowedAnalysisAxes", "usedAnalysisAxesBefore", "newAnalysisAxes"}
1527
+ if set(round_data) != required_round_keys:
1528
+ raise ReportContractError(f"round {expected_round} must use the exact round contract")
1529
+ questions = round_data.get("questions")
1530
+ if not isinstance(questions, list) or not 1 <= len(questions) <= max_questions:
1531
+ raise ReportContractError(f"round {expected_round} must contain one to {max_questions} questions")
1532
+ current_question_ids: set[str] = set()
1533
+ current_question_contracts: dict[str, dict[str, Any]] = {}
1534
+ for question in questions:
1535
+ question_id = _validate_round_question(
1536
+ question,
1537
+ expected_round,
1538
+ known_evidence,
1539
+ language,
1540
+ source_terms,
1541
+ set(chapter_evidence_plan),
1542
+ measure_props,
1543
+ dimension_props,
1544
+ time_dimensions,
1545
+ )
1546
+ if question_id in question_ids:
1547
+ raise ReportContractError("question ids must be unique across rounds")
1548
+ signature = _question_signature(question)
1549
+ if signature in question_signatures:
1550
+ raise ReportContractError("questions must not repeat across rounds")
1551
+ question_ids.add(question_id)
1552
+ current_question_ids.add(question_id)
1553
+ current_question_contracts[question_id] = {
1554
+ "data": copy.deepcopy(question["normalizedTokens"]),
1555
+ "chapterKey": question["chapterKey"],
1556
+ "evidenceRole": question["evidenceRole"],
1557
+ }
1558
+ question_signatures.add(signature)
1559
+
1560
+ cards = round_data.get("cards")
1561
+ if not isinstance(cards, list):
1562
+ raise ReportContractError(f"round {expected_round} cards must be a list")
1563
+ if len(cards) > len(questions):
1564
+ raise ReportContractError(f"round {expected_round} cannot contain more cards than questions")
1565
+ current_evidence: set[str] = set()
1566
+ card_question_ids: set[str] = set()
1567
+ card_ids_by_question: dict[str, str] = {}
1568
+ for card in cards:
1569
+ if not isinstance(card, dict) or set(card) != {"pinId", "evidenceRef"}:
1570
+ raise ReportContractError("round cards must contain only pinId and evidenceRef")
1571
+ pin_id = card["pinId"]
1572
+ evidence_ref = card["evidenceRef"]
1573
+ if not isinstance(pin_id, str) or not pin_id or pin_id in card_contracts:
1574
+ raise ReportContractError("round card pin ids must be non-empty and unique")
1575
+ question_id = _evidence_question_id(evidence_ref, current_question_ids)
1576
+ if evidence_ref != f"{question_id}:card0" or question_id in card_question_ids:
1577
+ raise ReportContractError("each round question may produce only one card0 evidence item")
1578
+ if evidence_ref in current_evidence or evidence_ref in known_evidence:
1579
+ raise ReportContractError("evidence references must be unique")
1580
+ question_contract = current_question_contracts[question_id]
1581
+ normalized_tokens = question_contract["data"]
1582
+ if normalized_tokens is None:
1583
+ raise ReportContractError("card-producing questions must contain normalizedTokens")
1584
+ card_contracts[pin_id] = {
1585
+ "data": normalized_tokens,
1586
+ "evidenceRefs": [evidence_ref],
1587
+ "chapterKey": question_contract["chapterKey"],
1588
+ "evidenceRole": question_contract["evidenceRole"],
1589
+ }
1590
+ card_question_ids.add(question_id)
1591
+ card_ids_by_question[question_id] = pin_id
1592
+ current_evidence.add(evidence_ref)
1593
+
1594
+ insight_refs = round_data.get("insightRefs")
1595
+ if not isinstance(insight_refs, list):
1596
+ raise ReportContractError(f"round {expected_round} insightRefs must be a list")
1597
+ insight_counts: dict[str, int] = {}
1598
+ for insight_ref in insight_refs:
1599
+ required_insight_keys = {
1600
+ "evidenceRef",
1601
+ "insightType",
1602
+ "source",
1603
+ "evidenceUnits",
1604
+ "comparisonType",
1605
+ "signature",
1606
+ }
1607
+ if not isinstance(insight_ref, dict) or set(insight_ref) != required_insight_keys:
1608
+ raise ReportContractError("insightRefs must use the complete structured candidate contract")
1609
+ evidence_ref = insight_ref["evidenceRef"]
1610
+ signature = insight_ref["signature"]
1611
+ question_id = _evidence_question_id(evidence_ref, current_question_ids)
1612
+ if question_id not in card_question_ids:
1613
+ raise ReportContractError("local insight evidence must belong to a card-producing question")
1614
+ expected_ref = f"{question_id}:insight{insight_counts.get(question_id, 0)}"
1615
+ if evidence_ref != expected_ref:
1616
+ raise ReportContractError("local insight evidence must use contiguous insightN references per question")
1617
+ if not isinstance(insight_ref["insightType"], str) or insight_ref["insightType"] not in _INSIGHT_PRIORITY:
1618
+ raise ReportContractError("local insight evidence has an unsupported insight type")
1619
+ if not isinstance(insight_ref["source"], str) or insight_ref["source"] not in {
1620
+ "anomalies",
1621
+ "attribution",
1622
+ }:
1623
+ raise ReportContractError("local insight evidence has an unsupported source")
1624
+ try:
1625
+ evidence_units = _evidence_units(insight_ref["evidenceUnits"])
1626
+ except ReportContractError as exc:
1627
+ raise ReportContractError(f"local insight evidence units are invalid: {exc}") from None
1628
+ if evidence_units != insight_ref["evidenceUnits"]:
1629
+ raise ReportContractError("local insight evidenceUnits must contain only word/prop tokens")
1630
+ _validate_tokens_in_analysis_scope(
1631
+ flatten_units(evidence_units),
1632
+ measure_props,
1633
+ dimension_props,
1634
+ time_dimensions,
1635
+ f"local insight {evidence_ref}",
1636
+ )
1637
+ comparison_type = insight_ref["comparisonType"]
1638
+ if comparison_type not in SUPPORTED_COMPARISON_TYPES:
1639
+ raise ReportContractError("local insight evidence comparisonType is invalid")
1640
+ if not isinstance(signature, str) or not SHA256_PATTERN.fullmatch(signature):
1641
+ raise ReportContractError("local insight evidence must contain its structured candidate SHA-256 signature")
1642
+ if signature != drill_signature(evidence_units, comparison_type):
1643
+ raise ReportContractError("local insight signature does not match its structured candidate")
1644
+ if signature in known_insight_signatures:
1645
+ raise ReportContractError("local insight signatures must be unique across rounds")
1646
+ if evidence_ref in current_evidence or evidence_ref in known_evidence:
1647
+ raise ReportContractError("evidence references must be unique")
1648
+ insight_counts[question_id] = insight_counts.get(question_id, 0) + 1
1649
+ known_insight_signatures.add(signature)
1650
+ current_evidence.add(evidence_ref)
1651
+ card_contracts[card_ids_by_question[question_id]]["evidenceRefs"].append(evidence_ref)
1652
+
1653
+ round_claims = _validate_claims(
1654
+ round_data.get("claims"),
1655
+ known_evidence | current_evidence,
1656
+ language,
1657
+ source_terms,
1658
+ round_number=expected_round,
1659
+ known_claim_ids=set(claims_by_id),
1660
+ )
1661
+ claims_by_id.update(round_claims)
1662
+ final_reason = round_data.get("stopOrNextReason")
1663
+ _validate_language_text(final_reason, language, f"round {expected_round} stop or next reason", source_terms)
1664
+ known_evidence.update(current_evidence)
1665
+
1666
+ if not MIN_CARDS_PER_ANALYSIS_CHAPTER <= len(card_contracts) <= max_cards:
1667
+ raise ReportContractError(f"round evidence cards must contain {MIN_CARDS_PER_ANALYSIS_CHAPTER} to {max_cards} data cards")
1668
+ if manifest.get("stopReason") != final_reason:
1669
+ raise ReportContractError("manifest stopReason must match the final round reason")
1670
+ if len(rounds) == 3:
1671
+ _validate_round_three_axes(rounds[2])
1672
+ return card_contracts, claims_by_id
1673
+
1674
+
1675
+ def _plan_question_bindings(questions: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
1676
+ fields = (
1677
+ "id",
1678
+ "round",
1679
+ "role",
1680
+ "question",
1681
+ "requestTuids",
1682
+ "chapterKey",
1683
+ "evidenceRole",
1684
+ "purpose",
1685
+ "expectedEvidence",
1686
+ "parentEvidenceRefs",
1687
+ )
1688
+ return [{key: question[key].strip() if key == "question" else copy.deepcopy(question[key]) for key in fields} for question in questions]
1689
+
1690
+
1691
+ def _validate_round_question(
1692
+ question: Any,
1693
+ round_number: int,
1694
+ known_evidence: set[str],
1695
+ language: str,
1696
+ source_terms: frozenset[str],
1697
+ chapter_keys: set[str],
1698
+ measure_props: frozenset[str],
1699
+ dimension_props: frozenset[str],
1700
+ time_dimensions: frozenset[str],
1701
+ ) -> str:
1702
+ required = {
1703
+ "id",
1704
+ "round",
1705
+ "role",
1706
+ "question",
1707
+ "normalizedTokens",
1708
+ "requestTuids",
1709
+ "chapterKey",
1710
+ "evidenceRole",
1711
+ "purpose",
1712
+ "expectedEvidence",
1713
+ "parentEvidenceRefs",
1714
+ }
1715
+ if not isinstance(question, dict) or set(question) != required or question.get("round") != round_number:
1716
+ raise ReportContractError("every round question must use the complete question contract")
1717
+ question_id = question["id"]
1718
+ if not isinstance(question_id, str) or not QUESTION_ID_PATTERN.fullmatch(question_id):
1719
+ raise ReportContractError("question id must use 1-64 ASCII letters, digits, dots, underscores, or hyphens")
1720
+ if not question_id.startswith(f"r{round_number}-"):
1721
+ raise ReportContractError("question id must start with the current round prefix")
1722
+ if not isinstance(question["role"], str) or question["role"] not in SUPPORTED_QUESTION_ROLES:
1723
+ raise ReportContractError("question role is invalid")
1724
+ value = question["question"]
1725
+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > MAX_QUESTION_CHARS:
1726
+ raise ReportContractError(f"question must be non-empty and at most {MAX_QUESTION_CHARS} characters")
1727
+ _validate_language_text(value, language, f"question {question_id}", source_terms)
1728
+ normalized_tokens = question["normalizedTokens"]
1729
+ if normalized_tokens is not None:
1730
+ _validate_question_tokens(normalized_tokens, f"question {question_id} normalizedTokens")
1731
+ _validate_tokens_in_analysis_scope(
1732
+ normalized_tokens,
1733
+ measure_props,
1734
+ dimension_props,
1735
+ time_dimensions,
1736
+ f"question {question_id} normalizedTokens",
1737
+ reject_multiple_time_dimensions=True,
1738
+ )
1739
+ if question["requestTuids"] != []:
1740
+ raise ReportContractError("question requestTuids must be an empty list for automatic model matching")
1741
+ if not isinstance(question["chapterKey"], str) or question["chapterKey"] not in chapter_keys:
1742
+ raise ReportContractError("question chapterKey must reference the approved chapterEvidencePlan")
1743
+ if not isinstance(question["evidenceRole"], str) or question["evidenceRole"] not in EVIDENCE_ROLES:
1744
+ raise ReportContractError("question evidenceRole is invalid")
1745
+ for field in ("purpose", "expectedEvidence"):
1746
+ _validate_language_text(question[field], language, f"question {question_id} {field}", source_terms)
1747
+ parents = question["parentEvidenceRefs"]
1748
+ if not isinstance(parents, list) or not all(isinstance(item, str) and item for item in parents):
1749
+ raise ReportContractError("parentEvidenceRefs must be a list of evidence references")
1750
+ if round_number == 1 and parents:
1751
+ raise ReportContractError("round 1 questions cannot have parent evidence")
1752
+ if round_number > 1 and (not parents or not set(parents).issubset(known_evidence)):
1753
+ raise ReportContractError("later-round questions must reference prior-round evidence")
1754
+ return question_id
1755
+
1756
+
1757
+ def _evidence_question_id(evidence_ref: Any, current_question_ids: set[str]) -> str:
1758
+ if not isinstance(evidence_ref, str) or ":" not in evidence_ref:
1759
+ raise ReportContractError("evidence references must belong to a question in the same round")
1760
+ question_id, _ = evidence_ref.rsplit(":", 1)
1761
+ if question_id not in current_question_ids:
1762
+ raise ReportContractError("evidence references must belong to a question in the same round")
1763
+ return question_id
1764
+
1765
+
1766
+ def _validate_claims(
1767
+ claims: Any,
1768
+ available_evidence: set[str],
1769
+ language: str,
1770
+ source_terms: frozenset[str],
1771
+ *,
1772
+ round_number: int,
1773
+ known_claim_ids: set[str],
1774
+ ) -> dict[str, dict[str, Any]]:
1775
+ if not isinstance(claims, list) or len(claims) < 2:
1776
+ raise ReportContractError("every completed round must contain at least two claims")
1777
+ validated: dict[str, dict[str, Any]] = {}
1778
+ for claim in claims:
1779
+ required = {"id", "kind", "text", "evidenceRefs", "confidence"}
1780
+ if not isinstance(claim, dict) or set(claim) != required:
1781
+ raise ReportContractError("every claim must use the complete claim contract")
1782
+ claim_id = claim["id"]
1783
+ if (
1784
+ not isinstance(claim_id, str)
1785
+ or not QUESTION_ID_PATTERN.fullmatch(claim_id)
1786
+ or not claim_id.startswith(f"r{round_number}-")
1787
+ or claim_id in known_claim_ids
1788
+ or claim_id in validated
1789
+ ):
1790
+ raise ReportContractError("claim ids must be globally unique safe identifiers with the current round prefix")
1791
+ if claim["kind"] not in {"fact", "inference", "recommendation", "limitation"}:
1792
+ raise ReportContractError("claim kind is invalid")
1793
+ if claim["confidence"] not in {"high", "medium", "low"}:
1794
+ raise ReportContractError("claim confidence is invalid")
1795
+ _validate_language_text(claim["text"], language, "claim text", source_terms)
1796
+ refs = claim["evidenceRefs"]
1797
+ if not isinstance(refs, list) or not all(isinstance(item, str) and item for item in refs) or len(refs) != len(set(refs)):
1798
+ raise ReportContractError("claim evidenceRefs must be a list of unique references")
1799
+ if not set(refs).issubset(available_evidence):
1800
+ raise ReportContractError("claim references unknown evidence")
1801
+ if claim["kind"] != "limitation" and not refs:
1802
+ raise ReportContractError("non-limitation claims require evidence")
1803
+ if claim["kind"] in {"inference", "recommendation"}:
1804
+ evidence_questions = {ref.rsplit(":", 1)[0] for ref in refs}
1805
+ if len(refs) < 2 or len(evidence_questions) < 2:
1806
+ raise ReportContractError("inference and recommendation claims require at least two evidence references from different questions")
1807
+ validated[claim_id] = copy.deepcopy(claim)
1808
+ return validated
1809
+
1810
+
1811
+ def _validate_round_three_axes(round_data: dict[str, Any]) -> None:
1812
+ allowed = round_data.get("allowedAnalysisAxes")
1813
+ used = round_data.get("usedAnalysisAxesBefore")
1814
+ new = round_data.get("newAnalysisAxes")
1815
+ if not all(isinstance(items, list) and all(isinstance(item, str) and item for item in items) for items in (allowed, used, new)):
1816
+ raise ReportContractError("round 3 must record allowed, used, and new analysis axes")
1817
+ if not set(new) or not set(new).issubset(set(allowed) - set(used)):
1818
+ raise ReportContractError("round 3 analysis axes must be allowed and previously unused")
1819
+
1820
+
1821
+ def _question_signature(question: dict[str, Any]) -> str:
1822
+ canonical = json.dumps(
1823
+ {"question": question["question"].strip(), "requestTuids": question["requestTuids"]},
1824
+ ensure_ascii=False,
1825
+ sort_keys=True,
1826
+ separators=(",", ":"),
1827
+ )
1828
+ return hashlib.sha256(canonical.encode()).hexdigest()
1829
+
1830
+
1831
+ def _content_by_id(content: Sequence[Any]) -> dict[str, dict[str, Any]]:
1832
+ result: dict[str, dict[str, Any]] = {}
1833
+ for pin in content:
1834
+ if not isinstance(pin, dict) or not isinstance(pin.get("i"), str) or not pin["i"]:
1835
+ raise ReportContractError("every existing pin must have a non-empty id")
1836
+ if pin["i"] in result:
1837
+ raise ReportContractError(f"duplicate existing pin id {pin['i']}")
1838
+ result[pin["i"]] = pin
1839
+ return result
1840
+
1841
+
1842
+ def _validate_card_signatures(
1843
+ content_by_id: dict[str, dict[str, Any]],
1844
+ card_ids: Sequence[str],
1845
+ manifest: dict[str, Any],
1846
+ ) -> None:
1847
+ signatures = manifest.get("cardSignatures")
1848
+ if not isinstance(signatures, dict) or set(signatures) != set(card_ids):
1849
+ raise ReportContractError("manifest cardSignatures must match assigned card ids")
1850
+ for card_id in card_ids:
1851
+ expected = signatures.get(card_id)
1852
+ _validate_expected_card_signature(expected, card_id)
1853
+ pin = content_by_id.get(card_id)
1854
+ if not isinstance(pin, dict) or _card_signature_from_pin(pin) != expected:
1855
+ raise ReportContractError(f"card signature mismatch for {card_id}")
1856
+
1857
+
1858
+ def _validate_expected_card_signature(signature: Any, card_id: str) -> None:
1859
+ if not isinstance(signature, dict):
1860
+ raise ReportContractError(f"card signature for {card_id} must be an object")
1861
+ required = {"data", "cardType", "pinboardTuids", "chartName"}
1862
+ if set(signature) != required:
1863
+ raise ReportContractError(f"card signature for {card_id} must contain data, cardType, pinboardTuids, and chartName")
1864
+ _validate_question_tokens(signature["data"], f"card signature for {card_id}")
1865
+ if (
1866
+ not isinstance(signature["pinboardTuids"], list)
1867
+ or not 0 <= len(signature["pinboardTuids"]) <= MAX_MODELS_PER_QUESTION
1868
+ or not all(isinstance(item, str) and item and len(item) <= MAX_MODEL_UID_CHARS for item in signature["pinboardTuids"])
1869
+ or len(signature["pinboardTuids"]) != len(set(signature["pinboardTuids"]))
1870
+ ):
1871
+ raise ReportContractError(f"card signature for {card_id} must contain zero to {MAX_MODELS_PER_QUESTION} unique report model uids")
1872
+ if not isinstance(signature["chartName"], str) or not signature["chartName"]:
1873
+ raise ReportContractError(f"card signature for {card_id} must contain a chart name")
1874
+
1875
+
1876
+ def _validate_question_tokens(tokens: Any, context: str) -> None:
1877
+ try:
1878
+ normalize_question_tokens(tokens)
1879
+ except ReportContractError as exc:
1880
+ raise ReportContractError(f"{context}: {exc}") from None
1881
+
1882
+
1883
+ def _validate_tokens_in_analysis_scope(
1884
+ tokens: Sequence[dict[str, Any]],
1885
+ measure_props: frozenset[str],
1886
+ dimension_props: frozenset[str],
1887
+ time_dimensions: frozenset[str],
1888
+ context: str,
1889
+ *,
1890
+ reject_multiple_time_dimensions: bool = False,
1891
+ ) -> None:
1892
+ """Reject out-of-scope fields and, for card-producing tokens, multiple time roots."""
1893
+ explicit_time_dimensions: set[str] = set()
1894
+ for token in tokens:
1895
+ prop = token["prop"]
1896
+ allowed_props: frozenset[str] | None = None
1897
+ base_prop = prop.split("=", 1)[0].split(".", 1)[0]
1898
+ if _MEASURE_PROP_PATTERN.fullmatch(base_prop):
1899
+ allowed_props = measure_props
1900
+ elif _DIMENSION_PROP_PATTERN.fullmatch(base_prop):
1901
+ allowed_props = dimension_props
1902
+ elif _TIME_DIMENSION_PROP_PATTERN.fullmatch(base_prop):
1903
+ allowed_props = time_dimensions
1904
+ explicit_time_dimensions.add(base_prop)
1905
+ elif _DATASET_PROP_PATTERN.fullmatch(base_prop):
1906
+ raise ReportContractError(f"{context} contains dataset prop {prop!r} outside the approved analysis scope")
1907
+ elif _FIELD_LIKE_PROP_PATTERN.match(prop):
1908
+ raise ReportContractError(f"{context} contains unrecognized field-like prop {prop!r} outside the approved analysis scope")
1909
+ if allowed_props is not None and base_prop not in allowed_props:
1910
+ raise ReportContractError(f"{context} contains field prop {prop!r} outside the approved analysis scope")
1911
+ if reject_multiple_time_dimensions and len(explicit_time_dimensions) > 1:
1912
+ raise ReportContractError(f"{context} contains more than one explicit time-dimension prop")
1913
+
1914
+
1915
+ def _source_terms_from_signatures(signatures: Any) -> frozenset[str]:
1916
+ """Collect only terms proven by the exact card data that final validation rechecks."""
1917
+ if not isinstance(signatures, dict) or not signatures:
1918
+ raise ReportContractError("manifest cardSignatures must be a non-empty object")
1919
+ terms: set[str] = set()
1920
+ for card_id, signature in signatures.items():
1921
+ if not isinstance(card_id, str) or not card_id:
1922
+ raise ReportContractError("card signature ids must be non-empty strings")
1923
+ _validate_expected_card_signature(signature, card_id)
1924
+ terms.update(token["word"] for token in signature["data"] if token["prop"] != "text" and _CJK_PATTERN.search(token["word"]))
1925
+ return frozenset(terms)
1926
+
1927
+
1928
+ def _card_signature_from_pin(pin: dict[str, Any]) -> dict[str, Any]:
1929
+ params = pin.get("params")
1930
+ return {
1931
+ "data": pin.get("data"),
1932
+ "cardType": _card_type(pin),
1933
+ "pinboardTuids": params.get("tuids") if isinstance(params, dict) else None,
1934
+ "chartName": params.get("chartName") if isinstance(params, dict) else None,
1935
+ }
1936
+
1937
+
1938
+ def _stable_pin_id(report_uid: str, chapter_key: str, role: str) -> str:
1939
+ value = f"datarc-analysis-report:{report_uid}:{chapter_key}:{role}"
1940
+ return hashlib.sha256(value.encode()).hexdigest()[:32]
1941
+
1942
+
1943
+ def _text_pin(pin_id: str, pin_type: int, delta: Any, allowed_link_origins: frozenset[str]) -> dict[str, Any]:
1944
+ _validate_delta(delta, allowed_link_origins)
1945
+ return {
1946
+ "i": pin_id,
1947
+ "key": pin_id,
1948
+ "type": pin_type,
1949
+ "data": copy.deepcopy(delta),
1950
+ }
1951
+
1952
+
1953
+ def _validate_delta(delta: Any, allowed_link_origins: frozenset[str] = frozenset()) -> None:
1954
+ if not isinstance(delta, dict) or not isinstance(delta.get("ops"), list) or not delta["ops"]:
1955
+ raise ReportContractError("text boxes must use a non-empty Quill Delta")
1956
+ for operation in delta["ops"]:
1957
+ if not isinstance(operation, dict) or not isinstance(operation.get("insert"), str):
1958
+ raise ReportContractError("every Quill operation must insert text")
1959
+ if _RAW_URL_PATTERN.search(operation["insert"]):
1960
+ raise ReportContractError("text boxes must not contain raw URLs")
1961
+ attributes = operation.get("attributes")
1962
+ if attributes is not None and not isinstance(attributes, dict):
1963
+ raise ReportContractError("Quill attributes must be an object")
1964
+ if isinstance(attributes, dict) and "link" in attributes:
1965
+ _validate_link(attributes["link"], allowed_link_origins)
1966
+
1967
+
1968
+ def _delta_text(delta: dict[str, Any]) -> str:
1969
+ return "".join(operation["insert"] for operation in delta["ops"])
1970
+
1971
+
1972
+ def _validate_link(link: Any, allowed_link_origins: frozenset[str]) -> None:
1973
+ if not isinstance(link, str) or not link:
1974
+ raise ReportContractError("link must be a non-empty string")
1975
+ parts = urlsplit(link)
1976
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
1977
+ raise ReportContractError("links must use http or https")
1978
+ if parts.username or parts.password:
1979
+ raise ReportContractError("links must not contain user info")
1980
+ if not allowed_link_origins:
1981
+ raise ReportContractError("text links are disabled by default")
1982
+ if _url_origin(parts) not in allowed_link_origins:
1983
+ raise ReportContractError("link origin is not explicitly allowlisted")
1984
+ if any(_JWT_PATTERN.fullmatch(unquote(segment)) for segment in parts.path.split("/") if segment):
1985
+ raise ReportContractError("link contains credentials or a signed secret")
1986
+ query_parts = list(parse_qsl(parts.query, keep_blank_values=True))
1987
+ if "?" in parts.fragment:
1988
+ query_parts.extend(parse_qsl(parts.fragment.split("?", 1)[1], keep_blank_values=True))
1989
+ elif "=" in parts.fragment:
1990
+ query_parts.extend(parse_qsl(parts.fragment, keep_blank_values=True))
1991
+ for key, value in query_parts:
1992
+ normalized = re.sub(r"[^a-z0-9]", "", key.casefold())
1993
+ is_signed_key = normalized.startswith(_SIGNED_LINK_KEY_PREFIXES) or normalized.endswith(_SIGNED_LINK_KEY_SUFFIXES)
1994
+ if normalized in _SENSITIVE_LINK_KEYS or is_signed_key or _JWT_PATTERN.search(value):
1995
+ raise ReportContractError("link contains credentials or a signed secret")
1996
+
1997
+
1998
+ def _validate_output_language(language: Any) -> str:
1999
+ if language not in SUPPORTED_OUTPUT_LANGUAGES:
2000
+ raise ReportContractError("login language must be zh-CN or en-US")
2001
+ return language
2002
+
2003
+
2004
+ def _validate_language_text(
2005
+ value: Any,
2006
+ language: str,
2007
+ field: str,
2008
+ source_terms: frozenset[str] = frozenset(),
2009
+ *,
2010
+ require_zh: bool = True,
2011
+ ) -> None:
2012
+ if not isinstance(value, str) or not value.strip():
2013
+ raise ReportContractError(f"{field} must be non-empty text")
2014
+ if _RAW_URL_PATTERN.search(value):
2015
+ raise ReportContractError(f"{field} must not contain a raw URL")
2016
+ narrative_only = value
2017
+ if language == "en-US":
2018
+ for source_term in sorted(source_terms, key=len, reverse=True):
2019
+ narrative_only = narrative_only.replace(source_term, "")
2020
+ has_cjk = bool(_CJK_PATTERN.search(narrative_only))
2021
+ if language == "en-US" and has_cjk:
2022
+ raise ReportContractError(f"{field} must use en-US")
2023
+ if language == "zh-CN" and require_zh and not has_cjk:
2024
+ raise ReportContractError(f"{field} must use zh-CN")
2025
+
2026
+
2027
+ def _validate_text_link_policy(policy: Any, runtime_report_origin: str | None) -> frozenset[str]:
2028
+ required = {"enabled", "userRequested", "reportOrigin", "approvedInternalOrigins", "allowedOrigins"}
2029
+ if not isinstance(policy, dict) or set(policy) != required:
2030
+ raise ReportContractError("textLinkPolicy must explicitly record the default no-link policy")
2031
+ enabled = policy["enabled"]
2032
+ user_requested = policy["userRequested"]
2033
+ report_origin = _normalize_allowed_origin(policy["reportOrigin"])
2034
+ approved = policy["approvedInternalOrigins"]
2035
+ origins = policy["allowedOrigins"]
2036
+ if not isinstance(enabled, bool) or not isinstance(user_requested, bool):
2037
+ raise ReportContractError("textLinkPolicy flags must be booleans")
2038
+ if not isinstance(approved, list) or not all(isinstance(item, str) and item for item in approved):
2039
+ raise ReportContractError("approvedInternalOrigins must be a list of origins")
2040
+ if not isinstance(origins, list) or not all(isinstance(item, str) and item for item in origins):
2041
+ raise ReportContractError("allowedOrigins must be a list of origins")
2042
+ approved_origins = frozenset(_normalize_allowed_origin(origin) for origin in approved)
2043
+ allowed_origins = frozenset(_normalize_allowed_origin(origin) for origin in origins)
2044
+ if not enabled:
2045
+ if user_requested or approved_origins or allowed_origins:
2046
+ raise ReportContractError("disabled textLinkPolicy cannot declare a request or link origins")
2047
+ return frozenset()
2048
+ if not user_requested:
2049
+ raise ReportContractError("text links require an explicit user request")
2050
+ if runtime_report_origin is None:
2051
+ raise ReportContractError("enabled text links require the trusted DATARC report origin")
2052
+ if report_origin != _normalize_allowed_origin(runtime_report_origin):
2053
+ raise ReportContractError("textLinkPolicy reportOrigin does not match the trusted DATARC report origin")
2054
+ if not allowed_origins:
2055
+ raise ReportContractError("enabled text links require allowlisted internal origins")
2056
+ if not allowed_origins.issubset({report_origin} | approved_origins):
2057
+ raise ReportContractError("allowed link origins must be same-origin or explicitly approved internal origins")
2058
+ return allowed_origins
2059
+
2060
+
2061
+ def _normalize_allowed_origin(origin: str) -> str:
2062
+ if not isinstance(origin, str) or not origin:
2063
+ raise ReportContractError("allowed link origins must be non-empty strings")
2064
+ parts = urlsplit(origin)
2065
+ if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password:
2066
+ raise ReportContractError("allowed link origins must be credential-free http(s) origins")
2067
+ if parts.path not in {"", "/"} or parts.query or parts.fragment:
2068
+ raise ReportContractError("allowed link origins must not contain a path, query, or fragment")
2069
+ return _url_origin(parts)
2070
+
2071
+
2072
+ def _url_origin(parts: Any) -> str:
2073
+ host = parts.hostname.casefold()
2074
+ if ":" in host:
2075
+ host = f"[{host}]"
2076
+ try:
2077
+ port = parts.port
2078
+ except ValueError as exc:
2079
+ raise ReportContractError("link contains an invalid port") from exc
2080
+ if port is not None and not ((parts.scheme == "http" and port == 80) or (parts.scheme == "https" and port == 443)):
2081
+ host = f"{host}:{port}"
2082
+ return f"{parts.scheme.casefold()}://{host}"
2083
+
2084
+
2085
+ def _interpretation_pins(manifest: dict[str, Any], sources: dict[str, dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
2086
+ configs = manifest.get("aiInterpretations", [])
2087
+ if not isinstance(configs, list):
2088
+ raise ReportContractError("aiInterpretations must be a list; provide the selected supplemental interpretations or omit it")
2089
+ card_ids = [card_id for chapter in manifest["chapters"] for card_id in chapter["cardIds"]]
2090
+ positions = {card_id: index for index, card_id in enumerate(card_ids)}
2091
+ declared_sources = {card_id: sources.get(card_id, {}) for card_id in card_ids}
2092
+ result: dict[str, list[dict[str, Any]]] = {}
2093
+ keys: set[str] = set()
2094
+ source_terms = _source_terms_from_signatures(manifest["cardSignatures"])
2095
+ for config in configs:
2096
+ if not isinstance(config, dict) or set(config) != {"key", "title", "sourcePinIds", "promptMode", "customPrompt"}:
2097
+ raise ReportContractError("AI interpretation requires key/title/sourcePinIds/promptMode/customPrompt; revise the manifest")
2098
+ key = config["key"]
2099
+ if not isinstance(key, str) or not key or key in keys:
2100
+ raise ReportContractError("AI interpretation keys must be non-empty and unique; assign each supplement its own key")
2101
+ keys.add(key)
2102
+ pin = _interpretation_pin(manifest["reportUid"], config, declared_sources)
2103
+ _validate_language_text(pin["title"], manifest["language"], f"AI interpretation title {key}", source_terms)
2104
+ last_source = max(pin["sourcePinIds"], key=positions.__getitem__)
2105
+ result.setdefault(last_source, []).append(pin)
2106
+ return result
2107
+
2108
+
2109
+ def _interpretation_pin(report_uid: str, config: dict[str, Any], sources: dict[str, dict[str, Any]]) -> dict[str, Any]:
2110
+ title = config["title"]
2111
+ if not isinstance(title, str) or not title.strip() or len(title) > 255:
2112
+ raise ReportContractError("AI interpretation title must contain 1 to 255 characters; revise the title")
2113
+ linked = config["sourcePinIds"]
2114
+ if (
2115
+ not isinstance(linked, list)
2116
+ or not 1 <= len(linked) <= 10
2117
+ or not all(isinstance(item, str) and item for item in linked)
2118
+ or len(set(linked)) != len(linked)
2119
+ or not set(linked).issubset(sources)
2120
+ ):
2121
+ raise ReportContractError("AI interpretation must link 1 to 10 unique evidence cards from this report; revise sourcePinIds")
2122
+ for source_id in linked:
2123
+ source = sources.get(source_id, {})
2124
+ card_type = _card_type(source)
2125
+ if (
2126
+ source.get("type") != 2
2127
+ or type(card_type) is not int
2128
+ or card_type not in INTERPRETATION_CARD_TYPES
2129
+ or source.get("interpretationSupported") is False
2130
+ ):
2131
+ raise ReportContractError(f"AI interpretation source {source_id} is unavailable; select a supported evidence card from this report")
2132
+ mode, prompt = config["promptMode"], config["customPrompt"]
2133
+ if not isinstance(mode, str) or mode not in {"default", "custom"} or not isinstance(prompt, str):
2134
+ raise ReportContractError("AI interpretation Prompt is invalid; select default or custom mode and provide a string")
2135
+ if mode == "default" and prompt != "":
2136
+ raise ReportContractError("Default AI interpretation must use an empty customPrompt; clear it to use the effective workspace template")
2137
+ if mode == "custom":
2138
+ if not prompt.strip() or len(prompt) > 30000:
2139
+ raise ReportContractError("Custom AI interpretation Prompt must contain 1 to 30000 characters; revise it or use default mode")
2140
+ try:
2141
+ for _, name, spec, conversion in string.Formatter().parse(prompt):
2142
+ if name is not None and (name not in INTERPRETATION_PROMPT_VARIABLES or spec or conversion):
2143
+ raise ValueError(name)
2144
+ except ValueError:
2145
+ raise ReportContractError(
2146
+ "Custom AI interpretation Prompt has an unsupported variable; use documented names and escape literal braces"
2147
+ ) from None
2148
+ pin = copy.deepcopy(config)
2149
+ key = pin.pop("key")
2150
+ return {"i": _stable_pin_id(report_uid, key, "ai-interpretation"), "type": 5, **pin}
2151
+
2152
+
2153
+ def _build_layouts(content: Sequence[dict[str, Any]]) -> dict[str, list[dict[str, int | str]]]:
2154
+ desktop: list[dict[str, int | str]] = []
2155
+ y = 0
2156
+ index = 0
2157
+ while index < len(content):
2158
+ pin = content[index]
2159
+ height = _pin_height(pin)
2160
+ if _is_half_width_card(pin):
2161
+ desktop.append({"i": pin["i"], "x": 0, "y": y, "w": 6, "h": height})
2162
+ if index + 1 < len(content) and _is_half_width_card(content[index + 1]):
2163
+ second = content[index + 1]
2164
+ second_height = _pin_height(second)
2165
+ desktop.append({"i": second["i"], "x": 6, "y": y, "w": 6, "h": second_height})
2166
+ y += max(height, second_height)
2167
+ index += 2
2168
+ continue
2169
+ y += height
2170
+ index += 1
2171
+ continue
2172
+ desktop.append({"i": pin["i"], "x": 0, "y": y, "w": 12, "h": height})
2173
+ y += height
2174
+ index += 1
2175
+
2176
+ mobile: list[dict[str, int | str]] = []
2177
+ y = 0
2178
+ for pin in content:
2179
+ height = _pin_height(pin)
2180
+ mobile.append({"i": pin["i"], "x": 0, "y": y, "w": 2, "h": height})
2181
+ y += height
2182
+ return {"sm": desktop, "xxs": mobile}
2183
+
2184
+
2185
+ def _pin_height(pin: dict[str, Any]) -> int:
2186
+ if pin.get("type") == 4:
2187
+ return 2
2188
+ if pin.get("type") == 5:
2189
+ return INTERPRETATION_CARD_HEIGHT
2190
+ if pin.get("type") == 2:
2191
+ card_type = _card_type(pin)
2192
+ if card_type == 1:
2193
+ return NUMERIC_CARD_HEIGHT
2194
+ if card_type == 13:
2195
+ return CONTRIBUTION_CARD_HEIGHT
2196
+ return DEFAULT_CARD_HEIGHT
2197
+ return 4
2198
+
2199
+
2200
+ def _is_half_width_card(pin: dict[str, Any]) -> bool:
2201
+ return pin.get("type") == 2 and _card_type(pin) != 13
2202
+
2203
+
2204
+ def _card_type(pin: dict[str, Any]) -> Any:
2205
+ params = pin.get("params") or {}
2206
+ return params.get("cardType", params.get("card_type")) if isinstance(params, dict) else None
2207
+
2208
+
2209
+ def _read_json(path: Path, *, max_bytes: int = MAX_JSON_INPUT_BYTES) -> Any:
2210
+ if not path.is_file():
2211
+ raise ReportContractError("input file does not exist")
2212
+ if path.stat().st_size > max_bytes:
2213
+ raise ReportContractError(f"input file exceeds {max_bytes // (1024 * 1024)} MiB")
2214
+ try:
2215
+ return json.loads(path.read_text(encoding="utf-8"))
2216
+ except (OSError, UnicodeError, json.JSONDecodeError):
2217
+ raise ReportContractError("input file must contain UTF-8 JSON") from None
2218
+
2219
+
2220
+ def _write_json(value: Any) -> None:
2221
+ sys.stdout.write(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
2222
+
2223
+
2224
+ if __name__ == "__main__":
2225
+ raise SystemExit(main())