# Document Process Audit

Audit date: 2026-06-26

Repo audited: `/home/hex/Project/BrainDrive-Test-01`

Branch/status at audit start: `dev`, clean working tree, tracking `origin/dev`.

## Scope

This audit checks the current BrainDrive code path for accepting user documents through the chat interface, uploading them, converting them to markdown when needed, and storing them under the correct project folder.

## Executive Status

The document upload pipeline is partially implemented and usable.

Implemented:

- The chat composer has an attachment button and drag/drop support.
- Project-scoped chat uploads call `POST /api/projects/:id/uploads`.
- Markdown, text, and CSV uploads are converted without a model call.
- Image and PDF uploads are converted to markdown through the configured model provider.
- OpenRouter PDF conversion uses the `file-parser` plugin with `mistral-ocr`.
- PDF conversion falls back to extracting embedded JPEG images and sending them to the vision model when provider file parsing returns empty markdown.
- Converted documents are saved as markdown under `documents/<projectId>/...`.
- Finance bank and credit-card statement-like uploads are routed to `documents/finance/budget/statements/...`.
- Finance statement uploads update `documents/finance/budget/statements/README.md` as source evidence.
- Other project uploads update the project index.
- Uploads create memory commits on best effort.
- Chat sends a follow-up upload summary message so the assistant can acknowledge the uploaded evidence and continue.

Not fully implemented:

- The user's typed instructions are not passed into the document conversion/OCR prompt. They are sent afterward to the chat model.
- There is no full document-type processing workflow beyond markdown conversion and Finance metadata classification.
- Raw original files are not stored; only converted markdown is saved.
- PDF fallback is limited to embedded JPEG extraction, capped at six images.
- Uploads require an active writable project folder for images/PDFs. Outside a project, only text-like attachments are read inline into chat.
- Server-side support for `.vtt` depends on text MIME handling; the converter does not explicitly branch on `.vtt`.

## Current User Flow

1. The user attaches files in chat with the composer attach button or by drag/drop.
2. The client validates file type against the accepted extension and MIME allowlist.
3. If a writable project is active, the client uploads each file sequentially through the selected project.
4. The gateway converts or wraps the uploaded file as markdown.
5. The gateway writes the markdown into project memory and updates the relevant index.
6. The client appends a synthetic chat message summarizing uploaded files and asking the model to acknowledge the evidence and update the Finance checklist.

Key client evidence:

- Attachment UI and file input: `builds/typescript/client_web/src/components/chat/Composer.tsx:96`, `builds/typescript/client_web/src/components/chat/Composer.tsx:200`
- Accepted file types: `builds/typescript/client_web/src/utils/file-utils.ts:1`
- Upload orchestration from chat: `builds/typescript/client_web/src/components/chat/ChatPanel.tsx:527`
- Project requirement and fallback behavior: `builds/typescript/client_web/src/components/chat/ChatPanel.tsx:803`
- App shell uploads to the selected project: `builds/typescript/client_web/src/components/layout/AppShell.tsx:242`

## Supported Inputs

Client allowlist:

- `.txt`
- `.md`
- `.markdown`
- `.vtt`
- `.csv`
- `.png`
- `.jpg`
- `.jpeg`
- `.webp`
- `.pdf`

Gateway conversion behavior:

- Markdown: saved directly if already markdown.
- Text: saved directly as markdown body.
- CSV: converted to a markdown table.
- Images: sent to the configured model as image inputs and converted to markdown.
- PDFs: sent to provider file input when supported; OpenRouter uses `file-parser` with `mistral-ocr`; if empty, embedded JPEGs are sent to the vision path.

Key gateway evidence:

- Main conversion dispatch: `builds/typescript/gateway/document-upload.ts:84`
- PDF file input and OpenRouter OCR plugin: `builds/typescript/gateway/document-upload.ts:750`
- Image/vision conversion path: `builds/typescript/gateway/document-upload.ts:858`
- Generic conversion prompt: `builds/typescript/gateway/document-upload.ts:909`
- Size limits: `builds/typescript/gateway/server.ts:2597`

## Upload API

The upload endpoint is:

`POST /api/projects/:id/uploads`

Request fields:

- `file_name`
- `mime_type`
- `content_base64`
- `size`

Server behavior:

- Rejects `braindrive-plus-one` with "Open a folder to upload documents".
- Rejects missing projects.
- Decodes base64 into a buffer.
- Rejects empty files.
- Applies size limits:
  - PDF: 25 MB
  - Image: 15 MB
  - Other: 5 MB
- Converts the upload to markdown.
- Runs metadata inference.
- Builds markdown with frontmatter.
- Saves the converted document through the project service.

Key route evidence:

- Upload route and validation: `builds/typescript/gateway/server.ts:2410`
- Conversion and metadata inference call: `builds/typescript/gateway/server.ts:2456`
- Finance statement routing decision: `builds/typescript/gateway/server.ts:2472`
- Response metadata for UI labels: `builds/typescript/gateway/server.ts:2505`

## Markdown Output

For non-frontmatter markdown uploads, generated markdown includes:

- YAML frontmatter with source filename, source type, import timestamp, conversion type, summary, and metadata when available.
- A title heading.
- A Summary section.
- A Source Content section containing converted or original content.

If a direct markdown upload already starts with frontmatter, the existing markdown is preserved without adding duplicate frontmatter.

Evidence:

- Markdown document builder: `builds/typescript/gateway/document-upload.ts:158`
- Index entry builder: `builds/typescript/gateway/document-upload.ts:212`

## OCR and Model Use

Current OCR/conversion is provider-driven, not local OCR.

For PDFs:

- If the selected provider supports PDF file input, the gateway sends the file as a base64 data URL in a chat completion request.
- For OpenRouter base URLs, the request includes:
  - plugin id: `file-parser`
  - PDF engine: `mistral-ocr`
- If the parser returns empty markdown, the gateway logs the empty result and tries embedded JPEG extraction.
- If no embedded JPEG images are found, the upload fails with "This PDF requires OpenRouter PDF parsing or a PDF with extractable page images."

For images:

- The gateway sends image data URLs to the model with a generic "convert uploaded document into markdown" prompt.

Important limitation:

- The conversion prompt includes only the source filename and destination project folder. It does not include the user's typed chat instructions, so instructions like "only extract the invoices table" or "summarize this for the health project" are not used during OCR/conversion. Those instructions can affect the later chat turn, but not the conversion output itself.

## Metadata and Document Type Handling

Metadata handling is strongest for Finance.

For every upload, the gateway creates deterministic metadata based on filename, converted title, and converted markdown. For Finance uploads only, it also attempts an LLM metadata pass and falls back to deterministic metadata if that pass fails.

Metadata fields include:

- document type
- statement-like flag
- institution
- account type
- statement month
- statement period start/end
- suggested filename
- summary
- tags
- confidence

Finance document classification includes:

- bank statement
- credit card statement
- investment statement
- budget export
- receipt
- tax document
- paystub
- other

Only bank and credit-card statement-like Finance uploads are routed to the budget statements source evidence folder. Investment statements are intentionally not routed there by the deterministic logic.

Evidence:

- Finance-only model metadata pass: `builds/typescript/gateway/document-upload.ts:228`
- Deterministic metadata inference: `builds/typescript/gateway/document-upload.ts:291`
- Safe filename sanitization: `builds/typescript/gateway/document-upload.ts:333`

## Project Storage

Storage is based on the active selected project id, not on model inference.

Normal project upload path:

`documents/<projectId>/<safe-file-name>.md`

Finance statement-like upload path:

`documents/finance/budget/statements/<safe-statement-file-name>.md`

The selected project id comes from the app shell's selected project and is passed into `uploadProjectDocument(selectedProject.id, file)`. The gateway resolves the project by id, includes `project.name` in the conversion prompt, and writes within that project's memory folder.

Project service behavior:

- Protected projects are rejected.
- Filenames are slugified and made unique with numeric suffixes.
- Paths are resolved under the project root to prevent path escape.
- The written file path is returned as authoritative.
- Finance budget statement uploads update `documents/finance/budget/statements/README.md`.
- Other uploads update the project `index.md`.

Evidence:

- Selected project upload call: `builds/typescript/client_web/src/components/layout/AppShell.tsx:253`
- Project-scoped markdown write: `builds/typescript/gateway/projects.ts:194`
- Finance statements README update branch: `builds/typescript/gateway/projects.ts:232`
- Finance statements README default content: `builds/typescript/gateway/projects.ts:463`

## Chat Model Awareness After Upload

After successful uploads, the client appends a chat message like:

- "Uploaded 1 file:"
- upload labels and destination labels
- failure summaries, if any
- "Please acknowledge the uploaded statement evidence and update the received/missing checklist for the budget setup before continuing."

The assistant then receives normal project context. For Finance, the project chat context includes specific guidance to use `documents/finance/budget/statements/` as source evidence and to call memory tools if an expected upload filename is not visible.

Evidence:

- Upload summary builder: `builds/typescript/client_web/src/components/chat/ChatPanel.tsx:492`
- Summary appended after uploads: `builds/typescript/client_web/src/components/chat/ChatPanel.tsx:660`
- Finance upload/source-evidence chat guidance: `builds/typescript/gateway/server.ts:3380`

## Tests Present

Relevant tests exist for:

- Markdown upload preservation.
- CSV to markdown table conversion.
- PDF conversion through OpenRouter file parser.
- BrainDrive Models PDF file input.
- Conversion retry for transient provider errors.
- PDF fallback to embedded image OCR.
- Finance statement metadata inference.
- Investment statements not routed into budget statement evidence.
- Safe statement filenames.
- Uploaded markdown frontmatter and index entries.
- Project upload writes and duplicate filenames.
- Finance upload to budget statements folder and README update.
- Chat upload of PDF attachments.
- Multi-file sequential upload.
- Partial success with owner-safe failure text.
- Retry of failed upload activity.

Key test files:

- `builds/typescript/gateway/document-upload.test.ts`
- `builds/typescript/gateway/projects.test.ts`
- `builds/typescript/client_web/src/components/chat/ChatPanel.test.tsx`

## Gaps and Risks

1. User instructions are not part of conversion/OCR.

   The upload conversion prompt is generic. The typed chat message is appended after upload success. If the product goal is "OCR based on document type and instructions," the conversion API needs an instruction field or the client needs to pass the message into the upload request.

2. Document-type-specific processing is mostly Finance-only.

   Finance gets statement metadata and routing. Other project types get generic markdown documents and index entries. There is no project-specific document classification for Fitness, Career, Relationships, or custom pages.

3. There is no durable raw-source preservation.

   The raw uploaded file is not saved. This is good for storage minimization, but it prevents reprocessing with improved OCR settings unless the user re-uploads.

4. PDF fallback is narrow.

   Embedded JPEG extraction will not handle many PDFs: vector PDFs, scanned PDFs without extractable JPEG streams, PNG-compressed scans, or multi-page documents beyond the six largest extracted JPEGs.

5. Attachments outside a selected project are not durable.

   Text-like attachments can be read inline into the message when no project is selected. Images and PDFs require a project folder. This is consistent with current UI error copy but may not match an expectation that chat always accepts documents.

6. Conversion uses the currently configured provider.

   Upload success depends on provider credentials, model support for image/file inputs, and provider PDF parsing support. Provider errors become owner-safe UI messages, but conversion cannot complete without a working model path.

7. `.vtt` support is client-accepted but not explicit in gateway conversion.

   It works when the browser provides a `text/*` MIME type. If uploaded as `application/octet-stream` with only a `.vtt` extension, the gateway conversion dispatch may reject it.

## Recommended Next Steps

1. Add upload instructions to the API contract.

   Extend `POST /api/projects/:id/uploads` with optional `instructions` and have chat pass the current message text into the upload call. Include instructions in `buildConversionPrompt` with guardrails against inventing content.

2. Decide whether raw originals should be retained.

   If reprocessing, auditability, or source download matters, store originals under a controlled source folder with clear privacy and size limits. If not, document that BrainDrive stores converted markdown only.

3. Generalize document metadata beyond Finance.

   Add project-aware metadata extraction for common document categories by project type, or explicitly document that only Finance has special routing today.

4. Improve PDF fallback.

   Consider a real PDF rendering/OCR path or a provider-normalized file parser contract rather than relying only on embedded JPEG extraction.

5. Add a focused test for instruction passthrough once implemented.

   The test should assert that user-provided upload instructions reach the conversion prompt and that the post-upload chat summary still includes the owner-facing request.

## Bottom Line

BrainDrive already supports project-scoped document upload through chat and can convert PDFs/images to markdown using the configured model provider. It stores converted markdown under the active project folder, with special Finance statement routing into budget source evidence. The main missing piece for the stated target is instruction-aware conversion: user instructions currently influence the follow-up chat turn, not the OCR/conversion step itself.
