Skip to main content
Glama
io.github.nslotus/on-file

io.github.nslotus/on-file

by nslotus
README.md
# Ocite

Names a held EU, Swiss, UK or US article. The reply names the article, the date stored on the text, and the source. It is not a compliance opinion, and it does not say that a document complies or that a trip is allowed. A Swiss article is not presented as the equivalent of an EU article.

<!-- mcp-name: io.github.nslotus/on-file -->

The Telegram bot, the HTTP API, and the MCP server call the same lookup, document match, travel-register door, and price functions. The bot still charges `PRICE_USD` (default 1) for a whole reply. Agents pay per call.

| Call | Default |
| --- | --- |
| One article or trip entry | $0.01 |
| EU and Swiss together | $0.02 |
| Document match | $0.05 |
| Search preview | free |

Misses are free. Each new API key also has a small free tier (`FREE_TIER_CALLS`, default 10). Prices are read from the environment. See `.env.example` for the names. That file has no values. `.env` is gitignored.

`X402_MODE` defaults to `demo`. Demo mode checks the shape of an x402 payment and records the nonce. It does not recover a signature and it does not broadcast a transaction. Do not expose a demo process on the public internet.

## What a call returns

A real answer from the current pack (`GET /v1/cite?instrument=FSMA%202000&article=19`, text shortened only where marked):

```json
{
  "held": true,
  "article": {
    "label": "Section 19",
    "jurisdiction": "GB",
    "instrument": "Financial Services and Markets Act 2000",
    "instrument_id": "ukpga-2000-8",
    "heading": "The general prohibition.",
    "text": "(1) No person may carry on a regulated activity in the United Kingdom, or purport to do so, unless he is—
(a) an authorised person; or
(b) an exempt person.
(2) The prohibition is referred to in this Act as the general prohibition.",
    "version_date": "2026-07-15",
    "url": "https://www.legislation.gov.uk/ukpga/2000/8",
    "source_notice": "Source: legislation.gov.uk. Contains public sector information licensed under the Open Government Licence v3.0. This is not the official version of the legislation ...",
    "disclaimer": "The reply names the article held in the pack, with the date stored on the text. It is not a compliance opinion ..."
  },
  "charged": false,
  "payment": "free_tier"
}
```

Other citations that work the same way: `GDPR 17`, `MiCA 59`, `FADP 25`, `26 USC 1202`, `31 CFR 800.241`, `IRC 174A`. Always quote the date, the URL and the notice, and say it is not legal advice.

## For agents

- Machine-readable guide: `/llms.txt`. What is held: `GET /v1/instruments` (free, no key). Tools over MCP: `cite`, `search`, `match_document`, `compare`.
- Get a key: `POST /v1/keys` (when the operator has opened self-serve keys), then top up with USDC on Base, TON or USDT at `POST /v1/credits/topup`. A new self-serve key holds no balance and no free calls unless the operator sets `SELF_SERVE_FREE_CALLS`. The operator opens issuing with `SELF_SERVE_KEYS_PER_DAY` (a daily cap; 0 or unset is closed). No key is issued while `X402_MODE=demo`.
- Use the hosted service from any MCP client without a local pack: set `CITE_REMOTE_URL` to the hosted `/mcp` address and `CITE_API_KEY` to your key, then run `python -m citebot mcp` (or `uvx citebot mcp` once the package is published). Messages are forwarded to the hosted server, which checks the key, the balance and the pack. The package does not ship the law pack.

## Quickstart

From this folder:

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python -m citebot key create --name local
python -m citebot serve
```

The key is printed once. Put it in `CITE_API_KEY` for MCP, or send it as `X-API-Key`. The server listens on `127.0.0.1:8080` unless `CITE_HTTP_HOST` and `CITE_HTTP_PORT` say otherwise.

Search previews are free. `EMBEDDING_PROVIDER` left empty uses a local hashing embedding mixed with BM25. Set it to `none` for BM25 only, or `openai` with `EMBEDDING_API_KEY` if you want a hosted embedding model. `LLM_PROVIDER=openai` and `LLM_API_KEY` turn on the Telegram button "Explain simply". Until those are set, the button is hidden.

```bash
curl -s http://127.0.0.1:8080/health
curl -s -H "X-API-Key: $CITE_API_KEY" \
  "http://127.0.0.1:8080/v1/cite?instrument=GDPR&article=17"
```

Interactive OpenAPI is at [http://127.0.0.1:8080/docs](http://127.0.0.1:8080/docs). The schema is `/openapi.json`.

A hit returns the instrument title, instrument id, article number, text, language, version date, source URL, and ELI when one can be derived. A search hit returns the same identity fields and a one-line preview, not the full text. EU rows carry the EUR-Lex acknowledgement. Swiss rows carry the Fedlex notice required by the Publications Ordinance: *Dies ist keine amtliche Veröffentlichung. Massgebend ist allein die Veröffentlichung durch die Bundeskanzlei.*

Without a pack database the health check reports `degraded` and cite returns 503. Build the pack on the machine that has the corpora (see below), then point `CITE_PACK` at `data/pack.db`.

### Pay for a call

Send the key on every paid route. The server then:

1. returns the miss with no charge, or
2. uses one free-tier call, or
3. debits the key's prepaid balance, or
4. returns HTTP 402 with a base64 `PAYMENT-REQUIRED` header (x402 version 2, exact scheme, USDC).

The 402 body does not include the article text. Retry the same request with `PAYMENT-SIGNATURE` set to the base64 payment payload. In demo mode any syntactically valid EIP-3009 authorization for the quoted amount is accepted and is not settled. Testnet mode quotes Base Sepolia (`eip155:84532`, USDC `0x036CbD53842c5426634e7929541eC2318f3dCF7e`) and still does not settle unless `X402_SETTLE=1` and `X402_FACILITATOR_URL` are both set. Mainnet (`eip155:8453`) is used only when `X402_MODE=mainnet`.

Prepaid balance is an alternative to x402. Top up with a USDC transfer on Base, or with TON / official Tether USDT whose comment is the key id:

```bash
curl -s -H "X-API-Key: $CITE_API_KEY" \
  -H "content-type: application/json" \
  -d '{"asset":"USDC","tx_hash":"0x..."}' \
  http://127.0.0.1:8080/v1/credits/topup
```

Demo mode does not fetch chain receipts. For a local balance while `X402_MODE=demo`:

```bash
python -m citebot key list
python -m citebot key credit --prefix cite_XXXXXXXX --usd 1
```

The same charge id cannot be used twice. A transaction already spent on a Telegram reply cannot top up a key, and the reverse is also refused.

Other routes: `GET /v1/search?q=` (free preview), `POST /v1/match` (multipart field `file`, txt / md / docx / pdf, 2 MB), `POST /v1/trip` with `{"text":"..."}`, `POST /v1/compare` with `{"query":"..."}` or `{"eu":"GDPR 17","ch":"FADP 6"}`. Compare returns both texts when both are held and says that no crosswalk was applied. The Telegram "Same topic elsewhere" button reads `citebot/concepts.json` and `citebot/concept_members.json` (articles filed under the same topic, any jurisdiction) and marks each unverified match as such. It never says two laws are equivalent.

### Telegram questions

Any message that is not a command or a file searches the pack and shows the top three previews with an unlock button for each full text. `/start` adds topic buttons. The questions live in `citebot/topics.json`. After a paid article, the chat offers "Same topic elsewhere" (the jurisdictions with articles filed under the same concept, verified matches first), related articles, and a watch. "Explain simply" appears only when an LLM provider is configured. An opened article can be watched: at the start of each polling run the bot compares watched articles with the pack it serves and messages the watcher once when the text changed (`/watching` lists and stops watches; webhook mode does not run this check). A person's first single article is free (`FREE_UNLOCKS=0` turns that off). Previews of up to three EU, Swiss, UK or US articles quote the opening words (at most 80 characters and never more than a third of the article), with the licence notice.

`/in ch,tr <question>` searches those countries only. A question that names a country searches only that country, by name ("in Singapore", "Swiss"), code (UK, CH) or regulator (FCA, FINMA). Codes and regulators count only in capitals. A country that is not held yet gets "… law is not held yet." It is free, with no button and no invoice. The API's `/v1/search` takes `jurisdictions=uk,sg` and MCP `search` takes `"jurisdictions": ["ch"]`. Both list `not_held_yet`. `citebot/countries.json` names the countries a question can name before they are held.

### Jurisdictions

Each held jurisdiction has `citebot/registry/<code>.json` (`eu.json`, `ch.json`, `tr.json`). It sets the jurisdiction's wording and rules: names and codes a question may use, article and id labels, source name, default licence, text layout, the language line ("Swiss text in German (official language version)", "(unofficial translation)" for a held translation), and which jurisdiction an article may be compared with. It also lists the instruments: `native_id`, `short_name`, `aliases`, `articles_kept`, `mode` (`full` or `link_only`), `official_url`, `required`, `max_age_days`, the English `scope` Jev reads, and optional query `keywords`. `aliases.EU`, `CH`, `SHORT`, `CH_ARTICLES` and `CH_ACTS` are built from these files. Nothing reads `required` or `max_age_days` yet.

A `link_only` instrument shows a free card: its title, the official link and "Text not held (publisher's terms)". It is never priced. No instrument is marked link-only today.

Each reply's notice and attribution come from the pack's licences table, so they match the licence the text was ingested under. A pack that records none falls back to the registry's licence in `licences.json`.

### Jev cost control

Search ranks each jurisdiction by keywords (BM25 plus the registry keywords). It then sends at most `JEV_MAX_CANDIDATES` (default 8) articles to Jev in one call. Only when Jev finds none of them answers does it run the older three steps: act, headings, answer. Every Jev answer is cached in `data/jev_cache.db` (or `JEV_CACHE`), keyed by the hash of the normalised question, the article's text hash and the model, so a repeated question makes no call. Real calls are counted per day before they are sent. At `JEV_DAILY_CAP` (default 2000) search fails closed, exactly as when Jev is down: "No article held answers this", no button, no invoice. `python -m citebot jev-usage` prints the daily counts. Only counts and hashes are stored, never question text.

### MCP

Stdio, from this folder, with `CITE_API_KEY` set:

```bash
python -m citebot mcp
```

A client config:

```json
{
  "mcpServers": {
    "on-file": {
      "command": "python",
      "args": ["-m", "citebot.mcp"],
      "cwd": "/absolute/path/on-file",
      "env": {
        "CITE_API_KEY": "paste-the-printed-key",
        "CITE_PACK": "/absolute/path/on-file/data/pack.db"
      }
    }
  }
}
```

The module is `citebot.mcp`. `python -m citebot mcp` is the same process.

Tools: `cite`, `search`, `match_document`, `compare`. A miss is a normal tool result with `"payment": "miss"`. A hit with no free tier, balance, or `payment_signature` argument comes back as an error result whose `structuredContent.payment_required` is the x402 object. `initialize` and `tools/list` do not charge.

The same tools are posted as one JSON-RPC body to `POST /mcp` with the API key header.

`server.json` is the Official MCP Registry manifest (schema `2025-12-11`, name `io.github.nslotus/on-file`). Before publishing, put the package on PyPI so the registry can see `mcp-name: io.github.nslotus/on-file` in this readme, and replace `https://onfile.example.com/mcp` with the hosted URL.

### Telegram

Unchanged entry point:

```bash
python -m citebot.bot
```

Set `TELEGRAM_BOT_TOKEN`, `PAY_TON_ADDRESS`, and `PAY_USDC_ADDRESS`. `PAY_DEMO=1` still unlocks `/paid demo` for a private chat. That switch does not turn on API demo credit.

### Tests

```bash
python -m unittest discover -s citebot -p 'test_*.py'
```

The payment, source, API, and MCP tests do not open a network connection and do not settle mainnet. `citebot.test_travel_door` still calls the travel register on this machine. If `TRAVEL_DB` and `TRAVEL_SRC` are not set, those tests fail closed on the missing register. The citation tests do not need it.

### Docker

```bash
docker build -t on-file .
docker run --rm -p 8080:8080 \
  -e X402_MODE=demo \
  -e CITE_HTTP_HOST=0.0.0.0 \
  -v "$PWD/data:/app/data" \
  on-file
```

The image does not contain `.env` or a pack. Mount `data/` so `/app/data/pack.db` and the billing file persist.

## Build the pack

The corpora are not in this repository.

```bash
export EU_DB="/path/to/lcg_eu.db"
export FEDLEX_DIR="/path/to/fedlex"
python -m citebot build
```

Fedlex files are named `SR_{sr}_{YYYY-MM-DD}_de.txt`. The build keeps the latest file whose date is on or before today. A consolidation dated 2027-01-01 for SR 952.02 or SR 956.1 is left out until that date. SR 951.311 Art. 126z is stored once, keeping the longer text.

EU source URLs are the EUR-Lex CELEX link plus an ELI derived from the CELEX number (`http://data.europa.eu/eli/reg/2016/679/oj` for the GDPR). Swiss source URLs are the Fedlex classified-compilation page and the point-in-time ELI for the instruments in `citebot/aliases.py`.

### Turkish acts

`citebot/registry/tr.json` lists the Turkish acts and the names a person can type (SPKn, MASAK Law, KVKK, Payments Law, Banking Law, or the law number). The `tr-lcg` converter reads them from `TR_DB` (the Turkish lcg corpus, read-only) and reports any act it cannot find as missing. Turkish text is held in Turkish only. Every reply starts with "Turkish text (official language). No English translation held." Nothing is machine-translated.

The `tr-mevzuat` licence has no `terms_checked_on` date yet, so `ingest tr-lcg` refuses. For local testing only:

```bash
python -m citebot ingest tr-lcg --allow-unchecked-licence          # writes data/akn-unchecked (gitignored)
python -m citebot pack --akn data/akn --akn data/akn-unchecked --include-unsold --allow-unchecked-licence
ONFILE_DEMO=1 CITE_PACK=data/pack.next.db python -m citebot cite KVKK 11
```

Licence flags are enforced in code. With `commercial_ok` 0, `pack` leaves the licence's text out and lists what it left out; only `--include-unsold` (demo and test builds) keeps it, and that pack is marked `unpublishable` and can never pass `--strict`. In such a pack the articles are still never cited, searched, previewed or matched, except under `ONFILE_DEMO=1`. With `raw_resale_ok` 0 there is no bulk or export route, and no reply carries more than five full texts. A test pins the route list. `tr-mevzuat` has both flags at 0: mevzuat.gov.tr publishes no reuse terms (see its `usage_note`).

That pack is marked `unpublishable`. The bot, the API, MCP and `cite` refuse to start on it unless `ONFILE_DEMO=1`. (`X402_MODE=demo` does not count, since it is the default.) Once the terms are read, record the date in `citebot/licences.json`, then re-ingest into `data/akn` without the flag.

### Strict packs, weekly updates and rollback

The bot, the API and MCP only start on a pack that passed `python -m citebot pack --strict` (`meta strict=1`), unless `ONFILE_DEMO=1`. The check fails, and lists why, when a required instrument (registry `required`) is missing or empty, an expression was fetched longer ago than its `max_age_days`, a licence in the pack has no `terms_checked_on`, an eId repeats within an expression, a provision has empty text (a Swiss top-level article with empty text is read as repealed), or the pack is `unpublishable`. Required acts of an unsold jurisdiction (Turkey) are listed as skipped.

```bash
python -m citebot pack --akn data/akn --akn data/akn-unchecked --strict   # data/pack.next.db
python -m citebot update            # fetch, rebuild, --strict, data/reports/diff-<date>.md, swap on success
python -m citebot update --jur ch   # fetch Swiss sources only; the rebuild still uses all of data/akn
python -m citebot update --no-swap  # report only
python -m citebot rollback          # the newest data/pack.<date>.db becomes pack.db again
```

`update` swaps only when strict passes and something changed (or `pack.db` itself has no `strict=1`): `pack.db` is copied to `data/pack.<date>.db`, `pack.next.db` becomes `pack.db`, and only the last three dated packs are kept. The report lists new, removed and changed provisions per instrument with a short word diff, the versions held, and consolidations that apply from a later date. Concept members whose article text changed go back to `unverified` in `citebot/concept_members.json`; review them with `python -m citebot concepts review` and commit the file. `rollback` keeps the pack it replaces as `data/pack.rolledback.db`.

Schedule it weekly. These commands are for you to run; nothing here creates them.

Windows Task Scheduler on the PC (Mondays 04:00):

```bat
schtasks /Create /TN "OnFile weekly update" /SC WEEKLY /D MON /ST 04:00 /TR "cmd /c cd /d \"C:\path\to\ocite\" && python -m citebot update >> data\reports\update.log 2>&1"
schtasks /Query /TN "OnFile weekly update"
schtasks /Delete /TN "OnFile weekly update" /F
```

cron on hostm (`crontab -e`; replace `<app>` with the app folder there). This only works if hostm has the EU corpus (`EU_DB`) and a full `data/akn` (the AKN XML files are not in git; only the manifest is). Without them the rebuild fails `--strict` and nothing is swapped, so the PC task plus the copy below is the simpler route:

```cron
0 4 * * 1 cd <app> && python3 -m citebot update >> data/reports/update.log 2>&1
```

Or copy a pack built on the PC to the server, after a successful `update` (the rename on the server is one step, so the bot never reads a half-copied file):

```bash
scp data/pack.db <user>@hostm:<app>/data/pack.next.db
ssh <user>@hostm 'cd <app> && cp data/pack.db "data/pack.$(date +%F).db" && mv data/pack.next.db data/pack.db && touch tmp/restart.txt'
```

`touch tmp/restart.txt` restarts the Passenger app so it reopens the pack. Use the cron job or the copy, not both.

### EU text

EU acts come from the Publications Office's Cellar, which serves the same documents as EUR-Lex (licence `eu-cellar` in `citebot/licences.json`: Commission Decision 2011/833/EU and the CC BY 4.0 EUR-Lex policy, the same attribution footer; confirmation requested from op-copyright@publications.europa.eu). For each act the latest consolidation that applies today is the expression held. An act with no English consolidation beyond its first is read from its Official Journal page; when a later consolidation has no English text the act is left out and `--strict` fails. Later consolidations are listed in the update report. It sends one request every two seconds with `ONFILE_CONTACT` in the User-Agent.

The local `lcg_eu.db` corpus is no longer needed. Its converter, `eu-lcg`, is an offline fallback only: on 2026-12-05 it held 21 articles that the official consolidated texts did not.

```bash
python -m citebot ingest eu-cellar --fetch
python -m citebot update --jur eu --no-swap   # the same, plus rebuild, --strict and the diff report
```

As of 2026-11-26 only the AI Act has one: the consolidation of 2026-07-27, which adds Articles 4a, 60a and 75a to 75d. Cellar lists an initial consolidation for the other five but holds no English text for it (HTTP 404), so their OJ text stays.

### US federal law

`citebot/ingest/us_gov.py` holds two converters. `us-usc` reads US Code titles from the Office of the Law Revision
Counsel (USLM XML; the zip link is read off `uscode.house.gov/download.html`, so the release point is never
hard-coded). `us-ecfr` reads CFR parts from the eCFR versioner API as of the date eCFR gives (the API insists on
gzip, which the converter reads back). US Government works are public domain (17 U.S.C. 105), so licences `us-usc` and
`us-ecfr` are checked and sold. Held:

- 26 USC: sections 11, 41, 174A, 871, 881, 892, 1202, 1441, 1442, 1445, 1471-1474 (FATCA), 7701;
- 31 USC 5311-5336 (Bank Secrecy Act);
- 15 USC: the Securities Act and Trust Indenture Act (77*), the Exchange Act and SIPA (78*), the Investment Company
  Act (80a*) and the Advisers Act (80b*);
- 31 CFR Parts 800 (CFIUS), 1010, 1022 and 1023 (FinCEN).

`articles_kept` in `registry/us.json` picks sections: an exact number (`1202`), a range (`1471..1474`, which also takes
`5318A`) or a prefix (`78*`, which takes `78j-1`). USLM prints hyphenated sections with an en dash; the pack keeps
`78j-1` as `78j1` and the card prints `§ 78J-1`. Cards say Title 26 and Title 31 are not positive law (1 U.S.C. 204)
and the eCFR is not the official CFR. Typed as `26 USC 1202`, `26 U.S.C. § 1202`, `IRC 174A`, `15 USC 78j-1`,
`BSA 5318A`, `31 CFR 1010.311`.

```bash
python -m citebot ingest us-usc --fetch
python -m citebot ingest us-ecfr --fetch
python -m citebot update --jur us --no-swap
```

### Singapore text (built, not live)

`citebot/ingest/sg_sso.py` reads Singapore Statutes Online pages (HTML; SSO publishes no Akoma Ntoso). It is not on
sale: licence `sso-agc` has an empty `terms_checked_on`, so `update` never fetches or builds it, and the registry is
`citebot/registry/sg.json.draft` (ignored until renamed to `sg.json`). SSO's Terms (clause 13) allow automated
extraction only 03:00-07:00 Singapore time = 19:00-23:00 UTC, and its WAF blocks quick requests, so the converter
fetches one Act every 65 s, only in that window, and stops at the first refusal (no retry). Outside the window it
uses the files already in `data/raw/sg`. Needs `pip install "citebot[ingest]"` (beautifulsoup4). First check of
the whole-Act URL and the Act codes, inside the window:

```bash
python -m citebot.ingest.sg_sso probe PSA2019 PDPA2012
```

### UK text

UK acts come from legislation.gov.uk as Akoma Ntoso XML (`uk-legislation`; licence `ogl-v3`: Open Government Licence v3.0, commercial reuse with attribution; the notice says the text is not the official version). The acts are the `GB` instruments in `citebot/registry/gb.json`, named `<type>-<year>-<number>` as in `legislation.gov.uk/<type>/<year>/<number>`. Each is fetched whole as it is in force today, one request every two seconds. One section (or UK GDPR article, or regulation) is one provision with each numbered paragraph on its own line. Left out: sections the file marks repealed or not yet in force, a section that prints only repeal dots, words inside `<del>`, and schedules. A UK act is cited by name: `DPA 2018 s 19`, `UK GDPR 5`, `MLR 2017 reg 27`, `FSMA 19`.

```bash
python -m citebot ingest uk-legislation --fetch
python -m citebot update --jur gb --no-swap
```

CLI, same core:

```bash
python -m citebot cite GDPR 17
python -m citebot file notes.txt
python -m citebot trip cheese from CH to IT by road
```

## What is still outside this process

- A public host, a domain, and TLS. The registry remote URL is a placeholder.
- A schedule that pulls new EUR-Lex consolidations and Fedlex files and rebuilds `pack.db`. The in-force rule only helps after those files are on disk.
- An EU–Swiss crosswalk. `compare` retrieves each side on its own and says so.
- Publishing `citebot` to PyPI. The registry will not verify the package until that exists.
- Mainnet settlement. Set `X402_MODE=mainnet`, `X402_SETTLE=1`, and `X402_FACILITATOR_URL` only when a facilitator should move USDC. Leave them unset for local use.
- The travel register, which still lives outside this repo. Set `TRAVEL_DB` and `TRAVEL_SRC`. Medicine stays out of scope. Silence is unchecked, not allowed.