Files
rengine/reports/base.py
T
Yogesh OjhaandClaude Opus 5 424e6d6e23 feat(reports): a document engine, not an export
reNgine 2 could produce a PDF. This produces a deliverable, and it is built
the way scan engines are built: sections are plug-and-play directories under
reports/, each with a pydantic config model that IS the source of truth. That
model feeds GET /reports/catalog, the builder renders its own form from it, and
the API validates against it. Adding a section is a directory. Scan Engine is to
stages what Report Template is to sections.

WeasyPrint 69 renders it, chosen over Chromium and Typst after measuring what
each can actually do. Only real CSS Paged Media gives a table of contents with
true page numbers, running headers, a PDF outline and footnotes; SysReptor
reaches the same verdict and pipes Chromium's HTML into WeasyPrint for exactly
that reason. reNgine drops the Chromium hop because it templates in Jinja and
draws its charts as SVG in Python, so a browser buys nothing and costs 400 MB
per report. Typst was rejected because a user-uploadable theme would then have
to be Typst code rather than CSS.

A theme is data. shared/definitions/report_theme.py is the schema, six themes
ship as YAML, and a user uploads their own; there is no markup in a theme, so
there is no injection surface. Fonts are vendored so an offline instance still
renders in Latin, Greek and Cyrillic.

Everything the document claims is computed once, in reports/analysis/engine.py:
a posture score whose every deduction is named, weaknesses ranked by the signals
behind the rank rather than severity alone, attack paths that chain observations
into a route, a remediation plan ordered by risk removed, per-dimension change
against the previous run, and caveats that state what was never assessed. Two
narrators read that one brief. Without AI the report still argues its case; with
AI the prose is better and the model never sees a row, only the brief, capped and
cached per check. An AI failure falls back and the report still completes.

Generation is a job. POST /reports queues, the worker walks progress over SSE,
and four formats come out of one render: PDF, self-contained HTML, Markdown and
JSON. The estimate reads each section's own limits, so the page count it promises
is close to the one it delivers.

AI moves out of Settings into its own top-level page: connection, a model per
tier, what it may be used for, what it has cost, and the narrative cache.

Verified on a 1,379-host gov.cy scan: 124 pages in 19.5s across 19 sections,
all six themes, and a broken key still producing a complete report.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017f2Mf2HGwFaTRnui4UxpRd
2026-09-06 11:45:51 +05:30

123 lines
3.4 KiB
Python

"""A section is a unit of the document: what it needs, what it configures, what it renders."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING, ClassVar
from reports.config import SectionConfig
from shared.definitions.reports import ReportSpec, SectionGroup
if TYPE_CHECKING:
from reports.analysis.brief import ReportBrief
from reports.data.source import ReportSource
from reports.narrate.base import Narrator
from shared.definitions.report_theme import ThemeTokens
@dataclass
class Counters:
figure: int = 0
table: int = 0
def next_figure(self) -> int:
self.figure += 1
return self.figure
def next_table(self) -> int:
self.table += 1
return self.table
@dataclass
class RenderContext:
spec: ReportSpec
theme: ThemeTokens
data: ReportSource
brief: ReportBrief
narrator: Narrator
now: datetime
counters: Counters = field(default_factory=Counters)
preview: bool = False
warnings: list[str] = field(default_factory=list)
@property
def style(self):
return self.spec.style
@property
def branding(self):
return self.spec.branding
@property
def palette(self) -> dict[str, str]:
colour = self.theme.color
return {
"ink": colour.ink,
"ink_soft": colour.ink_soft,
"ink_faint": colour.ink_faint,
"surface": colour.surface,
"accent": colour.accent,
"accent_ink": colour.accent_ink,
"rule": colour.rule,
}
def sev(self, severity: str | None) -> str:
table = self.theme.color.severity
return table.get((severity or "unknown").lower(), self.theme.color.ink_faint)
def hue(self, index: int) -> str:
scale = self.theme.color.chart or [self.theme.color.accent]
return scale[index % len(scale)]
def warn(self, message: str) -> None:
if message not in self.warnings:
self.warnings.append(message)
@dataclass
class SectionOutput:
"""What one section contributes to the document."""
html: str
title: str = ""
in_toc: bool = True
anchor: str = ""
page_break: str = "auto"
bookmarks: list[tuple[str, str]] = field(default_factory=list)
class Section(ABC):
name: ClassVar[str]
title: ClassVar[str]
description: ClassVar[str] = ""
group: ClassVar[str] = SectionGroup.SUMMARY.value
requires: ClassVar[frozenset[str]] = frozenset()
repeatable: ClassVar[bool] = False
default_enabled: ClassVar[bool] = True
in_toc: ClassVar[bool] = True
page_break: ClassVar[str] = "auto"
template: ClassVar[str] = ""
config_model: ClassVar[type[SectionConfig]] = SectionConfig
@classmethod
def template_name(cls) -> str:
return cls.template or f"{cls.name}/section.html"
@classmethod
def defaults(cls) -> dict:
return cls.config_model().model_dump()
@classmethod
def schema(cls) -> dict:
return cls.config_model.model_json_schema()
def available(self, ctx: RenderContext) -> bool:
return not self.requires or bool(self.requires & ctx.data.covered_dimensions)
@abstractmethod
def build(self, ctx: RenderContext, cfg: SectionConfig) -> dict | None:
"""Template variables, or None when the section has nothing to say."""