fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
+137
View File
@@ -0,0 +1,137 @@
# Parties, phase 0: measure before building
Phase 0 of the Kontakter plan (design doc: the "Vem du gör affärer med"
artifact, 2026-09). Nothing in this phase changes product behaviour. It makes
the resolver measurable so the model steps in later phases can be judged
against labelled data instead of opinions.
## What ships in this phase
- Migration `20260902120000`: enables `pg_trgm` (trigram blocking of
counterparty keys) and drops the two context-graph tables whose feature code
was never merged and which prod no longer has. Test:
`tests/pg/parties-phase0.pg.test.ts`.
- `draw-golden-set.sql`: the reproducible draw of the labelling sample and the
payee-change base rate. Read-only.
## The golden set (never in git)
The draw returns customer voucher text, which can contain person names. The
repository is public, so the drawn rows and the labels live in
`dev_docs/parties/golden/` (gitignored). Only aggregates and this vocabulary
are versioned.
Label vocabulary for the pre-classifier, one per key:
| label | meaning | example |
|---|---|---|
| `party` | a real counterpart the company pays or invoices | `Levfakt Beijer Byggmaterial AB (2089)`, `Loopia` |
| `category` | an expense description with no counterpart in it | `Inköp av varor`, `Banktjänster`, `Fika` |
| `payroll` | salary, benefits, expense claims to a person | `Löneutbetalning: 2024.M.01 - anställd: 5` |
| `adjustment` | periodisering, kostnadsföring, omföring, lagerförändring | `Periodisering av leverantörsfaktura 1311` |
| `authority` | Skatteverket, Bolagsverket, Transportstyrelsen, kommun | `Bolagsverket ändra bolagsordning` |
| `bank` | bank fees and bank products | `Baspaket Bank`, `Avgift Amex` |
| `intermediary` | payment rail or marketplace, not the counterpart | `Klarna`, `Stripe`, `Zettle`, `AmazonMktplc` |
| `unsure` | cannot tell from the text alone | |
A key whose text names a vendor but is booked as a category still gets
`party`: the resolver decides identity, the account comes from the ledger.
Edge rules settled with the founder on 2026-09-02, after the first labelling
round:
- State fees and taxes where the counterpart is fixed (Bolagsverket
registration fees, Skatteverket, Transportstyrelsen vehicle tax) are
`authority`. A kommun or a state company that invoices for a service is a
`party` like any supplier.
- A marketplace or payment processor that the company actually pays (Amazon
Marketplace purchases, Stripe or Amex fees) is a `party`. `intermediary` is
reserved for a rail that only carries someone else's money: Klarna, Swish
and Zettle payouts, "försäljning via" lines.
- A card-platform line that carries an employee's name (Pleo, Google Ads with
the cardholder appended) is a `party`; the name is the cardholder, not the
counterpart.
- Insurance and pension premiums are `party`: the insurer is the counterpart,
whatever the 74xx account says.
## Measured on prod, 2026-09-02
- 113,032 imported expense vouchers across 385 real companies; 99.5% yield a
key; 71% belong to a key that repeats within the company.
- Payee-identity base rate: 365 suppliers have an established bankgiro on two
or more documents; 13 of them (3.6%) carry two established bankgiro numbers,
with an average span of 29 days between them, which reads as parallel
accounts or OCR variance rather than changes over time. Any distinct value
at all: 8.4%. Consequence for the signal: a new bankgiro is rare enough to
warrant a "verify" sentence, never a block, and a value must be seen on two
documents before it counts as known.
## Pre-classifier shadow evaluation, 2026-09-02
`eval-preclassifier.ts` scores three routers on the same 180 held-out keys
(20 rows, chosen by md5 of the key, serve as few-shot examples and are never
scored). Rows the founder marked `unsure` always receive a label, so the
honest number is the one that excludes them.
| Router | Strict agreement | Excluding founder-unsure | Party TPR | Party TNR |
|---|---|---|---|---|
| Rules v0, lexicon from BAS account names | 0.917 | 0.965 | 0.992 | 0.930 |
| Rules v0, lexicon incl. BAS descriptions | 0.911 | 0.959 | 0.984 | 0.930 |
| Sonnet 5 on Bedrock EU, zero-shot | 0.861 | 0.906 | 0.906 | 0.977 |
| Sonnet 5 on Bedrock EU, 20 founder examples | 0.878 | 0.924 | 0.930 | 0.977 |
Read with two caveats. The rules were written after the labels were seen,
so their score is optimistic; the model scores are honest. And most of the
remaining disagreements are definitions, not errors: whether a Bolagsverket
fee is `authority` or `intermediary`, whether a marketplace or payment
processor (Amazon Marketplace, Stripe, Amex fees) is `party` or
`intermediary`, whether a card-platform line with a person's name (Pleo,
Google Ads) is `party` or `payroll`, and whether a pension insurance premium
is `party` or `payroll`. Settle those in the vocabulary above, relabel the
handful of rows, and re-run.
BAS description tokens in the lexicon make Google and Facebook look generic
because the descriptions name them as examples; the account-name lexicon is
the default for that reason. The model's remaining party misses are text
with a person's name or a card descriptor, exactly where a hard key from a
document would decide instead.
## Selection-step evaluation against document-anchored truth, 2026-09-02
`eval-selection.ts` scores the selection step (which similar keys in the same
company are the same party) without human labels: every key in the set has an
org number read by OCR from an invoice linked to its voucher, so two keys are
the same party exactly when the org numbers agree. Keys mapping to several
org numbers are excluded. 225 anchors, 1,038 candidate pairs (747 same, 291
different), 44 anchors with no true match. Draw: `draw-selection-gold.sql`.
The model selector is opt-in (`--llm`): it sends the same voucher text the
production categorizer already sends to the configured AI provider (Bedrock EU
on hosted), so run it only with an env file whose AI settings you have checked.
| Selector | Pair precision | Pair recall | Non-match recall | Anchors fully right | "None" precision / recall |
|---|---|---|---|---|---|
| Rules (same core name) | 0.909 | 0.776 | 0.801 | 0.547 | 0.40 / 0.86 |
| Sonnet 5 on Bedrock EU, zero-shot | 0.910 | 0.904 | 0.770 | 0.756 | 0.68 / 0.77 |
What the false merges are: both selectors merge "Levfakt Fortnox (325)" with
"Levfakt Fortnox (154)", "Vattenfall Kundservice" with "Vattenfall
Eldistribution", "Jämtkraft" with "Jämtkraft" under another org number. Those
are different legal entities sharing a trade name, or OCR variance in the org
number. Text cannot separate them and should not try: the hard key from the
document is the referee, which is exactly the resolver's precedence order.
What the model catches that the rules miss: "lån themax" versus "lån från
themax", and paraphrases with a changed word order.
Read with one caveat: sales-side vouchers ("kundbet ...") contribute noisy
truth because the org number on the linked document can be the customer's;
the next draw restricts to expense-side vouchers.
Cost: about 1,300 input tokens per anchor, 298k tokens for the run.
## Still to confirm in this phase
- SCB access: the free Företagsregistret API carries F-skattstatus,
Momsstatus and Arbetsgivarstatus (verified on scb.se 2026-09-02); access
requested by email, credentials pending.
- The pre-classifier and selection agreement bars (0.85 on the labelled set)
are enforced by the shadow harness in phase 1, not here.
+77
View File
@@ -0,0 +1,77 @@
-- Parties, phase 0: draw the golden set for the counterparty resolver.
--
-- Read-only. Run against prod through the Supabase MCP (execute_sql) or psql.
-- The OUTPUT contains customer voucher text, which can include person names
-- (salary vouchers, expense claims). It must never be committed to this
-- public repository: write it to dev_docs/parties/golden/ (gitignored) and
-- label it there. Only aggregate results and the labelling vocabulary belong
-- in the repo.
--
-- Scope: posted SIE-imported vouchers (source_type = 'import') with at least
-- one expense debit line (4xxx-7xxx), sandbox tenants excluded. Keys are the
-- shipped normalize_counterparty_key() so the sample matches what the
-- resolver will see. Three strata so the set is not dominated by one tenant:
-- fleet = key seen in 5+ companies (60 rows)
-- heavy = 20+ vouchers in fewer companies (60 rows)
-- tail = everything else with 3+ vouchers (80 rows)
-- Ordering by md5(key) makes the draw deterministic and re-runnable.
-- 1. Keys for the pre-classifier (party / category / payroll / adjustment /
-- authority / bank / intermediary / unsure).
WITH real_co AS (SELECT id FROM companies WHERE name NOT ILIKE '%sandl%'),
scope AS (
SELECT je.id, je.company_id, je.description, public.normalize_counterparty_key(je.description) AS k,
(SELECT l.account_number FROM journal_entry_lines l
WHERE l.journal_entry_id = je.id AND l.account_number ~ '^[4-7][0-9]{3}$'
ORDER BY l.debit_amount DESC LIMIT 1) AS acct,
(SELECT sum(l.debit_amount) FROM journal_entry_lines l
WHERE l.journal_entry_id = je.id AND l.account_number ~ '^[4-7][0-9]{3}$') AS sek
FROM journal_entries je JOIN real_co c ON c.id = je.company_id
WHERE je.status = 'posted' AND je.source_type = 'import'
AND EXISTS (SELECT 1 FROM journal_entry_lines l
WHERE l.journal_entry_id = je.id AND l.account_number ~ '^[4-7][0-9]{3}$' AND l.debit_amount > 0)
),
keys AS (
SELECT k, count(*) AS n, count(DISTINCT company_id) AS cos,
mode() WITHIN GROUP (ORDER BY description) AS example,
mode() WITHIN GROUP (ORDER BY acct) AS acct, round(sum(sek)) AS sek,
(array_agg(DISTINCT left(description, 60)))[1:3] AS variants
FROM scope WHERE k <> '' GROUP BY k HAVING count(*) >= 3
),
strata AS (
SELECT *,
CASE WHEN cos >= 5 THEN 'fleet' WHEN n >= 20 THEN 'heavy' ELSE 'tail' END AS stratum,
row_number() OVER (PARTITION BY (CASE WHEN cos >= 5 THEN 'fleet' WHEN n >= 20 THEN 'heavy' ELSE 'tail' END)
ORDER BY md5(k)) AS rn
FROM keys
)
SELECT stratum, k, example, n, cos, acct, sek, variants
FROM strata
WHERE (stratum = 'fleet' AND rn <= 60) OR (stratum = 'heavy' AND rn <= 60) OR (stratum = 'tail' AND rn <= 80)
ORDER BY stratum, rn;
-- 2. Base rate of supplier bankgiro changes in our own documents, to set the
-- severity of the payee-identity signal. "Established" = a bankgiro seen on
-- at least two documents for the same org number; a single differing value
-- is treated as OCR noise or a one-off account.
WITH real_co AS (SELECT id FROM companies WHERE name NOT ILIKE '%sandl%'),
docs AS (
SELECT d.company_id,
regexp_replace(coalesce(d.extracted_data->'supplier'->>'orgNumber',''), '[^0-9]', '', 'g') AS org,
regexp_replace(coalesce(d.extracted_data->'supplier'->>'bankgiro',''), '[^0-9]', '', 'g') AS bg,
d.created_at::date AS seen
FROM document_attachments d JOIN real_co c ON c.id = d.company_id
WHERE length(regexp_replace(coalesce(d.extracted_data->'supplier'->>'bankgiro',''), '[^0-9]', '', 'g')) BETWEEN 7 AND 8
AND length(regexp_replace(coalesce(d.extracted_data->'supplier'->>'orgNumber',''), '[^0-9]', '', 'g')) = 10
),
bg_counts AS (SELECT company_id, org, bg, count(*) AS n, min(seen) AS first_seen, max(seen) AS last_seen FROM docs GROUP BY 1,2,3),
established AS (SELECT * FROM bg_counts WHERE n >= 2),
per_supplier AS (
SELECT company_id, org, count(*) AS established_bgs, sum(n) AS docs, max(last_seen) - min(first_seen) AS span_days
FROM established GROUP BY 1,2
)
SELECT count(*) AS suppliers_with_established_bg,
count(*) FILTER (WHERE established_bgs >= 2) AS suppliers_with_2_established_bgs,
round(100.0 * count(*) FILTER (WHERE established_bgs >= 2) / nullif(count(*),0), 1) AS pct,
round(avg(span_days) FILTER (WHERE established_bgs >= 2)) AS avg_span_days_when_changed
FROM per_supplier;
+44
View File
@@ -0,0 +1,44 @@
-- Parties, phase 0/1: draw the document-anchored ground truth for the
-- SELECTION step. Read-only. Output contains customer voucher text: keep it
-- in dev_docs/parties/golden/, never in this public repository.
--
-- Truth without a human: a key whose voucher is linked to a document with an
-- OCR-read supplier org number is a known party; two keys in the same company
-- are the same party exactly when their org numbers agree. Keys that map to
-- several org numbers are dropped as ambiguous; documents whose "supplier"
-- org number is the company's own are dropped as the company's sales side.
WITH real_co AS (SELECT id, regexp_replace(coalesce(org_number,''), '[^0-9]', '', 'g') AS own_org FROM companies WHERE name NOT ILIKE '%sandl%'),
linked AS (
SELECT d.company_id, je.description,
regexp_replace(coalesce(d.extracted_data->'supplier'->>'orgNumber',''), '[^0-9]', '', 'g') AS org,
public.normalize_counterparty_key(je.description) AS k,
(SELECT l.account_number FROM journal_entry_lines l WHERE l.journal_entry_id = je.id AND l.account_number ~ '^[4-7][0-9]{3}$' ORDER BY l.debit_amount DESC LIMIT 1) AS acct
FROM document_attachments d
JOIN real_co c ON c.id = d.company_id
JOIN journal_entries je ON je.id = d.journal_entry_id AND je.status = 'posted'
WHERE d.extracted_data->'supplier'->>'orgNumber' IS NOT NULL
),
keys AS (
SELECT l.company_id, l.org, l.k, count(*) AS n, mode() WITHIN GROUP (ORDER BY l.description) AS example, mode() WITHIN GROUP (ORDER BY l.acct) AS acct,
btrim(regexp_replace(regexp_replace(l.k, '^(levfakt|levfkt|lev\.?fakt\.?|leverantörsfaktura från|leverantörsfaktura|levbet\.?|kvitto|faktura|utgift|inköp)\s+', '', 'g'), '\m\d+\M', '', 'g')) AS core
FROM linked l JOIN real_co c ON c.id = l.company_id
WHERE length(l.org) = 10 AND l.k <> '' AND l.org <> c.own_org
GROUP BY l.company_id, l.org, l.k
),
uniq AS (SELECT company_id, k, min(org) AS org, sum(n) AS n, min(example) AS example, min(acct) AS acct, min(core) AS core FROM keys GROUP BY company_id, k HAVING count(DISTINCT org) = 1),
co_ok AS (SELECT company_id FROM uniq GROUP BY 1 HAVING count(DISTINCT org) >= 2 AND count(*) >= 6),
anchors AS (SELECT u.*, row_number() OVER (ORDER BY md5(u.company_id::text || u.k)) AS rn FROM uniq u JOIN co_ok USING (company_id) WHERE length(u.core) >= 4),
sample AS (SELECT * FROM anchors WHERE rn <= 320),
cands AS (
SELECT s.rn AS anchor_rn, o.k, o.example, o.n, o.acct, o.org, extensions.similarity(s.core, o.core) AS sim,
row_number() OVER (PARTITION BY s.rn ORDER BY extensions.similarity(s.core, o.core) DESC, o.n DESC) AS cr
FROM sample s JOIN uniq o ON o.company_id = s.company_id AND o.k <> s.k
WHERE extensions.similarity(s.core, o.core) >= 0.25
),
agg AS (
SELECT s.rn, s.k AS anchor_k, s.example AS anchor_example, s.n AS anchor_n, s.acct AS anchor_acct, s.org AS anchor_org,
(SELECT json_agg(json_build_object('k', c.k, 'example', c.example, 'n', c.n, 'acct', c.acct, 'org', c.org, 'sim', round(c.sim::numeric, 2)) ORDER BY c.sim DESC)
FROM cands c WHERE c.anchor_rn = s.rn AND c.cr <= 6) AS candidates
FROM sample s
)
SELECT * FROM agg WHERE candidates IS NOT NULL ORDER BY rn LIMIT 300;
+276
View File
@@ -0,0 +1,276 @@
/**
* Parties, phase 0: shadow evaluation of the key pre-classifier against the
* founder-labelled golden set.
*
* WHAT: every counterparty key from the books must be routed before entity
* resolution: a real party, a category text, payroll, an adjustment, an
* authority, a bank product, or an intermediary. This script scores two
* candidate routers against the founder's labels on the same held-out rows:
* 1. a deterministic rule set (prefixes, lexicon, dominant account), and
* 2. the model behind getAiService().generateStructured, zero-shot and with
* twenty founder examples in the prompt.
* Agreement is reported as strict label match plus, for the routing decision
* that matters (party vs not), true-positive and true-negative rates, because
* failures are rare and raw agreement flatters.
*
* SAFETY: read-only. Reads a gitignored JSONL, calls the AI service for the
* model variants, writes a JSON report next to the input. It never opens a
* database connection. The golden rows contain customer voucher text; keep
* the report in dev_docs as well.
*
* Usage:
* npx tsx scripts/parties/eval-preclassifier.ts \
* --golden dev_docs/parties/golden/golden-2026-09-02.jsonl \
* --env .env.local [--out <report.json>] [--no-llm] [--batch 25]
*/
import { createHash } from 'node:crypto'
import { readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { config as dotenv } from 'dotenv'
import { z } from 'zod'
const LABELS = ['party', 'category', 'payroll', 'adjustment', 'authority', 'bank', 'intermediary', 'unsure'] as const
type Label = (typeof LABELS)[number]
interface GoldenRow {
id: number
stratum: string
k: string
example: string
n: number
cos: number
acct: string | null
sek: number
label: Label
}
function arg(name: string): string | undefined {
const i = process.argv.indexOf(`--${name}`)
return i >= 0 ? process.argv[i + 1] : undefined
}
const flag = (name: string) => process.argv.includes(`--${name}`)
const goldenPath = resolve(arg('golden') ?? 'dev_docs/parties/golden/golden-2026-09-02.jsonl')
const envPath = resolve(arg('env') ?? '.env.local')
const outPath = resolve(arg('out') ?? goldenPath.replace(/\.jsonl$/, '') + '.eval.json')
const batchSize = Number(arg('batch') ?? 25)
const runLlm = !flag('no-llm')
dotenv({ path: envPath })
// ── Golden set ──────────────────────────────────────────────────────────────
const rows: GoldenRow[] = readFileSync(goldenPath, 'utf8')
.split('\n')
.filter(Boolean)
.map((line) => JSON.parse(line) as GoldenRow)
.filter((r) => LABELS.includes(r.label))
// Deterministic split: the 20 rows with the lowest md5(key) are few-shot
// examples; every classifier is scored on the remaining rows only.
const md5 = (s: string) => createHash('md5').update(s).digest('hex')
const ordered = [...rows].sort((a, b) => md5(a.k).localeCompare(md5(b.k)))
const examples = ordered.slice(0, 20)
const exampleIds = new Set(examples.map((r) => r.id))
const evalRows = rows.filter((r) => !exampleIds.has(r.id))
// ── Deterministic router ────────────────────────────────────────────────────
// The rules live in lib/parties/classify.ts so the product and this
// evaluation share one implementation. --vocab is kept for the report's
// history: 'names' is what the library does; 'full' is no longer supported.
import { classifyKey } from '@/lib/parties/classify'
import { BAS_REFERENCE } from '@/lib/bookkeeping/bas-reference'
export function ruleLabel(row: { k: string; acct: string | null }): Label {
return classifyKey({ key: row.k, acct: row.acct })
}
// ── Model router ────────────────────────────────────────────────────────────
const SYSTEM = `Du sorterar nycklar från svensk bokföring innan de går vidare till motpartsmatchning.
Varje nyckel är en normaliserad verifikationstext från importerade verifikat, med exempeltext, dominerande BAS-konto, antal verifikat och antal bolag.
Sätt exakt en etikett per nyckel:
- party: en riktig motpart som bolaget betalar eller fakturerar (leverantör, butik, tjänst, kommun som fakturerar). Prefix som "levfakt", "leverantörsfaktura från", "levbet" betyder alltid party.
- category: bara en kostnadstext utan motpart i sig ("inköp av varor", "banktjänster", "fika", "diesel", "hyra momspliktig").
- payroll: lön, förmån, utlägg eller ersättning till en person.
- adjustment: periodisering, kostnadsföring, omföring, lagerförändring, nedskrivning, rättelse, valutaomräkning.
- authority: myndighet som mottagare av en avgift eller skatt (Skatteverket, Transportstyrelsen).
- bank: bankavgifter och bankprodukter.
- intermediary: betalväg eller marknadsplats som inte är den egentliga motparten.
- unsure: går inte att avgöra från texten.
En nyckel som nämner en leverantör men bokförts på ett kategorikonto är ändå party: identiteten avgörs här, kontot kommer från bokföringen.
Svara med exakt de id som frågan innehåller, inga andra.`
const ResponseSchema = z.object({
labels: z.array(z.object({ id: z.number().int(), label: z.enum(LABELS) })),
})
const jsonSchema = {
type: 'object',
properties: {
labels: {
type: 'array',
items: {
type: 'object',
properties: { id: { type: 'integer' }, label: { type: 'string', enum: [...LABELS] } },
required: ['id', 'label'],
additionalProperties: false,
},
},
},
required: ['labels'],
additionalProperties: false,
}
function basName(acct: string | null): string {
if (!acct) return ''
const hit = BAS_REFERENCE.find((a) => a.account_number === acct)
return hit ? hit.account_name : ''
}
function describe(r: GoldenRow): string {
return `id ${r.id}: nyckel "${r.k}" | exempel "${r.example}" | konto ${r.acct ?? '?'} ${basName(r.acct)} | ${r.n} verifikat | ${r.cos} bolag`
}
async function modelLabels(
batch: GoldenRow[],
fewShot: GoldenRow[] | null,
): Promise<{ labels: Map<number, Label>; usage: unknown; model: string }> {
const { getAiService } = await import('@/lib/ai')
const service = getAiService()
const shots = fewShot
? `Så här har grundaren märkt tjugo andra nycklar; följ samma bedömning:\n${fewShot
.map((r) => `${describe(r)} => ${r.label}`)
.join('\n')}\n\n`
: ''
const prompt = `${shots}Märk följande ${batch.length} nycklar:\n${batch.map(describe).join('\n')}`
let lastError: unknown
for (let attempt = 0; attempt < 2; attempt++) {
try {
const result = await service.generateStructured({
tier: 'assistant',
system: SYSTEM,
prompt,
maxTokens: 4096,
schema: { name: 'key_labels', description: 'One label per key id', jsonSchema },
})
const parsed = ResponseSchema.parse(result.value)
const valid = new Set(batch.map((r) => r.id))
const labels = new Map<number, Label>()
for (const l of parsed.labels) if (valid.has(l.id) && !labels.has(l.id)) labels.set(l.id, l.label)
return { labels, usage: result.usage, model: result.model }
} catch (err) {
lastError = err
}
}
throw lastError
}
// ── Scoring ─────────────────────────────────────────────────────────────────
interface Score {
n: number
strict_agreement: number
agreement_excluding_founder_unsure: number
party_tpr: number
party_tnr: number
per_label: Record<string, { precision: number | null; recall: number | null; support: number }>
confusions: { id: number; k: string; founder: Label; predicted: Label | null }[]
}
function score(pred: Map<number, Label | null>, subset: GoldenRow[]): Score {
let strict = 0
const decided = subset.filter((r) => r.label !== 'unsure')
let strictDecided = 0
let tp = 0, fn = 0, tn = 0, fp = 0
const per: Record<string, { tp: number; fp: number; fn: number }> = {}
for (const l of LABELS) per[l] = { tp: 0, fp: 0, fn: 0 }
const confusions: Score['confusions'] = []
for (const r of subset) {
const p = pred.get(r.id) ?? null
if (p === r.label) strict++
else confusions.push({ id: r.id, k: r.k, founder: r.label, predicted: p })
if (p) {
if (p === r.label) per[p].tp++
else {
per[p].fp++
per[r.label].fn++
}
} else per[r.label].fn++
}
for (const r of decided) {
const p = pred.get(r.id) ?? null
if (p === r.label) strictDecided++
const isParty = r.label === 'party'
const predParty = p === 'party'
if (isParty && predParty) tp++
else if (isParty && !predParty) fn++
else if (!isParty && !predParty) tn++
else fp++
}
const r4 = (x: number) => Math.round(x * 10000) / 10000
const perLabel: Score['per_label'] = {}
for (const l of LABELS) {
const { tp: a, fp: b, fn: c } = per[l]
perLabel[l] = {
precision: a + b > 0 ? r4(a / (a + b)) : null,
recall: a + c > 0 ? r4(a / (a + c)) : null,
support: subset.filter((r) => r.label === l).length,
}
}
return {
n: subset.length,
strict_agreement: r4(strict / subset.length),
agreement_excluding_founder_unsure: r4(strictDecided / decided.length),
party_tpr: r4(tp / Math.max(1, tp + fn)),
party_tnr: r4(tn / Math.max(1, tn + fp)),
per_label: perLabel,
confusions,
}
}
// ── Main ────────────────────────────────────────────────────────────────────
async function main() {
console.log(`golden rows ${rows.length}, few-shot examples ${examples.length}, scored rows ${evalRows.length}`)
const rulePred = new Map<number, Label | null>(evalRows.map((r) => [r.id, ruleLabel(r)]))
const report: Record<string, unknown> = {
golden: goldenPath,
scored_rows: evalRows.length,
example_ids: [...exampleIds],
rules_v0: score(rulePred, evalRows),
}
if (runLlm) {
for (const variant of ['zero_shot', 'few_shot'] as const) {
const pred = new Map<number, Label | null>()
const usages: unknown[] = []
let model = ''
for (let i = 0; i < evalRows.length; i += batchSize) {
const batch = evalRows.slice(i, i + batchSize)
const res = await modelLabels(batch, variant === 'few_shot' ? examples : null)
for (const r of batch) pred.set(r.id, res.labels.get(r.id) ?? null)
usages.push(res.usage)
model = res.model
console.log(`${variant}: batch ${i / batchSize + 1} done (${res.labels.size}/${batch.length} labelled)`)
}
report[`model_${variant}`] = { model, usages, ...score(pred, evalRows) }
}
}
writeFileSync(outPath, JSON.stringify(report, null, 2))
const line = (name: string, s: Score) =>
`${name.padEnd(16)} strict ${s.strict_agreement} excl-unsure ${s.agreement_excluding_founder_unsure} party TPR ${s.party_tpr} TNR ${s.party_tnr} (n=${s.n})`
console.log(line('rules_v0', report.rules_v0 as Score))
if (runLlm) {
console.log(line('model_zero_shot', report.model_zero_shot as Score))
console.log(line('model_few_shot', report.model_few_shot as Score))
}
console.log(`report: ${outPath}`)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
+226
View File
@@ -0,0 +1,226 @@
/**
* Parties, phase 0/1: shadow evaluation of the SELECTION step against
* document-anchored ground truth.
*
* WHAT: after blocking, the resolver must decide which of at most six
* similar keys in the same company are the same party as an anchor key, or
* none. Ground truth here needs no human: every key in the set carries an
* org number read by OCR from an invoice linked to its voucher, so two keys
* are the same party exactly when their org numbers agree. The draw is
* `draw-selection-gold.sql`; keys that map to several org numbers are
* excluded because they are ambiguous by construction.
*
* Two selectors are scored on the same anchors:
* 1. rules: a candidate is "same" when its core (AP prefix, supplier number
* and digit runs stripped) equals the anchor's core;
* 2. the model behind getAiService().generateStructured, asked to return the
* indices of candidates that are the same organisation, or none.
* Metrics are pair-level (same / different) precision and recall, plus the
* anchor-level "none" decision, because a resolver that merges where it
* should not is the failure mode the July design warned about.
*
* SAFETY: read-only. Reads a gitignored JSONL, writes a report next to the
* input. Never opens a database connection.
*
* DATA PROCESSING: the model selector is opt-in (--llm). It sends the voucher
* key text and account numbers in the gold file to getAiService(), which is
* the same configured provider the production categorizer already sends the
* same voucher text to (Claude on AWS Bedrock in the EU on hosted). Run it
* only with an env file whose AI configuration you have checked; without
* --llm the script scores the rules selector alone and makes no network call.
*
* Usage:
* npx tsx scripts/parties/eval-selection.ts \
* --gold dev_docs/parties/golden/selection-2026-09-02.jsonl --env .env.local \
* [--out <report.json>] [--llm] [--limit 300]
*/
import { readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { config as dotenv } from 'dotenv'
import { z } from 'zod'
interface Cand {
k: string
example: string
n: number
acct: string | null
org: string
sim: number
}
interface Anchor {
rn: number
anchor_k: string
anchor_example: string
anchor_n: number
anchor_acct: string | null
anchor_org: string
candidates: Cand[]
}
function arg(name: string): string | undefined {
const i = process.argv.indexOf(`--${name}`)
return i >= 0 ? process.argv[i + 1] : undefined
}
const flag = (name: string) => process.argv.includes(`--${name}`)
const goldPath = resolve(arg('gold') ?? 'dev_docs/parties/golden/selection-2026-09-02.jsonl')
const envPath = resolve(arg('env') ?? '.env.local')
const outPath = resolve(arg('out') ?? goldPath.replace(/\.jsonl$/, '') + '.eval.json')
const limit = Number(arg('limit') ?? 300)
const runLlm = flag('llm')
dotenv({ path: envPath })
const anchors: Anchor[] = readFileSync(goldPath, 'utf8')
.split('\n')
.filter(Boolean)
.map((l) => JSON.parse(l) as Anchor)
.slice(0, limit)
// ── Rules selector ──────────────────────────────────────────────────────────
const AP = /^(levfakt|levfkt|lev\.?fakt\.?|leverantörsfaktura från|leverantörsfaktura|levbet\.?|kvitto|faktura|utgift|inköp)\s+/
const SUFFIX = /\b(ab|aktiebolag|hb|kb|sverige|sweden|ltd|limited|oy|gmbh|inc|sarl|publ|filial)\b/g
export function core(k: string): string {
return k
.toLowerCase()
.replace(AP, '')
.replace(/\b\d+\b/g, '')
.replace(SUFFIX, '')
.replace(/[^a-zåäöé ]+/g, ' ')
.split(/\s+/)
.filter(Boolean)
.join(' ')
}
function rulesSelect(a: Anchor): number[] {
const ac = core(a.anchor_k)
if (!ac) return []
return a.candidates.map((c, i) => (core(c.k) === ac ? i : -1)).filter((i) => i >= 0)
}
// ── Model selector ──────────────────────────────────────────────────────────
const SYSTEM = `Du avgör identitet mellan motparter i svensk bokföring.
Du får ett ankare (en normaliserad verifikationstext från ett bolags bokföring) och upp till sex kandidater ur samma bolag som liknar det.
Svara med index för varje kandidat som är SAMMA organisation som ankaret, alltså samma juridiska person som skulle ha samma organisationsnummer. Olika bolag i samma koncern, franchisetagare med samma kedjenamn, eller ett företag och dess inkassobolag är INTE samma.
Leverantörsnummer inom parentes, fakturanummer och prefix som "levfakt" eller "leverantörsfaktura från" är brus, inte identitet.
Om ingen kandidat är samma organisation, svara med en tom lista. Gissa inte: hellre tom lista än en felaktig sammanslagning.`
const Out = z.object({ same: z.array(z.number().int().min(1).max(6)) })
const jsonSchema = {
type: 'object',
properties: { same: { type: 'array', items: { type: 'integer', minimum: 1, maximum: 6 } } },
required: ['same'],
additionalProperties: false,
}
async function modelSelect(a: Anchor): Promise<{ picks: number[]; usage: unknown; model: string }> {
const { getAiService } = await import('@/lib/ai')
const service = getAiService()
const prompt =
`Ankare: "${a.anchor_k}" (exempel "${a.anchor_example}", konto ${a.anchor_acct ?? '?'}, ${a.anchor_n} verifikat)\n` +
`Kandidater:\n` +
a.candidates
.map((c, i) => `[${i + 1}] "${c.k}" (exempel "${c.example}", konto ${c.acct ?? '?'}, ${c.n} verifikat, textlikhet ${c.sim})`)
.join('\n') +
`\nVilka kandidater är samma organisation som ankaret? Svara med index, eller tom lista.`
let lastErr: unknown
for (let attempt = 0; attempt < 2; attempt++) {
try {
const r = await service.generateStructured({
tier: 'assistant',
system: SYSTEM,
prompt,
maxTokens: 512,
schema: { name: 'same_party', description: 'Indices of candidates that are the same organisation', jsonSchema },
})
const parsed = Out.parse(r.value)
const picks = [...new Set(parsed.same.map((i) => i - 1).filter((i) => i >= 0 && i < a.candidates.length))]
return { picks, usage: r.usage, model: r.model }
} catch (e) {
lastErr = e
}
}
throw lastErr
}
// ── Scoring ─────────────────────────────────────────────────────────────────
interface Score {
anchors: number
pairs: number
pair_precision: number
pair_recall: number
pair_tnr: number
anchor_exact: number
none_precision: number
none_recall: number
false_merges: { anchor: string; candidate: string; sim: number }[]
missed: { anchor: string; candidate: string; sim: number }[]
}
function score(picksByAnchor: Map<number, number[]>): Score {
let tp = 0, fp = 0, fn = 0, tn = 0, exact = 0, pairs = 0
let noneTp = 0, noneFp = 0, noneFn = 0
const falseMerges: Score['false_merges'] = []
const missed: Score['missed'] = []
for (const a of anchors) {
const picks = new Set(picksByAnchor.get(a.rn) ?? [])
const truth = new Set(a.candidates.map((c, i) => (c.org === a.anchor_org ? i : -1)).filter((i) => i >= 0))
let ok = true
a.candidates.forEach((c, i) => {
pairs++
const p = picks.has(i), t = truth.has(i)
if (p && t) tp++
else if (p && !t) { fp++; falseMerges.push({ anchor: a.anchor_k, candidate: c.k, sim: c.sim }) }
else if (!p && t) { fn++; missed.push({ anchor: a.anchor_k, candidate: c.k, sim: c.sim }) }
else tn++
if (p !== t) ok = false
})
if (ok) exact++
const predNone = picks.size === 0, truthNone = truth.size === 0
if (predNone && truthNone) noneTp++
else if (predNone && !truthNone) noneFp++
else if (!predNone && truthNone) noneFn++
}
const r4 = (x: number) => Math.round(x * 10000) / 10000
return {
anchors: anchors.length,
pairs,
pair_precision: r4(tp / Math.max(1, tp + fp)),
pair_recall: r4(tp / Math.max(1, tp + fn)),
pair_tnr: r4(tn / Math.max(1, tn + fp)),
anchor_exact: r4(exact / anchors.length),
none_precision: r4(noneTp / Math.max(1, noneTp + noneFp)),
none_recall: r4(noneTp / Math.max(1, noneTp + noneFn)),
false_merges: falseMerges.slice(0, 40),
missed: missed.slice(0, 40),
}
}
async function main() {
const truthNone = anchors.filter((a) => !a.candidates.some((c) => c.org === a.anchor_org)).length
console.log(`anchors ${anchors.length}, pairs ${anchors.reduce((s, a) => s + a.candidates.length, 0)}, anchors with no true match ${truthNone}`)
const rules = new Map<number, number[]>(anchors.map((a) => [a.rn, rulesSelect(a)]))
const report: Record<string, unknown> = { gold: goldPath, rules_v0: score(rules) }
if (runLlm) {
const picks = new Map<number, number[]>()
const usages: unknown[] = []
let model = ''
let i = 0
for (const a of anchors) {
const r = await modelSelect(a)
picks.set(a.rn, r.picks)
usages.push(r.usage)
model = r.model
if (++i % 25 === 0) console.log(`model: ${i}/${anchors.length}`)
}
report.model_zero_shot = { model, usages, ...score(picks) }
}
writeFileSync(outPath, JSON.stringify(report, null, 2))
const line = (name: string, s: Score) =>
`${name.padEnd(16)} pair P ${s.pair_precision} R ${s.pair_recall} TNR ${s.pair_tnr} | anchor exact ${s.anchor_exact} | none P ${s.none_precision} R ${s.none_recall} (anchors ${s.anchors}, pairs ${s.pairs})`
console.log(line('rules_v0', report.rules_v0 as Score))
if (runLlm) console.log(line('model_zero_shot', report.model_zero_shot as Score))
console.log(`report: ${outPath}`)
}
main().catch((e) => {
console.error(e)
process.exit(1)
})