# Report Studio

Reports built from the research itself: a template's sections, one
section per explicitly chosen finding, the requests that prove it and
notes embedded by reference, rendered to Markdown or a printable HTML
page (PDF is the browser printing that page), validated before export,
reviewed with comments, made final with a frozen snapshot. One backend
service (`app/services/reports/`) serves REST and MCP; the interface is
the Reports page (see Interface).

Everything is vault-scoped: a report, section, comment or snapshot of
another vault answers exactly like one that does not exist, and a report
can only reach its own vault's findings, requests and notes.

Phantom never submits a report anywhere. External submission is a
separate, planned capability that will need explicit approval.

## Model

**Report** (`reports`, cascades from the vault)

| Field | Notes |
|---|---|
| `title` | 1-200 characters, one line; the template's title when omitted |
| `template` | `bug_bounty`, `pentest`, `executive` or `custom` |
| `status` | `draft`, `in_review` or `final` (locked) |
| `audience` | Default view: `technical` or `executive` |
| `branding` | `org_name`, `accent_color` (`#rrggbb` only), `footer` |
| `meta` | `client`, `program`, `tester`, `start_date`, `end_date`, `version` (`1.0` by default) |
| `actor`, `finalized_at` | Last writer (`user` / `agent`); time it last became final |

**Section** (`report_sections`, cascades from the report): `kind`
(`summary`, `scope`, `methodology`, `findings`, `finding`, `evidence`,
`impact`, `limitations`, `remediation`, `appendix`, `retest`, `custom`),
`position`, `title`, `body` (Markdown up to 256 KiB with `[[kind:id]]`
references), `included`, `finding_id`, `note_id`, `evidence_flow_ids`
(at most 20), `actor`.

**Snapshot** (`report_snapshots`): `number` (1, 2, ... per report),
`reason` (`manual` or `final`), `label`, `status`, `title`, `document`
(the resolved report as JSON), `markdown` (technical view), `checksum`
(SHA-256 of the Markdown), `size`, `finding_ids`, `actor`, `created_at`.
Never changed after it is written.

**Comment** (`report_comments`): `section_id` (null for the whole
report, cascades from the section), `author` (`user` / `agent`), `body`
(up to 10,000 characters), `resolved`, `resolved_at`.

Migration: `c8e2f4a6b9d1_research_reports` (after `d5a9c3e7f1b4`).
Additive.

### Data by reference

A finding section stores only the finding's id. Its title, severity,
status, CVSS, CWE / CVE, asset, description, steps (PoC), remediation
and scanner matches are read live on every read and render, so fixing a
finding fixes every draft that shows it. Evidence requests and embedded
notes work the same way, as do `[[kind:id]]` references in any body
(the note syntax, `docs/guides/notes.md`). Deleting an object never touches a
report: it reads as missing and validation flags it. A snapshot is the
only copy: it freezes the resolved document, so it renders the same
forever.

Files attached to a finding as evidence (`docs/files/index.md`) render
under **Evidence files** in its section: name, pinned revision, size,
SHA-256 and the note. They show the revision that was pinned, not the
file as it is now, and they count as evidence for `no_evidence`.

## Templates

| Template | Sections (required in bold) | Required details |
|---|---|---|
| `bug_bounty` | **Summary**, **Severity** (findings table), finding sections, **Impact**, Remediation, References | program, version |
| `pentest` | **Executive summary**, **Scope** (from the vault's scope), **Methodology** (OWASP WSTG, PTES), **Findings overview**, finding sections, **Limitations**, Remediation roadmap, Retest summary (excluded), Appendix | client, tester, start_date, end_date, version |
| `executive` | **Summary**, **Risk overview**, Business impact, Recommendations | client, version |
| `custom` | Summary, Findings | version |

Each starts with written guidance; validation warns while a section
still holds it. Finding sections add the template's finding starter
(impact and triager notes for bug bounty, business impact for pentest)
below the live fields.

## Generation

`POST /reports` with `template`, `finding_ids` (at most 200),
`note_ids` (at most 50), `evidence: [{finding_id, flow_ids}]`,
`auto_evidence` (default true), `branding`, `meta`:

- template sections in order; the scope section lists the vault's in
  and out patterns and references the targets of the chosen findings;
- one finding section per chosen finding after the findings overview,
  most severe first, titled after the finding;
- evidence: the chosen requests, then (with `auto_evidence`) requests
  that the finding's own text or notes referencing it mention, existing
  ones only;
- each chosen note embedded as a section before the appendix.

A finding, request or note outside the vault is refused (`422` naming
the ids) and nothing is stored.

## Rendering

Both formats render the same sections. Finding sections are numbered
`F-01`, `F-02`... in report order.

- **Technical** view: every included section. **Executive**: summary
  and findings tables only.
- `findings` sections add the severity counts and findings table,
  `retest` a retest table (resolved → Fixed, accepted / won't fix →
  Risk accepted, false positive → Not an issue, else Open), `evidence`
  every finding's requests, `appendix` a **Sources** table: each
  finding's Phantom id and evidence request ids (provenance).
- References become the text a reader sees (alias, else label, else
  `(removed kind)`); code is left as written.
- **Markdown** starts with a YAML front matter (title, template, status,
  details, generated time, snapshot number).
- **HTML** is one standalone page: a safe Markdown subset converter
  (`app/core/reports/html_*.py`) escapes every character of the text,
  never passes raw HTML through, and links only `http(s)` and `mailto`
  URLs (`noopener noreferrer nofollow`). The page's
  Content-Security-Policy allows no script, frame, font or remote
  resource. Branding header and footer, severity colours, print CSS: A4,
  each finding on a new page, the footer on every page.
- **PDF**: the interface opens the HTML page and uses the browser's
  print dialog. The backend has no PDF engine.
- **DOCX** (`format=docx`, **Word document** in the export menu): a Word
  file built from the same Markdown as the Markdown export, so the view
  and credential masking apply the same way. Headings, paragraphs,
  bullet and numbered lists (task items with a box), tables with a header
  row, code in a monospace font, quotes, bold, italics, inline code and
  links (the address after the text) use Word's own styles, so the
  client's template can restyle them. DOCX is a download only; preview a
  report as Markdown or HTML (`app/core/reports/docx.py`).

## Validation

`GET /validate` returns `{ok, errors, warnings}`; each issue has
`level`, `code`, `message`, `section_id` and `details`.

| Code | Level |
|---|---|
| `missing_section`, `excluded_section`, `empty_section` (required ones) | error |
| `missing_metadata` (template's required details) | error |
| `no_findings` | error for bug bounty, else warning |
| `missing_finding`, `missing_evidence`, `missing_note`, `broken_reference` | error |
| `rejected_finding` (false positive, duplicate) | error |
| `unvalidated_finding` (new, triaging), `duplicate_finding`, `no_evidence` | warning |
| `secrets` (counted per section with the shared detector) | warning; error when the export policy reveals |
| `starter_text`, `open_comments` | warning |

## Review and lifecycle

`draft → in_review → final`; `in_review` and `final` go back to
`draft` (reopen). Making a report final validates it (`409` with the
errors unless `force`), stores a `final` snapshot and locks it: changing
the report or any section answers `409 invalid_state` until it is
reopened. Comments can be added to a final report. Snapshots on demand
(`POST /snapshots`, optional `{label}`), at most 200 per report.

Every move through review is kept as the report's approval history
(`GET /history`, and in the Snapshots drawer): from and to which status,
who moved it (user or agent), whether finalising was forced past
validation errors, and the reviewer's note (`note` in the status change,
up to 2,000 characters). Staying in the same status adds nothing.

### Section history

A section keeps its earlier versions: before its title or body changes,
the version being replaced is stored with who wrote it and when. Edits by
the same writer within ten minutes of the last kept version add nothing,
so autosave while typing keeps one version per writing session, not one
per keystroke; a change by someone else (an agent appending a paragraph,
for example) or after a pause always keeps one. Restoring a version puts
its title and body back and keeps the text it replaces first, so a
restore can be undone. At most 50 versions per section, oldest dropped
first; they are deleted with the section. A final report lists versions
but refuses restores (`409`). In the studio, **History** above the
section title lists the versions (right click: view, copy text,
restore).

A section save that started from an older version than the stored one
(an agent or another window saved meanwhile) is refused with 409
`stale`; the studio stops autosaving and offers **Keep mine**, which
saves your text and always keeps the replaced one as a version, or
**Load theirs**. The stored time counts whole seconds on SQLite, so two
saves within the same second are not told apart.

## Export

`GET /export?format=markdown|html&view=&reveal=&force=` validates first
(`409` with the errors unless `force=true`), then applies the export
redaction policy exactly as note exports do: `redact` (default) masks
credentials in every text of the document and refuses `reveal=true`
(`403`); `reveal` keeps them unless `reveal=false`; `ask` needs
`reveal=true|false` (`409` without). Headers: `X-Phantom-Redacted`,
`X-Phantom-Checksum` (SHA-256 of the file), `Content-Security-Policy`,
`nosniff`. `GET /snapshots/{id}/export` renders a frozen version under
the same policy. `GET /render` is a JSON preview as written, for the
interface (show HTML only in a sandboxed frame).

## REST

Paths are under `/api/v1/vaults/{vault_id}/reports`.

| Route | Body / query | Response |
|---|---|---|
| `GET` | | `[ReportSummary]` newest change first |
| `POST` | `ReportCreate` (above) | `201 Report` |
| `GET /templates` | | `[{name, title, description, audience, required_meta, finding_body, sections}]` |
| `GET /{id}` / `PATCH /{id}` / `DELETE /{id}` | `{title?, audience?, branding?, meta?}` (only sent keys; `null` clears) | `Report` / `204` |
| `POST /{id}/status` | `{status, force?}` | `Report` |
| `POST /{id}/sections` | `{kind, title?, body?, included?, finding_id?, note_id?, evidence_flow_ids?, position?}` | `201 Section` |
| `PUT /{id}/sections/order` | `{section_ids}` (every id once) | `Report` |
| `PATCH /{id}/sections/{sid}` / `DELETE` | `{title?, body?, included?, note_id?, evidence_flow_ids?}` | `Section` / `204` |
| `POST /{id}/sections/{sid}/refresh` | | `Section`: title from the finding, newly linked evidence added |
| `GET /{id}/sections/{sid}/revisions` | | `[{id, title, body, actor, written_at, created_at}]` newest first |
| `POST /{id}/sections/{sid}/revisions/{rid}/restore` | | `Section` with the version's title and body |
| `GET /{id}/comments` | `section_id`, `resolved` | `[Comment]` oldest first |
| `POST /{id}/comments` / `PATCH /{cid}` / `DELETE /{cid}` | `{body, section_id?}` / `{body?, resolved?}` | `Comment` / `204` |
| `GET /{id}/validate` | | `{ok, errors, warnings}` |
| `GET /{id}/render` | `format`, `view` | `{format, view, content, checksum, size}` |
| `GET /{id}/export` | `format`, `view`, `reveal`, `force` | file |
| `GET /{id}/snapshots` / `POST` / `GET /{snid}` / `GET /{snid}/export` | `{label?}` | `[SnapshotSummary]` / `201 Snapshot` (with `markdown`) / file |

`Report` is the summary (`locked`, `section_count`, `finding_count`,
`open_comments`, `snapshot_count`, ...) with `sections`; each section
carries its resolved `links` and, for a finding section, `finding:
{id, exists, title, severity, status, cvss_score}`.

## Events

`report.updated` `{action, report}` with the summary (never section or
comment text); actions `created`, `updated`, `section_created`,
`section_updated`, `section_deleted`, `sections_reordered`,
`comment_created`, `comment_updated`, `comment_deleted`,
`snapshot_created`, `status_changed`. `report.deleted` `{id, vault_id}`.

## MCP

`report_templates`, `report_list`, `report_get`, `report_create`,
`report_section_add`, `report_section_update` (with `append`),
`report_section_revisions` (read),
`report_comment_add`, `report_validate`, `report_render`. Writes record
`actor: agent` / `author: agent`; every result goes through the MCP
redaction policy (`reveal_secrets` where allowed); text holding a
redaction placeholder is refused. Agents draft and comment; finalising,
reopening, export, snapshots, reorder, refresh, resolving and delete
have no tools, and the services refuse finalising, reopening and export
inside an agent call (`permission_denied`).

## Limits

`app/core/reports/limits.py`: 500 reports per vault, 300 sections per
report, 256 KiB per body, 200 findings and 50 notes per report, 20
evidence requests per finding, 2,000 comments, 200 snapshots, 200
characters per detail.

## Interface

Rail entry **Reports** (`G R`, also in the command palette); `?report=<id>`
opens a report. Code: `views/ReportsView.vue`, `components/reports/`,
`stores/reports.ts` (list, open report, sections), `stores/reportReview.ts`
(comments, validation, snapshots), pure helpers in `utils/reports/`
(tested in `reports.spec.ts`).

- **Sidebar.** Reports grouped Draft, In review, Final (newest change
  first), each with its template, finding count, open comments, a lock
  when final, "Agent" when an agent wrote last, and the relative time
  (exact on hover). Search matches every word over title, template,
  client, program, tester and organisation. "+" starts a new report.
  Right click a report (or Shift+F10): Open, Rename in place (F2; not
  when final), the status move that needs no validation (Submit for
  review, Back to draft, Reopen as draft; Finalize stays in the header),
  Export technical view (Markdown, HTML, PDF), Attach to conversation,
  and Delete (Del), confirmed in the row.
- **Empty page.** What Report Studio does and the templates as cards
  (sections in order, required ones marked, excluded ones faded, the
  details each needs); a card starts a report from it.
- **New report.** A docked panel in two steps. Step one: the templates
  as a radio group (arrows move, Enter or double click continues). Step
  two: the findings, most severe first, with search, a chip per severity
  that selects or clears all of it, and "Select shown"; false positives
  and duplicates are flagged as blocking. **Evidence** on a chosen
  finding lists the requests linked to it, all picked at first: unpick
  the ones the report should leave out. Then the title (the
  template's when empty), the details with the template's required ones
  first (version `1.0` by default; dates checked, end after start),
  automatic evidence, and notes to embed. Create opens the report.
- **Header.** Title in place (Enter or leaving saves, Escape reverts),
  template, status with the next move (Submit for review; Back to draft
  or Finalize; Reopen), Edit / Preview, Technical / Executive (saved as
  the report's default view; executive fades the sections it leaves
  out), validation at a glance (errors, warnings or Ready; click checks
  again and opens the panel), Export, Snapshots, More (details,
  comments, delete with a confirmation naming what goes), side panel.
- **Finalize.** Always confirmed: it locks the report and stores a
  snapshot. With blocking errors the dialog lists them (each leads to
  its fix) and offers Fix first; "Finalize anyway…" needs a second,
  explicit click before it forces.
- **Outline.** Sections in order with kind icon, `F-01` numbers for
  included finding sections, a red or amber dot from validation and open
  comments. Drag a row (a line shows where it lands) or press Alt+Up/Down
  on it to reorder (shown at once, undone if refused); Up/Down move
  between rows. Each row includes or excludes its section and deletes it
  in place (Delete key too; Enter deletes, Escape keeps). "+" adds a
  section of any kind, or a finding not yet in the report, after the
  selected one and opens it. Right click a section (or Shift+F10): Open,
  Attach to conversation, Include or Exclude, Refresh from the finding
  (finding sections), Move up or down, Delete; a final report offers
  only Open and Attach.
- **Section.** The focus of the page: kind, title and body. The body is
  the notes' live Markdown editor (`[[` link suggestions, `/` blocks,
  selection toolbar); edits save 0.7 s after typing stops (only changed
  fields), Ctrl/Cmd+S saves at once, and text changed elsewhere is
  adopted only while nothing is unsaved. The section's own validation
  issues sit above the text. Generated sections say what follows the
  text; an embedded note links to Notes.
- **Finding card.** Read live: severity, status, CVSS as stored, CWE /
  CVE, asset, description, then steps to reproduce (a raw request or
  curl as code, as the report renders it) and remediation on demand,
  and the evidence requests (method, host, path, status; each opens in
  History; deleted ones marked). Refresh takes the title from the
  finding and adds newly linked requests. Rejected and unconfirmed
  findings are called out; a deleted finding shows as missing.
- **Final reports** show a banner (locked since when, comments still
  allowed, Reopen as draft) and every section read-only in the safe
  reading view.
- **Side panel.** Validation: a verdict, then errors and warnings naming
  their section; clicking goes to the section, the details, the
  comments, or adds a missing section. Comments: on the open section,
  the report, or all; Ctrl/Cmd+Enter posts, resolve or reopen, delete in
  place, agent comments marked, resolved ones hidden unless shown.
  Details: client, program, tester, dates, version (required ones
  marked, missing ones flagged), organisation, accent colour (`#rrggbb`
  only, with a swatch and picker) and footer, checked as typed and saved
  with the button or Enter; read-only while final.
- **Preview.** `GET /render?format=html` in the chosen view, in an
  iframe with `sandbox=""` (no script, no same origin), on top of the
  page's own no-script policy; size and checksum shown; it follows
  changes.
- **Export.** Markdown, the HTML page, or PDF through the print dialog
  (the HTML export printed from a hidden frame that runs no script), in
  the chosen view, under the export redaction policy (masked unless the
  policy lets the user include credentials and they chose to). A 409
  with validation errors lists them with "Export anyway"
  (`force=true`). The file name comes from the answer; a toast says
  whether credentials were masked and the start of the checksum.
- **Snapshots.** A docked panel: take one with an optional label; the
  list shows number, reason (Manual, Final), label, time, size, finding
  count and checksum; View shows the snapshot's HTML export (masked) in
  a `sandbox=""` frame; Export as Markdown, HTML or PDF.
- **Realtime.** `report.updated` keeps the list and counts current,
  reloads the open report when someone else changed it, re-validates
  shortly after any change, and reloads comments and snapshots on their
  actions; `report.deleted` drops it.

## Not yet

Choosing individual evidence requests per finding in the interface
(the API takes them; the interface adds them automatically and through
Refresh); "Add to report" from the Findings page; logo images in branding (text branding only);
evidence objects beyond HTTP requests (screenshots, files) once the
evidence store exists; external submission.
