Metadata-Version: 2.4
Name: myopenfund-company-corpus
Version: 0.2.0
Summary: Open-data corpus of company filings (SEC EDGAR + EU OAMs + national registers) — the bottom-up/micro counterpart to central-bank-corpus.
Author: Marc Jeulin
Maintainer: Marc Jeulin
License-Expression: MIT
Project-URL: Homepage, https://github.com/MyOpenFund/company-corpus
Project-URL: Source, https://github.com/MyOpenFund/company-corpus
Project-URL: Issues, https://github.com/MyOpenFund/company-corpus/issues
Project-URL: Organization, https://github.com/MyOpenFund
Keywords: myopenfund,sec,edgar,esef,xbrl,filings,open-data
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Intended Audience :: Developers
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: DATA_LICENSE
Requires-Dist: requests>=2.31
Requires-Dist: beautifulsoup4>=4.12
Requires-Dist: lxml>=5.0
Requires-Dist: pandas>=2.0
Requires-Dist: python-dateutil>=2.9
Requires-Dist: duckdb<3,>=2.0
Requires-Dist: pyarrow>=17
Provides-Extra: be
Requires-Dist: curl_cffi>=0.7; extra == "be"
Provides-Extra: eu-financials
Requires-Dist: arelle-release; extra == "eu-financials"
Provides-Extra: store
Requires-Dist: myopenfund-open-data-store[writer]<0.2,>=0.1.0; extra == "store"
Provides-Extra: live
Requires-Dist: myopenfund-open-data-store<0.2,>=0.1.0; extra == "live"
Requires-Dist: markitdown<1,>=0.1; extra == "live"
Dynamic: license-file

# company-corpus

Created and maintained by [Marc Jeulin](https://github.com/jeulinmarc), part of [MyOpenFund](https://github.com/MyOpenFund).

An exhaustive, replicable, **open-data** corpus of **company** primary-source
documents — the *bottom-up / micro* layer that complements
[`central-bank-corpus`](https://github.com/MyOpenFund/central-bank-corpus). Both feed the
MyOpenFund stack (vault → [`data-orchestrator`](https://github.com/MyOpenFund/data-orchestrator) →
eigenmind/Qdrant). **Today only the SEC EDGAR pillar reaches that chain; the EU
and register pillars are acquired and parsed but not yet exported to the vault**
(tracked in the project notes).

Every document comes from the issuer's **regulator of record** (SEC, AMF, FCA,
CONSOB, …) — public, primary-source disclosures, with provenance recorded per
file. No proprietary datasets, no machine translation, no model-generated text.

## Three pillars

| Pillar | Region | Source of record | Identity | Status |
|---|---|---|---|---|
| **🇺🇸 SEC** | United States | EDGAR | CIK | complete (reports, ownership, XBRL financials) |
| **🇪🇺 EU** | 14 jurisdictions | national OAMs + Euronext + FCA NSM | LEI / ISIN | 13 backend keys / 12 classes (`IE` reuses `GB`) + Euronext for `PT` |
| **Register** | 8 countries | national business registers | local entity ID | 8 registers merged — [`REGISTER_FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/REGISTER_FINANCIALS.md) |

All three pillars share the same discipline (official sources only, stable ids,
exhaustive discovery, never silently partial) and feed the same RAG contract. The
SEC and EU pillars cover listed issuers (CIK / GLEIF LEI); the register pillar
targets the credit and private-company universe of non-listed entities.

### Structured financials

Beyond raw filings, a shared engine (`financials.py`) extracts curated metrics into
a unified per-period row schema (see [`docs/FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/FINANCIALS.md)):

| Layer | Universe | Source | Status |
|---|---|---|---|
| **SEC XBRL** | US listed issuers | EDGAR `companyfacts` | ✅ done |
| **EU ESEF / IFRS** (Pillar B) | EU listed issuers | `filings.xbrl.org` json_url + Arelle (Tier B) | ✅ done — [`EU_FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/EU_FINANCIALS.md) |
| **Register financials** | Private / credit universe (non-listed) | 8 national registers: 🇳🇴 NO · 🇬🇧 UK · 🇧🇪 BE · 🇱🇺 LU · 🇫🇮 FI · 🇩🇰 DK · 🇪🇪 EE · 🇸🇰 SK | ✅ all eight registers merged — [`REGISTER_FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/REGISTER_FINANCIALS.md) |

The register pillar targets issuers that never file ESEF — bond obligors, private
companies, bank counterparties. Output lands in `data/financials_register/` (never
merged with `data/financials_eu/`), labelled by `basis` (legal-entity vs.
consolidated). It is governed by a **no-false-data** discipline: any value that
cannot be confirmed from structural anchors is suppressed, not guessed. Leverage
rows carry a `leverage_basis` field (`"borrowings"` or `"total_liabilities"`)
because registers differ — some expose real financial borrowings (BE/LU/SK/DK-ESEF),
others only total liabilities (NO/UK/EE/DK-FSA) — so consumers cannot compare
`debt_to_equity` across registers without knowing the basis.

## Install

```
pip install "myopenfund-company-corpus"           # the corpus tool and the `company-corpus` command
pip install "myopenfund-company-corpus[store]"    # + the open-data-store writer, for `store-batches`
pip install "myopenfund-company-corpus[live]"     # + contract schemas and MarkItDown, for live mode
```

The PyPI distribution is `myopenfund-company-corpus` (the `myopenfund-` prefix groups the MyOpenFund
packages); the import name (`company_corpus`), the command (`company-corpus`) and the repository
name are unchanged. Other extras: `[be]` (Belgium backend) and `[eu-financials]` (Arelle).

If this environment installed the old distribution (`company-corpus`, from a clone or a git URL), run
`pip uninstall -y company-corpus` before installing `myopenfund-company-corpus`: both own the same
import package.

To try the latest `main` before a release (dependencies still come from PyPI):

```
pip install "myopenfund-company-corpus @ git+https://github.com/MyOpenFund/company-corpus"
```

**Working across repos**

Clone the repos side by side and install this package editable over the PyPI version in the
consumer's environment: `pip install -e ../company-corpus`. A consumer change that needs an
unreleased version waits for this package's release before the consumer's PR merges.

**How to release**

Bump `__version__` in `company_corpus/__init__.py` in a PR (the version is read from there). Run `pip install -e .` again locally so the installed metadata follows. After the PR merges, go to Actions, then release, then Run workflow: pick the `main` branch and target `pypi`. Approve the `pypi` deployment. The workflow builds the package, checks it, publishes it, then creates the tag `v<version>` and the GitHub Release itself.
It fails before publishing if it is not run on the default branch or if that tag already exists. Target `testpypi` is a rehearsal: it publishes to TestPyPI and creates no tag and no release.
Pushing a tag `v<version>` by hand still works: the workflow checks that the tag equals the package version and is on the default branch, then publishes and attaches the files to the Release.
If PyPI got the package but the tag or the Release is missing, re-run the failed `github-release` job from Actions; do not push the tag by hand (the re-run would fail at the PyPI upload).
To raise the cap of a sibling dependency (`[store]`), edit its range in `pyproject.toml` (floor `>=X.Y.Z`, cap the next breaking version) and the exact pins in `requirements-*.txt`; the tests check the rule, not a number.

## Quick start

```bash
pip install -r requirements.txt           # runtime-only
pip install -r requirements-dev.txt       # adds pytest-socket, the pinned myopenfund-vault-contract (tests only)
python -m pytest -q                       # network-free test suite

export COMPANY_CORPUS_CONTACT="you@example.com"   # required before any live crawl
```

There is **no default contact** — without it the `User-Agent` carries only the
tool name, so cloning the repo never leaks anyone's address. Regulators ask for a
real contact, so set it before crawling.

```bash
# SEC: build a tiny universe, discover + download
python -m company_corpus build-universe --tickers AAPL,MSFT --name demo --write
python -m company_corpus discover --universe demo --download --since 2015-01-01 --write

# EU: acquire one issuer's regulated filings by ISIN (resolves the LEI via GLEIF);
# dry-run by default (discovery only, nothing written), --write downloads
python -m company_corpus eu-acquire --isins FR0010193052
python -m company_corpus eu-acquire --isins FR0010193052 --write

# Register financials: Norwegian statutory accounts (Brreg, no key required)
python -m company_corpus register-financials --orgnrs 923609016 --write
# UK Companies House bulk iXBRL (Arelle required; --limit for a bounded test run)
python -m company_corpus register-financials --ch-bulk accounts_monthly_2024_01.zip --limit 100
```

## Feeding the vault (`documents` contract)

Every SEC manifest line (`data/manifest/<cik>.jsonl`, families `A`–`E`) is a row of the
vault's `documents` contract 1.0.0 (`corpus: company`, `source_code: sec`, `doc_type` = the
form code, `sha256` = the primary document as the SEC served it, `local_path` = the rendered
PDF else the cleaned text, `entity_scheme: cik`), and `data/vocabulary.json` declares its
codes; the vault ingests both as they are. F1 summaries are not vault documents: they live in
`data/derived/f1/<cik>.jsonl`. Every command reads the contract form only: a manifest row in
the pre-contract form (a clone whose data predates the contract) stops the command with
`ManifestNeedsMigration`, naming `migrate-contract`. Such a corpus is migrated once, and the
migration is a **one-way door**: code from before the contract cannot read the new rows and its
next write would rewrite a manifest from almost nothing.

```bash
# 0. back up: APFS snapshot (tmutil localsnapshot) or a copy of data/manifest and data/derived
# no `xbrl --write` between the code update and the end of the migration
python -m company_corpus migrate-contract            # dry run: read the counts
python -m company_corpus migrate-contract --write    # then: re-run -> rows_rewritten=0 f1_moved=0
python -m company_corpus verify --hash               # 0 findings
pip install -r requirements-dev.txt                  # then the vault's checker, exit 0:
python -m vault_contract.check data/manifest --corpus company --vocabulary data/vocabulary.json --no-transition --strict
```

After `--write`, only code that knows the contract may run with `--write` on that corpus;
rollback = restore the backup, never check out older code. The counters and the provenance
check: [`docs/INGESTION_RAG.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/INGESTION_RAG.md#migrating-a-corpus-written-before-the-contract).

Details, the artefact rule and the checks: [`docs/INGESTION_RAG.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/INGESTION_RAG.md).

## Feeding open-data-store (`store-batches`)

`store-batches` turns layer 0 (the stored `companyfacts.json` and the EDGAR
submissions archive) into [open-data-store](https://github.com/MyOpenFund/open-data-store)
batches. For each issuer it emits one `entity_observations` batch, one `fundamentals` 3.1.0
batch (facts as filed, by tag) and one `filing_statements` 1.0.0 batch (which tag is on which
statement) and one `filings` 1.0.0 batch (each report filing's form and `reportDate`, from the
submissions archive), always the full history; replaying the same inputs is a no-op in the store.
`company-corpus statements --universe <name> --write` first archives the SEC bulk files
(5.7 GB under `raw/_sec_statements/`) and extracts the positions per issuer. Which tag answers
which concept is decided when reading: see [`docs/FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/FINANCIALS.md).
`store-batches` writes into a landing zone and never publishes: you run
`open-data-store publish` afterwards. It is a dry run unless `--write`.
A `fundamentals.filing_ref` can lack a `filings` row when EDGAR lists the filing under another
accession number than the one companyfacts cites (3 of 40,049 on the 672-issuer corpus,
2026-11-09): a reader treats an unmatched `filing_ref` as form unknown.
Run with `--write` and without `--offline` to refresh stale archives: offline, filings made after
the last archive fetch are missing from `filings` and their facts carry the fallback `known_at`.

Before PyPI, the store was installed under its former names (`my-open-data`, renamed 2026-11-22,
then `open-data-store` from a git URL): run `pip uninstall -y open-data-store` (or `my-open-data`)
before it is installed again as `myopenfund-open-data-store`, and rename `MYOPENDATA_*` variables to
`OPEN_DATA_STORE_*` in your shell profile (an unset `OPEN_DATA_STORE_DATA_ROOT` turns the `--landing`
below into `/landing`).
Details: the store's
[`docs/MIGRATION.md`](https://github.com/MyOpenFund/open-data-store/blob/main/docs/MIGRATION.md).

```bash
# open-data-store writer (optional extra); publishing needs myopenfund-open-data-store[publisher]
pip install "myopenfund-company-corpus[store]"
company-corpus --contact "$SEC_CONTACT" store-batches --universe sp_curated \
    --landing "$OPEN_DATA_STORE_DATA_ROOT/landing" --write
open-data-store publish
```

The CLI stays importable without the extra; `store-batches` then fails cleanly
(exit 1) and says what to install.

**Submissions archive.** Identity observations come from `raw/<cik>/submissions/`
(the main `submissions` JSON plus its paginated files, each with a sidecar). A
missing archive is fetched on `--write`; `--refresh-submissions` re-fetches it to
pick up new observations; `--offline` never fetches, so an issuer without an archive
fails. `--refresh-submissions` with `--offline` is a usage error. `verify` treats
the archive as layer 0, like `companyfacts.json`. A dry run reports an issuer
without an archive as `pending_fetch` and writes nothing.

**Stale archive.** A new filing absent from the archive would get the fallback
`known_at`, and a later refresh would add a second vintage with an earlier `known_at`.
So on `--write` without `--offline`, an issuer's archive is re-fetched once
(`submissions_refreshed:stale`) when its companyfacts has a point the run would emit from
a filing the archive does not list and whose `filed` date is on or after the archive's
`fetched_at` date, in `Config.store_edgar_day_tz` (default `America/New_York`; independent
of the fallback zone). EDGAR's filing date is typically not before the acceptance date in
Eastern time, so such a filing can be newer than the archive; a retroactive adjustment is
the exception and costs one fallback vintage, without conflict. Older accessions missing
from the archive never trigger a refresh: they keep the fallback `known_at`, or they would
refresh on every run. A `filed` date more than `Config.store_stale_filed_max_days_ahead`
(default 7) days after the run day is implausible and ignored; the archive's own age does
not matter, so an old archive with a recent filing still refreshes. A dry run and `--offline`
never fetch: they count `submissions_stale` and keep the fallback. A failed refresh is
that issuer's failure, like any fetch failure, and leaves its archive as it was. A
refresh, automatic or not, also adds new identity rows, because the
`entity_observations` `known_at` is the archive's fetch time, at a new `valid_date`: about
one refresh per periodic filing; each adds one row per ticker and, for issuers without former
names, a CIK row. `entity_observations` is therefore not one row per identifier;
`entity_attributes` collapses them.

`--offline --write` with a stale archive publishes the fallback vintage, and those rows
stay in the append-only store.

**Point selection and `known_at`.** Fundamentals durations are classified by
fiscal-week bands (`Config.store_duration_bands`). `known_at` is the filing's
acceptance time. When a filing has no
acceptance time, a fallback is used (`Config.store_known_at_fallback_tz` /
`store_known_at_fallback_time`); when that filing was filed on the run day, the
fallback is capped at run time, so a later run records another version with a later
`known_at` (a new vintage, not a conflict) -- visible as `known_at_capped`.

**Namespaces.** Ingestion reads every taxonomy namespace the dictionary loads (`us-gaap`, `ifrs-full`) plus `dei`.

**Reporting currency.** It is decided per filing, from that filing's own facts in the loaded taxonomies (`us-gaap` and `ifrs-full`, not `dei`)
by a vote over its monetary facts, cross-checked against its balance sheet totals
(`Config.store_currency_anchor_tags`, full `ns:Tag` names: the us-gaap and ifrs-full balance sheet
totals). Values are stored as filed, in that reporting currency (GBP, CAD, ...). A tied vote is settled by the totals; a contradiction,
or nothing to settle a tie, publishes no money (`dropped:currency_ambiguous`). A filing
without balance sheet totals (a partial 10-K/A) rests on the vote alone. An issuer that switches
currency therefore has one natural key with different units across vintages, as filed.
This differs from the F1 engine's issuer-wide rule.
`Config.edgar_country_codes` maps EDGAR state/country codes to countries; an unmapped
code is reported, never guessed.

**`fiscal_year` is null by design.** The column is in every row and is always null; a
reader view in open-data-store will derive it. Fiscal years can only be computed from the
year-ends known today, so a later 10-K or 10-KT changes the label of rows that are
already published. The full history is re-emitted every run, and the publisher
quarantines a batch whose row has the same `(natural_key, known_at)` as a published row
but another value (`conflicting_republish`): the issuer's batch would stay quarantined
for good. Every emitted column must be a pure function of immutable inputs.

**Run report.** `data/runs.jsonl` carries `details.store_batches` (per-issuer status,
rows, batch ids, counters, plus totals). The run also prints one `coverage <concept>: ...` line
per concept, counting how many issuers have it on a statement, in a note, inferred, absent and so
on. Counters:

| counter | meaning |
|---|---|
| `dropped:odd_duration`, `dropped:period_shape` | duration points outside the configured bands or shape (the 9-month year-to-date band is emitted as `ytd9`) |
| `dropped:non_reporting_currency`, `dropped:unexpected_unit` | unit filters; the reporting currency is that of each filing, so later filings never change the points selected from earlier ones |
| `dropped:currency_ambiguous` | a filing's vote over its monetary facts and the currency of its balance sheet totals contradict each other, or tie with nothing to settle them (also: per-share points only, in several currencies): the filing publishes no money rather than risk a wrong row. Investigate any non-zero count |
| `dropped:not_a_report` | a point from a form that is not a financial report (`Config.store_report_forms`), such as a proxy statement |
| `statements_missing` | no statement positions archived for the issuer: run `company-corpus statements` |
| `dropped:bad_point`, `dropped:no_known_at`, `dropped:value_out_of_range` | unusable points |
| `dropped:implausible_filed` | a point with no acceptance time whose `filed` date is more than `Config.store_stale_filed_max_days_ahead` days after the run day (Eastern): dropped, or it would be a new vintage on every run |
| `ambiguous_observation` | competing points the selection could not separate |
| `submissions_refreshed:stale`, `submissions_stale` | the archive was older than a filing in companyfacts: re-fetched / not re-fetched (dry run, `--offline`) |
| `known_at_fallback`, `known_at_capped`, `known_at_naive` | `known_at` derived without an acceptance time (capped at run time / naive timestamp) |
| `source_doc_id_null` | any report form outside the taxonomy (10-KT, 10-QT): the row has a null `source_doc_id` |
| `filing_not_in_manifest` | informational: the `source_doc_id` is set but no manifest row holds it (an issuer whose filings were never discovered; F1 summaries live in `derived/f1/`, not in the manifest) |
| `filings:<counter>` | the `filings` batch's counters, prefixed: `filings:dropped:not_a_report` (non-report forms), `filings:dropped:bad_filing_date`, `filings:report_date_missing`, `filings:ambiguous_filing`, `filings:known_at_fallback`, plus the shared known_at / source_doc_id counters (`known_at_capped`, `known_at_naive`, `dropped:no_known_at`, `dropped:implausible_filed`, `source_doc_id_null`, `filing_not_in_manifest`), prefixed the same way |
| `value_rounded` | value rounded to fit the contract |
| `country_unknown[:code]` | unmapped EDGAR country code |
| `former_name_shadowed`, `former_name_undated` | former-name handling in identity rows |

`dropped:no_known_at`, `source_doc_id_null` and `filing_not_in_manifest` also count `filing_statements` rows, not only facts.

An unexpected exception in one issuer is recorded as `failed` with
`unexpected: <Type>: <msg>` and the run continues with the next issuer.
The command prints at most 10 failed issuers; the run report has them all.

**Good to know.**

- Changing `edgar_country_codes` after a publish needs `--refresh-submissions --write`
  for the affected issuers: identity rows then get a new `known_at`. Otherwise the same
  `(natural_key, known_at)` comes back with another value and the publisher quarantines
  the batch as `conflicting_republish`.
- A refresh does **not** help fundamentals: their `known_at` is the acceptance time, which
  never moves. The form taxonomy (`taxonomy.from_edgar_form`) and the currency rule are
  frozen once published, short of a store migration. The concept dictionary is not: rows are
  as filed, so changing it changes no row, and a new tag brings new rows.
  `tests/opendata/test_published_derivations.py` checks that, and pins the whole form index
  (additions and removals fail; 10-KT and 10-QT stay unmapped), the currency anchor tags, the
  ISO currency pattern and the `source_doc_id` recipe (one literal hash). The vote rule itself
  is covered by the point-selection tests, not the golden file. Changing a pinned item alters
  rows already published at the same `known_at`, which the publisher quarantines.
- Known limit: two filings of one issuer accepted in the same second (or sharing a `filed`
  day on the fallback path), with an equal value, where the lower accession appears only in
  a later companyfacts. `source_doc_id` then changes for that key, and the fundamentals
  batch is quarantined (`conflicting_republish`) until an operator repairs it. It is loud
  and has not been seen in the corpus.
- Former-name identity rows have a null country: EDGAR gives a country only for the
  current address.
- A 17-week fourth quarter (119 days) falls outside the default quarterly band (81 to
  115 days) and is dropped as `odd_duration`.

**Exit codes.** `0` every issuer emitted (or pending, in a dry run); `3` at least one
issuer failed (the run is `degraded`); `1` fatal (landing zone not writable,
open-data-store not installed, corpus lock held); `2` usage error.

The end-to-end test (writer, then publisher) needs the DuckDB `ducklake` extension
and skips when it cannot be installed. With `REQUIRE_DUCKLAKE=1` that is a failure
instead: the CI `store` job pre-installs the extension and sets it, so CI cannot pass
without having run the test.

**Reading the store back.** A store reader (such as `myopenfund-mcp`) gets F1's concepts and
ratios from published rows without recomputing anything: run
`concepts.selection.run_selection(facts, positions)` on one issuer's `fundamentals` vintages
and `filing_statements`, then `concepts.store_summaries.summaries_from_rows(rows, company=...,
vintages=<the same fundamentals rows>)`. It returns the same `PeriodSummary` objects as F1
(`values`, point-in-time `derived` ratios, `ttm` ratios); `concept_catalog()` (entries carry `kind`, not a unit) and
`metric_catalog()` list what exists. The store carries the 9-month YTD band (`ytd9`, fundamentals 3.1.0), so the fiscal-year-end
quarter is rebuilt as annual minus 9-month YTD like F1 (`q4_rule="ytd9"`, the default;
`"sum_of_quarters"` stays a parameter).
Publication dates are read in New York time (`publication_tz`); the module docstring lists
where they can differ from F1's by a few days. Without an SIC, pass `sector_known=False`:
`sector_relevant` is then null rather than false.

## Live mode (no store)

`company_corpus.live` builds one issuer's rows straight from the SEC, on demand: no corpus on
disk, no vault, no open-data-store instance (install the `[live]` extra). `issuer_tables` returns
the `entity_observations`, `fundamentals`, `filings` and `filing_statements` tables
`store-batches` would write, typed by the same contracts; `filing_document` returns a filing's
primary document as Markdown with its Item sections; `resolver_rows` and `list_filings` cover
company resolution and filing lists.

```python
from datetime import datetime, timezone
from company_corpus import Config
from company_corpus.live.sec import SecClient
from company_corpus.live.issuer import issuer_tables

sec = SecClient("you@example.org")    # the SEC contact: required, never read from the environment
t = issuer_tables("320193", sec, config=Config(), now=datetime.now(timezone.utc),
                  positions_from=None, positions_to=None,
                  facts_max_age_s=None, submissions_max_age_s=None)
```

The contact is mandatory (`SecContactMissing`), sent only in the `User-Agent` and never logged.
Requests are capped at 5 per second by default (`max_rps`, at most 10). Errors form one taxonomy
(`SecError`: `SecRefused`, `SecUnavailable`, `SecNotFound`, `SecHttpError`). There is no cache:
a cold issuer costs one request per submissions page and three per report filing, and a
document conversion can take seconds (refused above `max_html_bytes`). Details, error handling
and measured costs: [`docs/LIVE.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/LIVE.md).

## Operations

**Doctrine, in one sentence:** every work command folds its own counters into a
structured run-report before exiting, so a run that did no useful work can
never exit `0`.

### Exit codes

- `0` — clean: real work got done, or nothing was found and zero errors occurred.
- `1` — fatal: an uncaught exception, or a command that itself returned non-zero.
- `3` — degraded: any source reported a `truncated` (partial) result, OR zero
  new documents were produced while errors occurred (save errors and/or fetch
  errors, plus any write the corpus itself refused). Recovered transient errors
  alongside real new documents do **not** degrade a run.

### `data/runs.jsonl`

Every work command — `build-universe`, `discover`, `discover-index`, `download`,
`render-pdf`, `xbrl`, `ownership`, `enrich-openfigi`, `eu-financials`,
`eu-acquire`, `register-financials`, `store-batches`, `statements` — appends one JSON line (atomic `O_APPEND`
write) before returning:

```json
{"run_id": "...", "tool": "company-corpus", "command": "discover",
 "started_at": "...", "finished_at": "...", "outcome": "ok", "exit_code": 0,
 "totals": {"docs_seen": 120, "docs_new": 4, "docs_failed": 0},
 "sources": [{"source_code": "sec", "docs_seen": 120, "docs_new": 4,
              "docs_failed": 0, "fetch_errors": 0, "truncated": false,
              "error_samples": []}]}
```

A `failed` run also carries a `fatal` field (the exception, capped at 500
chars). A run in which the corpus refused one of its own writes (the no-shrink
guard, or the stale-F1 prune of `xbrl`) also carries `local_refusals` — `{"count": n, "samples": [...]}` — and
those refusals are included in `totals.docs_failed`: they are failures of the
run under **no** `source_code`, because no authority was involved (see
`SOURCE_CODES` below). The key is absent when there were none. The MyOpenFund vault ingests this file **unchanged** — the schema is
deliberately flat and stable, so it feeds a `runs` table with no transform step.

`COMPANY_DATA_DIR` is a test/ops override of the **run-report path only**
(`runs.jsonl`): it wins over everything else for that one file, and nothing
else honours it — the corpus and the error trail below stay under the data
dir. To relocate the corpus *and* the trail, use `--data-dir` (which also
places the report, absent the override); the default is `Config`'s `./data`.

### Unit of useful work, per command

`docs_new` is what a command reports as its actual output; `docs_seen` is what
it examined; `docs_failed` is its error count. A dry run still counts what it
*would* write (except `download`, whose producer has no would-download
counter), so a dry run that found candidates and hit no errors is `ok`, never
a green "nothing to do":

| command | source | docs_new (useful work) |
|---|---|---|
| `build-universe` | sec | issuers resolved to a CIK (an unresolved identifier ≠ error; each input counted once; upstream fetch failures — a dead cik-lookup, an EFTS error — are recorded as fetch errors, so a run left with nothing resolved by a dead upstream is degraded) |
| `discover` (`--download`) | sec | records added (+ files downloaded); both legs fold into the one `sec` row, so exit 3 needs both legs empty and either leg failing |
| `discover-index` | sec | records added |
| `download` | sec | files downloaded |
| `render-pdf` | sec | rendered + would_render |
| `xbrl` | sec | period summaries (a stale-F1 prune refusal is a local refusal, not a `sec` failure; `details.xbrl.prune` carries the prune counters) |
| `ownership` | sec | insider + 13F + passthrough filings (+ would-download on a dry run) |
| `enrich-openfigi` | sec | identifiers mapped (no-match ≠ error) |
| `eu-financials` | xbrlorg | period summaries |
| `eu-acquire` | one row per backend dispatched to | documents kept from that backend |
| `register-financials` | one row per register | period summaries |
| `store-batches` | sec | issuers emitted (dry run: computed) |
| `statements` | sec | issuers written (dry run: 0) |
| `migrate-contract` | sec | manifest rows rewritten + F1 rows moved (dry run: what would be); a refused issuer is a local refusal |

Full detail (every column, plus the three deliberate policy choices behind
this table) is documented in the `cli.py` module docstring.

### One writer at a time

A run that writes (`--write`, or `discover --download`) takes an exclusive
`flock` on `data/.corpus.lock` for its whole duration; a second writer refuses
to start and names the holder (pid, host, command, start time) instead of
interleaving read-modify-rewrite passes over the same manifests. Read-only runs
never take, wait for, or create the lock. `Config.lock_wait_seconds` (default
`0.0`; library callers only) turns the refusal into a bounded wait. There is no
stale-lock timeout: the kernel drops the lock when the holder dies.

Two caveats. The lock is **advisory** — it stops another company-corpus run, not
an unrelated process editing the same files — and it needs a filesystem that
implements `flock`: **SMB/CIFS does not**, and a data directory on such a mount
now fails immediately with a message naming it, rather than pretending the
corpus is busy. Write the corpus from **one host**; other hosts may read it.

Files land with the permissions your umask implies (`0666 & ~umask`, so `0644`
under the usual `022`), not the `0600` that the atomic-write temp file is
created with — the corpus is meant to be readable by the ingester and by share
consumers running as other accounts.

### `verify`: the read-only self-check

```bash
python -m company_corpus verify                 # human summary, exit 0 / 3
python -m company_corpus verify --json          # every finding, machine-readable
python -m company_corpus verify --ciks 320193   # one issuer (skips the LEI-keyed EU pillar)
python -m company_corpus verify --hash          # also re-hash every stored artefact (slow)
```

Asks the corpus on disk whether it is what it claims to be, and answers with
findings — never a repair. It **writes nothing**, creates no directory, and
takes **no corpus lock**, so it is safe to run beside a nightly crawl.

| kind | what it means |
|---|---|
| `missing-artefact` | a manifest row points at bytes that are not on disk (or outside the data dir) |
| `orphan-artefact` | a file under `raw/` that no manifest row points at (`raw/<cik>/submissions/`, `raw/<cik>/statements/` and `raw/_sec_statements/` (SEC bulk statement files) are layer 0, like `F1/companyfacts.json`, and never orphans; OS metadata such as `.DS_Store`, `._*` or anything under a dot-directory is skipped; `Config.verify_ignore_hidden=False` reports it too) |
| `duplicate-doc-id` | one `doc_id` on two rows (or under two LEI manifests) |
| `stale-doc-id` | a stored id the current identity rule does not reproduce (a pre-period-keyed F1 id, an EU manifest with no `native_id`) |
| `foreign-row` | a row filed under an entity other than the one naming its file |
| `invalid-identifier` | a filename or row id that is not a usable CIK / LEI / path component |
| `incomplete-record` | a submission is stored but `submission_sha256` is unset, or (no submission: an F1 summary) an artefact is stored and no hash is (half-processed; `download` repairs it from disk) |
| `pre-contract-row` | a manifest row in the pre-contract form; `migrate-contract --write` rewrites it, every other command that reads the manifest refuses it until then (the orphan check is dropped: what the row points at is not read) |
| `missing-primary-hash` | a row with a primary document but no `sha256` (its hash); `migrate-contract --write` computes it from the files on disk |
| `f1-in-manifest` | an F1 row in `manifest/` (its place is `derived/f1/`; `migrate-contract --write` moves it); the other commands refuse that manifest |
| `not-f1-in-f1-index` | a row of another family in `derived/f1/` |
| `submission-hash-mismatch` | `--hash` only: the stored submission no longer hashes to `submission_sha256` |
| `primary-hash-mismatch` | `--hash` only: the primary document hashes neither on disk nor re-derived from the submission to `sha256` (the file at `primary_path` may legitimately be an ownership summary that superseded the filed XML: the submission then decides) |
| `hash-mismatch` | `--hash` only: an EU file no longer hashes to its manifest's `sha256` |
| `unreadable-row` / `unreadable-file` | a line or a file that could not be parsed or read — reported, never a crash |

Exit codes follow the doctrine: `0` clean, `3` findings, `1` the data
directory itself cannot be read. The default pass is metadata-only — every
pointer is resolved against **one** listing of `raw/`, so a 9 GB corpus is a
directory walk, not a re-read; `--hash` is the opposite and is not a nightly
job. When part of the index cannot be read the orphan check is **skipped**
entirely (unreferenced could not be told from unknown) and says so. A corpus
with no `data/manifest/` at all gets one `note` saying that in a sentence,
beside the per-file findings.

### Adoption / migration: taking over an existing corpus

Pointing this tool at a directory an earlier version (or an earlier tool) wrote
is a supported move, and it costs far less bandwidth than it looks. The bytes
under `raw/` are the expensive part and they are kept: what is rebuilt is the
index that points at them.

```bash
python -m company_corpus verify --json > before.json   # measure, change nothing
python -m company_corpus discover --universe u --write # rebuild the manifest index
python -m company_corpus download  --universe u --write --limit 0   # repairs only
python -m company_corpus verify --json > after.json    # measure again
```

1. **Measure first.** `verify --json` writes nothing and takes no lock, so it is
   safe on a live corpus. Its `notes` say what is missing wholesale (no
   `data/manifest/` at all, no tables at all) instead of drowning you in one
   finding per file.
2. **Rebuild the index** with `discover --write`. Downloaded bytes are never
   orphaned by this: the artefact pointers are *sticky*, so a fresh discovery
   record cannot blank the pointers a stored one already carries.
3. **Adopt what is on disk** with `download --write`. `--limit` caps *new
   downloads only* — repairs cost no network, since they re-derive the primary,
   the cleaned text and the hash from the submission already stored — so
   `--limit 0` is a download-free convergence pass over the whole selection.
   Report the `repaired=` count; scope the pass with `--forms` / `--since` /
   `--years` if the corpus is large. Drop `--limit` when you also want the
   filings that were never fetched.
4. **Re-run the derived pillars.** Family **F** (XBRL period summaries) is
   *not* repaired from disk — its ids changed basis (they are period-keyed now),
   so old summaries are orphans: rebuild with `xbrl --write` and delete what
   `verify` then reports under `raw/<cik>/F1/`. Likewise, EU documents acquired
   before the computed EU identity keep their old directories: `eu-acquire
   --write` re-acquires them under their computed `doc_id`, but — exactly as
   with F1 — it does not delete what it replaced, so the old manifests stay on
   disk and keep reporting `stale-doc-id` (*no native_id recorded*) until you
   delete them by hand under `manifest/<LEI>/` and their bytes under
   `raw/<LEI>/`. Ownership summaries are rebuilt by `ownership --write`.
5. **Verify again** and diff the two reports. Expect `orphan-artefact` to fall
   and `incomplete-record` to reach zero. A remaining `orphan-artefact` whose
   detail says *interrupted atomic write, safe to delete* is a `.tmp`/`.part`
   leftover and needs no investigation. A remaining `stale-doc-id` is a
   superseded manifest from step 4 waiting to be deleted.

Three things to know before pointing it at a share:

- **Coverage files are cumulative.** `reports/*_coverage*.jsonl` are merged, not
  truncated, so rows from the old universe survive a narrower run. Reset one
  with `--replace --allow-shrink` on the command that writes it.
- **SMB/CIFS is refused, not tolerated.** A writing run takes an `flock` and
  fails immediately on a mount that cannot provide one (see *One writer at a
  time*). Write from a local filesystem; export it for readers.
- **File modes follow the crawler's umask** (`0666 & ~umask`), read once at
  import. If the ingester runs as another account, set the umask in the unit
  file or wrapper that launches the crawl, not afterwards.

### Logging

Work commands configure the root logger once (INFO, to stderr) so their own
progress is visible; register and EU/OAM fetch failures — a dead source, or a
partial multi-call traversal that still produced some periods — are logged as
WARNINGs, in addition to being folded into the run report and the trail below.

### The discovery-error trail

Every pillar that hits a dead source (SEC discovery, an EU/OAM backend, or a
national register) appends to `data/discovery_errors.jsonl`, one JSON line per
error, stamped by `Storage.record_errors` with `ts` (ISO-8601 UTC) and the
`run_id` of the run that hit it — so a trail entry ties back to its run report.
Written **only with `--write`** for the EU and register commands (a dry run
still reports the errors in `runs.jsonl`, but leaves no trail file — "DRY-RUN
(nothing written)" means exactly that). In a register's own coverage file,
`source-error` is a distinct status from `no-financials` / `unbalanced`: "the
register could not be read" is a fact about the source, never confused with
"the issuer filed nothing."

Every coverage file (`reports/eu_coverage.jsonl`,
`reports/eu_financials_coverage.jsonl`, `reports/register_coverage_<source>.jsonl`)
is **merged across runs**, keyed by entity: a run over a slice of the universe
updates that slice's rows and leaves every other entity's evidence where it was,
which is what makes "was ok yesterday, source-error today" observable at all.
The rows of an entity you stop crawling therefore persist. `--replace` (with
`--allow-shrink` to confirm the loss) resets a coverage file to what the run
itself produced — the way to rebuild a report after narrowing a universe.

### `SOURCE_CODES`: one code per authority

The corpus pulls filings through three pillars — SEC EDGAR, the EU/OAM network
(13 national mechanisms + the filings.xbrl.org aggregator), and 8 national
company registers — and
[`company_corpus/source_codes.py`](https://github.com/MyOpenFund/company-corpus/blob/main/company_corpus/source_codes.py) is the
canonical registry mapping every one of those **23 codes** to its real-world
regulatory authority, never to a module, class, or file-format variant (e.g.
`erst-fsa` and `erst-ifrs` are both the Danish `erst` authority; the finer
"how it reached us" detail lives in the row's `provenance` field, not in a
second near-duplicate code). `source_code_for()` resolves any producer/backend
tag to its canonical code and raises rather than guess.

A tag that names **this tool** rather than a publisher — `storage`, carried by
the refusals the no-shrink guard makes — is deliberately *not* a code:
`source_code_for()` raises on it, `is_local_source()` recognises it, and the run
report counts it under `local_refusals` (and in `totals.docs_failed`, so the
exit-code doctrine sees it) with **no source row at all**. Blaming an authority
for a decision taken on this side of the network would be the report's worst
possible lie.

## Documentation

| Doc | What's inside |
|---|---|
| [`docs/ARCHITECTURE.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/ARCHITECTURE.md) | Layer map, data model, corpus lifecycle, issuer-resolution waterfall, design invariants |
| [`docs/SEC_PILLAR.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/SEC_PILLAR.md) | 🇺🇸 SEC guide: taxonomy, storage layout & naming, the full CLI, identity (rename/merger), ownership & XBRL financials |
| [`docs/EU_PILLAR.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/EU_PILLAR.md) | 🇪🇺 EU guide: the "European EDGAR" — `OamSource` architecture, identity resolution (LEI/ISIN/OpenFIGI/name), listing dispatch, cross-backend dedup, the `eu-acquire` command / `acquire()` |
| [`docs/EU_BACKENDS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/EU_BACKENDS.md) | Per-country backend reference (source API, identity key, doc types, pagination caps) |
| [`docs/FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/FINANCIALS.md) | The shared financials engine (reported + derived metrics, 71 curated concepts) |
| [`docs/EU_FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/EU_FINANCIALS.md) | Structured EU ESEF/IFRS financials — json_url stdlib (Tier A) + Arelle (Tier B) |
| [`docs/REGISTER_FINANCIALS.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/REGISTER_FINANCIALS.md) | Statutory financials from 8 national registers (🇳🇴 NO · 🇬🇧 UK · 🇧🇪 BE · 🇱🇺 LU · 🇫🇮 FI · 🇩🇰 DK · 🇪🇪 EE · 🇸🇰 SK); no-false-data gate; `leverage_basis` field |
| [`docs/LIVE.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/LIVE.md) | Live mode (no store): the `company_corpus.live` API, the SEC contact, rate cap, error taxonomy, request and conversion costs |
| [`docs/INGESTION_RAG.md`](https://github.com/MyOpenFund/company-corpus/blob/main/docs/INGESTION_RAG.md) | The vault `documents` contract the manifests follow, the RAG artefact rule, `vocabulary.json`, F1 out of the vault, `migrate-contract` |

## Core principles

- **Official primary sources only** — every document comes from the issuer's
  regulator of record; provenance is recorded per filing.
- **Replicability** — stable, date-independent document ids; idempotent,
  convergent crawls; deterministic on-disk layout.
- **Exhaustivity** — discovery via each regulator's own indices/APIs; coverage is
  reconciled against what's expected; incompleteness is **recorded, never silently
  dropped** (a backend that caps a page records a `truncated` error).
- **No-guess identity** — an issuer is bound only on an exact/verified match
  (CIK, LEI, or ISIN); an ambiguous match is left unresolved, never guessed.
- **No-false-data** — in the register-financials pillar, any value that cannot be
  confirmed from structural anchors is suppressed and the reason recorded; a missing
  number beats a wrong one.

## Fair access

The HTTP client sends a declared, contact-carrying `User-Agent` and throttles per
host to stay at/under each regulator's published rate limit (e.g. the SEC's 10
requests/second). It retries only transient failures — connection errors,
timeouts, HTTP 429 and 5xx — with backoff (honouring `Retry-After`); any other
4xx is taken as the server's answer and costs exactly one request, so a missing
document never turns into four requests and seconds of backoff against the host.
Text bodies are decoded by their declared charset; when none is declared it
tries strict UTF-8 first and otherwise keeps the header default — `requests`
would otherwise default undeclared `text/*` to ISO-8859-1 and turn UTF-8 pages
into mojibake. There is no charset sniffing, which would mis-read genuine
latin-1 pages as something else.

**Belgium (FSMA STORI)** is the one exception, and it is opt-in
(`pip install "myopenfund-company-corpus[be]"`) and off by default. The FSMA JSON API sits behind an F5
BIG-IP ASM WAF that rejects plain HTTP clients, so `company_corpus/eu/sources/oam_be.py`
reaches it through `curl_cffi` impersonating Chrome (`impersonate="chrome124"`)
with browser-consistent `Origin`/`Referer` headers and a bootstrapped session
cookie, bypassing the shared `Fetcher` entirely — no project contact `User-Agent`,
no shared throttle. That is stated here factually as the reason this one backend
stays behind an explicit extra rather than being on by default.

## License

Code is licensed under the [MIT license](https://github.com/MyOpenFund/company-corpus/blob/main/LICENSE). The metadata files
committed under `data/` and the manifests/tables this tool produces are
licensed under [CC BY 4.0](https://github.com/MyOpenFund/company-corpus/blob/main/DATA_LICENSE); the underlying filings remain under
each issuing authority's own terms. The recorded response fixtures under
`tests/fixtures/` are reproductions of each authority's own output for
regression testing and are not covered by either license — see
[DATA_LICENSE](https://github.com/MyOpenFund/company-corpus/blob/main/DATA_LICENSE) for the per-directory provenance.
