# Research notes

The research notebook: Markdown notes that belong to a vault, in folders,
with the vault's research tags, autosaved revisions, references to any
research object and backlinks from it, built-in research templates, and
portable Markdown export. One backend service (`app/services/notes/`)
serves REST, MCP and the Notes page (see Interface below).

Everything is vault-scoped. A note, folder or tag of another vault answers
exactly like one that does not exist.

## Model

**Note** (`research_notes`, cascades from the vault)

| Field | Notes |
|---|---|
| `title` | 1-200 characters, one line, no control characters. "Untitled" or the template's title when omitted. |
| `body` | Markdown stored exactly as sent (no trimming), up to 1 MiB of UTF-8. |
| `folder_id` | Folder, or null for the top level. ON DELETE SET NULL. |
| `pinned` | Pin flag. |
| `template` | Built-in template the note was made from (`journal`, `hypothesis`, `checklist`, `timeline`, `finding`), or null. |
| `tag_ids` | The vault's research tags ([Research annotations](annotations.md)), through `note_tags`, returned ascending. |
| `size`, `tasks_total`, `tasks_done` | Read from the body on every save: UTF-8 bytes and Markdown task items (`- [ ]`, `- [x]`, outside code). |
| `actor` | Last writer: `user` (REST) or `agent` (MCP), set by the backend. |
| `created_at`, `updated_at`, `archived_at` | An archived note is left out of default lists and keeps everything. |

**Folder** (`note_folders`): `name` (1-100 characters, no slashes or
control characters, not `.` or `..`), `parent_id` (null for the top
level). Names are unique among siblings, case-insensitively; folder
changes in a vault run one at a time, so two simultaneous requests cannot
both create the same name (one process; a multi-process deployment would
need a database constraint). At most 8 levels and 500 folders per vault.

**Revision** (`note_revisions`, cascades from the note): `title`, `body`,
`size`, `actor`, `created_at` (when the revision began) and `updated_at`
(its last save).

**Reference** (`note_links`): `note_id`, `kind`, `object_id`, `vault_id`,
parsed from the body on every save. No foreign key to the object and no
copy of it.

**Tags** (`note_tags`): note and tag, both ON DELETE CASCADE.

Migration: `d5a9c3e7f1b4_research_notes` (after `b2f6c8d4a1e7`).
Additive. The initial schema's `notes` table, an early draft no interface
ever exposed, stays in existing databases untouched and unmapped
(`migrations/env.py` lists it in `RETIRED_TABLES` so `alembic check`
ignores it); a later cleanup migration may drop it once the owner agrees.

### Design choices

- **Folders are a table, not a path string.** Renaming or moving a folder
  is one row, empty folders exist, and ids stay stable for links from the
  interface. Deleting a folder moves its notes and subfolders to its
  parent (refused with `409` when a subfolder's name is taken there), so a
  delete never loses a note.
- **Tags link directly (`note_tags`), not through `AnnotationKind`.** An
  annotation adds a bookmark and a note to an object; a note already is
  the knowledge, so a second note on it would be confusing. Notes use the
  same vault `Tag` rows, so one tag joins requests, targets, findings and
  notes. Deleting a tag removes it from notes in the same statement. Tag
  `count` in `GET /tags` still counts annotated objects only; filter notes
  by tag with `GET /notes?tag=`.
- **References are resolved on read.** A note never copies an object's
  data, so a rename shows at once, and deleting a flow, finding, target,
  scan or note never touches the note: the reference reads
  `exists: false`. No delete path needs to know about notes.

## References

One syntax, written in the body:

```
[[finding:3]]               a reference
[[flow:812|login replay]]   with the text a reader sees
```

| Kind | Object | Label |
|---|---|---|
| `flow` | Request in HTTP history | `METHOD host/path` (query string left out) |
| `target` | Target | identifier |
| `finding` | Finding | title |
| `scan` | Scan | `<type> scan of <target>` |
| `asset` | Asset | value |
| `note` | Another note | title |
| `payloads` | Payload collection (vault or global library) | name |
| `attack` | Intruder attack | name |
| `repeater` | Repeater tab | name, or `Repeater tab <id>` |

Ids are numeric. The alias after `|` is 1-200 characters without `]` or a
line break. References inside fenced code blocks (```` ``` ```` or `~~~`)
and inline code are text. Unknown kinds (`[[evidence:4]]`) are text until
that object exists. At most 500 distinct objects per note.

Reads resolve each distinct reference, in first-mention order, with one
query per kind:

```json
{"kind": "finding", "id": 3, "label": "Stored XSS", "exists": true, "alias": null}
{"kind": "flow", "id": 812, "label": "login replay", "exists": false, "alias": "login replay"}
```

A missing object (deleted, or an id of another vault) reads
`exists: false`; its label is the alias or `<kind> <id>`, never anything
from another vault. On SQLite an id freed by deleting the newest row of a
table can be given to the next new row, so a reference to a deleted
newest object can later resolve to its successor; PostgreSQL sequences
never reuse ids.

## Revisions

Every save that changes the title or body is recorded. Saves by the same
writer within 60 seconds of the newest revision's start update that
revision instead of adding one, so autosave every keystroke pause keeps a
readable history; another writer (an agent after the user) always starts
a new revision. The newest revision always equals the note. A save that
changes neither title nor body (pin, folder, tags) records nothing.
Restoring a revision makes its title and body the note's again and
records the restore as a new revision. Per note at most 200 revisions and
32 MiB of revision bodies are kept; the oldest go first, the newest
always stays.

### Edit conflicts

The editor sends the version it started from (`base_updated_at`) with
each save. When the note was saved elsewhere meanwhile (an agent,
another window), the save is refused with 409 `stale` instead of
replacing that change, and the editor stops autosaving and asks:
**Keep mine** saves your text over it as a new revision (`resolve_conflict`),
so the other version stays in the history; **Load theirs** drops your
unsaved edits and shows the stored note. Saves without a base (agents,
scripts) work as before.

## Search and lists

`GET /notes` returns summaries without bodies, newest change first, in
keyset pages (`limit` 1-200, default 50; continue with
`cursor=next_cursor`). `search` takes up to 8 words; each must appear in
the title or body, case-insensitively, and notes whose title holds more
of the words rank first. It is portable SQL (`lower(column) LIKE` with
`%`, `_` and `\` escaped), identical on SQLite and PostgreSQL, with no
FTS tables, triggers or dialect branches to keep in step; a vault holds
at most 10,000 notes of at most 1 MiB, which a scan answers quickly on a
workstation. SQLite's `lower()` folds ASCII only, so non-ASCII letters
match case-sensitively there. Full-text indexing (FTS5 / `tsvector`) can
replace the conditions in `app/repositories/note_query.py` later without
changing the API.

## Limits

Constants in `app/core/notes/limits.py`, enforced for every interface;
going over fails with `invalid_value` (422) and stores nothing.

| Limit | Value |
|---|---|
| Body | 1 MiB of UTF-8 |
| Title | 200 characters |
| Notes per vault | 10,000 |
| Distinct references per note | 500 |
| Tags per note | 32 |
| Folders per vault / depth | 500 / 8 |
| Revisions per note | 200 and 32 MiB |
| Search | 8 words, 200 characters |
| Backlinks / graph edges | 500 / 5,000 |
| Export | 1,000 notes and 32 MiB |

## REST

Paths are under `/api/v1/vaults/{vault_id}/notes`. Errors use the
standard body `{"error": {"code", "message", "details"}}`.

| Route | Body / query | Response |
|---|---|---|
| `GET` (the list) | `folder_id`, `recursive`, `unfiled`, repeated `tag`, `pinned`, `template`, `open_tasks` (unticked task items), `actor` (`user` or `agent`, who last wrote it), `search`, `archived`, `cursor`, `limit` | `{items: [NoteSummary], next_cursor}` |
| `POST` (the list) | `{title?, body?, folder_id?, pinned?, template?, tag_ids?}` | `201 Note` |
| `GET /templates` | | `[{name, title, description, body}]` |
| `GET /{note_id}` | | `Note` |
| `PATCH /{note_id}` | `{title?, body?, folder_id?, pinned?, template?, tag_ids?}` | `Note` |
| `POST /{note_id}/archive`, `POST /{note_id}/restore` | | `Note` |
| `DELETE /{note_id}` | | `204` |
| `GET /{note_id}/revisions` | | `[RevisionSummary]`, newest first |
| `GET /{note_id}/revisions/{revision_id}` | | `Revision` (with `body`) |
| `POST /{note_id}/revisions/{revision_id}/restore` | | `Note` |
| `GET /backlinks` | `kind`, `id` | `{object: Link, notes: [NoteSummary]}` |
| `GET /graph` | `archived` | `{nodes, edges, truncated}` |
| `GET /{note_id}/export` | `portable` (default true), `reveal` | `text/markdown` file |
| `GET /export` | repeated `ids`, or `folder_id`, or neither (whole vault); `portable`, `archived`, `reveal` | `application/zip` |
| `GET /folders` | | `[Folder]` by name |
| `POST /folders` | `{name, parent_id?}` | `201 Folder`; `409` for a taken name |
| `PATCH /folders/{folder_id}` | `{name?, parent_id?}` (`null` moves to the top level) | `Folder` |
| `DELETE /folders/{folder_id}` | | `204`; contents move to the parent |

`PATCH` changes only the fields sent: `folder_id: null` moves the note to
the top level, `template: null` clears it, `tag_ids: null` or `[]`
removes the tags. A tag of another vault is `422` with
`{"field": "tag_ids", "tag_ids": [..]}`.

```json
POST /api/v1/vaults/1/notes
{"template": "hypothesis", "title": "Session fixation on login", "tag_ids": [3]}
```

```json
{"id": 7, "vault_id": 1, "folder_id": null, "title": "Session fixation on login",
 "excerpt": "# Hypothesis **Status:** open ## Statement If ..., then ...", "pinned": false,
 "template": "hypothesis", "actor": "user", "tag_ids": [3], "size": 312, "tasks_total": 1,
 "tasks_done": 0, "link_count": 0, "created_at": "2026-11-28T09:14:02Z",
 "updated_at": "2026-11-28T09:14:02Z", "archived_at": null,
 "body": "# Hypothesis\n\n**Status:** open\n...", "links": [], "backlinks": [], "revision_count": 1}
```

`backlinks` in a note lists the notes that reference it
(`{id, title, archived_at}`).

Graph: one node per active note (or every note with `archived=true`) and
per referenced object, keyed `<kind>:<id>`, and one edge per reference:

```json
{"nodes": [{"key": "note:7", "kind": "note", "id": 7, "label": "Session fixation on login", "exists": true},
           {"key": "flow:812", "kind": "flow", "id": 812, "label": "POST app.test/login", "exists": true}],
 "edges": [{"source": "note:7", "target": "flow:812"}], "truncated": false}
```

## Export

A note exports as Markdown with a front matter of `title`, `tags` (names),
`template`, `created` and `updated`. Several notes export as a ZIP of such
files laid out by folder (`recon/api/login-flow.md`, duplicate titles
become `-2`, `-3`).

- **Portable** (default): references become the text a reader sees, the
  alias, else the object's current label, else `(removed <kind>)`; no note,
  vault or object id and no `[[...]]` syntax is written. Code is left
  exactly as written.
- **`portable=false`**: the body as stored and `phantom_note: <id>` in the
  front matter, for moving notes between workstations.

The export redaction policy (`redaction.export`) applies to the finished
text exactly as to body downloads: `redact` (default) masks credentials
and refuses `reveal=true` (403); `reveal` keeps them unless
`reveal=false`; `ask` needs `reveal=true|false` on every export (409
without). `X-Phantom-Redacted` says whether credentials were masked and
`X-Phantom-Entries` how many notes the download holds.

Before any note export (Markdown, HTML, PDF or the ZIP of every note),
a review shows which notes carry credentials, of which kinds, and what
the export does with them. Exporting them unmasked needs an explicit
tick (`GET /notes/export/review` with `ids` or `folder_id`).

## Events

Announced after the commit, routed by `vault_id`:

| Event | Data |
|---|---|
| `note.updated` | `{action: created\|updated\|archived\|restored\|restored_revision, note}`: the summary without `excerpt`; never body text |
| `note.deleted` | `{id, vault_id}` |
| `note.folder.updated` | `{action: created\|updated\|deleted, folder}` |

## MCP

`note_list` (filters and `search`, paged), `note_get`, `note_create`,
`note_update`, `note_backlinks`, `note_graph`, `note_folder_list`,
`note_templates`. The tools call the same services as REST, and every
write records `actor: agent`.

- **Redaction**: titles, bodies, excerpts and reference labels go through
  the text redactor under the MCP redaction policy (a user may paste a
  token, and a flow label repeats a request path); `note_get` accepts
  `reveal_secrets` when the policy allows it. Results carry `redacted`.
- **Placeholders refused**: a `title`, `body` or `append` that contains a
  redaction placeholder is refused (`invalid_value`,
  `{"field": "body"}`), since text copied back from a redacted read would
  replace the user's credentials with placeholders.
- **Append**: `note_update` with `append` adds a paragraph at the end of
  the stored body, so an agent keeps an investigation journal without
  rewriting text it only saw redacted. `body` and `append` together are
  refused.
- `folder_id: 0` in `note_update` moves a note to the top level.
- Revisions and restore, archive, delete, export and folder changes are
  user actions and have no tools.

## Interface

Rail entry **Notes** (`G N`, also in the command palette); `?note=<id>`
opens a note.

- **Sidebar search.** On the backend (every word in title or body), as
  you type (150 ms); `/` or Ctrl/Cmd+Shift+F focuses it, Escape clears
  it, the down arrow moves into the results. Matching words are
  highlighted in titles and excerpts over the masked text, so a hidden
  credential never shows. A line counts the matches ("3 notes match
  'jwt'", Clear); while a folder is selected a chip ("in Recon" ×) says
  the search is limited to it. Previous results stay while a search
  runs, so the list never flashes empty; an empty result says why and
  offers Clear search or Clear filters.
- **Sidebar filters.** One bar: Pinned and Archived as toggles, a Filter
  menu (tags with their colours, several at once; template; has open
  tasks; written by an agent) and a Sort menu (Last edited, Created,
  Title A–Z, Open tasks; kept as a UI preference). Every filter runs on
  the backend (`open_tasks`, `actor=agent` among them); the sort orders
  the loaded pages. Active filters show as removable chips with "Clear
  all".
- **Sidebar list.** Pinned notes come first as their own group; notes an
  agent wrote carry an "Agent" badge; the relative time shows the exact
  time on hover. Up/Down, Home and End move between notes, Enter opens.
  Right click (or Shift+F10, or the context-menu key) opens a note's
  menu: Open, Rename (in place, F2; Enter saves, Escape cancels),
  Pin/Unpin, Move to (a folder, Unfiled, or a new folder named in
  place), Duplicate ("(copy)" with the same body, folder, template and
  tags), Copy link (`[[note:<id>]]`), Export (Markdown, HTML, PDF),
  Archive/Restore and Delete (Delete key too), which asks in the row
  itself (Enter deletes, Escape keeps).
- **Folders.** All notes, Unfiled, then the folder tree: create, rename
  by double click, delete with an in-place confirmation that says notes
  move up; right click a folder (or Shift+F10 on it) for Show its notes,
  Rename (F2), New subfolder and Delete (Delete).
  Drag a note or a folder onto a folder, or onto Unfiled for the top
  level; a folder never moves into its own subtree. "+" starts a blank
  note or one of the templates; the empty page shows them as a gallery.
- **Editor.** The title is written in place. The body is a CodeMirror 6
  editor in three views (a preference): **Live** (default) renders the
  Markdown as you type: headings,
  emphasis, code, quotes, lists, task checkboxes, rules and `[[links]]`
  are drawn in place and their marks appear only on the line with the
  cursor; **Source** shows the raw Markdown in the mono face; **Read** is
  the safe reading view. Enter continues lists and quotes, and Enter on
  an empty item or quote line ends it. Ctrl/Cmd+B and Ctrl/Cmd+I wrap
  the selection. Edits save 0.7 s after typing stops; **Ctrl/Cmd+S**
  saves at once from anywhere on the page (the browser's own save dialog
  never opens) and the state flashes "Saved". Changes from an agent or
  another window replace the text only while nothing is unsaved, and
  switching notes saves first. Pin, archive and restore, delete with an
  in-place confirmation, tags through the shared tag picker. List and
  backlink excerpts are plain text (the backend strips Markdown). Text
  adopted from the server stays out of the undo history, so Ctrl/Cmd+Z
  after an autosave undoes the user's own last edit.
- **Blocks and formatting.** `/` at the start of a line opens a block
  menu (Heading 1–3, task, bulleted and numbered lists, quote, code
  block, divider, "Link to…"), filtered as you type; arrows, Enter or
  Tab, Escape. Selecting text shows a toolbar: bold, italic, strike,
  inline code, link (the selection becomes the link search), heading 1
  and 2, quote, list, task; line blocks toggle off when already applied.
- **Code.** Fenced blocks are highlighted by their language (grammars
  from `@codemirror/language-data`, loaded on demand) in the app's token
  palette. In Live they are a rounded panel whose fence lines stay quiet
  until the cursor is on them; in Read they show the language name and a
  Copy button, and credential masking applies over the highlighted text.
- **Footer.** Words, reading time, task progress, "Written by an agent"
  when the last writer was an agent, and the keys: `/` blocks, `[[` link,
  Ctrl/Cmd+S save. The empty note's placeholder says the same.
- **Links.** Typing `[[` suggests kinds, then objects of the chosen kind
  (requests through the history search, notes through note search,
  findings, targets and scans from their lists, payload collections,
  attacks, Repeater tabs and files); Enter or Tab inserts `[[kind:id]]`. In the
  reading view a reference is a chip that opens the object (requests
  open History on that request); a missing object is struck through and
  marked missing.
- **Reading view.** Markdown is parsed into a tree and rendered as
  elements and text, never as HTML: raw HTML in a note shows as text,
  and only `http(s)` and `mailto` links become links (new tab,
  `noopener noreferrer nofollow`). Credentials are masked with the shared
  rules until "Reveal" for this note; while writing they are shown, with
  a line saying so. Task items are checkboxes that tick the source line.
- **Side panel.** Notes linking here, this note's links and the revision
  history (open one for a line diff against the current text, Restore;
  pending edits are saved first).
- **Export** (header). This note as Markdown, an HTML page or a PDF
  (through the browser's print dialog), or every note as a zip. HTML and
  PDF are rendered from the backend's Markdown export, so the export
  redaction policy applies to every format; the HTML escapes everything
  and keeps only `http(s)` and `mailto` links. Credentials are masked
  unless the policy allows including them and "Include credentials" is
  ticked; Markdown exports are probed before downloading.
- **Graph** (the graph button beside "+", or `?view=graph`). Every note
  and the objects it references, laid out by force (d3-force) on a
  canvas. The legend is the kind filter (with counts), "Unlinked notes"
  shows notes without references, and the search rings matching nodes
  without hiding the rest. Hover lights a node and its neighbours with a
  card (kind, name, links), click opens it, drag moves a node, the
  background pans, the wheel zooms around the pointer, Fit frames
  everything; positions survive filter changes. Missing objects are
  dimmed. It reloads when notes change; Escape returns to the notes. With
  reduced motion the layout is computed at once.
- **Elsewhere.** The target page, the finding inspector and the History
  request panel list the notes that mention the object, with "New note
  about this", which opens a note already linking to it (the request
  panel shows only that line until a note exists).

## Not yet

Evidence objects as a reference kind
(`[[evidence:id]]`) once the evidence store exists; report drafting from
notes; full-text indexes; note templates defined by the user; keyboard
moves for notes between folders (dragging only today).
