Update judiciary

From atanasster/electionsbg · View interactive version

Update judiciary is an AI agent skill from the GitHub repository atanasster/electionsbg. Refresh the judiciary (Съдебна власт) data — the court caseload/workload series in data/judiciary/caseload.json, the per-court натовареност map data in data/judiciary/court_load.json (Приложение № 2, ~178 geolocated courts), both parsed from the ВСС annual "Обобщени статистически таблици за дейностт

How to use this skill

Skill file

Update Judiciary skill

<!-- pipeline-pointer:start (generated from the registry; edit scripts/pipeline/registry) -->

Pipeline: handler CODE0 is still delegated — pipeline:ingest lists it under Needs agent; why is a comment on its entry in scripts/pipeline/registry/handlers/. Follow this runbook to run it.

<!-- pipeline-pointer:end -->

Two independent artifacts, two independent triggers.

| Artifact | Source | Watcher | Script |

|---|---|---|---|

| data/judiciary/caseload.json | ВСС annual statistical-tables PDFs (vss.justice.bg) | vss_court_statistics | scripts/judiciary/__write_caseload.ts |

| data/judiciary/court_load.json | Same PDFs, Приложение № 2 (per-court натовареност) | vss_court_statistics | scripts/judiciary/__write_court_load.ts |

| data/budget/vss/budget.json | ЗДБРБ „Бюджет на съдебната власт" article (cached law HTML) | budget_law (owned by update-budget) | scripts/budget/__write_judiciary.ts |

| data/judiciary/declarations.json | ИВСС declaration register + its non-compliance lists | ivss_declarations | scripts/judiciary/__write_declarations.ts |

When to run

| Trigger | Action |

|---|---|

| vss_court_statistics flips | The ВСС published a new annual (or half-year) table. First add the new year's PDF URL to VSS_ANNUAL_TABLES in scripts/judiciary/sources.ts — the filenames are NOT uniform across years, so the map is curated by hand. Then run the caseload script. |

| budget_law flips / new ЗДБ year | Handled by the update-budget skill, which runs scripts/budget/__write_judiciary.ts alongside __write_izdrazhka.ts. |

| ivss_declarations flips | A new year landed in the register, or the ИВСС added/cleared a name on one of its four non-compliance lists. Run the declarations script — no curated URL map needed, it discovers years from the register index. |

| Fresh clone, data/judiciary/ missing | Run the caseload script; it fetches the PDFs it needs. |

Step 1 — Caseload ingest

pnpm exec tsx scripts/judiciary/__write_caseload.ts

Fetches any missing raw_data/judiciary/tables-<year>-<urlhash>.pdf (gitignored,

regenerable; ~5-30 MB each), parses Приложение № 1 out of each, and writes

data/judiciary/caseload.json. It prints a per-year summary table — eyeball it.

The cache filename carries a hash of the source URL, so pointing VSS_ANNUAL_TABLES

at a corrected re-publication is a cache miss by construction. For a same-URL

re-upload (the ВСС does this — the 2021 file is literally named …-2021_new.pdf)

pass --refetch to force a re-download. The watcher can't detect that case: it

fingerprints the set of links, not their bytes.

The PDFs carry a real text layer, so there is no OCR step. Parsing reconstructs

the table with pdfjs text positioning (bucket items into rows by y, merge into cells

by x-gap), the same technique as the investment-annex parser.

Step 1b — Per-court load ingest (the map)

pnpm exec tsx scripts/judiciary/__write_court_load.ts

Parses Приложение № 2 „Таблица за натовареността на магистратите" (the per-court

grain) out of the SAME cached PDFs and writes data/judiciary/court_load.json — one

row per court (~178), geolocated, with its ДЕЙСТВИТЕЛНА натовареност (постъпили / за

разглеждане / свършени дела на съдия месечно). This drives the court-load map on

/judiciary. Run it after Step 1 — it reads caseload.json for its reconciliation

targets, so caseload must be current first.

Robustness notes (all documented in the script): each court row is anchored on the

действителна triple + the judge count that follows it, locked to the ВСС's own identity

load = case_count ÷ person-months so the administration ratios never mis-anchor;

tiers are assigned by court-name prefix (АС/ВС/ОС/СГС/АдмС/РС/СРС, plus the defunct

АСНС/СНС for 2018–2021) with районни split by the oblast-capital set; and the parse is

reconciled per tier against caseload.json (Σ person-months and the pm-weighted

действителна load), so a bad parse throws rather than shipping.

Step 2 — Verify (the script asserts, but read the output)

If ANY year fails to parse the script throws and writes nothing — a partial

rebuild would silently regress latestYear and ship a stale dashboard. Re-run with

--allow-partial only when the loss is intended; it warns loudly and prints the new

latestYear. Every year must satisfy:

Independent cross-checks, if you want more assurance: the same PDF's separate

"СРАВНИТЕЛЕН ОТЧЕТ ЗА ДВИЖЕНИЕТО НА ДЕЛАТА" page prints the last three years and must

agree with Приложение № 1; and the ВСС's published 2021 headline (546,530 filed /

550,209 resolved / 80% within deadline) matches the parsed row.

Step 3 — Stamp, commit, sync

pnpm exec tsx scripts/stamp-ingest.ts update-judiciary --summary "caseload <first>-<last>"

Commit data/judiciary/caseload.json and data/judiciary/court_load.json (+

scripts/judiciary/sources.ts if a year was added). data/ is served from the bucket

in prod, so bucket:sync data/judiciary/.

Declarations ingest

pnpm exec tsx scripts/judiciary/__write_declarations.ts

Crawls the register (9 years × 29 first-letter pages = 261 HTML pages, ~2 min at

concurrency 4) plus the ИВСС's four non-compliance lists, and writes

data/judiciary/declarations.json (~12 KB). The full per-declaration index with PDF

paths goes to raw_data/judiciary/declarations_index.json (gitignored) — it is the

input for the magistrate-holdings ingest below.

declarations.json is PG-served since persons-pg-retirement-v1 T2.6: /judiciary

(judiciary_payloads, migration 109), NOT the bucket — the file is excluded from

bucket:sync. So reload PG after writing it, or the live register stays stale:

pnpm run db:load:judiciary-payloads:pg          # local: judiciary_payloads blob
pnpm run db:load:judiciary-payloads:pg:cloud     # prod Cloud SQL (proxy on :5434 + PGPASSFILE=$PWD/.pgpass)

The JSON stays on disk as the loader source (the judiciary_payloads parity gate reads

it). bucket:sync data/judiciary/ still ships the bucket-served siblings

(caseload.json, court_load.json); it no longer carries declarations.json.

Magistrate declared-companies ingest (the connections slice)

pnpm exec tsx scripts/judiciary/__write_magistrate_holdings.ts

Reads declarations_index.json, fetches each latest-year annual declaration PDF from

the register (~3.1k, ~10 min, streamed to memory and discarded — the corpus is

~4 GB and never stored), harvests the company names in the ownership + participation

sections, resolves each to an EIK against the TR SQLite (raw_data/tr/state.sqlite —

run update-connections first if it is missing), and writes

data/judiciary/magistrate_holdings.json. Resumable: parsed holdings are cached in

raw_data/judiciary/holdings_cache.json, so a re-run only fetches new magistrates

(--limit N bounds a test run; --local <dir> parses already-downloaded PDFs).

Emits the full latest-year roster — every magistrate the parser reads, not only

the holders (current run: 3,113 emitted / 3,114 scanned, 1 fetch failure). Postgres

serves one record at a time, so the person page + procurement search cover all ~3.1k

while the „Магистрати с декларирани дружества" tile stays holder-only (server-side

WHERE company_count > 0). Companies stay sparse — magistrates are barred from

management — so only 208 have a declared company (363 companies, ~67% EIK-resolved).

Each record also carries financials{bankCashLv, securitiesLv, realEstateCount} — a

best-effort, INFORMATIONAL reproduction from the declaration (shown лв→EUR on the

/person/:name magistrate tile, NOT a ranking, NOT a net-worth total). Only reliable

dimensions are extracted (bank/cash, securities value, owned-property count); income and

liabilities are deliberately skipped as unreliable. **2,797 magistrates carry non-zero

financials, but only a small set was hand-checked** (Аглика 183,546 лв bank ✓, Vladimir

267,374 ✓, NADEZHDA 0 ✓, Marija 4 owned properties ✓). The distribution is plausible in

the middle (median ~78k лв, p95 ~395k лв) but the high tail is unreliable: ~15 rows

over 1M лв and a max of ~19.7M лв that is near-certainly a parse artifact (the bank/cash

extractor sums every row before Вземания, so a misread digit or a fat account list

inflates it). Before shipping a run, eyeball the top of

SELECT name, court, bank_cash_lv FROM magistrate ORDER BY bank_cash_lv DESC LIMIT 30

against source PDFs; the tile framing („ориентировъчни; следа, не доказателство") is the

safety net, not a licence to publish a wrong million-лв figure on a named judge.

FRAMING (non-negotiable): magistrates are NOT elected officials. Reproduce only

what the ИВСС publishes (a company name in a filed declaration), name-matched to the

registry — a LEAD, not proof. A name that does not resolve to exactly one registry

entity is shown as text, never invented into a link. There is **no reconciliation

ground-truth** for this parse (each declaration is unique), unlike the caseload/court

tables — so validate parser changes against a hand-checked sample.

Load to Postgres (both artifacts are PG-served)

court_load.json and magistrate_holdings.json are loaded into Postgres — the map

fetches one year (court_load_year), and the person/company/search/tile magistrate views

are all derived server-side from the magistrate table (schema 069/070). So after

generating the JSON:

pnpm run db:load:court-load:pg
pnpm run db:load:magistrates:pg
pnpm run db:load:magistrate-filing-assets:pg   # REPAIRS what the line above wipes — see below
pnpm run db:load:judicial-bodies:pg            # MUST follow court-load AND magistrates

⚠️ **All four are now wired into db:refresh, and the asymmetry this paragraph used to

warn about is GONE — do not re-create it.** Until 2026-08-28

db:load:magistrate-filing-assets:pg was a REFRESH_EXCLUSIONS member while the

magistrates loader that WIPES its output was in the chain, so every full local reload left

the property count blank even on a machine holding the crawl cache — and ended in a

guaranteed red at test:data, the chain's only verification step. It now runs at chain

step 28, immediately after the roster, pinned by an ORDER_PAIRS entry in

scripts/db/refresh_coverage.test.ts. Its input stays gitignored; that is declared in

TOLERATED_GITIGNORED_INPUTS, and the loader skips-and-warns at exit 0 without the cache.

So a db:refresh no longer needs a hand-run repair.

⚠️ THE CLOUD SIDE IS UNCHANGED AND STILL MANUAL. db:refresh only ever touches local

Postgres. db:load:magistrates:pg:cloud inflicts exactly the same wipe on the SERVING

database with nothing following it, which is the path an ivss_declarations watcher flip

takes — so the :cloud block below is still the thing that must not be split up.

Then publish to Cloud SQL — nothing does this automatically, and the order is the

same. Written out in full rather than as a bare-suffix shorthand: that form reads fine to a

human and is invisible to cloud_loader_coverage.test.ts, which is how

db:load:court-load:pg:cloud sat outside every skill's literal text while looking wired

here. (The other two were already named in update-persons.)

pnpm run db:load:court-load:pg:cloud
pnpm run db:load:magistrates:pg:cloud
pnpm run db:load:magistrate-filing-assets:pg:cloud   # MUST follow magistrates — see below
pnpm run db:load:judicial-bodies:pg:cloud   # MUST follow court-load AND magistrates
# Verify the alias table landed BEFORE resolving — afterwards it is too late to tell:
#   select count(*) from judicial_body_alias;   -- must be non-zero (~530)
pnpm run db:resolve:persons:cloud

⚠️ **db:load:magistrate-filing-assets:pg[:cloud] is a REPAIR, not an optional extra, and

the magistrates loader is what makes it necessary. This paragraph is the ONE home for that

rule — process-watch-report points here rather than restating it.**

db:load:magistrates:pg's load transaction opens with TRUNCATE magistrate CASCADE.

⚠️ TRUNCATE … CASCADE keys on the mere EXISTENCE of a foreign key, not on its

ON DELETE action — verified: a child with ON DELETE RESTRICT is truncated just the same.

So magistrate_filing, which references magistrate(name), is emptied and reloaded

without the facts only the document carries: kind, period_year, form_version and

the two table*_refused flags, plus magistrate.real_estate_count_parsed, which comes back

NULL. Measured on the current corpus, local and prod alike: kind on **36,995 of 37,023

filings and a parsed property count on 3,587 of 3,594 magistrates**.

070_magistrates.sql records that the card then shows no count at all rather than

falling back to the heuristic one, deliberately: the heuristic invents property against

magistrates who declared none. So every ivss_declarations flip that runs the magistrates

loader takes the count off every card site-wide until this repair runs. On the CLOUD side

that is still every time, because nothing sequences the repair there. Locally a full

pnpm run db:refresh now heals itself — the repair is chain step 28, pinned by ORDER_PAIRS

(see the local block above) — but a hand-run pnpm run db:load:magistrates:pg on its own

still leaves the count blank until you run the repair after it.

magistrate_filing_asset itself has no foreign key and survives the CASCADE, which is why

the row count reconciles while the cards are blank.

It needs no new crawl. It re-derives from the already-cached

raw_data/judiciary/filing_cache.json (the ~3.5 h operator crawl in

scripts/judiciary/crawl_declarations.ts). ⚠️ That file is gitignored, so on a machine

that has never run the crawl this loader applies its schema, prints that it has nothing to

load and exits 0 — a safe no-op, but "it ran and printed nothing" is NOT "the count is

back". Check both arms before trusting it:

SELECT count(*) FROM magistrate WHERE real_estate_count_parsed IS NOT NULL;  -- ~3,587 of 3,594
--   the ~7 shortfall is CORRECT, not a partial repair: those records' Таблица 1 was refused,
--   and NULL there means "not read" rather than "declared nothing".
SELECT count(*) FROM magistrate_filing WHERE kind IS NOT NULL;               -- ~36,995 of 37,023

**The same loader also fills the ИВСС MONEY tables (migration 202,

magistrate_filing_money + magistrate_filing_money_read) — STORAGE ONLY.** 202 grants

app_readonly nothing, by owner decision (2026-10-21): no page, route or wealth figure may

read them until a rule says which register wins when one person has both an ИВСС and a

КПКОНПИ / Сметна палата filing for a year. Do not add the GRANT as a "fix" — it IS that

decision; magistrate_filing_money.data.test.ts fails on it. A cache crawled before the

money reader existed carries no money on its records; fill it with

pnpm exec tsx scripts/judiciary/crawl_declarations.ts --backfill-money (current-form filings

only, ~19.8k, ~80 min at the default politeness), then re-run this loader. The loader's

money tables (storage only): N filing(s) parsed line says how far that has got.

⚠️ **db:resolve:persons:cloud is not optional, and every loader above it publishes

nothing to /person without it.** judicial_body / judicial_body_alias are a DIMENSION:

the resolve is what reads the alias table and rebuilds person_role. Stop at

db:load:judicial-bodies:pg:cloud

and the new and re-spelled magistrates have no roles on prod at all — green locally,

missing live, every row count reconciling. update-persons documents the same sequence;

if that skill is running in the same session, its resolve covers this one.

**db:load:judicial-bodies:pg rebuilds the canonical court/прокуратура/следствен-отдел

dimension** (migration 116) from magistrate.court ∪ court_load.name, so it has to run

after BOTH — and, on the cloud side, before db:resolve:persons:cloud, which reads

judicial_body_alias to give every magistrate their court on /person. Skipping it does

not fail anything: the resolve just finds an empty alias table and ~2,700 magistrate roles

publish with no institution.

The loader prints every institution name it could not classify, per source. That list is

the work-list for extending scripts/judiciary/judicialBodies.ts — it never guesses a

court, because a wrong court on a named magistrate's profile is a misstatement about a

real person. The magistrate views no longer emit

magistrate_company_index.json / magistrate_search.json — those are PG-derived.

The magistrate loader also applies 071_magistrate_connections.sql (the

magistrate→politician bridge, magistrate_politician_links) and refreshes the

company_officer_counts matview it uses. That schema depends on the connections

tables from 008 (company_politicians, officer_name_counts, tr_officers), which

db:refresh loads before magistrates — on a bare magistrate-only load against a DB

without them, the loader logs a warning and the bridge simply serves empty. The bridge

seeds an officer-graph BFS from the magistrate's DECLARED companies (they are not

officers, so the normal person_politicians never finds them a link) and excludes both

hub people (>12 companies) and hub companies (>20 officers — state entities), so a judge

holding public shares is not spuriously linked to every politician. Surfaced on

/person/:name only.

Rides the ivss_declarations watcher. Commit data/judiciary/magistrate_holdings.json

(the loader input) + reload PG. No bucket:sync needed for the PG-served views.

Asserts: ≥8 years; every closed year has ≥3,000 magistrates and BOTH filing

batches (annual + change); dedupe accounting balances and every surviving row has a

distinct PDF path; the page heading's year and the year in the PDF's own path agree,

except for a bounded handful (currently 5) where the ИВСС files a January change

declaration into the prior cycle's directory — any other offset means the pages are

mis-grouped and throws; >40% of annual declarations fall in May (if that clustering

vanishes, the входящ-номер date parsing broke); and each

non-compliance list matches the exact column count declared in INTEGRITY_PAGES

(the discrepancy list has five columns — a silent truncation would drop „Вид

декларация").

The newest year is exempt from the completeness asserts: change declarations

(чл. 175в, ал. 5) arrive through the autumn, so change === 0 in spring is the

truth, not a bad parse. It only warns. Failing there would also stop the fast-moving

integrity lists from refreshing, for a reason that has nothing to do with them.

The „(1)" footnote is data, not noise. Its legend reads „лицето е подало

декларация извън срока" — the person DID file, late. A name without the marker

never filed at all. The parser carries this through as filedLate, and the tile

renders a chip plus the legend. Never strip it: the two states are materially

different statements about a named private individual.

What this is NOT. It indexes that a declaration was filed and when — never the

contents. Each declaration is a 12-page PDF form (v3.0 since 2022) with a real text

layer, so extracting assets is feasible, but it is 46k PDFs / ~37 GB and a separate

project. Filing gaps across years mostly reflect entering or leaving the corps, NOT

misconduct, and must not be presented as a compliance score.

Framing. Magistrates are not elected officials. Report only what the ИВСС itself

publishes. An empty non-compliance list is a finding — show it as empty rather than

hiding the list, or a reader will assume the worst.

Register quirks:

site the ИВСС links to as "Публикувани декларации".

/declaracii/<year>-1/ (change declarations, filed through the autumn).

excluded from the calendar rather than silently dropped.

Trust boundary: the register is fetched over plain HTTP from a bare IP

IVSS_REGISTER is http://62.176.124.194 — no TLS, no hostname, no certificate.

The four ИВСС non-compliance lists come over HTTPS from inspectoratvss.bg, but the

46,528-row register behind the bare IP does not.

Everything that crawl returns is committed: magistrate names, входящи номера, positions,

courts, and PDF paths land in data/judiciary/declarations.json and are published. So

anyone able to observe or modify traffic on the path to that IP — a hostile network, a

compromised upstream, a DNS/BGP hijack of the address — chooses what this repository

asserts about named private individuals, including who appears on a non-compliance

list. The parser's asserts catch structural damage (column counts, year offsets, dedupe),

not a plausible-looking substituted name.

Consequences to respect:

untrusted VPN exit.

integrity list is a claim about a person; treat an unexplained one as suspect until

checked against inspectoratvss.bg (HTTPS) in a browser.

without revisiting this note.

IVSS_REGISTER immediately — that is the actual fix, and it is one line.

Parser gotchas (learned the hard way)

(8.74); from 2022 they use a comma (7,14). Thousands are always a space. The

num() helper accepts either as the decimal mark.

"Районни съдилища извън / областните центрове" label leaves its data row label-less

in section I, and the "Окръжни съдилища + СГС" label carried "+ СНС" until the

specialised criminal court closed in 2022.

(judges, load/post to-consider, load/post resolved) and the last three (person-months,

actual to-consider, actual resolved) — the civil/criminal middle block is absent for

the tiers whose bench doesn't split.

administrative courts. The supreme courts (ВКС, ВАС) and the prosecution report

separately and are NOT in this table — do not present the totals as "the whole

judiciary's caseload".

One-off backfill

Years before 2018 exist (Otchet-2006.pdf … stat-2015.pdf) but the layout differs.

Adding them is a backfill, not watcher work: extend VSS_ANNUAL_TABLES, confirm the

asserts hold for each new year, and note any layout branch here. Never wire a backfill

into the watcher or CI.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.