Files
accounted/scripts/fit-categorize-calibration.ts
T
Jakob Wennberg ad8566f1ae feat(settings): per-company data-analysis opt-in gating the calibration corpus (#1346) (#2007)
* feat(settings): per-company opt-in for data analysis of bookkeeping outcomes (#1346)

Adds company_settings.data_analysis_opt_in (default false, no grandfathering)
and gates every path that reads bookkeeping outcomes across companies on it:
POST /api/agent/categorize/outcome stops writing calibration samples for
companies that have not opted in, and the backtest / calibration-fit scripts
filter to opted-in company ids. One helper (lib/company/data-analysis.ts)
is the single gate for future analysis paths. A toggle on Inställningar >
Företag states plainly what is analysed (proposed vs booked account, amount,
confidence; no free text, no personal data) in sv and en. The flag is UI-only
by design: consent is a human action, so it is absent from the v1 REST / MCP
settings pick lists.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(settings): make data-analysis consent copy true for the backtest path (#1346)

Addresses adversarial review findings on PR #2007:

- Findings 1-3 (consent narrower than the gated processing): the flag also
  gates scripts/backtest-categorize.ts, which re-runs transaction
  descriptions, merchant names and matched underlag through the model. The
  sv/en toggle help and disclosure now state that explicitly as "evaluation
  runs" and no longer claim that free text or underlag are excluded. The
  migration header and COMMENT, the lib/company/data-analysis.ts docstring,
  the backtest script header and the DECISIONS line say the same. Kept the
  gate (un-gating would put the script back to reading every company with
  no consent at all). A test pins that both locales name those inputs and
  contain no "no free text / no underlag" denial.
- Finding 4 (member sees an active switch that RLS rejects): the toggle is
  now enabled only for owner/admin, matching the company_settings update
  policy; the disclosure says only administrators can change the choice.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(scripts): address round-2 review findings (#1346)

1. [minor] Opted-in company filter was an unbounded PostgREST `in` list in
   the URL (scripts/fit-categorize-calibration.ts, scripts/backtest-categorize.ts).
   Both scripts now read the opted-in ids through a shared, paginated helper
   (listDataAnalysisOptedInCompanyIds, fetchAllRows so the pre-fetch no longer
   caps at 1000) and query per chunk of 100 ids (chunkCompanyIds). The fit
   script pages each chunk on the id PK; the backtest merges per-chunk
   results and re-cuts to the N most recent overall. Early exit on zero
   opt-ins is kept. Pinned with tests in lib/company/__tests__/data-analysis.test.ts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

* fix(scripts): coerce a null transaction description in the backtest (#1346)

The typed row from the chunked consent query made description nullable,
which TransactionForSelect does not accept; fall back to the original
description or an empty string, as the untyped row did implicitly before.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 17:38:36 +02:00

110 lines
4.3 KiB
TypeScript

/**
* Fit and report the auto-booking confidence calibration (RIP-4 step 4).
*
* READ-ONLY. Reads categorize_calibration_samples, prints the reliability
* diagram + expected calibration error, fits an isotonic calibrator, and shows
* what the auto-book / suggest / review bands would look like on the calibrated
* probability. Run this once real outcomes have accumulated (>= a few hundred);
* it changes nothing on its own.
*
* npx tsx scripts/fit-categorize-calibration.ts
*
* Note: .env.local points at production; this only SELECTs, so it is safe, but
* it is still the prod corpus you are reading.
*
* Consent: samples are only written for, and only read from, companies with
* company_settings.data_analysis_opt_in = true (#1346). The write side is
* gated in POST /api/agent/categorize/outcome; the read side filters again
* here so a company that opted out after contributing drops out of the fit.
*/
import { createClient } from '@supabase/supabase-js'
import {
reliabilityByBucket,
expectedCalibrationError,
fitIsotonic,
calibrate,
bandFor,
type Sample,
} from '@/lib/agent/categorize/calibration'
import { chunkCompanyIds, listDataAnalysisOptedInCompanyIds } from '@/lib/company/data-analysis'
const url = process.env.NEXT_PUBLIC_SUPABASE_URL
const key = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!url || !key) {
console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env.local')
process.exit(1)
}
const supabase = createClient(url, key)
async function main() {
// Consent gate (#1346): only companies that opted in to data analysis.
const optedInIds = await listDataAnalysisOptedInCompanyIds(supabase)
if (optedInIds.length === 0) {
console.log('\nNo company has opted in to data analysis (company_settings.data_analysis_opt_in). Nothing to fit.')
return
}
// Query per chunk of company ids: `.in()` goes into the GET query string, so
// one request per few hundred opted-in companies would hit URL limits.
const rows: { confidence: number; was_correct: boolean }[] = []
const PAGE = 1000
for (const chunk of chunkCompanyIds(optedInIds)) {
for (let from = 0; ; from += PAGE) {
const { data, error } = await supabase
.from('categorize_calibration_samples')
.select('confidence, was_correct')
.in('company_id', chunk)
.order('id', { ascending: true })
.range(from, from + PAGE - 1)
if (error) throw error
if (!data || data.length === 0) break
rows.push(...(data as { confidence: number; was_correct: boolean }[]))
if (data.length < PAGE) break
}
}
const samples: Sample[] = rows.map((r) => ({ confidence: Number(r.confidence), correct: r.was_correct }))
console.log(`\nSamples: ${samples.length}`)
if (samples.length === 0) {
console.log('No calibration samples yet. Let people book AI proposals first.')
return
}
const overall = samples.filter((s) => s.correct).length / samples.length
console.log(`Overall accuracy (proposal booked unedited): ${(overall * 100).toFixed(1)}%`)
console.log(`Expected calibration error (ECE): ${expectedCalibrationError(samples).toFixed(4)}\n`)
console.log('Reliability diagram (raw confidence bucket → empirical accuracy):')
for (const b of reliabilityByBucket(samples)) {
if (b.n === 0) continue
const bar = '#'.repeat(Math.round(b.accuracy * 20))
console.log(
` ${b.lo.toFixed(1)}-${b.hi.toFixed(1)} n=${String(b.n).padStart(5)} ` +
`conf=${b.meanConfidence.toFixed(2)} acc=${b.accuracy.toFixed(2)} ${bar}`,
)
}
const cal = fitIsotonic(samples)
if (!cal) {
console.log(`\nNot enough data to fit a calibrator yet (need >= 200). Bands stay uncalibrated (no auto-book).`)
return
}
console.log(`\nFitted isotonic calibrator on ${cal.fittedOn} samples.`)
console.log('Raw → calibrated (and the band for a small, routine amount):')
for (const raw of [0.3, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99]) {
const p = calibrate(raw, cal)
const band = bandFor(raw, cal, { amount: 499 })
console.log(` ${raw.toFixed(2)}${p.toFixed(2)} ${band}`)
}
console.log(
`\nNext: store this calibrator (or its thresholds) where bandFor reads it, ` +
`then enable auto-book for the top band once the empirical accuracy there is acceptable.`,
)
}
main().catch((e) => {
console.error(e)
process.exit(1)
})