Coverage for app / documents / spec.py: 99%

100 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2The document schema — what a report *is*, independent of how it is drawn. 

3 

4It mirrors the report shape svc-core's built-in report skills return 

5(``REPORT_FIELDS`` in ``system_resources/skillsets.py``), so a skill's output 

6and a ``render_document`` call describe the same thing. 

7 

8Every field is bounded. A document comes from a model (the tool) or from 

9stored model output (a skill run, a chat message), so this is the boundary 

10where it is checked: text is stripped of control characters, lists and 

11strings are capped, and nothing here is ever interpreted as markup — the 

12renderer escapes all of it. 

13 

14Two shapes: :class:`DocumentSpec` is what a model (or a skill's outputs) 

15writes; :class:`StoredDocument` is what the fence carries — the same report 

16plus the copies of its images the ``render_document`` tool fetched and 

17stored (``images.py``). The model never fills ``images``: it is not in the 

18tool's schema, and the copies are named by the hash of the bytes the tool 

19stored, never by anything a model wrote. 

20""" 

21 

22from __future__ import annotations 

23 

24import json 

25import re 

26from typing import Annotated, Any, Literal 

27from urllib.parse import urlsplit 

28 

29from pydantic import ( 

30 BaseModel, 

31 ConfigDict, 

32 Field, 

33 OnErrorOmit, 

34 StringConstraints, 

35 field_validator, 

36 model_validator, 

37) 

38 

39from app.util import vocab 

40from app.util.document_images import ASSET_ID 

41 

42from .formats import ACCEPTED_FORMATS 

43from .visuals import VisualKind 

44 

45#: The fence language fe-core renders as a document card. 

46DOCUMENT_FENCE_LANGUAGE = "document" 

47 

48#: How well evidence supports a conclusion — the scale a document states and 

49#: every role agent's prompt asks for. Strongest first, the order prompts list it. 

50Confidence = Literal["high", "medium", "low"] 

51 

52_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]") 

53 

54MAX_BODY_CHARS = 60_000 

55 

56#: The most images one document carries. A constant, not a setting: a stored 

57#: document must validate the same on every deployment. 

58MAX_DOCUMENT_IMAGES = 20 

59 

60#: The longest image link kept. 

61MAX_IMAGE_SRC_CHARS = 2048 

62 

63Line = Annotated[str, StringConstraints(strip_whitespace=True, max_length=1000)] 

64 

65#: How a visual goes into a body: the fence its render tool returns, which 

66#: the card and the PDF both draw (``visuals``) and ``render_document`` 

67#: checks again with that tool. 

68VISUALS_IN_BODY = ( 

69 "To show a visual (a " 

70 + vocab.one_of(tuple(f"```{kind}" for kind in vocab.values(VisualKind)), quote="") 

71 + " fence), call its render tool first and put the fence it returns in the " 

72 "body where it belongs; the card and the PDF draw it." 

73) 

74 

75 

76def _clean(value: Any) -> Any: 

77 """Drop control characters (keeping tab and newline) from any string.""" 

78 if isinstance(value, str): 

79 return _CONTROL.sub("", value) 

80 if isinstance(value, list): 

81 return [_clean(v) for v in value] 

82 return value 

83 

84 

85class DocumentSpec(BaseModel): 

86 """A structured report. Unknown keys are ignored rather than refused, so a 

87 skill's outputs — which carry fields of their own — validate as-is.""" 

88 

89 model_config = ConfigDict(extra="ignore") 

90 

91 title: str = Field(min_length=1, max_length=200, description="The report's title.") 

92 subtitle: str | None = Field( 

93 default=None, max_length=300, description="Optional one-line subtitle." 

94 ) 

95 summary: str | None = Field( 

96 default=None, 

97 max_length=3000, 

98 description="An executive summary of two to four sentences.", 

99 ) 

100 key_findings: list[Line] = Field( 

101 default_factory=list, 

102 max_length=25, 

103 description="The most important findings, one sentence each.", 

104 ) 

105 body: str = Field( 

106 default="", 

107 max_length=MAX_BODY_CHARS, 

108 description=( 

109 "The report in Markdown: ## headings, paragraphs, bullet and " 

110 "numbered lists, **bold**, *italic*, tables and links. Cite each " 

111 "source inline by the id it was shown with, e.g. [S3]; the " 

112 "sources list is built from those ids. To show an image, write " 

113 "![what it shows](https://…) with a direct link to a " 

114 f"{vocab.one_of(ACCEPTED_FORMATS, quote='')} image you found — " 

115 "an open-licence one, Wikimedia Commons first; never a placeholder " 

116 "or a stock-photo library's preview, which is refused. Each image " 

117 "is fetched and embedded, and the tool tells you any it could not " 

118 "embed. " + VISUALS_IN_BODY + " HTML is not rendered." 

119 ), 

120 ) 

121 sources: list[Line] = Field( 

122 default_factory=list, 

123 max_length=100, 

124 description=( 

125 "Leave empty when the text cites source ids: the list is built " 

126 "from them. Otherwise, numbered sources as 'Title — URL (date)', " 

127 "in citation order." 

128 ), 

129 ) 

130 confidence: Confidence | None = Field( 

131 default=None, description="How well the evidence supports the conclusions." 

132 ) 

133 open_questions: list[Line] = Field( 

134 default_factory=list, 

135 max_length=25, 

136 description="What the evidence could not settle.", 

137 ) 

138 

139 @model_validator(mode="before") 

140 @classmethod 

141 def _null_is_absent(cls, data: Any) -> Any: 

142 """A null field is a missing one — a structured model output often 

143 sends ``null`` for what it has nothing to say about.""" 

144 if isinstance(data, dict): 

145 return {k: v for k, v in data.items() if v is not None} 

146 return data 

147 

148 @field_validator("*", mode="before") 

149 @classmethod 

150 def _strip_control(cls, value: Any) -> Any: 

151 return _clean(value) 

152 

153 @field_validator("key_findings", "sources", "open_questions") 

154 @classmethod 

155 def _drop_blank(cls, value: list[str]) -> list[str]: 

156 return [v for v in value if v] 

157 

158 def filename(self, suffix: str = ".pdf") -> str: 

159 """A safe download name derived from the title.""" 

160 stem = re.sub(r"[^A-Za-z0-9]+", "-", self.title).strip("-")[:80] 

161 return f"{stem or 'document'}{suffix}" 

162 

163 

164#: The fields a node writes to produce a document, as a skill-graph 

165#: ``output_schema`` — the same shape as svc-core's built-in report skills 

166#: (``REPORT_FIELDS``) and, field for field, :class:`DocumentSpec`. 

167REPORT_OUTPUT_SCHEMA: list[dict[str, Any]] = [ 

168 {"name": "title", "type": "string", "required": True, 

169 "description": "A specific, descriptive title."}, 

170 {"name": "summary", "type": "string", "required": True, 

171 "description": "An executive summary of two to four sentences."}, 

172 {"name": "key_findings", "type": "array", "items": "string", 

173 "description": "The most important findings, one sentence each."}, 

174 {"name": "body", "type": "string", "required": True, 

175 "description": "The full report in Markdown under ## headings, citing " 

176 "each source inline by the id it was shown with, e.g. [S3]. An image is " 

177 "![what it shows](https://…) with a direct link to a " 

178 f"{vocab.one_of(ACCEPTED_FORMATS, quote='')} image found in the " 

179 "material, never a placeholder. A visual is the fence its render tool " 

180 "returns, placed where it belongs."}, 

181 {"name": "sources", "type": "array", "items": "string", 

182 "description": "Leave empty when the report cites source ids: the list is " 

183 "built from them."}, 

184 {"name": "confidence", "type": "enum", "values": ["low", "medium", "high"], 

185 "required": True, 

186 "description": "How well the evidence supports the conclusions."}, 

187 {"name": "open_questions", "type": "array", "items": "string", 

188 "description": "What the evidence could not settle."}, 

189] # fmt: skip 

190 

191 

192class DocumentImage(BaseModel): 

193 """A stored copy of an image a document's body shows. Written by the 

194 render_document tool from what it fetched and stored, never by a model.""" 

195 

196 model_config = ConfigDict(extra="ignore") 

197 

198 #: The image's link exactly as the body's Markdown parser normalised it 

199 #: (``markdown.image_refs``) — the key the renderer and the card match on. 

200 src: str = Field(max_length=MAX_IMAGE_SRC_CHARS) 

201 #: The stored copy: the SHA-256 of its bytes (``document_images``). 

202 asset: str = Field(pattern=ASSET_ID.pattern) 

203 media_type: Literal["image/png", "image/jpeg"] 

204 width: int = Field(ge=1, le=4096) 

205 height: int = Field(ge=1, le=4096) 

206 

207 @field_validator("src") 

208 @classmethod 

209 def _https_link(cls, value: str) -> str: 

210 parts = urlsplit(value) 

211 if ( 

212 parts.scheme != "https" 

213 or not parts.hostname 

214 or "@" in parts.netloc 

215 or any(c.isspace() for c in value) 

216 ): 

217 raise ValueError("not an https link") 

218 return value 

219 

220 

221class StoredDocument(DocumentSpec): 

222 """A document as its fence carries it: the report, and the stored copies 

223 of the images its body shows.""" 

224 

225 images: list[OnErrorOmit[DocumentImage]] = Field(default_factory=list) 

226 

227 @field_validator("images", mode="before") 

228 @classmethod 

229 def _bounded(cls, value: Any) -> Any: 

230 # A stored fence is old data as often as new: anything that is not a 

231 # list of entries is no images, and a bad entry is dropped by 

232 # OnErrorOmit — the image is drawn as its alt text, the document 

233 # still renders. 

234 if not isinstance(value, list): 

235 return [] 

236 entries = [v for v in value if isinstance(v, (dict, DocumentImage))] 

237 return entries[:MAX_DOCUMENT_IMAGES] 

238 

239 @field_validator("images") 

240 @classmethod 

241 def _one_per_link(cls, value: list[DocumentImage]) -> list[DocumentImage]: 

242 seen: set[str] = set() 

243 kept: list[DocumentImage] = [] 

244 for image in value: 

245 if image.src not in seen: 

246 seen.add(image.src) 

247 kept.append(image) 

248 return kept 

249 

250 def image_for(self, src: str) -> DocumentImage | None: 

251 """The stored copy of the image the body links as ``src``.""" 

252 return next((i for i in self.images if i.src == src), None) 

253 

254 

255_FENCE_RE = re.compile(rf"```{DOCUMENT_FENCE_LANGUAGE}[ \t]*\n(.*?)\n```", re.DOTALL) 

256 

257 

258def document_fence(spec: DocumentSpec) -> str: 

259 """The ```document fence for ``spec`` — compact JSON, validated first. A 

260 :class:`StoredDocument`'s images ride in it; with none, it is exactly the 

261 report's fence.""" 

262 payload = spec.model_dump(exclude_none=True, exclude_defaults=True) 

263 payload["title"] = spec.title 

264 return ( 

265 f"```{DOCUMENT_FENCE_LANGUAGE}\n" 

266 f"{json.dumps(payload, ensure_ascii=False, separators=(',', ':'))}\n```" 

267 ) 

268 

269 

270def parse_document_fences(text: str) -> list[StoredDocument]: 

271 """Every valid document in ``text``, in order. Invalid fences are skipped, 

272 never repaired.""" 

273 documents: list[StoredDocument] = [] 

274 for match in _FENCE_RE.finditer(text or ""): 

275 try: 

276 documents.append(StoredDocument.model_validate(json.loads(match.group(1)))) 

277 except (ValueError, TypeError): 

278 continue 

279 return documents