cd ~/projects/snappy-os .md file to compare - side-by-side diff against document-summarize
document-summarize
What it does for you
Reads a PDF or spreadsheet you upload and answers questions about it.
What it produces
A recent result, so you can see the kind of work it returns.
loading…
How to get it
These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.
For developers how this skill is built, graded, and how it runs
at a glance- the short version
what's inside - the parts that make up a skill 2/4 present
A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.
state/skills/document-summarize/SKILL.md
present
state/lib/document-summarize.ts
not present
state/bin/document-summarize/
not present
state/skills/document-summarize/AGENTS.md
present
how it runs - the shared frame every skill uses 3/5 present
Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.
state/log/evals.ndjson what it has learned - fixes written back in over time sample
When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.
- Loading feedback rows…
how the work flows- step by step
SKILL.md- the skill, written out in plain English
document-summarize
Handles uploaded document attachments in snappy-chat. Extracts text server-side and lets the LLM summarize, analyze key points, answer questions, render tables, and compare documents.
Supported formats
| Format | Extension | Parser |
|---|---|---|
| pdf-parse (PDFParse class, pdfjs-dist) | ||
| Word document | .docx | mammoth (extractRawText) |
| CSV spreadsheet | .csv | csv-parse/sync (renders as markdown table) |
| Excel spreadsheet | .xlsx | xlsx package (optional; fallback error message) |
Install requirements
All parsers are installed in ~/projects/snappy-os:
cd ~/projects/snappy-os
npm install pdf-parse mammoth csv-parse
# optional:
npm install xlsx
Architecture
- file-attach-button.tsx - user drops/selects PDF/DOCX/XLSX/CSV:
- Binary files read as
ArrayBuffer→btoa()→ base64 string - Encoded as
[Document: name.pdf]\ndata:application/pdf;base64,<data>\n\n - Added to
pendingAttachment.content(same as text/image path)
- server.ts (POST /dispatch/chat):
- Extracts
[Document: ...]blocks via regex (parallel to image extraction) - Calls
state/lib/document-parse.ts→parseDocumentFromBase64() - Builds
<document name="..." [N page(s)]>extracted text</document>blocks - Injects into
promptForLLMas:"The user has attached the following document(s)...\n\n<document>...\n\nUser request: <intent>"
- state/lib/document-parse.ts - document parsing library:
parseDocumentFromBase64(name, mimeType, base64)→DocumentParseResult- Truncates to 12000 chars to stay within LLM context budget
- CLI self-test:
npx tsx state/lib/document-parse.ts <path-to-file>
Steps
- User attaches a document via the paperclip button or drag-drop in snappy-chat.
- file-attach-button.tsx detects binary doc (
isBinaryDoc()) → reads as ArrayBuffer → encodes as[Document: ...]marker. - User types intent ("summarize this", "what are the key points", etc.) and sends.
- App.tsx prepends
pendingAttachment.contentto the intent string before dispatch. - server.ts extracts the
[Document: ...]block, callsparseDocumentFromBase64(). - Extracted text is wrapped in
<document>tags and prepended topromptForLLM. - LLM receives clean prompt with document context; responds with summary/analysis.
- For follow-up questions (step 5-7 in the flow), prior conversation history includes the assistant's previous summary so the LLM can reference it.
Key points / limitations
- PDF text extraction requires selectable text (scanned/image PDFs will yield empty or garbled text).
- Max 12000 chars extracted per document; large documents are truncated with a note.
- XLSX requires
npm install xlsxseparately (not installed by default). - For .docx files, only raw text is extracted (no table structure, no images).
- CSV files render as a markdown table (max 200 rows; excess noted).
- "Compare this PDF to the previous one" works via conversation history - the previous summary is in the prior_conversation block.
- "Extract the table on page 3 as a Lang Table" works for PDFs with selectable table text; the LLM will structure it using OpenUI
Tableprimitive.
Testing
# Verify PDF parsing works:
npx tsx state/lib/document-parse.ts /path/to/test.pdf
# Verify CSV:
npx tsx state/lib/document-parse.ts /path/to/test.csv
# Verify DOCX:
npx tsx state/lib/document-parse.ts /path/to/test.docx
# Verify the server extracts documents (direct API):
curl -X POST 127.0.0.1:3147/dispatch/chat \
-H "Content-Type: application/json" \
-d "{\"intent\":\"[Document: test.pdf]\\ndata:application/pdf;base64,$(base64 -i /path/to/test.pdf | tr -d '\\n')\\n\\nSummarize this.\"}" \
| grep -o '"delta":"[^"]*' | head -5AGENTS.md- what the AI loads when this skill comes up
document-summarize - loader
Per-turn rules for document attachment + summarization in snappy-chat. Full skill: state/skills/document-summarize/SKILL.md.
Critical Rules
- Binary docs use ArrayBuffer, not readAsText.
readAsText()on PDF/DOCX/XLSX = garbage. Route viaisBinaryDoc()→readAsArrayBuffer()→ base64. - Encoding:
[Document: name]\ndata:<mime>;base64,<data>\n\n. Server regex/\[Document:([^\]]+)\]\ndata:([^;]+);base64,([^\n]+)\n*/g- exact format or silent extraction fail. - Parser at
state/lib/document-parse.ts. Import:await import("../../lib/document-parse.ts"). Test:npx tsx state/lib/document-parse.ts <file>. - PDF:
PDFParseclass, not default import. Wrong:import pdfParse from 'pdf-parse'. Correct:import { PDFParse } from 'pdf-parse'. - mammoth:
extractRawText({ buffer: buf })→{ value: string }. Import:import { extractRawText } from 'mammoth'. - csv-parse: sync path with
{ columns: true, skip_empty_lines: true, relax_column_count: true }. Renders as markdown table. - LLM context block:
<document name="filename" [N page(s)]>...text...</document>. Prepended with "The user has attached the following document(s) for analysis:\n\n". - Empty intent allowed when document attached. Defaults to "Please summarize this document."
- 12000 char truncation intentional. Suffix:
[...document truncated at 12000 chars]. - Follow-ups via conversation history. User does NOT need to re-attach. Works via
priorMessages. - XLSX requires separate install.
npm install xlsx- not default. - Drag-drop same as click.
useFileDrophook routes viareadAsArrayBuffer().
Commands
| what | command | |
|---|---|---|
| test PDF parsing | npx tsx ~/projects/snappy-os/state/lib/document-parse.ts /path/to/file.pdf | |
| test CSV parsing | npx tsx ~/projects/snappy-os/state/lib/document-parse.ts /path/to/file.csv | |
| test DOCX parsing | npx tsx ~/projects/snappy-os/state/lib/document-parse.ts /path/to/file.docx | |
| install parsers | cd ~/projects/snappy-os && npm install pdf-parse mammoth csv-parse | |
| install xlsx | cd ~/projects/snappy-os && npm install xlsx | |
| verify server extracts doc | `curl -s -X POST 127.0.0.1:3147/dispatch/chat -H "Content-Type: application/json" -d '{"intent":"[Document: test.pdf]\ndata:application/pdf;base64,...\n\nSummarize."}' \ | grep delta` |
| reference | state/skills/document-summarize/SKILL.md |
Self-Test
- [ ] Binary docs use
readAsArrayBuffer(), notreadAsText()? - [ ] Encoding format:
[Document: name]\ndata:<mime>;base64,...? - [ ] Parser location:
state/lib/document-parse.ts? - [ ] PDF uses
PDFParseclass import? - [ ] mammoth uses
extractRawText({ buffer })? - [ ] csv-parse uses sync path with correct options?
- [ ] 12000 char truncation is intentional (context budget)?
- [ ] Follow-ups work via
priorMessages(no re-attach)? - [ ] XLSX needs separate install?
- [ ] Drag-drop routes same as click (via
readAsArrayBuffer)?
<!-- kernel-ok: historical attribution for the PID-loader pattern. -->
Self-correcting loader (PID feedback)
This is the rule that makes loaders learn. Ported from snappy-kernel, where it demonstrably worked: the snappy-dom-cartographer skill mapped Skool admin UI once, every later ship-agent inherited the full map for free.
Before you finish, do two things:
1. Fix gaps (P - proportional). MANDATORY. If this loader didn't cover your case - if you had to read another file, run an undocumented command, work around a wrong selector, or discover a quirk - you MUST attempt an Edit to this AGENTS.md before you log.
- Default action: edit this file. Surgical. Add the missing line, table
row, or code example where it belongs. No restructuring.
- Only
LOGGEDis allowed when: the fix needs >10 lines, spans multiple
files, or requires a structural rewrite. In that case the state/regen/drain.sh queue picks it up asynchronously.
- "I didn't have time" / "it's minor" / "the next agent will figure it out"
are NOT valid reasons. Minor gaps compound - that's the whole point of this loop.
- Concrete example of a valid P-fix: discover
agent-browser screenshot
takes path positionally not as --output <path>. One line in a table. Edit it in. Do not just log it.
- The goal: the next agent never has to leave the loader.
2. Log the result.
echo "[$(date -u +%FT%TZ)] document-summarize: <what was missing or fixed> [FIXED|LOGGED] action_kind=<kind>" >> state/log/loader-feedback.log
<slug>MUST be the literal folder name of this loader
(state/skills/<slug>/AGENTS.md). The class token between [ts] and : is the producer slug, the writeback class, AND the grade class - they must be equal so state/lib/controller-tune.ts can pair the brief.
FIXED= you patched this loader inline (P-fix).LOGGED= too large for inline; the PostToolUse enqueue + Stop-hook drain
will rewrite the loader from scratch on next session-end.
action_kindis the SECOND pairing predicate. Pick the value that describes what you actually did:shape-ok- frontmatter-shape verification onlyskill-ran- the skill ran end-to-end with eval row in state/log/evals.ndjsonloader-rewritten- you EDITED this AGENTS.md inline (the FIXED case), OR regen rewrote itpattern-elevated- you promoted a recurring failure to a Critical Rule
Do not skip this. Every agent run must leave the system better than it found it. The loader is the setpoint; you are the sensor; the gap is the error signal; closing the gap is the correction.
api.ts- the code it can call
⚠ no api.ts - this skill has no typed action surface
scripts- helper scripts it can run
prose-only skill - 2 inline code blocks live in SKILL.md above (no state/bin/ sidecar yet).
how we check it- the checks, plus the last 10 runs
no recent runs logged - the eval contract is declared but nothing has been graded yet