Kevin Hu 82c76a82a9
feat(knowledge): read every format, show what the index holds, and let an agent search it (#489)
<img width="2318" height="1448" alt="image"
src="https://github.com/user-attachments/assets/bca71d69-4972-420c-b14e-c8cf74a17de9"
/>

## Summary

Everything a knowledge base could not read, and the pieces it cut them
into
saying what they are.

**Reading a PDF.** A PDF records glyphs at coordinates; whether they are
a
heading, a table cell or a running footer is inferred from how they
look. There
are now two readers. The geometric one infers structure from type size
and
position and needs nothing but the file. The other asks deepdoc's
models, ported
into `raven/knowledge/parser/deepdoc`: a layout model that says what
each region
is, a detector and recognizer that read a page carrying no text at all,
and a
table-structure model that rebuilds a grid from a picture of one. 
 Detecting boxes around text the file already spells
out exactly costs an inference pass per page to learn less, and
recognising it
costs accuracy.

The layout graph answers with a shape its own postprocessing
raises on, and its classes are DocLayout-YOLO's order rather than the
list
Both were established by running the model, and the label order is
pinned by a test.

**Tables go in as tables.** `<table>` is the only shape that keeps what
a grid
states -- which column a cell stood under, which cells are merged, which
row is
the header -- and it is the shape a model reads a table in, which is
what these
chunks are for. PDF, Word and PowerPoint all state their merges exactly,
and
they now survive as `colspan` and `rowspan`. The flat form this replaces
had to
repeat a header standing over two columns across both of them, because
there was
nowhere to record a span; it had no callers left afterwards and is gone.
Two
deviations from upstream, both about what the string is for: every
cell's text
is escaped, where upstream interpolates it raw and a cell holding a `<`
produces
markup that is no longer a table, and the span attributes are written
only where
there is a span, where upstream emits `<td  >` for every ordinary cell.

**A picture of where each chunk came from.** A chunk is a few hundred
words with
a page number on it, which is enough to cite and not enough to answer
whether
the parser read the page correctly. So every PDF chunk that knows where
it sits
carries one image: the regions it covers, cropped out of the rendered
pages and
stacked. here they are already structured in the parser's element spans,
so
the markers would only put text nobody wrote into the thing being
embedded.
The panel draws a chunk's tables as tables, parsed and
rebuilt as elements rather than injected: a person can rewrite any piece
from
that same panel, so what comes back from the store is user input however
it got
there.

**The page that reads them.** Upstream retired the knowledge page while
this
branch was out; it is rebuilt against the new architecture, and the half
that
never existed is the one a reader needs -- what a document actually
became once
it was cut and embedded. Documents sit in one-level folders and arrive
by four
routes: a file, a folder, a URL, a written note. Adding and indexing are
two
calls on the contract and nothing drains that queue on its own, so a
page that
stopped after the first left every upload saying Queued for good.

Opening a file takes the whole page: the document on the left, the
pieces the
index holds of it on the right. The left half is the file drawn as its
own
pages rather than framed by the browser's PDF viewer, which reads where
to open
once and answers to nothing afterwards -- and which nothing can be drawn
on.
Pages are rendered once and kept, and the region a piece was cut from is
washed
over the page it came from, placed in fractions of the page so the
picture's
own scale never enters the arithmetic. Clicking a piece takes the file
there;
double-clicking opens it for rewriting.

The pieces can be searched, filtered by state, turned on and off,
deleted,
rewritten and added to, one at a time or in a batch. Every one of those
was
already on the contract with no reader for it. A base's settings are
back and
fuller: how many pieces a search returns, how documents are cut, and how
much
prose comes with a table or a figure. The embedding model is a picker
while the
base holds no pieces and a stated fact once it does -- moving it then is
the
collection made again at the new width and every document re-cut, which
is not
a thing a panel does by being saved.

**An agent can read them.** The retrieval engine was there and nothing
could
reach it: no agent had a tool that opened a library. A reader now points
a
conversation at bases from the composer, the way they pin a working
directory,
and the selection rides in the same place -- the session's metadata,
bound
around the turn.

The tool takes a query and never a base. The scope is the reader's
choice, so a
model cannot reach material nobody offered it, and it is withheld where
nothing
was picked rather than offered and refused. A hit says which document
and page
it came from, because a hit a reader cannot place is a hit they cannot
check --
and the passages are pressable in the transcript, walking into the base,
the
document, the folder it is filed under and then the piece. A citation a
reader
cannot follow is a claim they have to take on trust, and the whole point
of
searching their own material is that they can go and look.

**The word segmenter and the resources.** `raven.core.Tokenizer` is
Infinity's
`rag_tokenizer`, ported: a forward and backward maximum match over a
dictionary
trie, with stemming and lemmatisation on the latin path. XGBoost is not
carried
over. None of the data lives in git -- the dictionary, the NLTK corpora
and the
ONNX graphs run to about a hundred megabytes, so `make fetch-resources`
on an
install and an optional Docker layer behind `RAVEN_RESOURCES` both point
at one
script. A checkout that could not reach the network still works, and
every
feature that reads this data says so when asked.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Run on macOS against Python 3.12, with the deepdoc weights fetched (the
model
tests skip without them):

```
uv run pytest                        27450 passed, 111 skipped, 3 failed
npm run test --prefix ui-web          3276 passed
npm run test --prefix ui-tui          2106 passed
npm run type-check --prefix ui-web    clean (tsc)
npm run lint --prefix ui-web          clean (4 pre-existing hook warnings)
make lint-python                      clean (ruff check + format)
make lint-types                       clean (ty)
make lint-imports                     10 contracts kept, 0 broken
make check-source-language            clean
make check-large-files                clean
make build-ui                         built, both boot snapshots match
node ui-web/scripts/check-css.mjs     clean
node ui-web/scripts/check-class-namespace.mjs  clean
```

The three Python failures are not this branch's and were each confirmed
on the
base alone: one asks a host without LibreOffice to refuse a render and
this host
has LibreOffice installed, and two simulation cases fail on an
unmodified
checkout of the base commit.

The RPC contract was regenerated for both consumers and both match it
(`npm run gen --prefix ui-web`, `npm run gen:rpc --prefix ui-tui`, then
`gen:check`). The page's boot snapshots and region goldens were
refreshed where
the composer bar gained a button, and each records that button and
nothing else.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

A PDF's tables, and a Word or PowerPoint file's, are now indexed as HTML
rather
than as header-prefixed lines. Chunk text changes shape for those
documents, so
a base indexed before this and searched after it holds both forms until
its
documents are reindexed; retrieval keeps working either way, because
both forms
are text. The same applies to how much prose a table or a figure carries
with
it: the setting now reaches as far as it says, where before it stopped
at the
nearest paragraph, so a chunk cut before this keeps the narrower context
until
its document is rebuilt. Rolling back is reverting the branch and
reindexing.

The deepdoc models are optional. An install that never ran `make
fetch-resources` reads PDFs geometrically, exactly as before, and says
so when
the models are asked for by name. Nothing here reaches the network at
request
time.

Chunk crops and rendered pages are written at index time and on first
view, both
under the state directory rather than in the repository, and both are
deleted
with their document. A page is immutable for the life of its document
id, so
the route serving them caches; the document route does not. All three
routes
take ids and no path, and the two image routes answer under the
strictest
sandbox in the tree.

What an agent may search is the reader's choice and nothing else. The
tool takes
no base argument, so a model cannot name one, and it is absent from the
schema
entirely for a conversation that named none -- a lane nobody pointed at
a base
is unchanged by this branch. The bases a session carries are stored
beside its
working directory and travel no further.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-10-12 19:05:16 +08:00
..

ui-web

The page raven serve hosts: one HTML file with the stylesheet and the whole script inlined, plus a directory of icons beside it. dist/index.html is what the wheel ships and what nginx serves in a container; nothing on the page fetches a second script.

The conventions a change here follows -- the layering, the shape of a domain, the store, the naming, the gates -- are CONTRIBUTING.md. The vocabulary is CONTEXT.md.

Layout

Path What it is
src/page.html the document skeleton: <head>, the two pre-JavaScript shells, and the two markers build.py splices into
src/main.tsx the entry, a straight line: the page root, the listeners, the island roots, the transport, the boot
src/App.tsx the page root: every region at the body, in one portal, in document order
src/app/ the page's lifecycle, called once from main.tsx: the boot's ordered list, the wiring, the connection, the update watch, the splash
src/rpc/ the typed gateway seam: the generated method contract, the gateway slot, the three transports and the offline fixture library under rpc/fixtures/
src/state/ the stores and tables every region reads (store.ts is the one store shape, sources.ts the data seam, pages.ts the page table), plus lang/ and session/
src/chrome/ the page's own furniture -- rail, chat header, dock, sheet rack, tooltip, chips and their popovers -- plus behaviour/, the two it installs rather than renders
src/features/<domain>/ one domain per directory: its types.ts, source.ts, store.ts, <Domain>App.tsx and manifest.ts, plus its own wire.ts, mount.tsx or styles.css where it needs them. features/manifests.ts assembles those declarations and features/hosts.ts holds the three detached nodes a tab re-attaches
src/components/ the small components more than one region renders
src/lib/ helpers with no store and no page of their own (lib/dom.ts is the page's $)
src/i18n/ t.ts: the lookup into the shared catalogue at the repo root
src/test/ helpers and suites about the assembled page, and the region goldens under src/test/__golden__/
src/styles/page.css the page's own stylesheet -- the frame and the --z ladder -- inlined at /*__STYLE__*/. A domain's own rules live in its styles.css
src/assets/ icons served from dist/assets
scripts/ the seven tools: the client generator, the three artifact checks, the boot snapshot, the test harness and the gates' fixture call table
scripts/gates/ the gates vitest runs over the tree, the stylesheet and the contract

Nothing is published on window, and nothing outside the bundle reaches in: a module imports what it calls, and the direction those imports may run in is scripts/gates/import-direction.test.mjs. Where the direction forbids the import -- src/state/ calling into a domain -- the call goes through a callback the state module declares and the domain fills (state/page.ts's onShow, state/settings.ts's onEnter).

Adding a domain

Seven steps, and which gate reddens for each omission: CONTRIBUTING.md section 10.

Build

Two steps, in this order:

npm ci
npm run build          # Vite -> .modern/modern.iife.js and .modern/domains.css
python3 build.py       # splice into src/page.html -> dist/index.html, copy assets

They are separate because build.py must run where npm may not be on PATH: the installer adds npm inside a subshell, and the python step is what the release wheel and make build-ui call. build.py is three substitutions and a copy -- every line of JavaScript the page runs comes from the one bundle, and the one <style> block is styles/page.css followed by the domains' own sheets, which Vite collects into .modern/domains.css -- and it ends by booting the artifact in happy-dom twice: once on its fixtures (?stub=1), once in live mode with no gateway answering, comparing each DOM shape against its golden under scripts/__golden__/, so a structural regression fails the build rather than the browser.

Develop

raven serve            # start the gateway first, in another terminal
npm run dev            # http://127.0.0.1:5173/src/page.html

The dev server serves src/page.html with hot reload and proxies /rpc, /health, /auth, /file, /files, /knowledge/file and /oauth/callback to the gateway, whose port it reads from ~/.raven/serve.json (18792 if there is no record). Same origin, so the session cookie works: sign in once through the proxied /auth page. Dev never produces a dist/ -- the artifact only ever comes from the two build steps above.

Without a gateway, ?stub=1 runs the page against its own fixtures. So does opening dist/index.html from disk.

Checks

npm test                               # vitest: every unit suite and every gate
npm run type-check                     # tsc
npm run lint                           # eslint: import order, unused imports and locals
npm run gen:check                      # src/rpc/generated.ts matches the schema
node scripts/check-page.mjs            # the artifact: one style, two inline scripts, no markers
node scripts/check-css.mjs
node scripts/check-class-namespace.mjs

The page checks read dist/, so build before running them. The two boot snapshots run on their own, from build.py. The last two also run as gates under npm test, so the inner loop covers them.

make lint-ui at the repo root is gen:check, npm run lint and type-check in that order, matching lint-tui; the ui job in .github/workflows/ci.yml runs the same three and then npm test.

Gates

npm test is one run over both trees, so the 38 gate suites under scripts/gates/ go with the unit suites. Each one's header says what it pins and why; the conventions they are written to are CONTRIBUTING.md section 8.

Gate What it pins
import-direction which way an import may point; every upward and cross-domain edge, and every runtime cycle, as shrink-only lists
domain-shape the files a domain has and the name its root component exports
domain-registration every domain declared once, every page claimed by one domain, every seam key answered by one
store-shape one store shape and one set of verbs; the listener set lives only in state/store.ts
state-dom-touch how often each module in state/ and app/ may reach for an element -- counted per match, the page's own $ included -- how often the page frame -- chrome/, App.tsx, main.tsx -- may, zero for lib/ and components/, and how many text, class and markup writes each of those files still holds
seam-assignment only app/install.ts puts a source on the data seam -- under any name a file bound to it, and through a destructuring target or defineProperty too -- plus the first frame's one pinned exception, held to exactly one assignment; setSources stays the test seam, named nowhere else
island-lang every island's root subscribes to the language store
i18n-keys every literal key exists in the catalogue, sits under a namespace, and the namespace belongs to one domain
first-frame-literals the words the page shows without a t(key) behind them -- the served first frame and today's literals -- counted per file as unbroken CJK runs, escaped or not, and shrink-only
file-names what a file may be called: PascalCase components, camelCase modules, <module>.test.ts, kebab-case gates
rpc-names every method name is in the contract, and every call inside features/ is in that domain's source.ts
fixture-shape every offline responder answers the shape the contract declares, plus the fields it never sends
offline-coverage every method the page calls has an offline answer, or a reason it does not
fixture-now the offline library has no clock of its own
check-class-namespace a domain's class names carry the domain's prefix, the page frame's carry chrome- and a shared component's carry its own file name -- however the class is written: a className attribute, a class attribute inside a string of markup, a classList call, or a className={...} expression; every .tsx belongs to one of the three namespaces, the shared, unprefixed and borrowed debts may only shrink, and a class the stylesheets do not define is pinned by name
check-css the stylesheet's own declaration-level invariants
boot-order the page defers its first data-driven paint until every source is installed
first-run-model-setup a page with no provider configured sends every task action to Models
permission-chip the permission chip mirrors every settings load
rail-nav-registry every rail button a page can light is one the rail writes to
pipeline-coverage every turn event the contract declares has a stage, and no stage names one it does not
notifications-contract the notification table is the server's roster plus exactly one name
provider-mark-assets every logo the provider map names is in the bundle, and every file is named
agent-mark-css which agent marks the dark theme filters, and with which filter
agent-fold-css the roster's fold slot keeps its width on a head that cannot fold
rail-row-css the session row's height contract
rail-sig-css every state the session row's tail slot can hold has a visible mark
desk-header-css the pane header's two controls sit on one line
desk-layer-css the three layers a drag puts on the desk, in order
desk-reserve-css the chat's right inset while the anchored desk is over it
desk-page-gate the desk is bound to the chat, by a stylesheet rule
instance-composer-css a sub-agent's composer is the page's composer, one size down
agents-roster-live what the desk's agent list is a list of, on the shipped wiring
direct-chat-media-live the instance composer's send carries its attachments